repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
linux-scraping/linux-grsecurity | drivers/net/ethernet/broadcom/b44.c | 74 | 64797 | /* b44.c: Broadcom 44xx/47xx Fast Ethernet device driver.
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
* Copyright (C) 2004 Pekka Pietikainen (pp@ee.oulu.fi)
* Copyright (C) 2004 Florian Schirmer (jolt@tuxbox.org)
* Copyright (C) 2006 Felix Fietkau (nbd@openwrt.org)
* Copyright (C) 2006 Broadcom Corporation.
* Copyright (C) 2007 Michael Buesch <m@bues.ch>
* Copyright (C) 2013 Hauke Mehrtens <hauke@hauke-m.de>
*
* Distribute under GPL.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/if_ether.h>
#include <linux/if_vlan.h>
#include <linux/etherdevice.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/ssb/ssb.h>
#include <linux/slab.h>
#include <linux/phy.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/irq.h>
#include "b44.h"
#define DRV_MODULE_NAME "b44"
#define DRV_MODULE_VERSION "2.0"
#define DRV_DESCRIPTION "Broadcom 44xx/47xx 10/100 PCI ethernet driver"
#define B44_DEF_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)
/* length of time before we decide the hardware is borked,
* and dev->tx_timeout() should be called to fix the problem
*/
#define B44_TX_TIMEOUT (5 * HZ)
/* hardware minimum and maximum for a single frame's data payload */
#define B44_MIN_MTU 60
#define B44_MAX_MTU 1500
#define B44_RX_RING_SIZE 512
#define B44_DEF_RX_RING_PENDING 200
#define B44_RX_RING_BYTES (sizeof(struct dma_desc) * \
B44_RX_RING_SIZE)
#define B44_TX_RING_SIZE 512
#define B44_DEF_TX_RING_PENDING (B44_TX_RING_SIZE - 1)
#define B44_TX_RING_BYTES (sizeof(struct dma_desc) * \
B44_TX_RING_SIZE)
#define TX_RING_GAP(BP) \
(B44_TX_RING_SIZE - (BP)->tx_pending)
#define TX_BUFFS_AVAIL(BP) \
(((BP)->tx_cons <= (BP)->tx_prod) ? \
(BP)->tx_cons + (BP)->tx_pending - (BP)->tx_prod : \
(BP)->tx_cons - (BP)->tx_prod - TX_RING_GAP(BP))
#define NEXT_TX(N) (((N) + 1) & (B44_TX_RING_SIZE - 1))
#define RX_PKT_OFFSET (RX_HEADER_LEN + 2)
#define RX_PKT_BUF_SZ (1536 + RX_PKT_OFFSET)
/* minimum number of free TX descriptors required to wake up TX process */
#define B44_TX_WAKEUP_THRESH (B44_TX_RING_SIZE / 4)
/* b44 internal pattern match filter info */
#define B44_PATTERN_BASE 0x400
#define B44_PATTERN_SIZE 0x80
#define B44_PMASK_BASE 0x600
#define B44_PMASK_SIZE 0x10
#define B44_MAX_PATTERNS 16
#define B44_ETHIPV6UDP_HLEN 62
#define B44_ETHIPV4UDP_HLEN 42
MODULE_AUTHOR("Felix Fietkau, Florian Schirmer, Pekka Pietikainen, David S. Miller");
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_MODULE_VERSION);
static int b44_debug = -1; /* -1 == use B44_DEF_MSG_ENABLE as value */
module_param(b44_debug, int, 0);
MODULE_PARM_DESC(b44_debug, "B44 bitmapped debugging message enable value");
#ifdef CONFIG_B44_PCI
static const struct pci_device_id b44_pci_tbl[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_BCM4401) },
{ PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_BCM4401B0) },
{ PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, PCI_DEVICE_ID_BCM4401B1) },
{ 0 } /* terminate list with empty entry */
};
MODULE_DEVICE_TABLE(pci, b44_pci_tbl);
static struct pci_driver b44_pci_driver = {
.name = DRV_MODULE_NAME,
.id_table = b44_pci_tbl,
};
#endif /* CONFIG_B44_PCI */
static const struct ssb_device_id b44_ssb_tbl[] = {
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_ETHERNET, SSB_ANY_REV),
{},
};
MODULE_DEVICE_TABLE(ssb, b44_ssb_tbl);
static void b44_halt(struct b44 *);
static void b44_init_rings(struct b44 *);
#define B44_FULL_RESET 1
#define B44_FULL_RESET_SKIP_PHY 2
#define B44_PARTIAL_RESET 3
#define B44_CHIP_RESET_FULL 4
#define B44_CHIP_RESET_PARTIAL 5
static void b44_init_hw(struct b44 *, int);
static int dma_desc_sync_size;
static int instance;
static const char b44_gstrings[][ETH_GSTRING_LEN] = {
#define _B44(x...) # x,
B44_STAT_REG_DECLARE
#undef _B44
};
static inline void b44_sync_dma_desc_for_device(struct ssb_device *sdev,
dma_addr_t dma_base,
unsigned long offset,
enum dma_data_direction dir)
{
dma_sync_single_for_device(sdev->dma_dev, dma_base + offset,
dma_desc_sync_size, dir);
}
static inline void b44_sync_dma_desc_for_cpu(struct ssb_device *sdev,
dma_addr_t dma_base,
unsigned long offset,
enum dma_data_direction dir)
{
dma_sync_single_for_cpu(sdev->dma_dev, dma_base + offset,
dma_desc_sync_size, dir);
}
static inline unsigned long br32(const struct b44 *bp, unsigned long reg)
{
return ssb_read32(bp->sdev, reg);
}
static inline void bw32(const struct b44 *bp,
unsigned long reg, unsigned long val)
{
ssb_write32(bp->sdev, reg, val);
}
static int b44_wait_bit(struct b44 *bp, unsigned long reg,
u32 bit, unsigned long timeout, const int clear)
{
unsigned long i;
for (i = 0; i < timeout; i++) {
u32 val = br32(bp, reg);
if (clear && !(val & bit))
break;
if (!clear && (val & bit))
break;
udelay(10);
}
if (i == timeout) {
if (net_ratelimit())
netdev_err(bp->dev, "BUG! Timeout waiting for bit %08x of register %lx to %s\n",
bit, reg, clear ? "clear" : "set");
return -ENODEV;
}
return 0;
}
static inline void __b44_cam_read(struct b44 *bp, unsigned char *data, int index)
{
u32 val;
bw32(bp, B44_CAM_CTRL, (CAM_CTRL_READ |
(index << CAM_CTRL_INDEX_SHIFT)));
b44_wait_bit(bp, B44_CAM_CTRL, CAM_CTRL_BUSY, 100, 1);
val = br32(bp, B44_CAM_DATA_LO);
data[2] = (val >> 24) & 0xFF;
data[3] = (val >> 16) & 0xFF;
data[4] = (val >> 8) & 0xFF;
data[5] = (val >> 0) & 0xFF;
val = br32(bp, B44_CAM_DATA_HI);
data[0] = (val >> 8) & 0xFF;
data[1] = (val >> 0) & 0xFF;
}
static inline void __b44_cam_write(struct b44 *bp, unsigned char *data, int index)
{
u32 val;
val = ((u32) data[2]) << 24;
val |= ((u32) data[3]) << 16;
val |= ((u32) data[4]) << 8;
val |= ((u32) data[5]) << 0;
bw32(bp, B44_CAM_DATA_LO, val);
val = (CAM_DATA_HI_VALID |
(((u32) data[0]) << 8) |
(((u32) data[1]) << 0));
bw32(bp, B44_CAM_DATA_HI, val);
bw32(bp, B44_CAM_CTRL, (CAM_CTRL_WRITE |
(index << CAM_CTRL_INDEX_SHIFT)));
b44_wait_bit(bp, B44_CAM_CTRL, CAM_CTRL_BUSY, 100, 1);
}
static inline void __b44_disable_ints(struct b44 *bp)
{
bw32(bp, B44_IMASK, 0);
}
static void b44_disable_ints(struct b44 *bp)
{
__b44_disable_ints(bp);
/* Flush posted writes. */
br32(bp, B44_IMASK);
}
static void b44_enable_ints(struct b44 *bp)
{
bw32(bp, B44_IMASK, bp->imask);
}
static int __b44_readphy(struct b44 *bp, int phy_addr, int reg, u32 *val)
{
int err;
bw32(bp, B44_EMAC_ISTAT, EMAC_INT_MII);
bw32(bp, B44_MDIO_DATA, (MDIO_DATA_SB_START |
(MDIO_OP_READ << MDIO_DATA_OP_SHIFT) |
(phy_addr << MDIO_DATA_PMD_SHIFT) |
(reg << MDIO_DATA_RA_SHIFT) |
(MDIO_TA_VALID << MDIO_DATA_TA_SHIFT)));
err = b44_wait_bit(bp, B44_EMAC_ISTAT, EMAC_INT_MII, 100, 0);
*val = br32(bp, B44_MDIO_DATA) & MDIO_DATA_DATA;
return err;
}
static int __b44_writephy(struct b44 *bp, int phy_addr, int reg, u32 val)
{
bw32(bp, B44_EMAC_ISTAT, EMAC_INT_MII);
bw32(bp, B44_MDIO_DATA, (MDIO_DATA_SB_START |
(MDIO_OP_WRITE << MDIO_DATA_OP_SHIFT) |
(phy_addr << MDIO_DATA_PMD_SHIFT) |
(reg << MDIO_DATA_RA_SHIFT) |
(MDIO_TA_VALID << MDIO_DATA_TA_SHIFT) |
(val & MDIO_DATA_DATA)));
return b44_wait_bit(bp, B44_EMAC_ISTAT, EMAC_INT_MII, 100, 0);
}
static inline int b44_readphy(struct b44 *bp, int reg, u32 *val)
{
if (bp->flags & B44_FLAG_EXTERNAL_PHY)
return 0;
return __b44_readphy(bp, bp->phy_addr, reg, val);
}
static inline int b44_writephy(struct b44 *bp, int reg, u32 val)
{
if (bp->flags & B44_FLAG_EXTERNAL_PHY)
return 0;
return __b44_writephy(bp, bp->phy_addr, reg, val);
}
/* miilib interface */
static int b44_mdio_read_mii(struct net_device *dev, int phy_id, int location)
{
u32 val;
struct b44 *bp = netdev_priv(dev);
int rc = __b44_readphy(bp, phy_id, location, &val);
if (rc)
return 0xffffffff;
return val;
}
static void b44_mdio_write_mii(struct net_device *dev, int phy_id, int location,
int val)
{
struct b44 *bp = netdev_priv(dev);
__b44_writephy(bp, phy_id, location, val);
}
static int b44_mdio_read_phylib(struct mii_bus *bus, int phy_id, int location)
{
u32 val;
struct b44 *bp = bus->priv;
int rc = __b44_readphy(bp, phy_id, location, &val);
if (rc)
return 0xffffffff;
return val;
}
static int b44_mdio_write_phylib(struct mii_bus *bus, int phy_id, int location,
u16 val)
{
struct b44 *bp = bus->priv;
return __b44_writephy(bp, phy_id, location, val);
}
static int b44_phy_reset(struct b44 *bp)
{
u32 val;
int err;
if (bp->flags & B44_FLAG_EXTERNAL_PHY)
return 0;
err = b44_writephy(bp, MII_BMCR, BMCR_RESET);
if (err)
return err;
udelay(100);
err = b44_readphy(bp, MII_BMCR, &val);
if (!err) {
if (val & BMCR_RESET) {
netdev_err(bp->dev, "PHY Reset would not complete\n");
err = -ENODEV;
}
}
return err;
}
static void __b44_set_flow_ctrl(struct b44 *bp, u32 pause_flags)
{
u32 val;
bp->flags &= ~(B44_FLAG_TX_PAUSE | B44_FLAG_RX_PAUSE);
bp->flags |= pause_flags;
val = br32(bp, B44_RXCONFIG);
if (pause_flags & B44_FLAG_RX_PAUSE)
val |= RXCONFIG_FLOW;
else
val &= ~RXCONFIG_FLOW;
bw32(bp, B44_RXCONFIG, val);
val = br32(bp, B44_MAC_FLOW);
if (pause_flags & B44_FLAG_TX_PAUSE)
val |= (MAC_FLOW_PAUSE_ENAB |
(0xc0 & MAC_FLOW_RX_HI_WATER));
else
val &= ~MAC_FLOW_PAUSE_ENAB;
bw32(bp, B44_MAC_FLOW, val);
}
static void b44_set_flow_ctrl(struct b44 *bp, u32 local, u32 remote)
{
u32 pause_enab = 0;
/* The driver supports only rx pause by default because
the b44 mac tx pause mechanism generates excessive
pause frames.
Use ethtool to turn on b44 tx pause if necessary.
*/
if ((local & ADVERTISE_PAUSE_CAP) &&
(local & ADVERTISE_PAUSE_ASYM)){
if ((remote & LPA_PAUSE_ASYM) &&
!(remote & LPA_PAUSE_CAP))
pause_enab |= B44_FLAG_RX_PAUSE;
}
__b44_set_flow_ctrl(bp, pause_enab);
}
#ifdef CONFIG_BCM47XX
#include <linux/bcm47xx_nvram.h>
static void b44_wap54g10_workaround(struct b44 *bp)
{
char buf[20];
u32 val;
int err;
/*
* workaround for bad hardware design in Linksys WAP54G v1.0
* see https://dev.openwrt.org/ticket/146
* check and reset bit "isolate"
*/
if (bcm47xx_nvram_getenv("boardnum", buf, sizeof(buf)) < 0)
return;
if (simple_strtoul(buf, NULL, 0) == 2) {
err = __b44_readphy(bp, 0, MII_BMCR, &val);
if (err)
goto error;
if (!(val & BMCR_ISOLATE))
return;
val &= ~BMCR_ISOLATE;
err = __b44_writephy(bp, 0, MII_BMCR, val);
if (err)
goto error;
}
return;
error:
pr_warn("PHY: cannot reset MII transceiver isolate bit\n");
}
#else
static inline void b44_wap54g10_workaround(struct b44 *bp)
{
}
#endif
static int b44_setup_phy(struct b44 *bp)
{
u32 val;
int err;
b44_wap54g10_workaround(bp);
if (bp->flags & B44_FLAG_EXTERNAL_PHY)
return 0;
if ((err = b44_readphy(bp, B44_MII_ALEDCTRL, &val)) != 0)
goto out;
if ((err = b44_writephy(bp, B44_MII_ALEDCTRL,
val & MII_ALEDCTRL_ALLMSK)) != 0)
goto out;
if ((err = b44_readphy(bp, B44_MII_TLEDCTRL, &val)) != 0)
goto out;
if ((err = b44_writephy(bp, B44_MII_TLEDCTRL,
val | MII_TLEDCTRL_ENABLE)) != 0)
goto out;
if (!(bp->flags & B44_FLAG_FORCE_LINK)) {
u32 adv = ADVERTISE_CSMA;
if (bp->flags & B44_FLAG_ADV_10HALF)
adv |= ADVERTISE_10HALF;
if (bp->flags & B44_FLAG_ADV_10FULL)
adv |= ADVERTISE_10FULL;
if (bp->flags & B44_FLAG_ADV_100HALF)
adv |= ADVERTISE_100HALF;
if (bp->flags & B44_FLAG_ADV_100FULL)
adv |= ADVERTISE_100FULL;
if (bp->flags & B44_FLAG_PAUSE_AUTO)
adv |= ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM;
if ((err = b44_writephy(bp, MII_ADVERTISE, adv)) != 0)
goto out;
if ((err = b44_writephy(bp, MII_BMCR, (BMCR_ANENABLE |
BMCR_ANRESTART))) != 0)
goto out;
} else {
u32 bmcr;
if ((err = b44_readphy(bp, MII_BMCR, &bmcr)) != 0)
goto out;
bmcr &= ~(BMCR_FULLDPLX | BMCR_ANENABLE | BMCR_SPEED100);
if (bp->flags & B44_FLAG_100_BASE_T)
bmcr |= BMCR_SPEED100;
if (bp->flags & B44_FLAG_FULL_DUPLEX)
bmcr |= BMCR_FULLDPLX;
if ((err = b44_writephy(bp, MII_BMCR, bmcr)) != 0)
goto out;
/* Since we will not be negotiating there is no safe way
* to determine if the link partner supports flow control
* or not. So just disable it completely in this case.
*/
b44_set_flow_ctrl(bp, 0, 0);
}
out:
return err;
}
static void b44_stats_update(struct b44 *bp)
{
unsigned long reg;
u64 *val;
val = &bp->hw_stats.tx_good_octets;
u64_stats_update_begin(&bp->hw_stats.syncp);
for (reg = B44_TX_GOOD_O; reg <= B44_TX_PAUSE; reg += 4UL) {
*val++ += br32(bp, reg);
}
/* Pad */
reg += 8*4UL;
for (reg = B44_RX_GOOD_O; reg <= B44_RX_NPAUSE; reg += 4UL) {
*val++ += br32(bp, reg);
}
u64_stats_update_end(&bp->hw_stats.syncp);
}
static void b44_link_report(struct b44 *bp)
{
if (!netif_carrier_ok(bp->dev)) {
netdev_info(bp->dev, "Link is down\n");
} else {
netdev_info(bp->dev, "Link is up at %d Mbps, %s duplex\n",
(bp->flags & B44_FLAG_100_BASE_T) ? 100 : 10,
(bp->flags & B44_FLAG_FULL_DUPLEX) ? "full" : "half");
netdev_info(bp->dev, "Flow control is %s for TX and %s for RX\n",
(bp->flags & B44_FLAG_TX_PAUSE) ? "on" : "off",
(bp->flags & B44_FLAG_RX_PAUSE) ? "on" : "off");
}
}
static void b44_check_phy(struct b44 *bp)
{
u32 bmsr, aux;
if (bp->flags & B44_FLAG_EXTERNAL_PHY) {
bp->flags |= B44_FLAG_100_BASE_T;
if (!netif_carrier_ok(bp->dev)) {
u32 val = br32(bp, B44_TX_CTRL);
if (bp->flags & B44_FLAG_FULL_DUPLEX)
val |= TX_CTRL_DUPLEX;
else
val &= ~TX_CTRL_DUPLEX;
bw32(bp, B44_TX_CTRL, val);
netif_carrier_on(bp->dev);
b44_link_report(bp);
}
return;
}
if (!b44_readphy(bp, MII_BMSR, &bmsr) &&
!b44_readphy(bp, B44_MII_AUXCTRL, &aux) &&
(bmsr != 0xffff)) {
if (aux & MII_AUXCTRL_SPEED)
bp->flags |= B44_FLAG_100_BASE_T;
else
bp->flags &= ~B44_FLAG_100_BASE_T;
if (aux & MII_AUXCTRL_DUPLEX)
bp->flags |= B44_FLAG_FULL_DUPLEX;
else
bp->flags &= ~B44_FLAG_FULL_DUPLEX;
if (!netif_carrier_ok(bp->dev) &&
(bmsr & BMSR_LSTATUS)) {
u32 val = br32(bp, B44_TX_CTRL);
u32 local_adv, remote_adv;
if (bp->flags & B44_FLAG_FULL_DUPLEX)
val |= TX_CTRL_DUPLEX;
else
val &= ~TX_CTRL_DUPLEX;
bw32(bp, B44_TX_CTRL, val);
if (!(bp->flags & B44_FLAG_FORCE_LINK) &&
!b44_readphy(bp, MII_ADVERTISE, &local_adv) &&
!b44_readphy(bp, MII_LPA, &remote_adv))
b44_set_flow_ctrl(bp, local_adv, remote_adv);
/* Link now up */
netif_carrier_on(bp->dev);
b44_link_report(bp);
} else if (netif_carrier_ok(bp->dev) && !(bmsr & BMSR_LSTATUS)) {
/* Link now down */
netif_carrier_off(bp->dev);
b44_link_report(bp);
}
if (bmsr & BMSR_RFAULT)
netdev_warn(bp->dev, "Remote fault detected in PHY\n");
if (bmsr & BMSR_JCD)
netdev_warn(bp->dev, "Jabber detected in PHY\n");
}
}
static void b44_timer(unsigned long __opaque)
{
struct b44 *bp = (struct b44 *) __opaque;
spin_lock_irq(&bp->lock);
b44_check_phy(bp);
b44_stats_update(bp);
spin_unlock_irq(&bp->lock);
mod_timer(&bp->timer, round_jiffies(jiffies + HZ));
}
static void b44_tx(struct b44 *bp)
{
u32 cur, cons;
unsigned bytes_compl = 0, pkts_compl = 0;
cur = br32(bp, B44_DMATX_STAT) & DMATX_STAT_CDMASK;
cur /= sizeof(struct dma_desc);
/* XXX needs updating when NETIF_F_SG is supported */
for (cons = bp->tx_cons; cons != cur; cons = NEXT_TX(cons)) {
struct ring_info *rp = &bp->tx_buffers[cons];
struct sk_buff *skb = rp->skb;
BUG_ON(skb == NULL);
dma_unmap_single(bp->sdev->dma_dev,
rp->mapping,
skb->len,
DMA_TO_DEVICE);
rp->skb = NULL;
bytes_compl += skb->len;
pkts_compl++;
dev_kfree_skb_irq(skb);
}
netdev_completed_queue(bp->dev, pkts_compl, bytes_compl);
bp->tx_cons = cons;
if (netif_queue_stopped(bp->dev) &&
TX_BUFFS_AVAIL(bp) > B44_TX_WAKEUP_THRESH)
netif_wake_queue(bp->dev);
bw32(bp, B44_GPTIMER, 0);
}
/* Works like this. This chip writes a 'struct rx_header" 30 bytes
* before the DMA address you give it. So we allocate 30 more bytes
* for the RX buffer, DMA map all of it, skb_reserve the 30 bytes, then
* point the chip at 30 bytes past where the rx_header will go.
*/
static int b44_alloc_rx_skb(struct b44 *bp, int src_idx, u32 dest_idx_unmasked)
{
struct dma_desc *dp;
struct ring_info *src_map, *map;
struct rx_header *rh;
struct sk_buff *skb;
dma_addr_t mapping;
int dest_idx;
u32 ctrl;
src_map = NULL;
if (src_idx >= 0)
src_map = &bp->rx_buffers[src_idx];
dest_idx = dest_idx_unmasked & (B44_RX_RING_SIZE - 1);
map = &bp->rx_buffers[dest_idx];
skb = netdev_alloc_skb(bp->dev, RX_PKT_BUF_SZ);
if (skb == NULL)
return -ENOMEM;
mapping = dma_map_single(bp->sdev->dma_dev, skb->data,
RX_PKT_BUF_SZ,
DMA_FROM_DEVICE);
/* Hardware bug work-around, the chip is unable to do PCI DMA
to/from anything above 1GB :-( */
if (dma_mapping_error(bp->sdev->dma_dev, mapping) ||
mapping + RX_PKT_BUF_SZ > DMA_BIT_MASK(30)) {
/* Sigh... */
if (!dma_mapping_error(bp->sdev->dma_dev, mapping))
dma_unmap_single(bp->sdev->dma_dev, mapping,
RX_PKT_BUF_SZ, DMA_FROM_DEVICE);
dev_kfree_skb_any(skb);
skb = alloc_skb(RX_PKT_BUF_SZ, GFP_ATOMIC | GFP_DMA);
if (skb == NULL)
return -ENOMEM;
mapping = dma_map_single(bp->sdev->dma_dev, skb->data,
RX_PKT_BUF_SZ,
DMA_FROM_DEVICE);
if (dma_mapping_error(bp->sdev->dma_dev, mapping) ||
mapping + RX_PKT_BUF_SZ > DMA_BIT_MASK(30)) {
if (!dma_mapping_error(bp->sdev->dma_dev, mapping))
dma_unmap_single(bp->sdev->dma_dev, mapping, RX_PKT_BUF_SZ,DMA_FROM_DEVICE);
dev_kfree_skb_any(skb);
return -ENOMEM;
}
bp->force_copybreak = 1;
}
rh = (struct rx_header *) skb->data;
rh->len = 0;
rh->flags = 0;
map->skb = skb;
map->mapping = mapping;
if (src_map != NULL)
src_map->skb = NULL;
ctrl = (DESC_CTRL_LEN & RX_PKT_BUF_SZ);
if (dest_idx == (B44_RX_RING_SIZE - 1))
ctrl |= DESC_CTRL_EOT;
dp = &bp->rx_ring[dest_idx];
dp->ctrl = cpu_to_le32(ctrl);
dp->addr = cpu_to_le32((u32) mapping + bp->dma_offset);
if (bp->flags & B44_FLAG_RX_RING_HACK)
b44_sync_dma_desc_for_device(bp->sdev, bp->rx_ring_dma,
dest_idx * sizeof(*dp),
DMA_BIDIRECTIONAL);
return RX_PKT_BUF_SZ;
}
static void b44_recycle_rx(struct b44 *bp, int src_idx, u32 dest_idx_unmasked)
{
struct dma_desc *src_desc, *dest_desc;
struct ring_info *src_map, *dest_map;
struct rx_header *rh;
int dest_idx;
__le32 ctrl;
dest_idx = dest_idx_unmasked & (B44_RX_RING_SIZE - 1);
dest_desc = &bp->rx_ring[dest_idx];
dest_map = &bp->rx_buffers[dest_idx];
src_desc = &bp->rx_ring[src_idx];
src_map = &bp->rx_buffers[src_idx];
dest_map->skb = src_map->skb;
rh = (struct rx_header *) src_map->skb->data;
rh->len = 0;
rh->flags = 0;
dest_map->mapping = src_map->mapping;
if (bp->flags & B44_FLAG_RX_RING_HACK)
b44_sync_dma_desc_for_cpu(bp->sdev, bp->rx_ring_dma,
src_idx * sizeof(*src_desc),
DMA_BIDIRECTIONAL);
ctrl = src_desc->ctrl;
if (dest_idx == (B44_RX_RING_SIZE - 1))
ctrl |= cpu_to_le32(DESC_CTRL_EOT);
else
ctrl &= cpu_to_le32(~DESC_CTRL_EOT);
dest_desc->ctrl = ctrl;
dest_desc->addr = src_desc->addr;
src_map->skb = NULL;
if (bp->flags & B44_FLAG_RX_RING_HACK)
b44_sync_dma_desc_for_device(bp->sdev, bp->rx_ring_dma,
dest_idx * sizeof(*dest_desc),
DMA_BIDIRECTIONAL);
dma_sync_single_for_device(bp->sdev->dma_dev, dest_map->mapping,
RX_PKT_BUF_SZ,
DMA_FROM_DEVICE);
}
static int b44_rx(struct b44 *bp, int budget)
{
int received;
u32 cons, prod;
received = 0;
prod = br32(bp, B44_DMARX_STAT) & DMARX_STAT_CDMASK;
prod /= sizeof(struct dma_desc);
cons = bp->rx_cons;
while (cons != prod && budget > 0) {
struct ring_info *rp = &bp->rx_buffers[cons];
struct sk_buff *skb = rp->skb;
dma_addr_t map = rp->mapping;
struct rx_header *rh;
u16 len;
dma_sync_single_for_cpu(bp->sdev->dma_dev, map,
RX_PKT_BUF_SZ,
DMA_FROM_DEVICE);
rh = (struct rx_header *) skb->data;
len = le16_to_cpu(rh->len);
if ((len > (RX_PKT_BUF_SZ - RX_PKT_OFFSET)) ||
(rh->flags & cpu_to_le16(RX_FLAG_ERRORS))) {
drop_it:
b44_recycle_rx(bp, cons, bp->rx_prod);
drop_it_no_recycle:
bp->dev->stats.rx_dropped++;
goto next_pkt;
}
if (len == 0) {
int i = 0;
do {
udelay(2);
barrier();
len = le16_to_cpu(rh->len);
} while (len == 0 && i++ < 5);
if (len == 0)
goto drop_it;
}
/* Omit CRC. */
len -= 4;
if (!bp->force_copybreak && len > RX_COPY_THRESHOLD) {
int skb_size;
skb_size = b44_alloc_rx_skb(bp, cons, bp->rx_prod);
if (skb_size < 0)
goto drop_it;
dma_unmap_single(bp->sdev->dma_dev, map,
skb_size, DMA_FROM_DEVICE);
/* Leave out rx_header */
skb_put(skb, len + RX_PKT_OFFSET);
skb_pull(skb, RX_PKT_OFFSET);
} else {
struct sk_buff *copy_skb;
b44_recycle_rx(bp, cons, bp->rx_prod);
copy_skb = napi_alloc_skb(&bp->napi, len);
if (copy_skb == NULL)
goto drop_it_no_recycle;
skb_put(copy_skb, len);
/* DMA sync done above, copy just the actual packet */
skb_copy_from_linear_data_offset(skb, RX_PKT_OFFSET,
copy_skb->data, len);
skb = copy_skb;
}
skb_checksum_none_assert(skb);
skb->protocol = eth_type_trans(skb, bp->dev);
netif_receive_skb(skb);
received++;
budget--;
next_pkt:
bp->rx_prod = (bp->rx_prod + 1) &
(B44_RX_RING_SIZE - 1);
cons = (cons + 1) & (B44_RX_RING_SIZE - 1);
}
bp->rx_cons = cons;
bw32(bp, B44_DMARX_PTR, cons * sizeof(struct dma_desc));
return received;
}
static int b44_poll(struct napi_struct *napi, int budget)
{
struct b44 *bp = container_of(napi, struct b44, napi);
int work_done;
unsigned long flags;
spin_lock_irqsave(&bp->lock, flags);
if (bp->istat & (ISTAT_TX | ISTAT_TO)) {
/* spin_lock(&bp->tx_lock); */
b44_tx(bp);
/* spin_unlock(&bp->tx_lock); */
}
if (bp->istat & ISTAT_RFO) { /* fast recovery, in ~20msec */
bp->istat &= ~ISTAT_RFO;
b44_disable_ints(bp);
ssb_device_enable(bp->sdev, 0); /* resets ISTAT_RFO */
b44_init_rings(bp);
b44_init_hw(bp, B44_FULL_RESET_SKIP_PHY);
netif_wake_queue(bp->dev);
}
spin_unlock_irqrestore(&bp->lock, flags);
work_done = 0;
if (bp->istat & ISTAT_RX)
work_done += b44_rx(bp, budget);
if (bp->istat & ISTAT_ERRORS) {
spin_lock_irqsave(&bp->lock, flags);
b44_halt(bp);
b44_init_rings(bp);
b44_init_hw(bp, B44_FULL_RESET_SKIP_PHY);
netif_wake_queue(bp->dev);
spin_unlock_irqrestore(&bp->lock, flags);
work_done = 0;
}
if (work_done < budget) {
napi_complete(napi);
b44_enable_ints(bp);
}
return work_done;
}
static irqreturn_t b44_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct b44 *bp = netdev_priv(dev);
u32 istat, imask;
int handled = 0;
spin_lock(&bp->lock);
istat = br32(bp, B44_ISTAT);
imask = br32(bp, B44_IMASK);
/* The interrupt mask register controls which interrupt bits
* will actually raise an interrupt to the CPU when set by hw/firmware,
* but doesn't mask off the bits.
*/
istat &= imask;
if (istat) {
handled = 1;
if (unlikely(!netif_running(dev))) {
netdev_info(dev, "late interrupt\n");
goto irq_ack;
}
if (napi_schedule_prep(&bp->napi)) {
/* NOTE: These writes are posted by the readback of
* the ISTAT register below.
*/
bp->istat = istat;
__b44_disable_ints(bp);
__napi_schedule(&bp->napi);
}
irq_ack:
bw32(bp, B44_ISTAT, istat);
br32(bp, B44_ISTAT);
}
spin_unlock(&bp->lock);
return IRQ_RETVAL(handled);
}
static void b44_tx_timeout(struct net_device *dev)
{
struct b44 *bp = netdev_priv(dev);
netdev_err(dev, "transmit timed out, resetting\n");
spin_lock_irq(&bp->lock);
b44_halt(bp);
b44_init_rings(bp);
b44_init_hw(bp, B44_FULL_RESET);
spin_unlock_irq(&bp->lock);
b44_enable_ints(bp);
netif_wake_queue(dev);
}
static netdev_tx_t b44_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct b44 *bp = netdev_priv(dev);
int rc = NETDEV_TX_OK;
dma_addr_t mapping;
u32 len, entry, ctrl;
unsigned long flags;
len = skb->len;
spin_lock_irqsave(&bp->lock, flags);
/* This is a hard error, log it. */
if (unlikely(TX_BUFFS_AVAIL(bp) < 1)) {
netif_stop_queue(dev);
netdev_err(dev, "BUG! Tx Ring full when queue awake!\n");
goto err_out;
}
mapping = dma_map_single(bp->sdev->dma_dev, skb->data, len, DMA_TO_DEVICE);
if (dma_mapping_error(bp->sdev->dma_dev, mapping) || mapping + len > DMA_BIT_MASK(30)) {
struct sk_buff *bounce_skb;
/* Chip can't handle DMA to/from >1GB, use bounce buffer */
if (!dma_mapping_error(bp->sdev->dma_dev, mapping))
dma_unmap_single(bp->sdev->dma_dev, mapping, len,
DMA_TO_DEVICE);
bounce_skb = alloc_skb(len, GFP_ATOMIC | GFP_DMA);
if (!bounce_skb)
goto err_out;
mapping = dma_map_single(bp->sdev->dma_dev, bounce_skb->data,
len, DMA_TO_DEVICE);
if (dma_mapping_error(bp->sdev->dma_dev, mapping) || mapping + len > DMA_BIT_MASK(30)) {
if (!dma_mapping_error(bp->sdev->dma_dev, mapping))
dma_unmap_single(bp->sdev->dma_dev, mapping,
len, DMA_TO_DEVICE);
dev_kfree_skb_any(bounce_skb);
goto err_out;
}
skb_copy_from_linear_data(skb, skb_put(bounce_skb, len), len);
dev_kfree_skb_any(skb);
skb = bounce_skb;
}
entry = bp->tx_prod;
bp->tx_buffers[entry].skb = skb;
bp->tx_buffers[entry].mapping = mapping;
ctrl = (len & DESC_CTRL_LEN);
ctrl |= DESC_CTRL_IOC | DESC_CTRL_SOF | DESC_CTRL_EOF;
if (entry == (B44_TX_RING_SIZE - 1))
ctrl |= DESC_CTRL_EOT;
bp->tx_ring[entry].ctrl = cpu_to_le32(ctrl);
bp->tx_ring[entry].addr = cpu_to_le32((u32) mapping+bp->dma_offset);
if (bp->flags & B44_FLAG_TX_RING_HACK)
b44_sync_dma_desc_for_device(bp->sdev, bp->tx_ring_dma,
entry * sizeof(bp->tx_ring[0]),
DMA_TO_DEVICE);
entry = NEXT_TX(entry);
bp->tx_prod = entry;
wmb();
bw32(bp, B44_DMATX_PTR, entry * sizeof(struct dma_desc));
if (bp->flags & B44_FLAG_BUGGY_TXPTR)
bw32(bp, B44_DMATX_PTR, entry * sizeof(struct dma_desc));
if (bp->flags & B44_FLAG_REORDER_BUG)
br32(bp, B44_DMATX_PTR);
netdev_sent_queue(dev, skb->len);
if (TX_BUFFS_AVAIL(bp) < 1)
netif_stop_queue(dev);
out_unlock:
spin_unlock_irqrestore(&bp->lock, flags);
return rc;
err_out:
rc = NETDEV_TX_BUSY;
goto out_unlock;
}
static int b44_change_mtu(struct net_device *dev, int new_mtu)
{
struct b44 *bp = netdev_priv(dev);
if (new_mtu < B44_MIN_MTU || new_mtu > B44_MAX_MTU)
return -EINVAL;
if (!netif_running(dev)) {
/* We'll just catch it later when the
* device is up'd.
*/
dev->mtu = new_mtu;
return 0;
}
spin_lock_irq(&bp->lock);
b44_halt(bp);
dev->mtu = new_mtu;
b44_init_rings(bp);
b44_init_hw(bp, B44_FULL_RESET);
spin_unlock_irq(&bp->lock);
b44_enable_ints(bp);
return 0;
}
/* Free up pending packets in all rx/tx rings.
*
* The chip has been shut down and the driver detached from
* the networking, so no interrupts or new tx packets will
* end up in the driver. bp->lock is not held and we are not
* in an interrupt context and thus may sleep.
*/
static void b44_free_rings(struct b44 *bp)
{
struct ring_info *rp;
int i;
for (i = 0; i < B44_RX_RING_SIZE; i++) {
rp = &bp->rx_buffers[i];
if (rp->skb == NULL)
continue;
dma_unmap_single(bp->sdev->dma_dev, rp->mapping, RX_PKT_BUF_SZ,
DMA_FROM_DEVICE);
dev_kfree_skb_any(rp->skb);
rp->skb = NULL;
}
/* XXX needs changes once NETIF_F_SG is set... */
for (i = 0; i < B44_TX_RING_SIZE; i++) {
rp = &bp->tx_buffers[i];
if (rp->skb == NULL)
continue;
dma_unmap_single(bp->sdev->dma_dev, rp->mapping, rp->skb->len,
DMA_TO_DEVICE);
dev_kfree_skb_any(rp->skb);
rp->skb = NULL;
}
}
/* Initialize tx/rx rings for packet processing.
*
* The chip has been shut down and the driver detached from
* the networking, so no interrupts or new tx packets will
* end up in the driver.
*/
static void b44_init_rings(struct b44 *bp)
{
int i;
b44_free_rings(bp);
memset(bp->rx_ring, 0, B44_RX_RING_BYTES);
memset(bp->tx_ring, 0, B44_TX_RING_BYTES);
if (bp->flags & B44_FLAG_RX_RING_HACK)
dma_sync_single_for_device(bp->sdev->dma_dev, bp->rx_ring_dma,
DMA_TABLE_BYTES, DMA_BIDIRECTIONAL);
if (bp->flags & B44_FLAG_TX_RING_HACK)
dma_sync_single_for_device(bp->sdev->dma_dev, bp->tx_ring_dma,
DMA_TABLE_BYTES, DMA_TO_DEVICE);
for (i = 0; i < bp->rx_pending; i++) {
if (b44_alloc_rx_skb(bp, -1, i) < 0)
break;
}
}
/*
* Must not be invoked with interrupt sources disabled and
* the hardware shutdown down.
*/
static void b44_free_consistent(struct b44 *bp)
{
kfree(bp->rx_buffers);
bp->rx_buffers = NULL;
kfree(bp->tx_buffers);
bp->tx_buffers = NULL;
if (bp->rx_ring) {
if (bp->flags & B44_FLAG_RX_RING_HACK) {
dma_unmap_single(bp->sdev->dma_dev, bp->rx_ring_dma,
DMA_TABLE_BYTES, DMA_BIDIRECTIONAL);
kfree(bp->rx_ring);
} else
dma_free_coherent(bp->sdev->dma_dev, DMA_TABLE_BYTES,
bp->rx_ring, bp->rx_ring_dma);
bp->rx_ring = NULL;
bp->flags &= ~B44_FLAG_RX_RING_HACK;
}
if (bp->tx_ring) {
if (bp->flags & B44_FLAG_TX_RING_HACK) {
dma_unmap_single(bp->sdev->dma_dev, bp->tx_ring_dma,
DMA_TABLE_BYTES, DMA_TO_DEVICE);
kfree(bp->tx_ring);
} else
dma_free_coherent(bp->sdev->dma_dev, DMA_TABLE_BYTES,
bp->tx_ring, bp->tx_ring_dma);
bp->tx_ring = NULL;
bp->flags &= ~B44_FLAG_TX_RING_HACK;
}
}
/*
* Must not be invoked with interrupt sources disabled and
* the hardware shutdown down. Can sleep.
*/
static int b44_alloc_consistent(struct b44 *bp, gfp_t gfp)
{
int size;
size = B44_RX_RING_SIZE * sizeof(struct ring_info);
bp->rx_buffers = kzalloc(size, gfp);
if (!bp->rx_buffers)
goto out_err;
size = B44_TX_RING_SIZE * sizeof(struct ring_info);
bp->tx_buffers = kzalloc(size, gfp);
if (!bp->tx_buffers)
goto out_err;
size = DMA_TABLE_BYTES;
bp->rx_ring = dma_alloc_coherent(bp->sdev->dma_dev, size,
&bp->rx_ring_dma, gfp);
if (!bp->rx_ring) {
/* Allocation may have failed due to pci_alloc_consistent
insisting on use of GFP_DMA, which is more restrictive
than necessary... */
struct dma_desc *rx_ring;
dma_addr_t rx_ring_dma;
rx_ring = kzalloc(size, gfp);
if (!rx_ring)
goto out_err;
rx_ring_dma = dma_map_single(bp->sdev->dma_dev, rx_ring,
DMA_TABLE_BYTES,
DMA_BIDIRECTIONAL);
if (dma_mapping_error(bp->sdev->dma_dev, rx_ring_dma) ||
rx_ring_dma + size > DMA_BIT_MASK(30)) {
kfree(rx_ring);
goto out_err;
}
bp->rx_ring = rx_ring;
bp->rx_ring_dma = rx_ring_dma;
bp->flags |= B44_FLAG_RX_RING_HACK;
}
bp->tx_ring = dma_alloc_coherent(bp->sdev->dma_dev, size,
&bp->tx_ring_dma, gfp);
if (!bp->tx_ring) {
/* Allocation may have failed due to ssb_dma_alloc_consistent
insisting on use of GFP_DMA, which is more restrictive
than necessary... */
struct dma_desc *tx_ring;
dma_addr_t tx_ring_dma;
tx_ring = kzalloc(size, gfp);
if (!tx_ring)
goto out_err;
tx_ring_dma = dma_map_single(bp->sdev->dma_dev, tx_ring,
DMA_TABLE_BYTES,
DMA_TO_DEVICE);
if (dma_mapping_error(bp->sdev->dma_dev, tx_ring_dma) ||
tx_ring_dma + size > DMA_BIT_MASK(30)) {
kfree(tx_ring);
goto out_err;
}
bp->tx_ring = tx_ring;
bp->tx_ring_dma = tx_ring_dma;
bp->flags |= B44_FLAG_TX_RING_HACK;
}
return 0;
out_err:
b44_free_consistent(bp);
return -ENOMEM;
}
/* bp->lock is held. */
static void b44_clear_stats(struct b44 *bp)
{
unsigned long reg;
bw32(bp, B44_MIB_CTRL, MIB_CTRL_CLR_ON_READ);
for (reg = B44_TX_GOOD_O; reg <= B44_TX_PAUSE; reg += 4UL)
br32(bp, reg);
for (reg = B44_RX_GOOD_O; reg <= B44_RX_NPAUSE; reg += 4UL)
br32(bp, reg);
}
/* bp->lock is held. */
static void b44_chip_reset(struct b44 *bp, int reset_kind)
{
struct ssb_device *sdev = bp->sdev;
bool was_enabled;
was_enabled = ssb_device_is_enabled(bp->sdev);
ssb_device_enable(bp->sdev, 0);
ssb_pcicore_dev_irqvecs_enable(&sdev->bus->pcicore, sdev);
if (was_enabled) {
bw32(bp, B44_RCV_LAZY, 0);
bw32(bp, B44_ENET_CTRL, ENET_CTRL_DISABLE);
b44_wait_bit(bp, B44_ENET_CTRL, ENET_CTRL_DISABLE, 200, 1);
bw32(bp, B44_DMATX_CTRL, 0);
bp->tx_prod = bp->tx_cons = 0;
if (br32(bp, B44_DMARX_STAT) & DMARX_STAT_EMASK) {
b44_wait_bit(bp, B44_DMARX_STAT, DMARX_STAT_SIDLE,
100, 0);
}
bw32(bp, B44_DMARX_CTRL, 0);
bp->rx_prod = bp->rx_cons = 0;
}
b44_clear_stats(bp);
/*
* Don't enable PHY if we are doing a partial reset
* we are probably going to power down
*/
if (reset_kind == B44_CHIP_RESET_PARTIAL)
return;
switch (sdev->bus->bustype) {
case SSB_BUSTYPE_SSB:
bw32(bp, B44_MDIO_CTRL, (MDIO_CTRL_PREAMBLE |
(DIV_ROUND_CLOSEST(ssb_clockspeed(sdev->bus),
B44_MDC_RATIO)
& MDIO_CTRL_MAXF_MASK)));
break;
case SSB_BUSTYPE_PCI:
bw32(bp, B44_MDIO_CTRL, (MDIO_CTRL_PREAMBLE |
(0x0d & MDIO_CTRL_MAXF_MASK)));
break;
case SSB_BUSTYPE_PCMCIA:
case SSB_BUSTYPE_SDIO:
WARN_ON(1); /* A device with this bus does not exist. */
break;
}
br32(bp, B44_MDIO_CTRL);
if (!(br32(bp, B44_DEVCTRL) & DEVCTRL_IPP)) {
bw32(bp, B44_ENET_CTRL, ENET_CTRL_EPSEL);
br32(bp, B44_ENET_CTRL);
bp->flags |= B44_FLAG_EXTERNAL_PHY;
} else {
u32 val = br32(bp, B44_DEVCTRL);
if (val & DEVCTRL_EPR) {
bw32(bp, B44_DEVCTRL, (val & ~DEVCTRL_EPR));
br32(bp, B44_DEVCTRL);
udelay(100);
}
bp->flags &= ~B44_FLAG_EXTERNAL_PHY;
}
}
/* bp->lock is held. */
static void b44_halt(struct b44 *bp)
{
b44_disable_ints(bp);
/* reset PHY */
b44_phy_reset(bp);
/* power down PHY */
netdev_info(bp->dev, "powering down PHY\n");
bw32(bp, B44_MAC_CTRL, MAC_CTRL_PHY_PDOWN);
/* now reset the chip, but without enabling the MAC&PHY
* part of it. This has to be done _after_ we shut down the PHY */
if (bp->flags & B44_FLAG_EXTERNAL_PHY)
b44_chip_reset(bp, B44_CHIP_RESET_FULL);
else
b44_chip_reset(bp, B44_CHIP_RESET_PARTIAL);
}
/* bp->lock is held. */
static void __b44_set_mac_addr(struct b44 *bp)
{
bw32(bp, B44_CAM_CTRL, 0);
if (!(bp->dev->flags & IFF_PROMISC)) {
u32 val;
__b44_cam_write(bp, bp->dev->dev_addr, 0);
val = br32(bp, B44_CAM_CTRL);
bw32(bp, B44_CAM_CTRL, val | CAM_CTRL_ENABLE);
}
}
static int b44_set_mac_addr(struct net_device *dev, void *p)
{
struct b44 *bp = netdev_priv(dev);
struct sockaddr *addr = p;
u32 val;
if (netif_running(dev))
return -EBUSY;
if (!is_valid_ether_addr(addr->sa_data))
return -EINVAL;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
spin_lock_irq(&bp->lock);
val = br32(bp, B44_RXCONFIG);
if (!(val & RXCONFIG_CAM_ABSENT))
__b44_set_mac_addr(bp);
spin_unlock_irq(&bp->lock);
return 0;
}
/* Called at device open time to get the chip ready for
* packet processing. Invoked with bp->lock held.
*/
static void __b44_set_rx_mode(struct net_device *);
static void b44_init_hw(struct b44 *bp, int reset_kind)
{
u32 val;
b44_chip_reset(bp, B44_CHIP_RESET_FULL);
if (reset_kind == B44_FULL_RESET) {
b44_phy_reset(bp);
b44_setup_phy(bp);
}
/* Enable CRC32, set proper LED modes and power on PHY */
bw32(bp, B44_MAC_CTRL, MAC_CTRL_CRC32_ENAB | MAC_CTRL_PHY_LEDCTRL);
bw32(bp, B44_RCV_LAZY, (1 << RCV_LAZY_FC_SHIFT));
/* This sets the MAC address too. */
__b44_set_rx_mode(bp->dev);
/* MTU + eth header + possible VLAN tag + struct rx_header */
bw32(bp, B44_RXMAXLEN, bp->dev->mtu + ETH_HLEN + 8 + RX_HEADER_LEN);
bw32(bp, B44_TXMAXLEN, bp->dev->mtu + ETH_HLEN + 8 + RX_HEADER_LEN);
bw32(bp, B44_TX_WMARK, 56); /* XXX magic */
if (reset_kind == B44_PARTIAL_RESET) {
bw32(bp, B44_DMARX_CTRL, (DMARX_CTRL_ENABLE |
(RX_PKT_OFFSET << DMARX_CTRL_ROSHIFT)));
} else {
bw32(bp, B44_DMATX_CTRL, DMATX_CTRL_ENABLE);
bw32(bp, B44_DMATX_ADDR, bp->tx_ring_dma + bp->dma_offset);
bw32(bp, B44_DMARX_CTRL, (DMARX_CTRL_ENABLE |
(RX_PKT_OFFSET << DMARX_CTRL_ROSHIFT)));
bw32(bp, B44_DMARX_ADDR, bp->rx_ring_dma + bp->dma_offset);
bw32(bp, B44_DMARX_PTR, bp->rx_pending);
bp->rx_prod = bp->rx_pending;
bw32(bp, B44_MIB_CTRL, MIB_CTRL_CLR_ON_READ);
}
val = br32(bp, B44_ENET_CTRL);
bw32(bp, B44_ENET_CTRL, (val | ENET_CTRL_ENABLE));
netdev_reset_queue(bp->dev);
}
static int b44_open(struct net_device *dev)
{
struct b44 *bp = netdev_priv(dev);
int err;
err = b44_alloc_consistent(bp, GFP_KERNEL);
if (err)
goto out;
napi_enable(&bp->napi);
b44_init_rings(bp);
b44_init_hw(bp, B44_FULL_RESET);
b44_check_phy(bp);
err = request_irq(dev->irq, b44_interrupt, IRQF_SHARED, dev->name, dev);
if (unlikely(err < 0)) {
napi_disable(&bp->napi);
b44_chip_reset(bp, B44_CHIP_RESET_PARTIAL);
b44_free_rings(bp);
b44_free_consistent(bp);
goto out;
}
init_timer(&bp->timer);
bp->timer.expires = jiffies + HZ;
bp->timer.data = (unsigned long) bp;
bp->timer.function = b44_timer;
add_timer(&bp->timer);
b44_enable_ints(bp);
if (bp->flags & B44_FLAG_EXTERNAL_PHY)
phy_start(dev->phydev);
netif_start_queue(dev);
out:
return err;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling receive - used by netconsole and other diagnostic tools
* to allow network i/o with interrupts disabled.
*/
static void b44_poll_controller(struct net_device *dev)
{
disable_irq(dev->irq);
b44_interrupt(dev->irq, dev);
enable_irq(dev->irq);
}
#endif
static void bwfilter_table(struct b44 *bp, u8 *pp, u32 bytes, u32 table_offset)
{
u32 i;
u32 *pattern = (u32 *) pp;
for (i = 0; i < bytes; i += sizeof(u32)) {
bw32(bp, B44_FILT_ADDR, table_offset + i);
bw32(bp, B44_FILT_DATA, pattern[i / sizeof(u32)]);
}
}
static int b44_magic_pattern(u8 *macaddr, u8 *ppattern, u8 *pmask, int offset)
{
int magicsync = 6;
int k, j, len = offset;
int ethaddr_bytes = ETH_ALEN;
memset(ppattern + offset, 0xff, magicsync);
for (j = 0; j < magicsync; j++)
set_bit(len++, (unsigned long *) pmask);
for (j = 0; j < B44_MAX_PATTERNS; j++) {
if ((B44_PATTERN_SIZE - len) >= ETH_ALEN)
ethaddr_bytes = ETH_ALEN;
else
ethaddr_bytes = B44_PATTERN_SIZE - len;
if (ethaddr_bytes <=0)
break;
for (k = 0; k< ethaddr_bytes; k++) {
ppattern[offset + magicsync +
(j * ETH_ALEN) + k] = macaddr[k];
set_bit(len++, (unsigned long *) pmask);
}
}
return len - 1;
}
/* Setup magic packet patterns in the b44 WOL
* pattern matching filter.
*/
static void b44_setup_pseudo_magicp(struct b44 *bp)
{
u32 val;
int plen0, plen1, plen2;
u8 *pwol_pattern;
u8 pwol_mask[B44_PMASK_SIZE];
pwol_pattern = kzalloc(B44_PATTERN_SIZE, GFP_KERNEL);
if (!pwol_pattern)
return;
/* Ipv4 magic packet pattern - pattern 0.*/
memset(pwol_mask, 0, B44_PMASK_SIZE);
plen0 = b44_magic_pattern(bp->dev->dev_addr, pwol_pattern, pwol_mask,
B44_ETHIPV4UDP_HLEN);
bwfilter_table(bp, pwol_pattern, B44_PATTERN_SIZE, B44_PATTERN_BASE);
bwfilter_table(bp, pwol_mask, B44_PMASK_SIZE, B44_PMASK_BASE);
/* Raw ethernet II magic packet pattern - pattern 1 */
memset(pwol_pattern, 0, B44_PATTERN_SIZE);
memset(pwol_mask, 0, B44_PMASK_SIZE);
plen1 = b44_magic_pattern(bp->dev->dev_addr, pwol_pattern, pwol_mask,
ETH_HLEN);
bwfilter_table(bp, pwol_pattern, B44_PATTERN_SIZE,
B44_PATTERN_BASE + B44_PATTERN_SIZE);
bwfilter_table(bp, pwol_mask, B44_PMASK_SIZE,
B44_PMASK_BASE + B44_PMASK_SIZE);
/* Ipv6 magic packet pattern - pattern 2 */
memset(pwol_pattern, 0, B44_PATTERN_SIZE);
memset(pwol_mask, 0, B44_PMASK_SIZE);
plen2 = b44_magic_pattern(bp->dev->dev_addr, pwol_pattern, pwol_mask,
B44_ETHIPV6UDP_HLEN);
bwfilter_table(bp, pwol_pattern, B44_PATTERN_SIZE,
B44_PATTERN_BASE + B44_PATTERN_SIZE + B44_PATTERN_SIZE);
bwfilter_table(bp, pwol_mask, B44_PMASK_SIZE,
B44_PMASK_BASE + B44_PMASK_SIZE + B44_PMASK_SIZE);
kfree(pwol_pattern);
/* set these pattern's lengths: one less than each real length */
val = plen0 | (plen1 << 8) | (plen2 << 16) | WKUP_LEN_ENABLE_THREE;
bw32(bp, B44_WKUP_LEN, val);
/* enable wakeup pattern matching */
val = br32(bp, B44_DEVCTRL);
bw32(bp, B44_DEVCTRL, val | DEVCTRL_PFE);
}
#ifdef CONFIG_B44_PCI
static void b44_setup_wol_pci(struct b44 *bp)
{
u16 val;
if (bp->sdev->bus->bustype != SSB_BUSTYPE_SSB) {
bw32(bp, SSB_TMSLOW, br32(bp, SSB_TMSLOW) | SSB_TMSLOW_PE);
pci_read_config_word(bp->sdev->bus->host_pci, SSB_PMCSR, &val);
pci_write_config_word(bp->sdev->bus->host_pci, SSB_PMCSR, val | SSB_PE);
}
}
#else
static inline void b44_setup_wol_pci(struct b44 *bp) { }
#endif /* CONFIG_B44_PCI */
static void b44_setup_wol(struct b44 *bp)
{
u32 val;
bw32(bp, B44_RXCONFIG, RXCONFIG_ALLMULTI);
if (bp->flags & B44_FLAG_B0_ANDLATER) {
bw32(bp, B44_WKUP_LEN, WKUP_LEN_DISABLE);
val = bp->dev->dev_addr[2] << 24 |
bp->dev->dev_addr[3] << 16 |
bp->dev->dev_addr[4] << 8 |
bp->dev->dev_addr[5];
bw32(bp, B44_ADDR_LO, val);
val = bp->dev->dev_addr[0] << 8 |
bp->dev->dev_addr[1];
bw32(bp, B44_ADDR_HI, val);
val = br32(bp, B44_DEVCTRL);
bw32(bp, B44_DEVCTRL, val | DEVCTRL_MPM | DEVCTRL_PFE);
} else {
b44_setup_pseudo_magicp(bp);
}
b44_setup_wol_pci(bp);
}
static int b44_close(struct net_device *dev)
{
struct b44 *bp = netdev_priv(dev);
netif_stop_queue(dev);
if (bp->flags & B44_FLAG_EXTERNAL_PHY)
phy_stop(dev->phydev);
napi_disable(&bp->napi);
del_timer_sync(&bp->timer);
spin_lock_irq(&bp->lock);
b44_halt(bp);
b44_free_rings(bp);
netif_carrier_off(dev);
spin_unlock_irq(&bp->lock);
free_irq(dev->irq, dev);
if (bp->flags & B44_FLAG_WOL_ENABLE) {
b44_init_hw(bp, B44_PARTIAL_RESET);
b44_setup_wol(bp);
}
b44_free_consistent(bp);
return 0;
}
static struct rtnl_link_stats64 *b44_get_stats64(struct net_device *dev,
struct rtnl_link_stats64 *nstat)
{
struct b44 *bp = netdev_priv(dev);
struct b44_hw_stats *hwstat = &bp->hw_stats;
unsigned int start;
do {
start = u64_stats_fetch_begin_irq(&hwstat->syncp);
/* Convert HW stats into rtnl_link_stats64 stats. */
nstat->rx_packets = hwstat->rx_pkts;
nstat->tx_packets = hwstat->tx_pkts;
nstat->rx_bytes = hwstat->rx_octets;
nstat->tx_bytes = hwstat->tx_octets;
nstat->tx_errors = (hwstat->tx_jabber_pkts +
hwstat->tx_oversize_pkts +
hwstat->tx_underruns +
hwstat->tx_excessive_cols +
hwstat->tx_late_cols);
nstat->multicast = hwstat->rx_multicast_pkts;
nstat->collisions = hwstat->tx_total_cols;
nstat->rx_length_errors = (hwstat->rx_oversize_pkts +
hwstat->rx_undersize);
nstat->rx_over_errors = hwstat->rx_missed_pkts;
nstat->rx_frame_errors = hwstat->rx_align_errs;
nstat->rx_crc_errors = hwstat->rx_crc_errs;
nstat->rx_errors = (hwstat->rx_jabber_pkts +
hwstat->rx_oversize_pkts +
hwstat->rx_missed_pkts +
hwstat->rx_crc_align_errs +
hwstat->rx_undersize +
hwstat->rx_crc_errs +
hwstat->rx_align_errs +
hwstat->rx_symbol_errs);
nstat->tx_aborted_errors = hwstat->tx_underruns;
#if 0
/* Carrier lost counter seems to be broken for some devices */
nstat->tx_carrier_errors = hwstat->tx_carrier_lost;
#endif
} while (u64_stats_fetch_retry_irq(&hwstat->syncp, start));
return nstat;
}
static int __b44_load_mcast(struct b44 *bp, struct net_device *dev)
{
struct netdev_hw_addr *ha;
int i, num_ents;
num_ents = min_t(int, netdev_mc_count(dev), B44_MCAST_TABLE_SIZE);
i = 0;
netdev_for_each_mc_addr(ha, dev) {
if (i == num_ents)
break;
__b44_cam_write(bp, ha->addr, i++ + 1);
}
return i+1;
}
static void __b44_set_rx_mode(struct net_device *dev)
{
struct b44 *bp = netdev_priv(dev);
u32 val;
val = br32(bp, B44_RXCONFIG);
val &= ~(RXCONFIG_PROMISC | RXCONFIG_ALLMULTI);
if ((dev->flags & IFF_PROMISC) || (val & RXCONFIG_CAM_ABSENT)) {
val |= RXCONFIG_PROMISC;
bw32(bp, B44_RXCONFIG, val);
} else {
unsigned char zero[6] = {0, 0, 0, 0, 0, 0};
int i = 1;
__b44_set_mac_addr(bp);
if ((dev->flags & IFF_ALLMULTI) ||
(netdev_mc_count(dev) > B44_MCAST_TABLE_SIZE))
val |= RXCONFIG_ALLMULTI;
else
i = __b44_load_mcast(bp, dev);
for (; i < 64; i++)
__b44_cam_write(bp, zero, i);
bw32(bp, B44_RXCONFIG, val);
val = br32(bp, B44_CAM_CTRL);
bw32(bp, B44_CAM_CTRL, val | CAM_CTRL_ENABLE);
}
}
static void b44_set_rx_mode(struct net_device *dev)
{
struct b44 *bp = netdev_priv(dev);
spin_lock_irq(&bp->lock);
__b44_set_rx_mode(dev);
spin_unlock_irq(&bp->lock);
}
static u32 b44_get_msglevel(struct net_device *dev)
{
struct b44 *bp = netdev_priv(dev);
return bp->msg_enable;
}
static void b44_set_msglevel(struct net_device *dev, u32 value)
{
struct b44 *bp = netdev_priv(dev);
bp->msg_enable = value;
}
static void b44_get_drvinfo (struct net_device *dev, struct ethtool_drvinfo *info)
{
struct b44 *bp = netdev_priv(dev);
struct ssb_bus *bus = bp->sdev->bus;
strlcpy(info->driver, DRV_MODULE_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version));
switch (bus->bustype) {
case SSB_BUSTYPE_PCI:
strlcpy(info->bus_info, pci_name(bus->host_pci), sizeof(info->bus_info));
break;
case SSB_BUSTYPE_SSB:
strlcpy(info->bus_info, "SSB", sizeof(info->bus_info));
break;
case SSB_BUSTYPE_PCMCIA:
case SSB_BUSTYPE_SDIO:
WARN_ON(1); /* A device with this bus does not exist. */
break;
}
}
static int b44_nway_reset(struct net_device *dev)
{
struct b44 *bp = netdev_priv(dev);
u32 bmcr;
int r;
spin_lock_irq(&bp->lock);
b44_readphy(bp, MII_BMCR, &bmcr);
b44_readphy(bp, MII_BMCR, &bmcr);
r = -EINVAL;
if (bmcr & BMCR_ANENABLE) {
b44_writephy(bp, MII_BMCR,
bmcr | BMCR_ANRESTART);
r = 0;
}
spin_unlock_irq(&bp->lock);
return r;
}
static int b44_get_link_ksettings(struct net_device *dev,
struct ethtool_link_ksettings *cmd)
{
struct b44 *bp = netdev_priv(dev);
u32 supported, advertising;
if (bp->flags & B44_FLAG_EXTERNAL_PHY) {
BUG_ON(!dev->phydev);
return phy_ethtool_ksettings_get(dev->phydev, cmd);
}
supported = (SUPPORTED_Autoneg);
supported |= (SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_MII);
advertising = 0;
if (bp->flags & B44_FLAG_ADV_10HALF)
advertising |= ADVERTISED_10baseT_Half;
if (bp->flags & B44_FLAG_ADV_10FULL)
advertising |= ADVERTISED_10baseT_Full;
if (bp->flags & B44_FLAG_ADV_100HALF)
advertising |= ADVERTISED_100baseT_Half;
if (bp->flags & B44_FLAG_ADV_100FULL)
advertising |= ADVERTISED_100baseT_Full;
advertising |= ADVERTISED_Pause | ADVERTISED_Asym_Pause;
cmd->base.speed = (bp->flags & B44_FLAG_100_BASE_T) ?
SPEED_100 : SPEED_10;
cmd->base.duplex = (bp->flags & B44_FLAG_FULL_DUPLEX) ?
DUPLEX_FULL : DUPLEX_HALF;
cmd->base.port = 0;
cmd->base.phy_address = bp->phy_addr;
cmd->base.autoneg = (bp->flags & B44_FLAG_FORCE_LINK) ?
AUTONEG_DISABLE : AUTONEG_ENABLE;
if (cmd->base.autoneg == AUTONEG_ENABLE)
advertising |= ADVERTISED_Autoneg;
ethtool_convert_legacy_u32_to_link_mode(cmd->link_modes.supported,
supported);
ethtool_convert_legacy_u32_to_link_mode(cmd->link_modes.advertising,
advertising);
if (!netif_running(dev)){
cmd->base.speed = 0;
cmd->base.duplex = 0xff;
}
return 0;
}
static int b44_set_link_ksettings(struct net_device *dev,
const struct ethtool_link_ksettings *cmd)
{
struct b44 *bp = netdev_priv(dev);
u32 speed;
int ret;
u32 advertising;
if (bp->flags & B44_FLAG_EXTERNAL_PHY) {
BUG_ON(!dev->phydev);
spin_lock_irq(&bp->lock);
if (netif_running(dev))
b44_setup_phy(bp);
ret = phy_ethtool_ksettings_set(dev->phydev, cmd);
spin_unlock_irq(&bp->lock);
return ret;
}
speed = cmd->base.speed;
ethtool_convert_link_mode_to_legacy_u32(&advertising,
cmd->link_modes.advertising);
/* We do not support gigabit. */
if (cmd->base.autoneg == AUTONEG_ENABLE) {
if (advertising &
(ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full))
return -EINVAL;
} else if ((speed != SPEED_100 &&
speed != SPEED_10) ||
(cmd->base.duplex != DUPLEX_HALF &&
cmd->base.duplex != DUPLEX_FULL)) {
return -EINVAL;
}
spin_lock_irq(&bp->lock);
if (cmd->base.autoneg == AUTONEG_ENABLE) {
bp->flags &= ~(B44_FLAG_FORCE_LINK |
B44_FLAG_100_BASE_T |
B44_FLAG_FULL_DUPLEX |
B44_FLAG_ADV_10HALF |
B44_FLAG_ADV_10FULL |
B44_FLAG_ADV_100HALF |
B44_FLAG_ADV_100FULL);
if (advertising == 0) {
bp->flags |= (B44_FLAG_ADV_10HALF |
B44_FLAG_ADV_10FULL |
B44_FLAG_ADV_100HALF |
B44_FLAG_ADV_100FULL);
} else {
if (advertising & ADVERTISED_10baseT_Half)
bp->flags |= B44_FLAG_ADV_10HALF;
if (advertising & ADVERTISED_10baseT_Full)
bp->flags |= B44_FLAG_ADV_10FULL;
if (advertising & ADVERTISED_100baseT_Half)
bp->flags |= B44_FLAG_ADV_100HALF;
if (advertising & ADVERTISED_100baseT_Full)
bp->flags |= B44_FLAG_ADV_100FULL;
}
} else {
bp->flags |= B44_FLAG_FORCE_LINK;
bp->flags &= ~(B44_FLAG_100_BASE_T | B44_FLAG_FULL_DUPLEX);
if (speed == SPEED_100)
bp->flags |= B44_FLAG_100_BASE_T;
if (cmd->base.duplex == DUPLEX_FULL)
bp->flags |= B44_FLAG_FULL_DUPLEX;
}
if (netif_running(dev))
b44_setup_phy(bp);
spin_unlock_irq(&bp->lock);
return 0;
}
static void b44_get_ringparam(struct net_device *dev,
struct ethtool_ringparam *ering)
{
struct b44 *bp = netdev_priv(dev);
ering->rx_max_pending = B44_RX_RING_SIZE - 1;
ering->rx_pending = bp->rx_pending;
/* XXX ethtool lacks a tx_max_pending, oops... */
}
static int b44_set_ringparam(struct net_device *dev,
struct ethtool_ringparam *ering)
{
struct b44 *bp = netdev_priv(dev);
if ((ering->rx_pending > B44_RX_RING_SIZE - 1) ||
(ering->rx_mini_pending != 0) ||
(ering->rx_jumbo_pending != 0) ||
(ering->tx_pending > B44_TX_RING_SIZE - 1))
return -EINVAL;
spin_lock_irq(&bp->lock);
bp->rx_pending = ering->rx_pending;
bp->tx_pending = ering->tx_pending;
b44_halt(bp);
b44_init_rings(bp);
b44_init_hw(bp, B44_FULL_RESET);
netif_wake_queue(bp->dev);
spin_unlock_irq(&bp->lock);
b44_enable_ints(bp);
return 0;
}
static void b44_get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct b44 *bp = netdev_priv(dev);
epause->autoneg =
(bp->flags & B44_FLAG_PAUSE_AUTO) != 0;
epause->rx_pause =
(bp->flags & B44_FLAG_RX_PAUSE) != 0;
epause->tx_pause =
(bp->flags & B44_FLAG_TX_PAUSE) != 0;
}
static int b44_set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct b44 *bp = netdev_priv(dev);
spin_lock_irq(&bp->lock);
if (epause->autoneg)
bp->flags |= B44_FLAG_PAUSE_AUTO;
else
bp->flags &= ~B44_FLAG_PAUSE_AUTO;
if (epause->rx_pause)
bp->flags |= B44_FLAG_RX_PAUSE;
else
bp->flags &= ~B44_FLAG_RX_PAUSE;
if (epause->tx_pause)
bp->flags |= B44_FLAG_TX_PAUSE;
else
bp->flags &= ~B44_FLAG_TX_PAUSE;
if (bp->flags & B44_FLAG_PAUSE_AUTO) {
b44_halt(bp);
b44_init_rings(bp);
b44_init_hw(bp, B44_FULL_RESET);
} else {
__b44_set_flow_ctrl(bp, bp->flags);
}
spin_unlock_irq(&bp->lock);
b44_enable_ints(bp);
return 0;
}
static void b44_get_strings(struct net_device *dev, u32 stringset, u8 *data)
{
switch(stringset) {
case ETH_SS_STATS:
memcpy(data, *b44_gstrings, sizeof(b44_gstrings));
break;
}
}
static int b44_get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(b44_gstrings);
default:
return -EOPNOTSUPP;
}
}
static void b44_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *stats, u64 *data)
{
struct b44 *bp = netdev_priv(dev);
struct b44_hw_stats *hwstat = &bp->hw_stats;
u64 *data_src, *data_dst;
unsigned int start;
u32 i;
spin_lock_irq(&bp->lock);
b44_stats_update(bp);
spin_unlock_irq(&bp->lock);
do {
data_src = &hwstat->tx_good_octets;
data_dst = data;
start = u64_stats_fetch_begin_irq(&hwstat->syncp);
for (i = 0; i < ARRAY_SIZE(b44_gstrings); i++)
*data_dst++ = *data_src++;
} while (u64_stats_fetch_retry_irq(&hwstat->syncp, start));
}
static void b44_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct b44 *bp = netdev_priv(dev);
wol->supported = WAKE_MAGIC;
if (bp->flags & B44_FLAG_WOL_ENABLE)
wol->wolopts = WAKE_MAGIC;
else
wol->wolopts = 0;
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static int b44_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct b44 *bp = netdev_priv(dev);
spin_lock_irq(&bp->lock);
if (wol->wolopts & WAKE_MAGIC)
bp->flags |= B44_FLAG_WOL_ENABLE;
else
bp->flags &= ~B44_FLAG_WOL_ENABLE;
spin_unlock_irq(&bp->lock);
device_set_wakeup_enable(bp->sdev->dev, wol->wolopts & WAKE_MAGIC);
return 0;
}
static const struct ethtool_ops b44_ethtool_ops = {
.get_drvinfo = b44_get_drvinfo,
.nway_reset = b44_nway_reset,
.get_link = ethtool_op_get_link,
.get_wol = b44_get_wol,
.set_wol = b44_set_wol,
.get_ringparam = b44_get_ringparam,
.set_ringparam = b44_set_ringparam,
.get_pauseparam = b44_get_pauseparam,
.set_pauseparam = b44_set_pauseparam,
.get_msglevel = b44_get_msglevel,
.set_msglevel = b44_set_msglevel,
.get_strings = b44_get_strings,
.get_sset_count = b44_get_sset_count,
.get_ethtool_stats = b44_get_ethtool_stats,
.get_link_ksettings = b44_get_link_ksettings,
.set_link_ksettings = b44_set_link_ksettings,
};
static int b44_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct b44 *bp = netdev_priv(dev);
int err = -EINVAL;
if (!netif_running(dev))
goto out;
spin_lock_irq(&bp->lock);
if (bp->flags & B44_FLAG_EXTERNAL_PHY) {
BUG_ON(!dev->phydev);
err = phy_mii_ioctl(dev->phydev, ifr, cmd);
} else {
err = generic_mii_ioctl(&bp->mii_if, if_mii(ifr), cmd, NULL);
}
spin_unlock_irq(&bp->lock);
out:
return err;
}
static int b44_get_invariants(struct b44 *bp)
{
struct ssb_device *sdev = bp->sdev;
int err = 0;
u8 *addr;
bp->dma_offset = ssb_dma_translation(sdev);
if (sdev->bus->bustype == SSB_BUSTYPE_SSB &&
instance > 1) {
addr = sdev->bus->sprom.et1mac;
bp->phy_addr = sdev->bus->sprom.et1phyaddr;
} else {
addr = sdev->bus->sprom.et0mac;
bp->phy_addr = sdev->bus->sprom.et0phyaddr;
}
/* Some ROMs have buggy PHY addresses with the high
* bits set (sign extension?). Truncate them to a
* valid PHY address. */
bp->phy_addr &= 0x1F;
memcpy(bp->dev->dev_addr, addr, ETH_ALEN);
if (!is_valid_ether_addr(&bp->dev->dev_addr[0])){
pr_err("Invalid MAC address found in EEPROM\n");
return -EINVAL;
}
bp->imask = IMASK_DEF;
/* XXX - really required?
bp->flags |= B44_FLAG_BUGGY_TXPTR;
*/
if (bp->sdev->id.revision >= 7)
bp->flags |= B44_FLAG_B0_ANDLATER;
return err;
}
static const struct net_device_ops b44_netdev_ops = {
.ndo_open = b44_open,
.ndo_stop = b44_close,
.ndo_start_xmit = b44_start_xmit,
.ndo_get_stats64 = b44_get_stats64,
.ndo_set_rx_mode = b44_set_rx_mode,
.ndo_set_mac_address = b44_set_mac_addr,
.ndo_validate_addr = eth_validate_addr,
.ndo_do_ioctl = b44_ioctl,
.ndo_tx_timeout = b44_tx_timeout,
.ndo_change_mtu = b44_change_mtu,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = b44_poll_controller,
#endif
};
static void b44_adjust_link(struct net_device *dev)
{
struct b44 *bp = netdev_priv(dev);
struct phy_device *phydev = dev->phydev;
bool status_changed = 0;
BUG_ON(!phydev);
if (bp->old_link != phydev->link) {
status_changed = 1;
bp->old_link = phydev->link;
}
/* reflect duplex change */
if (phydev->link) {
if ((phydev->duplex == DUPLEX_HALF) &&
(bp->flags & B44_FLAG_FULL_DUPLEX)) {
status_changed = 1;
bp->flags &= ~B44_FLAG_FULL_DUPLEX;
} else if ((phydev->duplex == DUPLEX_FULL) &&
!(bp->flags & B44_FLAG_FULL_DUPLEX)) {
status_changed = 1;
bp->flags |= B44_FLAG_FULL_DUPLEX;
}
}
if (status_changed) {
u32 val = br32(bp, B44_TX_CTRL);
if (bp->flags & B44_FLAG_FULL_DUPLEX)
val |= TX_CTRL_DUPLEX;
else
val &= ~TX_CTRL_DUPLEX;
bw32(bp, B44_TX_CTRL, val);
phy_print_status(phydev);
}
}
static int b44_register_phy_one(struct b44 *bp)
{
struct mii_bus *mii_bus;
struct ssb_device *sdev = bp->sdev;
struct phy_device *phydev;
char bus_id[MII_BUS_ID_SIZE + 3];
struct ssb_sprom *sprom = &sdev->bus->sprom;
int err;
mii_bus = mdiobus_alloc();
if (!mii_bus) {
dev_err(sdev->dev, "mdiobus_alloc() failed\n");
err = -ENOMEM;
goto err_out;
}
mii_bus->priv = bp;
mii_bus->read = b44_mdio_read_phylib;
mii_bus->write = b44_mdio_write_phylib;
mii_bus->name = "b44_eth_mii";
mii_bus->parent = sdev->dev;
mii_bus->phy_mask = ~(1 << bp->phy_addr);
snprintf(mii_bus->id, MII_BUS_ID_SIZE, "%x", instance);
bp->mii_bus = mii_bus;
err = mdiobus_register(mii_bus);
if (err) {
dev_err(sdev->dev, "failed to register MII bus\n");
goto err_out_mdiobus;
}
if (!mdiobus_is_registered_device(bp->mii_bus, bp->phy_addr) &&
(sprom->boardflags_lo & (B44_BOARDFLAG_ROBO | B44_BOARDFLAG_ADM))) {
dev_info(sdev->dev,
"could not find PHY at %i, use fixed one\n",
bp->phy_addr);
bp->phy_addr = 0;
snprintf(bus_id, sizeof(bus_id), PHY_ID_FMT, "fixed-0",
bp->phy_addr);
} else {
snprintf(bus_id, sizeof(bus_id), PHY_ID_FMT, mii_bus->id,
bp->phy_addr);
}
phydev = phy_connect(bp->dev, bus_id, &b44_adjust_link,
PHY_INTERFACE_MODE_MII);
if (IS_ERR(phydev)) {
dev_err(sdev->dev, "could not attach PHY at %i\n",
bp->phy_addr);
err = PTR_ERR(phydev);
goto err_out_mdiobus_unregister;
}
/* mask with MAC supported features */
phydev->supported &= (SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_Autoneg |
SUPPORTED_MII);
phydev->advertising = phydev->supported;
bp->old_link = 0;
bp->phy_addr = phydev->mdio.addr;
phy_attached_info(phydev);
return 0;
err_out_mdiobus_unregister:
mdiobus_unregister(mii_bus);
err_out_mdiobus:
mdiobus_free(mii_bus);
err_out:
return err;
}
static void b44_unregister_phy_one(struct b44 *bp)
{
struct net_device *dev = bp->dev;
struct mii_bus *mii_bus = bp->mii_bus;
phy_disconnect(dev->phydev);
mdiobus_unregister(mii_bus);
mdiobus_free(mii_bus);
}
static int b44_init_one(struct ssb_device *sdev,
const struct ssb_device_id *ent)
{
struct net_device *dev;
struct b44 *bp;
int err;
instance++;
pr_info_once("%s version %s\n", DRV_DESCRIPTION, DRV_MODULE_VERSION);
dev = alloc_etherdev(sizeof(*bp));
if (!dev) {
err = -ENOMEM;
goto out;
}
SET_NETDEV_DEV(dev, sdev->dev);
/* No interesting netdevice features in this card... */
dev->features |= 0;
bp = netdev_priv(dev);
bp->sdev = sdev;
bp->dev = dev;
bp->force_copybreak = 0;
bp->msg_enable = netif_msg_init(b44_debug, B44_DEF_MSG_ENABLE);
spin_lock_init(&bp->lock);
bp->rx_pending = B44_DEF_RX_RING_PENDING;
bp->tx_pending = B44_DEF_TX_RING_PENDING;
dev->netdev_ops = &b44_netdev_ops;
netif_napi_add(dev, &bp->napi, b44_poll, 64);
dev->watchdog_timeo = B44_TX_TIMEOUT;
dev->irq = sdev->irq;
dev->ethtool_ops = &b44_ethtool_ops;
err = ssb_bus_powerup(sdev->bus, 0);
if (err) {
dev_err(sdev->dev,
"Failed to powerup the bus\n");
goto err_out_free_dev;
}
if (dma_set_mask_and_coherent(sdev->dma_dev, DMA_BIT_MASK(30))) {
dev_err(sdev->dev,
"Required 30BIT DMA mask unsupported by the system\n");
goto err_out_powerdown;
}
err = b44_get_invariants(bp);
if (err) {
dev_err(sdev->dev,
"Problem fetching invariants of chip, aborting\n");
goto err_out_powerdown;
}
if (bp->phy_addr == B44_PHY_ADDR_NO_PHY) {
dev_err(sdev->dev, "No PHY present on this MAC, aborting\n");
err = -ENODEV;
goto err_out_powerdown;
}
bp->mii_if.dev = dev;
bp->mii_if.mdio_read = b44_mdio_read_mii;
bp->mii_if.mdio_write = b44_mdio_write_mii;
bp->mii_if.phy_id = bp->phy_addr;
bp->mii_if.phy_id_mask = 0x1f;
bp->mii_if.reg_num_mask = 0x1f;
/* By default, advertise all speed/duplex settings. */
bp->flags |= (B44_FLAG_ADV_10HALF | B44_FLAG_ADV_10FULL |
B44_FLAG_ADV_100HALF | B44_FLAG_ADV_100FULL);
/* By default, auto-negotiate PAUSE. */
bp->flags |= B44_FLAG_PAUSE_AUTO;
err = register_netdev(dev);
if (err) {
dev_err(sdev->dev, "Cannot register net device, aborting\n");
goto err_out_powerdown;
}
netif_carrier_off(dev);
ssb_set_drvdata(sdev, dev);
/* Chip reset provides power to the b44 MAC & PCI cores, which
* is necessary for MAC register access.
*/
b44_chip_reset(bp, B44_CHIP_RESET_FULL);
/* do a phy reset to test if there is an active phy */
err = b44_phy_reset(bp);
if (err < 0) {
dev_err(sdev->dev, "phy reset failed\n");
goto err_out_unregister_netdev;
}
if (bp->flags & B44_FLAG_EXTERNAL_PHY) {
err = b44_register_phy_one(bp);
if (err) {
dev_err(sdev->dev, "Cannot register PHY, aborting\n");
goto err_out_unregister_netdev;
}
}
device_set_wakeup_capable(sdev->dev, true);
netdev_info(dev, "%s %pM\n", DRV_DESCRIPTION, dev->dev_addr);
return 0;
err_out_unregister_netdev:
unregister_netdev(dev);
err_out_powerdown:
ssb_bus_may_powerdown(sdev->bus);
err_out_free_dev:
netif_napi_del(&bp->napi);
free_netdev(dev);
out:
return err;
}
static void b44_remove_one(struct ssb_device *sdev)
{
struct net_device *dev = ssb_get_drvdata(sdev);
struct b44 *bp = netdev_priv(dev);
unregister_netdev(dev);
if (bp->flags & B44_FLAG_EXTERNAL_PHY)
b44_unregister_phy_one(bp);
ssb_device_disable(sdev, 0);
ssb_bus_may_powerdown(sdev->bus);
netif_napi_del(&bp->napi);
free_netdev(dev);
ssb_pcihost_set_power_state(sdev, PCI_D3hot);
ssb_set_drvdata(sdev, NULL);
}
static int b44_suspend(struct ssb_device *sdev, pm_message_t state)
{
struct net_device *dev = ssb_get_drvdata(sdev);
struct b44 *bp = netdev_priv(dev);
if (!netif_running(dev))
return 0;
del_timer_sync(&bp->timer);
spin_lock_irq(&bp->lock);
b44_halt(bp);
netif_carrier_off(bp->dev);
netif_device_detach(bp->dev);
b44_free_rings(bp);
spin_unlock_irq(&bp->lock);
free_irq(dev->irq, dev);
if (bp->flags & B44_FLAG_WOL_ENABLE) {
b44_init_hw(bp, B44_PARTIAL_RESET);
b44_setup_wol(bp);
}
ssb_pcihost_set_power_state(sdev, PCI_D3hot);
return 0;
}
static int b44_resume(struct ssb_device *sdev)
{
struct net_device *dev = ssb_get_drvdata(sdev);
struct b44 *bp = netdev_priv(dev);
int rc = 0;
rc = ssb_bus_powerup(sdev->bus, 0);
if (rc) {
dev_err(sdev->dev,
"Failed to powerup the bus\n");
return rc;
}
if (!netif_running(dev))
return 0;
spin_lock_irq(&bp->lock);
b44_init_rings(bp);
b44_init_hw(bp, B44_FULL_RESET);
spin_unlock_irq(&bp->lock);
/*
* As a shared interrupt, the handler can be called immediately. To be
* able to check the interrupt status the hardware must already be
* powered back on (b44_init_hw).
*/
rc = request_irq(dev->irq, b44_interrupt, IRQF_SHARED, dev->name, dev);
if (rc) {
netdev_err(dev, "request_irq failed\n");
spin_lock_irq(&bp->lock);
b44_halt(bp);
b44_free_rings(bp);
spin_unlock_irq(&bp->lock);
return rc;
}
netif_device_attach(bp->dev);
b44_enable_ints(bp);
netif_wake_queue(dev);
mod_timer(&bp->timer, jiffies + 1);
return 0;
}
static struct ssb_driver b44_ssb_driver = {
.name = DRV_MODULE_NAME,
.id_table = b44_ssb_tbl,
.probe = b44_init_one,
.remove = b44_remove_one,
.suspend = b44_suspend,
.resume = b44_resume,
};
static inline int __init b44_pci_init(void)
{
int err = 0;
#ifdef CONFIG_B44_PCI
err = ssb_pcihost_register(&b44_pci_driver);
#endif
return err;
}
static inline void b44_pci_exit(void)
{
#ifdef CONFIG_B44_PCI
ssb_pcihost_unregister(&b44_pci_driver);
#endif
}
static int __init b44_init(void)
{
unsigned int dma_desc_align_size = dma_get_cache_alignment();
int err;
/* Setup paramaters for syncing RX/TX DMA descriptors */
dma_desc_sync_size = max_t(unsigned int, dma_desc_align_size, sizeof(struct dma_desc));
err = b44_pci_init();
if (err)
return err;
err = ssb_driver_register(&b44_ssb_driver);
if (err)
b44_pci_exit();
return err;
}
static void __exit b44_cleanup(void)
{
ssb_driver_unregister(&b44_ssb_driver);
b44_pci_exit();
}
module_init(b44_init);
module_exit(b44_cleanup);
| gpl-2.0 |
vkomenda/linux-sunxi | drivers/gpio/gpio-dwapb.c | 74 | 17894 | /*
* Copyright (c) 2011 Jamie Iles
*
* 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.
*
* All enquiries to support@picochip.com
*/
#include <linux/basic_mmio_gpio.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/platform_data/gpio-dwapb.h>
#include <linux/slab.h>
#define GPIO_SWPORTA_DR 0x00
#define GPIO_SWPORTA_DDR 0x04
#define GPIO_SWPORTB_DR 0x0c
#define GPIO_SWPORTB_DDR 0x10
#define GPIO_SWPORTC_DR 0x18
#define GPIO_SWPORTC_DDR 0x1c
#define GPIO_SWPORTD_DR 0x24
#define GPIO_SWPORTD_DDR 0x28
#define GPIO_INTEN 0x30
#define GPIO_INTMASK 0x34
#define GPIO_INTTYPE_LEVEL 0x38
#define GPIO_INT_POLARITY 0x3c
#define GPIO_INTSTATUS 0x40
#define GPIO_PORTA_DEBOUNCE 0x48
#define GPIO_PORTA_EOI 0x4c
#define GPIO_EXT_PORTA 0x50
#define GPIO_EXT_PORTB 0x54
#define GPIO_EXT_PORTC 0x58
#define GPIO_EXT_PORTD 0x5c
#define DWAPB_MAX_PORTS 4
#define GPIO_EXT_PORT_SIZE (GPIO_EXT_PORTB - GPIO_EXT_PORTA)
#define GPIO_SWPORT_DR_SIZE (GPIO_SWPORTB_DR - GPIO_SWPORTA_DR)
#define GPIO_SWPORT_DDR_SIZE (GPIO_SWPORTB_DDR - GPIO_SWPORTA_DDR)
struct dwapb_gpio;
#ifdef CONFIG_PM_SLEEP
/* Store GPIO context across system-wide suspend/resume transitions */
struct dwapb_context {
u32 data;
u32 dir;
u32 ext;
u32 int_en;
u32 int_mask;
u32 int_type;
u32 int_pol;
u32 int_deb;
};
#endif
struct dwapb_gpio_port {
struct bgpio_chip bgc;
bool is_registered;
struct dwapb_gpio *gpio;
#ifdef CONFIG_PM_SLEEP
struct dwapb_context *ctx;
#endif
unsigned int idx;
};
struct dwapb_gpio {
struct device *dev;
void __iomem *regs;
struct dwapb_gpio_port *ports;
unsigned int nr_ports;
struct irq_domain *domain;
};
static inline struct dwapb_gpio_port *
to_dwapb_gpio_port(struct bgpio_chip *bgc)
{
return container_of(bgc, struct dwapb_gpio_port, bgc);
}
static inline u32 dwapb_read(struct dwapb_gpio *gpio, unsigned int offset)
{
struct bgpio_chip *bgc = &gpio->ports[0].bgc;
void __iomem *reg_base = gpio->regs;
return bgc->read_reg(reg_base + offset);
}
static inline void dwapb_write(struct dwapb_gpio *gpio, unsigned int offset,
u32 val)
{
struct bgpio_chip *bgc = &gpio->ports[0].bgc;
void __iomem *reg_base = gpio->regs;
bgc->write_reg(reg_base + offset, val);
}
static int dwapb_gpio_to_irq(struct gpio_chip *gc, unsigned offset)
{
struct bgpio_chip *bgc = to_bgpio_chip(gc);
struct dwapb_gpio_port *port = to_dwapb_gpio_port(bgc);
struct dwapb_gpio *gpio = port->gpio;
return irq_find_mapping(gpio->domain, offset);
}
static void dwapb_toggle_trigger(struct dwapb_gpio *gpio, unsigned int offs)
{
u32 v = dwapb_read(gpio, GPIO_INT_POLARITY);
if (gpio_get_value(gpio->ports[0].bgc.gc.base + offs))
v &= ~BIT(offs);
else
v |= BIT(offs);
dwapb_write(gpio, GPIO_INT_POLARITY, v);
}
static u32 dwapb_do_irq(struct dwapb_gpio *gpio)
{
u32 irq_status = readl_relaxed(gpio->regs + GPIO_INTSTATUS);
u32 ret = irq_status;
while (irq_status) {
int hwirq = fls(irq_status) - 1;
int gpio_irq = irq_find_mapping(gpio->domain, hwirq);
generic_handle_irq(gpio_irq);
irq_status &= ~BIT(hwirq);
if ((irq_get_trigger_type(gpio_irq) & IRQ_TYPE_SENSE_MASK)
== IRQ_TYPE_EDGE_BOTH)
dwapb_toggle_trigger(gpio, hwirq);
}
return ret;
}
static void dwapb_irq_handler(u32 irq, struct irq_desc *desc)
{
struct dwapb_gpio *gpio = irq_get_handler_data(irq);
struct irq_chip *chip = irq_desc_get_chip(desc);
dwapb_do_irq(gpio);
if (chip->irq_eoi)
chip->irq_eoi(irq_desc_get_irq_data(desc));
}
static void dwapb_irq_enable(struct irq_data *d)
{
struct irq_chip_generic *igc = irq_data_get_irq_chip_data(d);
struct dwapb_gpio *gpio = igc->private;
struct bgpio_chip *bgc = &gpio->ports[0].bgc;
unsigned long flags;
u32 val;
spin_lock_irqsave(&bgc->lock, flags);
val = dwapb_read(gpio, GPIO_INTEN);
val |= BIT(d->hwirq);
dwapb_write(gpio, GPIO_INTEN, val);
spin_unlock_irqrestore(&bgc->lock, flags);
}
static void dwapb_irq_disable(struct irq_data *d)
{
struct irq_chip_generic *igc = irq_data_get_irq_chip_data(d);
struct dwapb_gpio *gpio = igc->private;
struct bgpio_chip *bgc = &gpio->ports[0].bgc;
unsigned long flags;
u32 val;
spin_lock_irqsave(&bgc->lock, flags);
val = dwapb_read(gpio, GPIO_INTEN);
val &= ~BIT(d->hwirq);
dwapb_write(gpio, GPIO_INTEN, val);
spin_unlock_irqrestore(&bgc->lock, flags);
}
static int dwapb_irq_reqres(struct irq_data *d)
{
struct irq_chip_generic *igc = irq_data_get_irq_chip_data(d);
struct dwapb_gpio *gpio = igc->private;
struct bgpio_chip *bgc = &gpio->ports[0].bgc;
if (gpiochip_lock_as_irq(&bgc->gc, irqd_to_hwirq(d))) {
dev_err(gpio->dev, "unable to lock HW IRQ %lu for IRQ\n",
irqd_to_hwirq(d));
return -EINVAL;
}
return 0;
}
static void dwapb_irq_relres(struct irq_data *d)
{
struct irq_chip_generic *igc = irq_data_get_irq_chip_data(d);
struct dwapb_gpio *gpio = igc->private;
struct bgpio_chip *bgc = &gpio->ports[0].bgc;
gpiochip_unlock_as_irq(&bgc->gc, irqd_to_hwirq(d));
}
static int dwapb_irq_set_type(struct irq_data *d, u32 type)
{
struct irq_chip_generic *igc = irq_data_get_irq_chip_data(d);
struct dwapb_gpio *gpio = igc->private;
struct bgpio_chip *bgc = &gpio->ports[0].bgc;
int bit = d->hwirq;
unsigned long level, polarity, flags;
if (type & ~(IRQ_TYPE_EDGE_RISING | IRQ_TYPE_EDGE_FALLING |
IRQ_TYPE_LEVEL_HIGH | IRQ_TYPE_LEVEL_LOW))
return -EINVAL;
spin_lock_irqsave(&bgc->lock, flags);
level = dwapb_read(gpio, GPIO_INTTYPE_LEVEL);
polarity = dwapb_read(gpio, GPIO_INT_POLARITY);
switch (type) {
case IRQ_TYPE_EDGE_BOTH:
level |= BIT(bit);
dwapb_toggle_trigger(gpio, bit);
break;
case IRQ_TYPE_EDGE_RISING:
level |= BIT(bit);
polarity |= BIT(bit);
break;
case IRQ_TYPE_EDGE_FALLING:
level |= BIT(bit);
polarity &= ~BIT(bit);
break;
case IRQ_TYPE_LEVEL_HIGH:
level &= ~BIT(bit);
polarity |= BIT(bit);
break;
case IRQ_TYPE_LEVEL_LOW:
level &= ~BIT(bit);
polarity &= ~BIT(bit);
break;
}
irq_setup_alt_chip(d, type);
dwapb_write(gpio, GPIO_INTTYPE_LEVEL, level);
dwapb_write(gpio, GPIO_INT_POLARITY, polarity);
spin_unlock_irqrestore(&bgc->lock, flags);
return 0;
}
static int dwapb_gpio_set_debounce(struct gpio_chip *gc,
unsigned offset, unsigned debounce)
{
struct bgpio_chip *bgc = to_bgpio_chip(gc);
struct dwapb_gpio_port *port = to_dwapb_gpio_port(bgc);
struct dwapb_gpio *gpio = port->gpio;
unsigned long flags, val_deb;
unsigned long mask = bgc->pin2mask(bgc, offset);
spin_lock_irqsave(&bgc->lock, flags);
val_deb = dwapb_read(gpio, GPIO_PORTA_DEBOUNCE);
if (debounce)
dwapb_write(gpio, GPIO_PORTA_DEBOUNCE, val_deb | mask);
else
dwapb_write(gpio, GPIO_PORTA_DEBOUNCE, val_deb & ~mask);
spin_unlock_irqrestore(&bgc->lock, flags);
return 0;
}
static irqreturn_t dwapb_irq_handler_mfd(int irq, void *dev_id)
{
u32 worked;
struct dwapb_gpio *gpio = dev_id;
worked = dwapb_do_irq(gpio);
return worked ? IRQ_HANDLED : IRQ_NONE;
}
static void dwapb_configure_irqs(struct dwapb_gpio *gpio,
struct dwapb_gpio_port *port,
struct dwapb_port_property *pp)
{
struct gpio_chip *gc = &port->bgc.gc;
struct device_node *node = pp->node;
struct irq_chip_generic *irq_gc = NULL;
unsigned int hwirq, ngpio = gc->ngpio;
struct irq_chip_type *ct;
int err, i;
gpio->domain = irq_domain_add_linear(node, ngpio,
&irq_generic_chip_ops, gpio);
if (!gpio->domain)
return;
err = irq_alloc_domain_generic_chips(gpio->domain, ngpio, 2,
"gpio-dwapb", handle_level_irq,
IRQ_NOREQUEST, 0,
IRQ_GC_INIT_NESTED_LOCK);
if (err) {
dev_info(gpio->dev, "irq_alloc_domain_generic_chips failed\n");
irq_domain_remove(gpio->domain);
gpio->domain = NULL;
return;
}
irq_gc = irq_get_domain_generic_chip(gpio->domain, 0);
if (!irq_gc) {
irq_domain_remove(gpio->domain);
gpio->domain = NULL;
return;
}
irq_gc->reg_base = gpio->regs;
irq_gc->private = gpio;
for (i = 0; i < 2; i++) {
ct = &irq_gc->chip_types[i];
ct->chip.irq_ack = irq_gc_ack_set_bit;
ct->chip.irq_mask = irq_gc_mask_set_bit;
ct->chip.irq_unmask = irq_gc_mask_clr_bit;
ct->chip.irq_set_type = dwapb_irq_set_type;
ct->chip.irq_enable = dwapb_irq_enable;
ct->chip.irq_disable = dwapb_irq_disable;
ct->chip.irq_request_resources = dwapb_irq_reqres;
ct->chip.irq_release_resources = dwapb_irq_relres;
ct->regs.ack = GPIO_PORTA_EOI;
ct->regs.mask = GPIO_INTMASK;
ct->type = IRQ_TYPE_LEVEL_MASK;
}
irq_gc->chip_types[0].type = IRQ_TYPE_LEVEL_MASK;
irq_gc->chip_types[1].type = IRQ_TYPE_EDGE_BOTH;
irq_gc->chip_types[1].handler = handle_edge_irq;
if (!pp->irq_shared) {
irq_set_chained_handler(pp->irq, dwapb_irq_handler);
irq_set_handler_data(pp->irq, gpio);
} else {
/*
* Request a shared IRQ since where MFD would have devices
* using the same irq pin
*/
err = devm_request_irq(gpio->dev, pp->irq,
dwapb_irq_handler_mfd,
IRQF_SHARED, "gpio-dwapb-mfd", gpio);
if (err) {
dev_err(gpio->dev, "error requesting IRQ\n");
irq_domain_remove(gpio->domain);
gpio->domain = NULL;
return;
}
}
for (hwirq = 0 ; hwirq < ngpio ; hwirq++)
irq_create_mapping(gpio->domain, hwirq);
port->bgc.gc.to_irq = dwapb_gpio_to_irq;
}
static void dwapb_irq_teardown(struct dwapb_gpio *gpio)
{
struct dwapb_gpio_port *port = &gpio->ports[0];
struct gpio_chip *gc = &port->bgc.gc;
unsigned int ngpio = gc->ngpio;
irq_hw_number_t hwirq;
if (!gpio->domain)
return;
for (hwirq = 0 ; hwirq < ngpio ; hwirq++)
irq_dispose_mapping(irq_find_mapping(gpio->domain, hwirq));
irq_domain_remove(gpio->domain);
gpio->domain = NULL;
}
static int dwapb_gpio_add_port(struct dwapb_gpio *gpio,
struct dwapb_port_property *pp,
unsigned int offs)
{
struct dwapb_gpio_port *port;
void __iomem *dat, *set, *dirout;
int err;
port = &gpio->ports[offs];
port->gpio = gpio;
port->idx = pp->idx;
#ifdef CONFIG_PM_SLEEP
port->ctx = devm_kzalloc(gpio->dev, sizeof(*port->ctx), GFP_KERNEL);
if (!port->ctx)
return -ENOMEM;
#endif
dat = gpio->regs + GPIO_EXT_PORTA + (pp->idx * GPIO_EXT_PORT_SIZE);
set = gpio->regs + GPIO_SWPORTA_DR + (pp->idx * GPIO_SWPORT_DR_SIZE);
dirout = gpio->regs + GPIO_SWPORTA_DDR +
(pp->idx * GPIO_SWPORT_DDR_SIZE);
err = bgpio_init(&port->bgc, gpio->dev, 4, dat, set, NULL, dirout,
NULL, false);
if (err) {
dev_err(gpio->dev, "failed to init gpio chip for %s\n",
pp->name);
return err;
}
#ifdef CONFIG_OF_GPIO
port->bgc.gc.of_node = pp->node;
#endif
port->bgc.gc.ngpio = pp->ngpio;
port->bgc.gc.base = pp->gpio_base;
/* Only port A support debounce */
if (pp->idx == 0)
port->bgc.gc.set_debounce = dwapb_gpio_set_debounce;
if (pp->irq)
dwapb_configure_irqs(gpio, port, pp);
err = gpiochip_add(&port->bgc.gc);
if (err)
dev_err(gpio->dev, "failed to register gpiochip for %s\n",
pp->name);
else
port->is_registered = true;
return err;
}
static void dwapb_gpio_unregister(struct dwapb_gpio *gpio)
{
unsigned int m;
for (m = 0; m < gpio->nr_ports; ++m)
if (gpio->ports[m].is_registered)
gpiochip_remove(&gpio->ports[m].bgc.gc);
}
static struct dwapb_platform_data *
dwapb_gpio_get_pdata_of(struct device *dev)
{
struct device_node *node, *port_np;
struct dwapb_platform_data *pdata;
struct dwapb_port_property *pp;
int nports;
int i;
node = dev->of_node;
if (!IS_ENABLED(CONFIG_OF_GPIO) || !node)
return ERR_PTR(-ENODEV);
nports = of_get_child_count(node);
if (nports == 0)
return ERR_PTR(-ENODEV);
pdata = kzalloc(sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return ERR_PTR(-ENOMEM);
pdata->properties = kcalloc(nports, sizeof(*pp), GFP_KERNEL);
if (!pdata->properties) {
kfree(pdata);
return ERR_PTR(-ENOMEM);
}
pdata->nports = nports;
i = 0;
for_each_child_of_node(node, port_np) {
pp = &pdata->properties[i++];
pp->node = port_np;
if (of_property_read_u32(port_np, "reg", &pp->idx) ||
pp->idx >= DWAPB_MAX_PORTS) {
dev_err(dev, "missing/invalid port index for %s\n",
port_np->full_name);
kfree(pdata->properties);
kfree(pdata);
return ERR_PTR(-EINVAL);
}
if (of_property_read_u32(port_np, "snps,nr-gpios",
&pp->ngpio)) {
dev_info(dev, "failed to get number of gpios for %s\n",
port_np->full_name);
pp->ngpio = 32;
}
/*
* Only port A can provide interrupts in all configurations of
* the IP.
*/
if (pp->idx == 0 &&
of_property_read_bool(port_np, "interrupt-controller")) {
pp->irq = irq_of_parse_and_map(port_np, 0);
if (!pp->irq) {
dev_warn(dev, "no irq for bank %s\n",
port_np->full_name);
}
}
pp->irq_shared = false;
pp->gpio_base = -1;
pp->name = port_np->full_name;
}
return pdata;
}
static inline void dwapb_free_pdata_of(struct dwapb_platform_data *pdata)
{
if (!IS_ENABLED(CONFIG_OF_GPIO) || !pdata)
return;
kfree(pdata->properties);
kfree(pdata);
}
static int dwapb_gpio_probe(struct platform_device *pdev)
{
unsigned int i;
struct resource *res;
struct dwapb_gpio *gpio;
int err;
struct device *dev = &pdev->dev;
struct dwapb_platform_data *pdata = dev_get_platdata(dev);
bool is_pdata_alloc = !pdata;
if (is_pdata_alloc) {
pdata = dwapb_gpio_get_pdata_of(dev);
if (IS_ERR(pdata))
return PTR_ERR(pdata);
}
if (!pdata->nports) {
err = -ENODEV;
goto out_err;
}
gpio = devm_kzalloc(&pdev->dev, sizeof(*gpio), GFP_KERNEL);
if (!gpio) {
err = -ENOMEM;
goto out_err;
}
gpio->dev = &pdev->dev;
gpio->nr_ports = pdata->nports;
gpio->ports = devm_kcalloc(&pdev->dev, gpio->nr_ports,
sizeof(*gpio->ports), GFP_KERNEL);
if (!gpio->ports) {
err = -ENOMEM;
goto out_err;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
gpio->regs = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(gpio->regs)) {
err = PTR_ERR(gpio->regs);
goto out_err;
}
for (i = 0; i < gpio->nr_ports; i++) {
err = dwapb_gpio_add_port(gpio, &pdata->properties[i], i);
if (err)
goto out_unregister;
}
platform_set_drvdata(pdev, gpio);
goto out_err;
out_unregister:
dwapb_gpio_unregister(gpio);
dwapb_irq_teardown(gpio);
out_err:
if (is_pdata_alloc)
dwapb_free_pdata_of(pdata);
return err;
}
static int dwapb_gpio_remove(struct platform_device *pdev)
{
struct dwapb_gpio *gpio = platform_get_drvdata(pdev);
dwapb_gpio_unregister(gpio);
dwapb_irq_teardown(gpio);
return 0;
}
static const struct of_device_id dwapb_of_match[] = {
{ .compatible = "snps,dw-apb-gpio" },
{ /* Sentinel */ }
};
MODULE_DEVICE_TABLE(of, dwapb_of_match);
#ifdef CONFIG_PM_SLEEP
static int dwapb_gpio_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct dwapb_gpio *gpio = platform_get_drvdata(pdev);
struct bgpio_chip *bgc = &gpio->ports[0].bgc;
unsigned long flags;
int i;
spin_lock_irqsave(&bgc->lock, flags);
for (i = 0; i < gpio->nr_ports; i++) {
unsigned int offset;
unsigned int idx = gpio->ports[i].idx;
struct dwapb_context *ctx = gpio->ports[i].ctx;
BUG_ON(!ctx);
offset = GPIO_SWPORTA_DDR + idx * GPIO_SWPORT_DDR_SIZE;
ctx->dir = dwapb_read(gpio, offset);
offset = GPIO_SWPORTA_DR + idx * GPIO_SWPORT_DR_SIZE;
ctx->data = dwapb_read(gpio, offset);
offset = GPIO_EXT_PORTA + idx * GPIO_EXT_PORT_SIZE;
ctx->ext = dwapb_read(gpio, offset);
/* Only port A can provide interrupts */
if (idx == 0) {
ctx->int_mask = dwapb_read(gpio, GPIO_INTMASK);
ctx->int_en = dwapb_read(gpio, GPIO_INTEN);
ctx->int_pol = dwapb_read(gpio, GPIO_INT_POLARITY);
ctx->int_type = dwapb_read(gpio, GPIO_INTTYPE_LEVEL);
ctx->int_deb = dwapb_read(gpio, GPIO_PORTA_DEBOUNCE);
/* Mask out interrupts */
dwapb_write(gpio, GPIO_INTMASK, 0xffffffff);
}
}
spin_unlock_irqrestore(&bgc->lock, flags);
return 0;
}
static int dwapb_gpio_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct dwapb_gpio *gpio = platform_get_drvdata(pdev);
struct bgpio_chip *bgc = &gpio->ports[0].bgc;
unsigned long flags;
int i;
spin_lock_irqsave(&bgc->lock, flags);
for (i = 0; i < gpio->nr_ports; i++) {
unsigned int offset;
unsigned int idx = gpio->ports[i].idx;
struct dwapb_context *ctx = gpio->ports[i].ctx;
BUG_ON(!ctx);
offset = GPIO_SWPORTA_DR + idx * GPIO_SWPORT_DR_SIZE;
dwapb_write(gpio, offset, ctx->data);
offset = GPIO_SWPORTA_DDR + idx * GPIO_SWPORT_DDR_SIZE;
dwapb_write(gpio, offset, ctx->dir);
offset = GPIO_EXT_PORTA + idx * GPIO_EXT_PORT_SIZE;
dwapb_write(gpio, offset, ctx->ext);
/* Only port A can provide interrupts */
if (idx == 0) {
dwapb_write(gpio, GPIO_INTTYPE_LEVEL, ctx->int_type);
dwapb_write(gpio, GPIO_INT_POLARITY, ctx->int_pol);
dwapb_write(gpio, GPIO_PORTA_DEBOUNCE, ctx->int_deb);
dwapb_write(gpio, GPIO_INTEN, ctx->int_en);
dwapb_write(gpio, GPIO_INTMASK, ctx->int_mask);
/* Clear out spurious interrupts */
dwapb_write(gpio, GPIO_PORTA_EOI, 0xffffffff);
}
}
spin_unlock_irqrestore(&bgc->lock, flags);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(dwapb_gpio_pm_ops, dwapb_gpio_suspend,
dwapb_gpio_resume);
static struct platform_driver dwapb_gpio_driver = {
.driver = {
.name = "gpio-dwapb",
.pm = &dwapb_gpio_pm_ops,
.of_match_table = of_match_ptr(dwapb_of_match),
},
.probe = dwapb_gpio_probe,
.remove = dwapb_gpio_remove,
};
module_platform_driver(dwapb_gpio_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jamie Iles");
MODULE_DESCRIPTION("Synopsys DesignWare APB GPIO driver");
| gpl-2.0 |
eugene373/Galaxy-S2-ICS | drivers/usb/host/ehci-hub.c | 586 | 36251 | /*
* Copyright (C) 2001-2004 by David Brownell
*
* 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.
*/
/* this file is part of ehci-hcd.c */
/*-------------------------------------------------------------------------*/
/*
* EHCI Root Hub ... the nonsharable stuff
*
* Registers don't need cpu_to_le32, that happens transparently
*/
/*-------------------------------------------------------------------------*/
#include <linux/usb/otg.h>
#define PORT_WAKE_BITS (PORT_WKOC_E|PORT_WKDISC_E|PORT_WKCONN_E)
#ifdef CONFIG_PM
static int ehci_hub_control(
struct usb_hcd *hcd,
u16 typeReq,
u16 wValue,
u16 wIndex,
char *buf,
u16 wLength
);
/* After a power loss, ports that were owned by the companion must be
* reset so that the companion can still own them.
*/
static void ehci_handover_companion_ports(struct ehci_hcd *ehci)
{
u32 __iomem *reg;
u32 status;
int port;
__le32 buf;
struct usb_hcd *hcd = ehci_to_hcd(ehci);
if (!ehci->owned_ports)
return;
/* Give the connections some time to appear */
msleep(20);
port = HCS_N_PORTS(ehci->hcs_params);
while (port--) {
if (test_bit(port, &ehci->owned_ports)) {
reg = &ehci->regs->port_status[port];
status = ehci_readl(ehci, reg) & ~PORT_RWC_BITS;
/* Port already owned by companion? */
if (status & PORT_OWNER)
clear_bit(port, &ehci->owned_ports);
else if (test_bit(port, &ehci->companion_ports))
ehci_writel(ehci, status & ~PORT_PE, reg);
else
ehci_hub_control(hcd, SetPortFeature,
USB_PORT_FEAT_RESET, port + 1,
NULL, 0);
}
}
if (!ehci->owned_ports)
return;
msleep(90); /* Wait for resets to complete */
port = HCS_N_PORTS(ehci->hcs_params);
while (port--) {
if (test_bit(port, &ehci->owned_ports)) {
ehci_hub_control(hcd, GetPortStatus,
0, port + 1,
(char *) &buf, sizeof(buf));
/* The companion should now own the port,
* but if something went wrong the port must not
* remain enabled.
*/
reg = &ehci->regs->port_status[port];
status = ehci_readl(ehci, reg) & ~PORT_RWC_BITS;
if (status & PORT_OWNER)
ehci_writel(ehci, status | PORT_CSC, reg);
else {
ehci_dbg(ehci, "failed handover port %d: %x\n",
port + 1, status);
ehci_writel(ehci, status & ~PORT_PE, reg);
}
}
}
ehci->owned_ports = 0;
}
static int ehci_port_change(struct ehci_hcd *ehci)
{
int i = HCS_N_PORTS(ehci->hcs_params);
/* First check if the controller indicates a change event */
if (ehci_readl(ehci, &ehci->regs->status) & STS_PCD)
return 1;
/*
* Not all controllers appear to update this while going from D3 to D0,
* so check the individual port status registers as well
*/
while (i--)
if (ehci_readl(ehci, &ehci->regs->port_status[i]) & PORT_CSC)
return 1;
return 0;
}
static __maybe_unused void ehci_adjust_port_wakeup_flags(struct ehci_hcd *ehci,
bool suspending, bool do_wakeup)
{
int port;
u32 temp;
unsigned long flags;
/* If remote wakeup is enabled for the root hub but disabled
* for the controller, we must adjust all the port wakeup flags
* when the controller is suspended or resumed. In all other
* cases they don't need to be changed.
*/
if (!ehci_to_hcd(ehci)->self.root_hub->do_remote_wakeup || do_wakeup)
return;
spin_lock_irqsave(&ehci->lock, flags);
/* clear phy low-power mode before changing wakeup flags */
if (ehci->has_hostpc) {
port = HCS_N_PORTS(ehci->hcs_params);
while (port--) {
u32 __iomem *hostpc_reg;
hostpc_reg = (u32 __iomem *)((u8 *) ehci->regs
+ HOSTPC0 + 4 * port);
temp = ehci_readl(ehci, hostpc_reg);
ehci_writel(ehci, temp & ~HOSTPC_PHCD, hostpc_reg);
}
spin_unlock_irqrestore(&ehci->lock, flags);
msleep(5);
spin_lock_irqsave(&ehci->lock, flags);
}
port = HCS_N_PORTS(ehci->hcs_params);
while (port--) {
u32 __iomem *reg = &ehci->regs->port_status[port];
u32 t1 = ehci_readl(ehci, reg) & ~PORT_RWC_BITS;
u32 t2 = t1 & ~PORT_WAKE_BITS;
/* If we are suspending the controller, clear the flags.
* If we are resuming the controller, set the wakeup flags.
*/
if (!suspending) {
if (t1 & PORT_CONNECT)
t2 |= PORT_WKOC_E | PORT_WKDISC_E;
else
t2 |= PORT_WKOC_E | PORT_WKCONN_E;
}
ehci_vdbg(ehci, "port %d, %08x -> %08x\n",
port + 1, t1, t2);
ehci_writel(ehci, t2, reg);
}
/* enter phy low-power mode again */
if (ehci->has_hostpc) {
port = HCS_N_PORTS(ehci->hcs_params);
while (port--) {
u32 __iomem *hostpc_reg;
hostpc_reg = (u32 __iomem *)((u8 *) ehci->regs
+ HOSTPC0 + 4 * port);
temp = ehci_readl(ehci, hostpc_reg);
ehci_writel(ehci, temp | HOSTPC_PHCD, hostpc_reg);
}
}
/* Does the root hub have a port wakeup pending? */
if (!suspending && ehci_port_change(ehci))
usb_hcd_resume_root_hub(ehci_to_hcd(ehci));
spin_unlock_irqrestore(&ehci->lock, flags);
}
static int ehci_bus_suspend (struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
int port;
int mask;
int changed;
ehci_dbg(ehci, "suspend root hub\n");
if (time_before (jiffies, ehci->next_statechange))
msleep(5);
del_timer_sync(&ehci->watchdog);
del_timer_sync(&ehci->iaa_watchdog);
spin_lock_irq (&ehci->lock);
/* Once the controller is stopped, port resumes that are already
* in progress won't complete. Hence if remote wakeup is enabled
* for the root hub and any ports are in the middle of a resume or
* remote wakeup, we must fail the suspend.
*/
if (hcd->self.root_hub->do_remote_wakeup) {
port = HCS_N_PORTS(ehci->hcs_params);
while (port--) {
if (ehci->reset_done[port] != 0) {
spin_unlock_irq(&ehci->lock);
ehci_dbg(ehci, "suspend failed because "
"port %d is resuming\n",
port + 1);
return -EBUSY;
}
}
}
/* stop schedules, clean any completed work */
if (HC_IS_RUNNING(hcd->state)) {
ehci_quiesce (ehci);
hcd->state = HC_STATE_QUIESCING;
}
ehci->command = ehci_readl(ehci, &ehci->regs->command);
ehci_work(ehci);
/* Unlike other USB host controller types, EHCI doesn't have
* any notion of "global" or bus-wide suspend. The driver has
* to manually suspend all the active unsuspended ports, and
* then manually resume them in the bus_resume() routine.
*/
ehci->bus_suspended = 0;
ehci->owned_ports = 0;
changed = 0;
port = HCS_N_PORTS(ehci->hcs_params);
while (port--) {
u32 __iomem *reg = &ehci->regs->port_status [port];
u32 t1 = ehci_readl(ehci, reg) & ~PORT_RWC_BITS;
u32 t2 = t1 & ~PORT_WAKE_BITS;
/* keep track of which ports we suspend */
if (t1 & PORT_OWNER)
set_bit(port, &ehci->owned_ports);
else if ((t1 & PORT_PE) && !(t1 & PORT_SUSPEND)) {
t2 |= PORT_SUSPEND;
set_bit(port, &ehci->bus_suspended);
}
/* enable remote wakeup on all ports, if told to do so */
if (hcd->self.root_hub->do_remote_wakeup) {
/* only enable appropriate wake bits, otherwise the
* hardware can not go phy low power mode. If a race
* condition happens here(connection change during bits
* set), the port change detection will finally fix it.
*/
if (t1 & PORT_CONNECT)
t2 |= PORT_WKOC_E | PORT_WKDISC_E;
else
t2 |= PORT_WKOC_E | PORT_WKCONN_E;
}
if (t1 != t2) {
ehci_vdbg (ehci, "port %d, %08x -> %08x\n",
port + 1, t1, t2);
ehci_writel(ehci, t2, reg);
changed = 1;
}
}
if (changed && ehci->has_hostpc) {
spin_unlock_irq(&ehci->lock);
msleep(5); /* 5 ms for HCD to enter low-power mode */
spin_lock_irq(&ehci->lock);
port = HCS_N_PORTS(ehci->hcs_params);
while (port--) {
u32 __iomem *hostpc_reg;
u32 t3;
hostpc_reg = (u32 __iomem *)((u8 *) ehci->regs
+ HOSTPC0 + 4 * port);
t3 = ehci_readl(ehci, hostpc_reg);
ehci_writel(ehci, t3 | HOSTPC_PHCD, hostpc_reg);
t3 = ehci_readl(ehci, hostpc_reg);
ehci_dbg(ehci, "Port %d phy low-power mode %s\n",
port, (t3 & HOSTPC_PHCD) ?
"succeeded" : "failed");
}
}
/* Apparently some devices need a >= 1-uframe delay here */
if (ehci->bus_suspended)
udelay(150);
/* turn off now-idle HC */
ehci_halt (ehci);
hcd->state = HC_STATE_SUSPENDED;
if (ehci->reclaim)
end_unlink_async(ehci);
/* allow remote wakeup */
mask = INTR_MASK;
if (!hcd->self.root_hub->do_remote_wakeup)
mask &= ~STS_PCD;
ehci_writel(ehci, mask, &ehci->regs->intr_enable);
ehci_readl(ehci, &ehci->regs->intr_enable);
ehci->next_statechange = jiffies + msecs_to_jiffies(10);
spin_unlock_irq (&ehci->lock);
/* ehci_work() may have re-enabled the watchdog timer, which we do not
* want, and so we must delete any pending watchdog timer events.
*/
del_timer_sync(&ehci->watchdog);
return 0;
}
/* caller has locked the root hub, and should reset/reinit on error */
static int ehci_bus_resume (struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
u32 temp;
u32 power_okay;
int i;
unsigned long resume_needed = 0;
if (time_before (jiffies, ehci->next_statechange))
msleep(5);
spin_lock_irq (&ehci->lock);
if (!HCD_HW_ACCESSIBLE(hcd)) {
spin_unlock_irq(&ehci->lock);
return -ESHUTDOWN;
}
if (unlikely(ehci->debug)) {
if (!dbgp_reset_prep())
ehci->debug = NULL;
else
dbgp_external_startup();
}
/* Ideally and we've got a real resume here, and no port's power
* was lost. (For PCI, that means Vaux was maintained.) But we
* could instead be restoring a swsusp snapshot -- so that BIOS was
* the last user of the controller, not reset/pm hardware keeping
* state we gave to it.
*/
power_okay = ehci_readl(ehci, &ehci->regs->intr_enable);
ehci_dbg(ehci, "resume root hub%s\n",
power_okay ? "" : " after power loss");
/* at least some APM implementations will try to deliver
* IRQs right away, so delay them until we're ready.
*/
ehci_writel(ehci, 0, &ehci->regs->intr_enable);
/* re-init operational registers */
ehci_writel(ehci, 0, &ehci->regs->segment);
ehci_writel(ehci, ehci->periodic_dma, &ehci->regs->frame_list);
ehci_writel(ehci, (u32) ehci->async->qh_dma, &ehci->regs->async_next);
/* restore CMD_RUN, framelist size, and irq threshold */
ehci_writel(ehci, ehci->command, &ehci->regs->command);
/* Some controller/firmware combinations need a delay during which
* they set up the port statuses. See Bugzilla #8190. */
spin_unlock_irq(&ehci->lock);
msleep(8);
spin_lock_irq(&ehci->lock);
/* clear phy low-power mode before resume */
if (ehci->bus_suspended && ehci->has_hostpc) {
i = HCS_N_PORTS(ehci->hcs_params);
while (i--) {
if (test_bit(i, &ehci->bus_suspended)) {
u32 __iomem *hostpc_reg;
hostpc_reg = (u32 __iomem *)((u8 *) ehci->regs
+ HOSTPC0 + 4 * i);
temp = ehci_readl(ehci, hostpc_reg);
ehci_writel(ehci, temp & ~HOSTPC_PHCD,
hostpc_reg);
}
}
spin_unlock_irq(&ehci->lock);
msleep(5);
spin_lock_irq(&ehci->lock);
}
/* manually resume the ports we suspended during bus_suspend() */
i = HCS_N_PORTS (ehci->hcs_params);
while (i--) {
temp = ehci_readl(ehci, &ehci->regs->port_status [i]);
temp &= ~(PORT_RWC_BITS | PORT_WAKE_BITS);
if (test_bit(i, &ehci->bus_suspended) &&
(temp & PORT_SUSPEND)) {
temp |= PORT_RESUME;
set_bit(i, &resume_needed);
}
ehci_writel(ehci, temp, &ehci->regs->port_status [i]);
}
/* msleep for 20ms only if code is trying to resume port */
if (resume_needed) {
spin_unlock_irq(&ehci->lock);
msleep(20);
spin_lock_irq(&ehci->lock);
}
i = HCS_N_PORTS (ehci->hcs_params);
while (i--) {
temp = ehci_readl(ehci, &ehci->regs->port_status [i]);
if (test_bit(i, &resume_needed)) {
temp &= ~(PORT_RWC_BITS | PORT_RESUME);
ehci_writel(ehci, temp, &ehci->regs->port_status [i]);
ehci_vdbg (ehci, "resumed port %d\n", i + 1);
}
}
(void) ehci_readl(ehci, &ehci->regs->command);
/* maybe re-activate the schedule(s) */
temp = 0;
if (ehci->async->qh_next.qh)
temp |= CMD_ASE;
if (ehci->periodic_sched)
temp |= CMD_PSE;
if (temp) {
ehci->command |= temp;
ehci_writel(ehci, ehci->command, &ehci->regs->command);
}
ehci->next_statechange = jiffies + msecs_to_jiffies(5);
hcd->state = HC_STATE_RUNNING;
/* Now we can safely re-enable irqs */
ehci_writel(ehci, INTR_MASK, &ehci->regs->intr_enable);
spin_unlock_irq (&ehci->lock);
ehci_handover_companion_ports(ehci);
return 0;
}
#else
#define ehci_bus_suspend NULL
#define ehci_bus_resume NULL
#endif /* CONFIG_PM */
/*-------------------------------------------------------------------------*/
/* Display the ports dedicated to the companion controller */
static ssize_t show_companion(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct ehci_hcd *ehci;
int nports, index, n;
int count = PAGE_SIZE;
char *ptr = buf;
ehci = hcd_to_ehci(bus_to_hcd(dev_get_drvdata(dev)));
nports = HCS_N_PORTS(ehci->hcs_params);
for (index = 0; index < nports; ++index) {
if (test_bit(index, &ehci->companion_ports)) {
n = scnprintf(ptr, count, "%d\n", index + 1);
ptr += n;
count -= n;
}
}
return ptr - buf;
}
/*
* Sets the owner of a port
*/
static void set_owner(struct ehci_hcd *ehci, int portnum, int new_owner)
{
u32 __iomem *status_reg;
u32 port_status;
int try;
status_reg = &ehci->regs->port_status[portnum];
/*
* The controller won't set the OWNER bit if the port is
* enabled, so this loop will sometimes require at least two
* iterations: one to disable the port and one to set OWNER.
*/
for (try = 4; try > 0; --try) {
spin_lock_irq(&ehci->lock);
port_status = ehci_readl(ehci, status_reg);
if ((port_status & PORT_OWNER) == new_owner
|| (port_status & (PORT_OWNER | PORT_CONNECT))
== 0)
try = 0;
else {
port_status ^= PORT_OWNER;
port_status &= ~(PORT_PE | PORT_RWC_BITS);
ehci_writel(ehci, port_status, status_reg);
}
spin_unlock_irq(&ehci->lock);
if (try > 1)
msleep(5);
}
}
/*
* Dedicate or undedicate a port to the companion controller.
* Syntax is "[-]portnum", where a leading '-' sign means
* return control of the port to the EHCI controller.
*/
static ssize_t store_companion(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ehci_hcd *ehci;
int portnum, new_owner;
ehci = hcd_to_ehci(bus_to_hcd(dev_get_drvdata(dev)));
new_owner = PORT_OWNER; /* Owned by companion */
if (sscanf(buf, "%d", &portnum) != 1)
return -EINVAL;
if (portnum < 0) {
portnum = - portnum;
new_owner = 0; /* Owned by EHCI */
}
if (portnum <= 0 || portnum > HCS_N_PORTS(ehci->hcs_params))
return -ENOENT;
portnum--;
if (new_owner)
set_bit(portnum, &ehci->companion_ports);
else
clear_bit(portnum, &ehci->companion_ports);
set_owner(ehci, portnum, new_owner);
return count;
}
static DEVICE_ATTR(companion, 0644, show_companion, store_companion);
static inline int create_companion_file(struct ehci_hcd *ehci)
{
int i = 0;
/* with integrated TT there is no companion! */
if (!ehci_is_TDI(ehci))
i = device_create_file(ehci_to_hcd(ehci)->self.controller,
&dev_attr_companion);
return i;
}
static inline void remove_companion_file(struct ehci_hcd *ehci)
{
/* with integrated TT there is no companion! */
if (!ehci_is_TDI(ehci))
device_remove_file(ehci_to_hcd(ehci)->self.controller,
&dev_attr_companion);
}
/*-------------------------------------------------------------------------*/
static int check_reset_complete (
struct ehci_hcd *ehci,
int index,
u32 __iomem *status_reg,
int port_status
) {
if (!(port_status & PORT_CONNECT))
return port_status;
/* if reset finished and it's still not enabled -- handoff */
if (!(port_status & PORT_PE)) {
/* with integrated TT, there's nobody to hand it to! */
if (ehci_is_TDI(ehci)) {
ehci_dbg (ehci,
"Failed to enable port %d on root hub TT\n",
index+1);
return port_status;
}
ehci_dbg (ehci, "port %d full speed --> companion\n",
index + 1);
// what happens if HCS_N_CC(params) == 0 ?
port_status |= PORT_OWNER;
port_status &= ~PORT_RWC_BITS;
ehci_writel(ehci, port_status, status_reg);
/* ensure 440EPX ohci controller state is operational */
if (ehci->has_amcc_usb23)
set_ohci_hcfs(ehci, 1);
} else {
ehci_dbg (ehci, "port %d high speed\n", index + 1);
/* ensure 440EPx ohci controller state is suspended */
if (ehci->has_amcc_usb23)
set_ohci_hcfs(ehci, 0);
}
return port_status;
}
/*-------------------------------------------------------------------------*/
/* build "status change" packet (one or two bytes) from HC registers */
static int
ehci_hub_status_data (struct usb_hcd *hcd, char *buf)
{
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
u32 temp, status = 0;
u32 mask;
int ports, i, retval = 1;
unsigned long flags;
u32 ppcd = 0;
/* if !USB_SUSPEND, root hub timers won't get shut down ... */
if (!HC_IS_RUNNING(hcd->state))
return 0;
/* init status to no-changes */
buf [0] = 0;
ports = HCS_N_PORTS (ehci->hcs_params);
if (ports > 7) {
buf [1] = 0;
retval++;
}
/* Some boards (mostly VIA?) report bogus overcurrent indications,
* causing massive log spam unless we completely ignore them. It
* may be relevant that VIA VT8235 controllers, where PORT_POWER is
* always set, seem to clear PORT_OCC and PORT_CSC when writing to
* PORT_POWER; that's surprising, but maybe within-spec.
*/
if (!ignore_oc)
mask = PORT_CSC | PORT_PEC | PORT_OCC;
else
mask = PORT_CSC | PORT_PEC;
// PORT_RESUME from hardware ~= PORT_STAT_C_SUSPEND
/* no hub change reports (bit 0) for now (power, ...) */
/* port N changes (bit N)? */
spin_lock_irqsave (&ehci->lock, flags);
/* get per-port change detect bits */
if (ehci->has_ppcd)
ppcd = ehci_readl(ehci, &ehci->regs->status) >> 16;
for (i = 0; i < ports; i++) {
/* leverage per-port change bits feature */
if (ehci->has_ppcd && !(ppcd & (1 << i)))
continue;
temp = ehci_readl(ehci, &ehci->regs->port_status [i]);
/*
* Return status information even for ports with OWNER set.
* Otherwise khubd wouldn't see the disconnect event when a
* high-speed device is switched over to the companion
* controller by the user.
*/
if ((temp & mask) != 0 || test_bit(i, &ehci->port_c_suspend)
|| (ehci->reset_done[i] && time_after_eq(
jiffies, ehci->reset_done[i]))) {
if (i < 7)
buf [0] |= 1 << (i + 1);
else
buf [1] |= 1 << (i - 7);
status = STS_PCD;
}
}
/* FIXME autosuspend idle root hubs */
spin_unlock_irqrestore (&ehci->lock, flags);
return status ? retval : 0;
}
/*-------------------------------------------------------------------------*/
static void
ehci_hub_descriptor (
struct ehci_hcd *ehci,
struct usb_hub_descriptor *desc
) {
int ports = HCS_N_PORTS (ehci->hcs_params);
u16 temp;
desc->bDescriptorType = 0x29;
desc->bPwrOn2PwrGood = 10; /* ehci 1.0, 2.3.9 says 20ms max */
desc->bHubContrCurrent = 0;
desc->bNbrPorts = ports;
temp = 1 + (ports / 8);
desc->bDescLength = 7 + 2 * temp;
/* two bitmaps: ports removable, and usb 1.0 legacy PortPwrCtrlMask */
memset(&desc->u.hs.DeviceRemovable[0], 0, temp);
memset(&desc->u.hs.DeviceRemovable[temp], 0xff, temp);
temp = 0x0008; /* per-port overcurrent reporting */
if (HCS_PPC (ehci->hcs_params))
temp |= 0x0001; /* per-port power control */
else
temp |= 0x0002; /* no power switching */
#if 0
// re-enable when we support USB_PORT_FEAT_INDICATOR below.
if (HCS_INDICATOR (ehci->hcs_params))
temp |= 0x0080; /* per-port indicators (LEDs) */
#endif
desc->wHubCharacteristics = cpu_to_le16(temp);
}
/*-------------------------------------------------------------------------*/
#ifdef CONFIG_USB_EHCI_EHSET
#define EHSET_TEST_SINGLE_STEP_SET_FEATURE 0x06
static void usb_ehset_completion(struct urb *urb)
{
struct completion *done = urb->context;
complete(done);
}
static int submit_single_step_set_feature(
struct usb_hcd *hcd,
struct urb *urb,
int is_setup
);
/* Allocate a URB and initialize the various fields of it.
* This API is used by the single_step_set_feature test of
* EHSET where IN packet of the GetDescriptor request is
* sent after 15secs of the SETUP packet.
* Return NULL if failed.
*/
static struct urb *
request_single_step_set_feature_urb(
struct usb_device *udev,
void *dr,
void *buf,
struct completion *done
) {
struct urb *urb;
struct usb_hcd *hcd = bus_to_hcd(udev->bus);
struct usb_host_endpoint *ep;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb)
return NULL;
urb->pipe = usb_rcvctrlpipe(udev, 0);
ep = (usb_pipein(urb->pipe) ? udev->ep_in : udev->ep_out)
[usb_pipeendpoint(urb->pipe)];
if (!ep) {
usb_free_urb(urb);
return NULL;
}
/* Initialize the various URB fields as these are used
* by the HCD driver to queue it and as well as
* when completion happens.
*/
urb->ep = ep;
urb->dev = udev;
urb->setup_packet = (void *)dr;
urb->transfer_buffer = buf;
urb->transfer_buffer_length = USB_DT_DEVICE_SIZE;
urb->complete = usb_ehset_completion;
urb->status = -EINPROGRESS;
urb->actual_length = 0;
urb->transfer_flags = (urb->transfer_flags & ~URB_DIR_MASK)
| URB_DIR_IN ;
usb_get_urb(urb);
atomic_inc(&urb->use_count);
atomic_inc(&urb->dev->urbnum);
urb->setup_dma = dma_map_single(
hcd->self.controller,
urb->setup_packet,
sizeof(struct usb_ctrlrequest),
DMA_TO_DEVICE);
urb->transfer_dma = dma_map_single(
hcd->self.controller,
urb->transfer_buffer,
urb->transfer_buffer_length,
DMA_FROM_DEVICE);
urb->context = done;
return urb;
}
static int ehset_single_step_set_feature(struct usb_hcd *hcd, int port)
{
int retval = -ENOMEM;
struct usb_ctrlrequest *dr;
struct urb *urb;
struct usb_device *udev ;
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
struct usb_device_descriptor *buf;
DECLARE_COMPLETION_ONSTACK(done);
/*Obtain udev of the rhub's child port */
udev = hcd->self.root_hub->children[port];
if (!udev) {
ehci_err(ehci, "No device attached to the RootHub\n");
return -ENODEV;
}
buf = kmalloc(USB_DT_DEVICE_SIZE, GFP_KERNEL);
if (!buf)
return -ENOMEM;
dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
if (!dr) {
kfree(buf);
return -ENOMEM;
}
/* Fill Setup packet for GetDescriptor */
dr->bRequestType = USB_DIR_IN;
dr->bRequest = USB_REQ_GET_DESCRIPTOR;
dr->wValue = cpu_to_le16(USB_DT_DEVICE << 8);
dr->wIndex = 0;
dr->wLength = cpu_to_le16(USB_DT_DEVICE_SIZE);
urb = request_single_step_set_feature_urb(udev, dr, buf, &done);
if (!urb)
goto cleanup;
/* Now complete just the SETUP stage */
retval = submit_single_step_set_feature(hcd, urb, 1);
if (retval)
goto out1;
if (!wait_for_completion_timeout(&done, msecs_to_jiffies(2000))) {
usb_kill_urb(urb);
retval = -ETIMEDOUT;
ehci_err(ehci, "%s SETUP stage timed out on ep0\n", __func__);
goto out1;
}
msleep(15 * 1000);
/* Complete remaining DATA and status stages */
/* No need to free the URB, we can reuse the same */
urb->status = -EINPROGRESS;
usb_get_urb(urb);
atomic_inc(&urb->use_count);
atomic_inc(&urb->dev->urbnum);
retval = submit_single_step_set_feature(hcd, urb, 0);
if (!retval && !wait_for_completion_timeout(&done,
msecs_to_jiffies(2000))) {
usb_kill_urb(urb);
retval = -ETIMEDOUT;
ehci_err(ehci, "%s IN stage timed out on ep0\n", __func__);
}
out1:
usb_free_urb(urb);
cleanup:
kfree(dr);
kfree(buf);
return retval;
}
#endif
/*-------------------------------------------------------------------------*/
static int ehci_hub_control (
struct usb_hcd *hcd,
u16 typeReq,
u16 wValue,
u16 wIndex,
char *buf,
u16 wLength
) {
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
int ports = HCS_N_PORTS (ehci->hcs_params);
u32 __iomem *status_reg = &ehci->regs->port_status[
(wIndex & 0xff) - 1];
u32 __iomem *hostpc_reg = NULL;
u32 temp, temp1, status;
unsigned long flags;
int retval = 0;
unsigned selector;
/*
* FIXME: support SetPortFeatures USB_PORT_FEAT_INDICATOR.
* HCS_INDICATOR may say we can change LEDs to off/amber/green.
* (track current state ourselves) ... blink for diagnostics,
* power, "this is the one", etc. EHCI spec supports this.
*/
if (ehci->has_hostpc)
hostpc_reg = (u32 __iomem *)((u8 *)ehci->regs
+ HOSTPC0 + 4 * ((wIndex & 0xff) - 1));
spin_lock_irqsave (&ehci->lock, flags);
switch (typeReq) {
case ClearHubFeature:
switch (wValue) {
case C_HUB_LOCAL_POWER:
case C_HUB_OVER_CURRENT:
/* no hub-wide feature/status flags */
break;
default:
goto error;
}
break;
case ClearPortFeature:
if (!wIndex || wIndex > ports)
goto error;
wIndex--;
temp = ehci_readl(ehci, status_reg);
/*
* Even if OWNER is set, so the port is owned by the
* companion controller, khubd needs to be able to clear
* the port-change status bits (especially
* USB_PORT_STAT_C_CONNECTION).
*/
switch (wValue) {
case USB_PORT_FEAT_ENABLE:
ehci_writel(ehci, temp & ~PORT_PE, status_reg);
break;
case USB_PORT_FEAT_C_ENABLE:
ehci_writel(ehci, (temp & ~PORT_RWC_BITS) | PORT_PEC,
status_reg);
break;
case USB_PORT_FEAT_SUSPEND:
if (temp & PORT_RESET)
goto error;
if (ehci->no_selective_suspend)
break;
#ifdef CONFIG_USB_OTG
if ((hcd->self.otg_port == (wIndex + 1))
&& hcd->self.b_hnp_enable) {
otg_start_hnp(ehci->transceiver);
break;
}
#endif
if (!(temp & PORT_SUSPEND))
break;
if ((temp & PORT_PE) == 0)
goto error;
/* clear phy low-power mode before resume */
if (hostpc_reg) {
temp1 = ehci_readl(ehci, hostpc_reg);
ehci_writel(ehci, temp1 & ~HOSTPC_PHCD,
hostpc_reg);
spin_unlock_irqrestore(&ehci->lock, flags);
msleep(5);/* wait to leave low-power mode */
spin_lock_irqsave(&ehci->lock, flags);
}
/* resume signaling for 20 msec */
temp &= ~(PORT_RWC_BITS | PORT_WAKE_BITS);
ehci_writel(ehci, temp | PORT_RESUME, status_reg);
ehci->reset_done[wIndex] = jiffies
+ msecs_to_jiffies(20);
break;
case USB_PORT_FEAT_C_SUSPEND:
clear_bit(wIndex, &ehci->port_c_suspend);
break;
case USB_PORT_FEAT_POWER:
if (HCS_PPC (ehci->hcs_params))
ehci_writel(ehci,
temp & ~(PORT_RWC_BITS | PORT_POWER),
status_reg);
break;
case USB_PORT_FEAT_C_CONNECTION:
if (ehci->has_lpm) {
/* clear PORTSC bits on disconnect */
temp &= ~PORT_LPM;
temp &= ~PORT_DEV_ADDR;
}
ehci_writel(ehci, (temp & ~PORT_RWC_BITS) | PORT_CSC,
status_reg);
break;
case USB_PORT_FEAT_C_OVER_CURRENT:
ehci_writel(ehci, (temp & ~PORT_RWC_BITS) | PORT_OCC,
status_reg);
break;
case USB_PORT_FEAT_C_RESET:
/* GetPortStatus clears reset */
break;
default:
goto error;
}
ehci_readl(ehci, &ehci->regs->command); /* unblock posted write */
break;
case GetHubDescriptor:
ehci_hub_descriptor (ehci, (struct usb_hub_descriptor *)
buf);
break;
case GetHubStatus:
/* no hub-wide feature/status flags */
memset (buf, 0, 4);
//cpu_to_le32s ((u32 *) buf);
break;
case GetPortStatus:
if (!wIndex || wIndex > ports)
goto error;
wIndex--;
status = 0;
temp = ehci_readl(ehci, status_reg);
// wPortChange bits
if (temp & PORT_CSC)
status |= USB_PORT_STAT_C_CONNECTION << 16;
if (temp & PORT_PEC)
status |= USB_PORT_STAT_C_ENABLE << 16;
if ((temp & PORT_OCC) && !ignore_oc){
status |= USB_PORT_STAT_C_OVERCURRENT << 16;
/*
* Hubs should disable port power on over-current.
* However, not all EHCI implementations do this
* automatically, even if they _do_ support per-port
* power switching; they're allowed to just limit the
* current. khubd will turn the power back on.
*/
if ((temp & PORT_OC) && HCS_PPC(ehci->hcs_params)) {
ehci_writel(ehci,
temp & ~(PORT_RWC_BITS | PORT_POWER),
status_reg);
temp = ehci_readl(ehci, status_reg);
}
}
/* whoever resumes must GetPortStatus to complete it!! */
if (temp & PORT_RESUME) {
/* Remote Wakeup received? */
if (!ehci->reset_done[wIndex]) {
/* resume signaling for 20 msec */
ehci->reset_done[wIndex] = jiffies
+ msecs_to_jiffies(20);
/* check the port again */
mod_timer(&ehci_to_hcd(ehci)->rh_timer,
ehci->reset_done[wIndex]);
}
/* resume completed? */
else if (time_after_eq(jiffies,
ehci->reset_done[wIndex])) {
clear_bit(wIndex, &ehci->suspended_ports);
set_bit(wIndex, &ehci->port_c_suspend);
ehci->reset_done[wIndex] = 0;
/* stop resume signaling */
temp = ehci_readl(ehci, status_reg);
ehci_writel(ehci,
temp & ~(PORT_RWC_BITS | PORT_RESUME),
status_reg);
retval = handshake(ehci, status_reg,
PORT_RESUME, 0, 2000 /* 2msec */);
if (retval != 0) {
ehci_err(ehci,
"port %d resume error %d\n",
wIndex + 1, retval);
goto error;
}
temp &= ~(PORT_SUSPEND|PORT_RESUME|(3<<10));
}
}
/* whoever resets must GetPortStatus to complete it!! */
if ((temp & PORT_RESET)
&& time_after_eq(jiffies,
ehci->reset_done[wIndex])) {
status |= USB_PORT_STAT_C_RESET << 16;
ehci->reset_done [wIndex] = 0;
/* force reset to complete */
ehci_writel(ehci, temp & ~(PORT_RWC_BITS | PORT_RESET),
status_reg);
/* REVISIT: some hardware needs 550+ usec to clear
* this bit; seems too long to spin routinely...
*/
retval = handshake(ehci, status_reg,
PORT_RESET, 0, 1000);
if (retval != 0) {
ehci_err (ehci, "port %d reset error %d\n",
wIndex + 1, retval);
goto error;
}
/* see what we found out */
temp = check_reset_complete (ehci, wIndex, status_reg,
ehci_readl(ehci, status_reg));
}
if (!(temp & (PORT_RESUME|PORT_RESET)))
ehci->reset_done[wIndex] = 0;
/* transfer dedicated ports to the companion hc */
if ((temp & PORT_CONNECT) &&
test_bit(wIndex, &ehci->companion_ports)) {
temp &= ~PORT_RWC_BITS;
temp |= PORT_OWNER;
ehci_writel(ehci, temp, status_reg);
ehci_dbg(ehci, "port %d --> companion\n", wIndex + 1);
temp = ehci_readl(ehci, status_reg);
}
/*
* Even if OWNER is set, there's no harm letting khubd
* see the wPortStatus values (they should all be 0 except
* for PORT_POWER anyway).
*/
if (temp & PORT_CONNECT) {
status |= USB_PORT_STAT_CONNECTION;
// status may be from integrated TT
if (ehci->has_hostpc) {
temp1 = ehci_readl(ehci, hostpc_reg);
status |= ehci_port_speed(ehci, temp1);
} else
status |= ehci_port_speed(ehci, temp);
}
if (temp & PORT_PE)
status |= USB_PORT_STAT_ENABLE;
/* maybe the port was unsuspended without our knowledge */
if (temp & (PORT_SUSPEND|PORT_RESUME)) {
status |= USB_PORT_STAT_SUSPEND;
} else if (test_bit(wIndex, &ehci->suspended_ports)) {
clear_bit(wIndex, &ehci->suspended_ports);
ehci->reset_done[wIndex] = 0;
if (temp & PORT_PE)
set_bit(wIndex, &ehci->port_c_suspend);
}
if (temp & PORT_OC)
status |= USB_PORT_STAT_OVERCURRENT;
if (temp & PORT_RESET)
status |= USB_PORT_STAT_RESET;
if (temp & PORT_POWER)
status |= USB_PORT_STAT_POWER;
if (test_bit(wIndex, &ehci->port_c_suspend))
status |= USB_PORT_STAT_C_SUSPEND << 16;
#ifndef VERBOSE_DEBUG
if (status & ~0xffff) /* only if wPortChange is interesting */
#endif
dbg_port (ehci, "GetStatus", wIndex + 1, temp);
put_unaligned_le32(status, buf);
break;
case SetHubFeature:
switch (wValue) {
case C_HUB_LOCAL_POWER:
case C_HUB_OVER_CURRENT:
/* no hub-wide feature/status flags */
break;
default:
goto error;
}
break;
case SetPortFeature:
selector = wIndex >> 8;
wIndex &= 0xff;
if (unlikely(ehci->debug)) {
/* If the debug port is active any port
* feature requests should get denied */
if (wIndex == HCS_DEBUG_PORT(ehci->hcs_params) &&
(readl(&ehci->debug->control) & DBGP_ENABLED)) {
retval = -ENODEV;
goto error_exit;
}
}
if (!wIndex || wIndex > ports)
goto error;
wIndex--;
temp = ehci_readl(ehci, status_reg);
if (temp & PORT_OWNER)
break;
temp &= ~PORT_RWC_BITS;
switch (wValue) {
case USB_PORT_FEAT_SUSPEND:
if (ehci->no_selective_suspend)
break;
if ((temp & PORT_PE) == 0
|| (temp & PORT_RESET) != 0)
goto error;
ehci_writel(ehci, temp | PORT_SUSPEND, status_reg);
#ifdef CONFIG_USB_OTG
if (hcd->self.otg_port == (wIndex + 1) &&
hcd->self.b_hnp_enable &&
ehci->start_hnp) {
set_bit(wIndex, &ehci->suspended_ports);
ehci->start_hnp(ehci);
break;
}
#endif
/* After above check the port must be connected.
* Set appropriate bit thus could put phy into low power
* mode if we have hostpc feature
*/
temp &= ~PORT_WKCONN_E;
temp |= PORT_WKDISC_E | PORT_WKOC_E;
ehci_writel(ehci, temp | PORT_SUSPEND, status_reg);
if (hostpc_reg) {
spin_unlock_irqrestore(&ehci->lock, flags);
msleep(5);/* 5ms for HCD enter low pwr mode */
spin_lock_irqsave(&ehci->lock, flags);
temp1 = ehci_readl(ehci, hostpc_reg);
ehci_writel(ehci, temp1 | HOSTPC_PHCD,
hostpc_reg);
temp1 = ehci_readl(ehci, hostpc_reg);
ehci_dbg(ehci, "Port%d phy low pwr mode %s\n",
wIndex, (temp1 & HOSTPC_PHCD) ?
"succeeded" : "failed");
}
set_bit(wIndex, &ehci->suspended_ports);
break;
case USB_PORT_FEAT_POWER:
if (HCS_PPC (ehci->hcs_params))
ehci_writel(ehci, temp | PORT_POWER,
status_reg);
break;
case USB_PORT_FEAT_RESET:
if (temp & PORT_RESUME)
goto error;
/* line status bits may report this as low speed,
* which can be fine if this root hub has a
* transaction translator built in.
*/
if ((temp & (PORT_PE|PORT_CONNECT)) == PORT_CONNECT
&& !ehci_is_TDI(ehci)
&& PORT_USB11 (temp)) {
ehci_dbg (ehci,
"port %d low speed --> companion\n",
wIndex + 1);
temp |= PORT_OWNER;
} else {
ehci_vdbg (ehci, "port %d reset\n", wIndex + 1);
temp |= PORT_RESET;
temp &= ~PORT_PE;
/*
* caller must wait, then call GetPortStatus
* usb 2.0 spec says 50 ms resets on root
*/
ehci->reset_done [wIndex] = jiffies
+ msecs_to_jiffies (50);
}
ehci_writel(ehci, temp, status_reg);
break;
/* For downstream facing ports (these): one hub port is put
* into test mode according to USB2 11.24.2.13, then the hub
* must be reset (which for root hub now means rmmod+modprobe,
* or else system reboot). See EHCI 2.3.9 and 4.14 for info
* about the EHCI-specific stuff.
*/
case USB_PORT_FEAT_TEST:
if (selector && selector <= 5) {
ehci_quiesce(ehci);
ehci_halt(ehci);
temp |= selector << 16;
ehci_writel(ehci, temp, status_reg);
}
#ifdef CONFIG_USB_EHCI_EHSET
else if (selector
== EHSET_TEST_SINGLE_STEP_SET_FEATURE) {
spin_unlock_irqrestore(&ehci->lock, flags);
retval = ehset_single_step_set_feature(hcd,
wIndex);
spin_lock_irqsave(&ehci->lock, flags);
}
#endif
else
goto error;
break;
default:
goto error;
}
ehci_readl(ehci, &ehci->regs->command); /* unblock posted writes */
break;
default:
error:
/* "stall" on error */
retval = -EPIPE;
}
error_exit:
spin_unlock_irqrestore (&ehci->lock, flags);
return retval;
}
static void ehci_relinquish_port(struct usb_hcd *hcd, int portnum)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
if (ehci_is_TDI(ehci))
return;
set_owner(ehci, --portnum, PORT_OWNER);
}
static int __maybe_unused ehci_port_handed_over(struct usb_hcd *hcd, int portnum)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
u32 __iomem *reg;
if (ehci_is_TDI(ehci))
return 0;
reg = &ehci->regs->port_status[portnum - 1];
return ehci_readl(ehci, reg) & PORT_OWNER;
}
| gpl-2.0 |
oskarpearson/linux | drivers/staging/xgifb/vb_setmode.c | 586 | 145342 | #include <linux/delay.h>
#include "XGIfb.h"
#include "vb_def.h"
#include "vb_init.h"
#include "vb_util.h"
#include "vb_table.h"
#include "vb_setmode.h"
#define IndexMask 0xff
#define TVCLKBASE_315_25 (TVCLKBASE_315 + 25)
static const unsigned short XGINew_VGA_DAC[] = {
0x00, 0x10, 0x04, 0x14, 0x01, 0x11, 0x09, 0x15,
0x2A, 0x3A, 0x2E, 0x3E, 0x2B, 0x3B, 0x2F, 0x3F,
0x00, 0x05, 0x08, 0x0B, 0x0E, 0x11, 0x14, 0x18,
0x1C, 0x20, 0x24, 0x28, 0x2D, 0x32, 0x38, 0x3F,
0x00, 0x10, 0x1F, 0x2F, 0x3F, 0x1F, 0x27, 0x2F,
0x37, 0x3F, 0x2D, 0x31, 0x36, 0x3A, 0x3F, 0x00,
0x07, 0x0E, 0x15, 0x1C, 0x0E, 0x11, 0x15, 0x18,
0x1C, 0x14, 0x16, 0x18, 0x1A, 0x1C, 0x00, 0x04,
0x08, 0x0C, 0x10, 0x08, 0x0A, 0x0C, 0x0E, 0x10,
0x0B, 0x0C, 0x0D, 0x0F, 0x10};
void InitTo330Pointer(unsigned char ChipType, struct vb_device_info *pVBInfo)
{
pVBInfo->MCLKData = XGI340New_MCLKData;
pVBInfo->LCDResInfo = 0;
pVBInfo->LCDTypeInfo = 0;
pVBInfo->LCDInfo = 0;
pVBInfo->VBInfo = 0;
pVBInfo->TVInfo = 0;
pVBInfo->SR18 = XGI340_SR18;
pVBInfo->CR40 = XGI340_cr41;
if (ChipType < XG20)
XGI_GetVBType(pVBInfo);
/* 310 customization related */
if ((pVBInfo->VBType & VB_SIS301LV) || (pVBInfo->VBType & VB_SIS302LV))
pVBInfo->LCDCapList = XGI_LCDDLCapList;
else
pVBInfo->LCDCapList = XGI_LCDCapList;
if (ChipType >= XG20)
pVBInfo->XGINew_CR97 = 0x10;
if (ChipType == XG27) {
unsigned char temp;
pVBInfo->MCLKData = XGI27New_MCLKData;
pVBInfo->CR40 = XGI27_cr41;
pVBInfo->XGINew_CR97 = 0xc1;
pVBInfo->SR18 = XG27_SR18;
/*Z11m DDR*/
temp = xgifb_reg_get(pVBInfo->P3c4, 0x3B);
/* SR3B[7][3]MAA15 MAA11 (Power on Trapping) */
if (((temp & 0x88) == 0x80) || ((temp & 0x88) == 0x08))
pVBInfo->XGINew_CR97 = 0x80;
}
}
static void XGI_SetSeqRegs(struct vb_device_info *pVBInfo)
{
unsigned char SRdata, i;
xgifb_reg_set(pVBInfo->P3c4, 0x00, 0x03); /* Set SR0 */
for (i = 0; i < 4; i++) {
/* Get SR1,2,3,4 from file */
/* SR1 is with screen off 0x20 */
SRdata = XGI330_StandTable.SR[i];
xgifb_reg_set(pVBInfo->P3c4, i+1, SRdata); /* Set SR 1 2 3 4 */
}
}
static void XGI_SetCRTCRegs(struct vb_device_info *pVBInfo)
{
unsigned char CRTCdata;
unsigned short i;
CRTCdata = xgifb_reg_get(pVBInfo->P3d4, 0x11);
CRTCdata &= 0x7f;
xgifb_reg_set(pVBInfo->P3d4, 0x11, CRTCdata); /* Unlock CRTC */
for (i = 0; i <= 0x18; i++) {
/* Get CRTC from file */
CRTCdata = XGI330_StandTable.CRTC[i];
xgifb_reg_set(pVBInfo->P3d4, i, CRTCdata); /* Set CRTC(3d4) */
}
}
static void XGI_SetATTRegs(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned char ARdata;
unsigned short i, modeflag;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
for (i = 0; i <= 0x13; i++) {
ARdata = XGI330_StandTable.ATTR[i];
if ((modeflag & Charx8Dot) && i == 0x13) { /* ifndef Dot9 */
if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA) {
ARdata = 0;
} else if ((pVBInfo->VBInfo &
(SetCRT2ToTV | SetCRT2ToLCD)) &&
(pVBInfo->VBInfo & SetInSlaveMode)) {
ARdata = 0;
}
}
inb(pVBInfo->P3da); /* reset 3da */
outb(i, pVBInfo->P3c0); /* set index */
outb(ARdata, pVBInfo->P3c0); /* set data */
}
inb(pVBInfo->P3da); /* reset 3da */
outb(0x14, pVBInfo->P3c0); /* set index */
outb(0x00, pVBInfo->P3c0); /* set data */
inb(pVBInfo->P3da); /* Enable Attribute */
outb(0x20, pVBInfo->P3c0);
}
static void XGI_SetGRCRegs(struct vb_device_info *pVBInfo)
{
unsigned char GRdata;
unsigned short i;
for (i = 0; i <= 0x08; i++) {
/* Get GR from file */
GRdata = XGI330_StandTable.GRC[i];
xgifb_reg_set(pVBInfo->P3ce, i, GRdata); /* Set GR(3ce) */
}
if (pVBInfo->ModeType > ModeVGA) {
GRdata = xgifb_reg_get(pVBInfo->P3ce, 0x05);
GRdata &= 0xBF; /* 256 color disable */
xgifb_reg_set(pVBInfo->P3ce, 0x05, GRdata);
}
}
static void XGI_ClearExt1Regs(struct vb_device_info *pVBInfo)
{
unsigned short i;
for (i = 0x0A; i <= 0x0E; i++)
xgifb_reg_set(pVBInfo->P3c4, i, 0x00); /* Clear SR0A-SR0E */
}
static unsigned char XGI_SetDefaultVCLK(struct vb_device_info *pVBInfo)
{
xgifb_reg_and_or(pVBInfo->P3c4, 0x31, ~0x30, 0x20);
xgifb_reg_set(pVBInfo->P3c4, 0x2B, XGI_VCLKData[0].SR2B);
xgifb_reg_set(pVBInfo->P3c4, 0x2C, XGI_VCLKData[0].SR2C);
xgifb_reg_and_or(pVBInfo->P3c4, 0x31, ~0x30, 0x10);
xgifb_reg_set(pVBInfo->P3c4, 0x2B, XGI_VCLKData[1].SR2B);
xgifb_reg_set(pVBInfo->P3c4, 0x2C, XGI_VCLKData[1].SR2C);
xgifb_reg_and(pVBInfo->P3c4, 0x31, ~0x30);
return 0;
}
static unsigned char XGI_AjustCRT2Rate(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex, unsigned short *i,
struct vb_device_info *pVBInfo)
{
unsigned short tempax, tempbx, resinfo, modeflag, infoflag;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
resinfo = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
tempbx = XGI330_RefIndex[RefreshRateTableIndex + (*i)].ModeID;
tempax = 0;
if (pVBInfo->VBInfo & SetCRT2ToRAMDAC) {
tempax |= SupportRAMDAC2;
if (pVBInfo->VBType & VB_XGI301C)
tempax |= SupportCRT2in301C;
}
/* 301b */
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)) {
tempax |= SupportLCD;
if (pVBInfo->LCDResInfo != Panel_1280x1024 &&
pVBInfo->LCDResInfo != Panel_1280x960 &&
(pVBInfo->LCDInfo & LCDNonExpanding) &&
resinfo >= 9)
return 0;
}
if (pVBInfo->VBInfo & SetCRT2ToHiVision) { /* for HiTV */
tempax |= SupportHiVision;
if ((pVBInfo->VBInfo & SetInSlaveMode) &&
((resinfo == 4) ||
(resinfo == 3 && (pVBInfo->SetFlag & TVSimuMode)) ||
(resinfo > 7)))
return 0;
} else if (pVBInfo->VBInfo & (SetCRT2ToAVIDEO | SetCRT2ToSVIDEO |
SetCRT2ToSCART | SetCRT2ToYPbPr525750 |
SetCRT2ToHiVision)) {
tempax |= SupportTV;
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV |
VB_SIS302LV | VB_XGI301C))
tempax |= SupportTV1024;
if (!(pVBInfo->VBInfo & TVSetPAL) &&
(modeflag & NoSupportSimuTV) &&
(pVBInfo->VBInfo & SetInSlaveMode) &&
(!(pVBInfo->VBInfo & SetNotSimuMode)))
return 0;
}
for (; XGI330_RefIndex[RefreshRateTableIndex + (*i)].ModeID ==
tempbx; (*i)--) {
infoflag = XGI330_RefIndex[RefreshRateTableIndex + (*i)].
Ext_InfoFlag;
if (infoflag & tempax)
return 1;
if ((*i) == 0)
break;
}
for ((*i) = 0;; (*i)++) {
infoflag = XGI330_RefIndex[RefreshRateTableIndex + (*i)].
Ext_InfoFlag;
if (XGI330_RefIndex[RefreshRateTableIndex + (*i)].ModeID
!= tempbx) {
return 0;
}
if (infoflag & tempax)
return 1;
}
return 1;
}
static void XGI_SetSync(unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short sync, temp;
/* di+0x00 */
sync = XGI330_RefIndex[RefreshRateTableIndex].Ext_InfoFlag >> 8;
sync &= 0xC0;
temp = 0x2F;
temp |= sync;
outb(temp, pVBInfo->P3c2); /* Set Misc(3c2) */
}
static void XGI_SetCRT1Timing_H(struct vb_device_info *pVBInfo,
struct xgi_hw_device_info *HwDeviceExtension)
{
unsigned char data, data1, pushax;
unsigned short i, j;
/* unlock cr0-7 */
data = xgifb_reg_get(pVBInfo->P3d4, 0x11);
data &= 0x7F;
xgifb_reg_set(pVBInfo->P3d4, 0x11, data);
data = pVBInfo->TimingH.data[0];
xgifb_reg_set(pVBInfo->P3d4, 0, data);
for (i = 0x01; i <= 0x04; i++) {
data = pVBInfo->TimingH.data[i];
xgifb_reg_set(pVBInfo->P3d4, (unsigned short) (i + 1), data);
}
for (i = 0x05; i <= 0x06; i++) {
data = pVBInfo->TimingH.data[i];
xgifb_reg_set(pVBInfo->P3c4, (unsigned short) (i + 6), data);
}
j = xgifb_reg_get(pVBInfo->P3c4, 0x0e);
j &= 0x1F;
data = pVBInfo->TimingH.data[7];
data &= 0xE0;
data |= j;
xgifb_reg_set(pVBInfo->P3c4, 0x0e, data);
if (HwDeviceExtension->jChipType >= XG20) {
data = xgifb_reg_get(pVBInfo->P3d4, 0x04);
data = data - 1;
xgifb_reg_set(pVBInfo->P3d4, 0x04, data);
data = xgifb_reg_get(pVBInfo->P3d4, 0x05);
data1 = data;
data1 &= 0xE0;
data &= 0x1F;
if (data == 0) {
pushax = data;
data = xgifb_reg_get(pVBInfo->P3c4, 0x0c);
data &= 0xFB;
xgifb_reg_set(pVBInfo->P3c4, 0x0c, data);
data = pushax;
}
data = data - 1;
data |= data1;
xgifb_reg_set(pVBInfo->P3d4, 0x05, data);
data = xgifb_reg_get(pVBInfo->P3c4, 0x0e);
data >>= 5;
data = data + 3;
if (data > 7)
data = data - 7;
data <<= 5;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0e, ~0xE0, data);
}
}
static void XGI_SetCRT1Timing_V(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned char data;
unsigned short i, j;
for (i = 0x00; i <= 0x01; i++) {
data = pVBInfo->TimingV.data[i];
xgifb_reg_set(pVBInfo->P3d4, (unsigned short) (i + 6), data);
}
for (i = 0x02; i <= 0x03; i++) {
data = pVBInfo->TimingV.data[i];
xgifb_reg_set(pVBInfo->P3d4, (unsigned short) (i + 0x0e), data);
}
for (i = 0x04; i <= 0x05; i++) {
data = pVBInfo->TimingV.data[i];
xgifb_reg_set(pVBInfo->P3d4, (unsigned short) (i + 0x11), data);
}
j = xgifb_reg_get(pVBInfo->P3c4, 0x0a);
j &= 0xC0;
data = pVBInfo->TimingV.data[6];
data &= 0x3F;
data |= j;
xgifb_reg_set(pVBInfo->P3c4, 0x0a, data);
data = pVBInfo->TimingV.data[6];
data &= 0x80;
data >>= 2;
i = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
i &= DoubleScanMode;
if (i)
data |= 0x80;
j = xgifb_reg_get(pVBInfo->P3d4, 0x09);
j &= 0x5F;
data |= j;
xgifb_reg_set(pVBInfo->P3d4, 0x09, data);
}
static void XGI_SetCRT1CRTC(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo,
struct xgi_hw_device_info *HwDeviceExtension)
{
unsigned char index, data;
unsigned short i;
/* Get index */
index = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRT1CRTC;
index = index & IndexMask;
data = xgifb_reg_get(pVBInfo->P3d4, 0x11);
data &= 0x7F;
xgifb_reg_set(pVBInfo->P3d4, 0x11, data); /* Unlock CRTC */
for (i = 0; i < 8; i++)
pVBInfo->TimingH.data[i]
= XGI_CRT1Table[index].CR[i];
for (i = 0; i < 7; i++)
pVBInfo->TimingV.data[i]
= XGI_CRT1Table[index].CR[i + 8];
XGI_SetCRT1Timing_H(pVBInfo, HwDeviceExtension);
XGI_SetCRT1Timing_V(ModeIdIndex, pVBInfo);
if (pVBInfo->ModeType > 0x03)
xgifb_reg_set(pVBInfo->P3d4, 0x14, 0x4F);
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetXG21CRTC */
/* Input : Stand or enhance CRTC table */
/* Output : Fill CRT Hsync/Vsync to SR2E/SR2F/SR30/SR33/SR34/SR3F */
/* Description : Set LCD timing */
/* --------------------------------------------------------------------- */
static void XGI_SetXG21CRTC(unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned char index, Tempax, Tempbx, Tempcx, Tempdx;
unsigned short Temp1, Temp2, Temp3;
index = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRT1CRTC;
/* Tempax: CR4 HRS */
Tempax = XGI_CRT1Table[index].CR[3];
Tempcx = Tempax; /* Tempcx: HRS */
/* SR2E[7:0]->HRS */
xgifb_reg_set(pVBInfo->P3c4, 0x2E, Tempax);
Tempdx = XGI_CRT1Table[index].CR[5]; /* SRB */
Tempdx &= 0xC0; /* Tempdx[7:6]: SRB[7:6] */
Temp1 = Tempdx; /* Temp1[7:6]: HRS[9:8] */
Temp1 <<= 2; /* Temp1[9:8]: HRS[9:8] */
Temp1 |= Tempax; /* Temp1[9:0]: HRS[9:0] */
Tempax = XGI_CRT1Table[index].CR[4]; /* CR5 HRE */
Tempax &= 0x1F; /* Tempax[4:0]: HRE[4:0] */
Tempbx = XGI_CRT1Table[index].CR[6]; /* SRC */
Tempbx &= 0x04; /* Tempbx[2]: HRE[5] */
Tempbx <<= 3; /* Tempbx[5]: HRE[5] */
Tempax |= Tempbx; /* Tempax[5:0]: HRE[5:0] */
Temp2 = Temp1 & 0x3C0; /* Temp2[9:6]: HRS[9:6] */
Temp2 |= Tempax; /* Temp2[9:0]: HRE[9:0] */
Tempcx &= 0x3F; /* Tempcx[5:0]: HRS[5:0] */
if (Tempax < Tempcx) /* HRE < HRS */
Temp2 |= 0x40; /* Temp2 + 0x40 */
Temp2 &= 0xFF;
Tempax = (unsigned char) Temp2; /* Tempax: HRE[7:0] */
Tempax <<= 2; /* Tempax[7:2]: HRE[5:0] */
Tempdx >>= 6; /* Tempdx[7:6]->[1:0] HRS[9:8] */
Tempax |= Tempdx; /* HRE[5:0]HRS[9:8] */
/* SR2F D[7:2]->HRE, D[1:0]->HRS */
xgifb_reg_set(pVBInfo->P3c4, 0x2F, Tempax);
xgifb_reg_and_or(pVBInfo->P3c4, 0x30, 0xE3, 00);
/* CR10 VRS */
Tempax = XGI_CRT1Table[index].CR[10];
Tempbx = Tempax; /* Tempbx: VRS */
Tempax &= 0x01; /* Tempax[0]: VRS[0] */
xgifb_reg_or(pVBInfo->P3c4, 0x33, Tempax); /* SR33[0]->VRS[0] */
/* CR7[2][7] VRE */
Tempax = XGI_CRT1Table[index].CR[9];
Tempcx = Tempbx >> 1; /* Tempcx[6:0]: VRS[7:1] */
Tempdx = Tempax & 0x04; /* Tempdx[2]: CR7[2] */
Tempdx <<= 5; /* Tempdx[7]: VRS[8] */
Tempcx |= Tempdx; /* Tempcx[7:0]: VRS[8:1] */
xgifb_reg_set(pVBInfo->P3c4, 0x34, Tempcx); /* SR34[8:1]->VRS */
Temp1 = Tempdx; /* Temp1[7]: Tempdx[7] */
Temp1 <<= 1; /* Temp1[8]: VRS[8] */
Temp1 |= Tempbx; /* Temp1[8:0]: VRS[8:0] */
Tempax &= 0x80;
Temp2 = Tempax << 2; /* Temp2[9]: VRS[9] */
Temp1 |= Temp2; /* Temp1[9:0]: VRS[9:0] */
/* Tempax: SRA */
Tempax = XGI_CRT1Table[index].CR[14];
Tempax &= 0x08; /* Tempax[3]: VRS[3] */
Temp2 = Tempax;
Temp2 <<= 7; /* Temp2[10]: VRS[10] */
Temp1 |= Temp2; /* Temp1[10:0]: VRS[10:0] */
/* Tempax: CR11 VRE */
Tempax = XGI_CRT1Table[index].CR[11];
Tempax &= 0x0F; /* Tempax[3:0]: VRE[3:0] */
/* Tempbx: SRA */
Tempbx = XGI_CRT1Table[index].CR[14];
Tempbx &= 0x20; /* Tempbx[5]: VRE[5] */
Tempbx >>= 1; /* Tempbx[4]: VRE[4] */
Tempax |= Tempbx; /* Tempax[4:0]: VRE[4:0] */
Temp2 = Temp1 & 0x7E0; /* Temp2[10:5]: VRS[10:5] */
Temp2 |= Tempax; /* Temp2[10:5]: VRE[10:5] */
Temp3 = Temp1 & 0x1F; /* Temp3[4:0]: VRS[4:0] */
if (Tempax < Temp3) /* VRE < VRS */
Temp2 |= 0x20; /* VRE + 0x20 */
Temp2 &= 0xFF;
Tempax = (unsigned char) Temp2; /* Tempax: VRE[7:0] */
Tempax <<= 2; /* Tempax[7:0]; VRE[5:0]00 */
Temp1 &= 0x600; /* Temp1[10:9]: VRS[10:9] */
Temp1 >>= 9; /* Temp1[1:0]: VRS[10:9] */
Tempbx = (unsigned char) Temp1;
Tempax |= Tempbx; /* Tempax[7:0]: VRE[5:0]VRS[10:9] */
Tempax &= 0x7F;
/* SR3F D[7:2]->VRE D[1:0]->VRS */
xgifb_reg_set(pVBInfo->P3c4, 0x3F, Tempax);
}
static void XGI_SetXG27CRTC(unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short index, Tempax, Tempbx, Tempcx;
index = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRT1CRTC;
/* Tempax: CR4 HRS */
Tempax = XGI_CRT1Table[index].CR[3];
Tempbx = Tempax; /* Tempbx: HRS[7:0] */
/* SR2E[7:0]->HRS */
xgifb_reg_set(pVBInfo->P3c4, 0x2E, Tempax);
/* SR0B */
Tempax = XGI_CRT1Table[index].CR[5];
Tempax &= 0xC0; /* Tempax[7:6]: SR0B[7:6]: HRS[9:8]*/
Tempbx |= (Tempax << 2); /* Tempbx: HRS[9:0] */
Tempax = XGI_CRT1Table[index].CR[4]; /* CR5 HRE */
Tempax &= 0x1F; /* Tempax[4:0]: HRE[4:0] */
Tempcx = Tempax; /* Tempcx: HRE[4:0] */
Tempax = XGI_CRT1Table[index].CR[6]; /* SRC */
Tempax &= 0x04; /* Tempax[2]: HRE[5] */
Tempax <<= 3; /* Tempax[5]: HRE[5] */
Tempcx |= Tempax; /* Tempcx[5:0]: HRE[5:0] */
Tempbx = Tempbx & 0x3C0; /* Tempbx[9:6]: HRS[9:6] */
Tempbx |= Tempcx; /* Tempbx: HRS[9:6]HRE[5:0] */
/* Tempax: CR4 HRS */
Tempax = XGI_CRT1Table[index].CR[3];
Tempax &= 0x3F; /* Tempax: HRS[5:0] */
if (Tempcx <= Tempax) /* HRE[5:0] < HRS[5:0] */
Tempbx += 0x40; /* Tempbx= Tempbx + 0x40 : HRE[9:0]*/
Tempax = XGI_CRT1Table[index].CR[5]; /* SR0B */
Tempax &= 0xC0; /* Tempax[7:6]: SR0B[7:6]: HRS[9:8]*/
Tempax >>= 6; /* Tempax[1:0]: HRS[9:8]*/
Tempax |= ((Tempbx << 2) & 0xFF); /* Tempax[7:2]: HRE[5:0] */
/* SR2F [7:2][1:0]: HRE[5:0]HRS[9:8] */
xgifb_reg_set(pVBInfo->P3c4, 0x2F, Tempax);
xgifb_reg_and_or(pVBInfo->P3c4, 0x30, 0xE3, 00);
/* CR10 VRS */
Tempax = XGI_CRT1Table[index].CR[10];
/* SR34[7:0]->VRS[7:0] */
xgifb_reg_set(pVBInfo->P3c4, 0x34, Tempax);
Tempcx = Tempax; /* Tempcx <= VRS[7:0] */
/* CR7[7][2] VRS[9][8] */
Tempax = XGI_CRT1Table[index].CR[9];
Tempbx = Tempax; /* Tempbx <= CR07[7:0] */
Tempax = Tempax & 0x04; /* Tempax[2]: CR7[2]: VRS[8] */
Tempax >>= 2; /* Tempax[0]: VRS[8] */
/* SR35[0]: VRS[8] */
xgifb_reg_and_or(pVBInfo->P3c4, 0x35, ~0x01, Tempax);
Tempcx |= (Tempax << 8); /* Tempcx <= VRS[8:0] */
Tempcx |= ((Tempbx & 0x80) << 2); /* Tempcx <= VRS[9:0] */
/* Tempax: SR0A */
Tempax = XGI_CRT1Table[index].CR[14];
Tempax &= 0x08; /* SR0A[3] VRS[10] */
Tempcx |= (Tempax << 7); /* Tempcx <= VRS[10:0] */
/* Tempax: CR11 VRE */
Tempax = XGI_CRT1Table[index].CR[11];
Tempax &= 0x0F; /* Tempax[3:0]: VRE[3:0] */
/* Tempbx: SR0A */
Tempbx = XGI_CRT1Table[index].CR[14];
Tempbx &= 0x20; /* Tempbx[5]: SR0A[5]: VRE[4] */
Tempbx >>= 1; /* Tempbx[4]: VRE[4] */
Tempax |= Tempbx; /* Tempax[4:0]: VRE[4:0] */
Tempbx = Tempcx; /* Tempbx: VRS[10:0] */
Tempbx &= 0x7E0; /* Tempbx[10:5]: VRS[10:5] */
Tempbx |= Tempax; /* Tempbx: VRS[10:5]VRE[4:0] */
if (Tempbx <= Tempcx) /* VRE <= VRS */
Tempbx |= 0x20; /* VRE + 0x20 */
/* Tempax: Tempax[7:0]; VRE[5:0]00 */
Tempax = (Tempbx << 2) & 0xFF;
/* SR3F[7:2]:VRE[5:0] */
xgifb_reg_and_or(pVBInfo->P3c4, 0x3F, ~0xFC, Tempax);
Tempax = Tempcx >> 8;
/* SR35[2:0]:VRS[10:8] */
xgifb_reg_and_or(pVBInfo->P3c4, 0x35, ~0x07, Tempax);
}
static void XGI_SetXG27FPBits(struct vb_device_info *pVBInfo)
{
unsigned char temp;
/* D[1:0] 01: 18bit, 00: dual 12, 10: single 24 */
temp = xgifb_reg_get(pVBInfo->P3d4, 0x37);
temp = (temp & 3) << 6;
/* SR06[7]0: dual 12/1: single 24 [6] 18bit Dither <= 0 h/w recommend */
xgifb_reg_and_or(pVBInfo->P3c4, 0x06, ~0xc0, temp & 0x80);
/* SR09[7] enable FP output, SR09[6] 1: sigle 18bits, 0: 24bits */
xgifb_reg_and_or(pVBInfo->P3c4, 0x09, ~0xc0, temp | 0x80);
}
static void xgifb_set_lcd(int chip_id,
struct vb_device_info *pVBInfo,
unsigned short RefreshRateTableIndex)
{
unsigned short temp;
xgifb_reg_set(pVBInfo->P3d4, 0x2E, 0x00);
xgifb_reg_set(pVBInfo->P3d4, 0x2F, 0x00);
xgifb_reg_set(pVBInfo->P3d4, 0x46, 0x00);
xgifb_reg_set(pVBInfo->P3d4, 0x47, 0x00);
if (chip_id == XG27) {
temp = xgifb_reg_get(pVBInfo->P3d4, 0x37);
if ((temp & 0x03) == 0) { /* dual 12 */
xgifb_reg_set(pVBInfo->P3d4, 0x46, 0x13);
xgifb_reg_set(pVBInfo->P3d4, 0x47, 0x13);
}
}
if (chip_id == XG27) {
XGI_SetXG27FPBits(pVBInfo);
} else {
temp = xgifb_reg_get(pVBInfo->P3d4, 0x37);
if (temp & 0x01) {
/* 18 bits FP */
xgifb_reg_or(pVBInfo->P3c4, 0x06, 0x40);
xgifb_reg_or(pVBInfo->P3c4, 0x09, 0x40);
}
}
xgifb_reg_or(pVBInfo->P3c4, 0x1E, 0x01); /* Negative blank polarity */
xgifb_reg_and(pVBInfo->P3c4, 0x30, ~0x20); /* Hsync polarity */
xgifb_reg_and(pVBInfo->P3c4, 0x35, ~0x80); /* Vsync polarity */
temp = XGI330_RefIndex[RefreshRateTableIndex].Ext_InfoFlag;
if (temp & 0x4000)
/* Hsync polarity */
xgifb_reg_or(pVBInfo->P3c4, 0x30, 0x20);
if (temp & 0x8000)
/* Vsync polarity */
xgifb_reg_or(pVBInfo->P3c4, 0x35, 0x80);
}
/* --------------------------------------------------------------------- */
/* Function : XGI_UpdateXG21CRTC */
/* Input : */
/* Output : CRT1 CRTC */
/* Description : Modify CRT1 Hsync/Vsync to fix LCD mode timing */
/* --------------------------------------------------------------------- */
static void XGI_UpdateXG21CRTC(unsigned short ModeNo,
struct vb_device_info *pVBInfo,
unsigned short RefreshRateTableIndex)
{
int index = -1;
xgifb_reg_and(pVBInfo->P3d4, 0x11, 0x7F); /* Unlock CR0~7 */
if (ModeNo == 0x2E &&
(XGI330_RefIndex[RefreshRateTableIndex].Ext_CRT1CRTC ==
RES640x480x60))
index = 12;
else if (ModeNo == 0x2E && (XGI330_RefIndex[RefreshRateTableIndex].
Ext_CRT1CRTC == RES640x480x72))
index = 13;
else if (ModeNo == 0x2F)
index = 14;
else if (ModeNo == 0x50)
index = 15;
else if (ModeNo == 0x59)
index = 16;
if (index != -1) {
xgifb_reg_set(pVBInfo->P3d4, 0x02,
XGI_UpdateCRT1Table[index].CR02);
xgifb_reg_set(pVBInfo->P3d4, 0x03,
XGI_UpdateCRT1Table[index].CR03);
xgifb_reg_set(pVBInfo->P3d4, 0x15,
XGI_UpdateCRT1Table[index].CR15);
xgifb_reg_set(pVBInfo->P3d4, 0x16,
XGI_UpdateCRT1Table[index].CR16);
}
}
static void XGI_SetCRT1DE(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short resindex, tempax, tempbx, tempcx, temp, modeflag;
unsigned char data;
resindex = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
tempax = XGI330_ModeResInfo[resindex].HTotal;
tempbx = XGI330_ModeResInfo[resindex].VTotal;
if (modeflag & HalfDCLK)
tempax >>= 1;
if (modeflag & HalfDCLK)
tempax <<= 1;
temp = XGI330_RefIndex[RefreshRateTableIndex].Ext_InfoFlag;
if (temp & InterlaceMode)
tempbx >>= 1;
if (modeflag & DoubleScanMode)
tempbx <<= 1;
tempcx = 8;
tempax /= tempcx;
tempax -= 1;
tempbx -= 1;
tempcx = tempax;
temp = xgifb_reg_get(pVBInfo->P3d4, 0x11);
data = xgifb_reg_get(pVBInfo->P3d4, 0x11);
data &= 0x7F;
xgifb_reg_set(pVBInfo->P3d4, 0x11, data); /* Unlock CRTC */
xgifb_reg_set(pVBInfo->P3d4, 0x01, (unsigned short) (tempcx & 0xff));
xgifb_reg_and_or(pVBInfo->P3d4, 0x0b, ~0x0c,
(unsigned short) ((tempcx & 0x0ff00) >> 10));
xgifb_reg_set(pVBInfo->P3d4, 0x12, (unsigned short) (tempbx & 0xff));
tempax = 0;
tempbx >>= 8;
if (tempbx & 0x01)
tempax |= 0x02;
if (tempbx & 0x02)
tempax |= 0x40;
xgifb_reg_and_or(pVBInfo->P3d4, 0x07, ~0x42, tempax);
data = xgifb_reg_get(pVBInfo->P3d4, 0x07);
tempax = 0;
if (tempbx & 0x04)
tempax |= 0x02;
xgifb_reg_and_or(pVBInfo->P3d4, 0x0a, ~0x02, tempax);
xgifb_reg_set(pVBInfo->P3d4, 0x11, temp);
}
static void XGI_SetCRT1Offset(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short temp, ah, al, temp2, i, DisplayUnit;
/* GetOffset */
temp = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeInfo;
temp >>= 8;
temp = XGI330_ScreenOffset[temp];
temp2 = XGI330_RefIndex[RefreshRateTableIndex].Ext_InfoFlag;
temp2 &= InterlaceMode;
if (temp2)
temp <<= 1;
temp2 = pVBInfo->ModeType - ModeEGA;
switch (temp2) {
case 0:
temp2 = 1;
break;
case 1:
temp2 = 2;
break;
case 2:
temp2 = 4;
break;
case 3:
temp2 = 4;
break;
case 4:
temp2 = 6;
break;
case 5:
temp2 = 8;
break;
default:
break;
}
if ((ModeNo >= 0x26) && (ModeNo <= 0x28))
temp = temp * temp2 + temp2 / 2;
else
temp *= temp2;
/* SetOffset */
DisplayUnit = temp;
temp2 = temp;
temp >>= 8; /* ah */
temp &= 0x0F;
i = xgifb_reg_get(pVBInfo->P3c4, 0x0E);
i &= 0xF0;
i |= temp;
xgifb_reg_set(pVBInfo->P3c4, 0x0E, i);
temp = (unsigned char) temp2;
temp &= 0xFF; /* al */
xgifb_reg_set(pVBInfo->P3d4, 0x13, temp);
/* SetDisplayUnit */
temp2 = XGI330_RefIndex[RefreshRateTableIndex].Ext_InfoFlag;
temp2 &= InterlaceMode;
if (temp2)
DisplayUnit >>= 1;
DisplayUnit <<= 5;
ah = (DisplayUnit & 0xff00) >> 8;
al = DisplayUnit & 0x00ff;
if (al == 0)
ah += 1;
else
ah += 2;
if (HwDeviceExtension->jChipType >= XG20)
if ((ModeNo == 0x4A) | (ModeNo == 0x49))
ah -= 1;
xgifb_reg_set(pVBInfo->P3c4, 0x10, ah);
}
static unsigned short XGI_GetVCLK2Ptr(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short VCLKIndex, modeflag;
/* si+Ext_ResInfo */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)) { /*301b*/
if (pVBInfo->LCDResInfo != Panel_1024x768)
/* LCDXlat2VCLK */
VCLKIndex = VCLK108_2_315 + 5;
else
VCLKIndex = VCLK65_315 + 2; /* LCDXlat1VCLK */
} else if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
if (pVBInfo->SetFlag & RPLLDIV2XO)
VCLKIndex = TVCLKBASE_315_25 + HiTVVCLKDIV2;
else
VCLKIndex = TVCLKBASE_315_25 + HiTVVCLK;
if (pVBInfo->SetFlag & TVSimuMode) {
if (modeflag & Charx8Dot)
VCLKIndex = TVCLKBASE_315_25 + HiTVSimuVCLK;
else
VCLKIndex = TVCLKBASE_315_25 + HiTVTextVCLK;
}
/* 301lv */
if (pVBInfo->VBType & VB_SIS301LV) {
if (pVBInfo->SetFlag & RPLLDIV2XO)
VCLKIndex = YPbPr525iVCLK_2;
else
VCLKIndex = YPbPr525iVCLK;
}
} else if (pVBInfo->VBInfo & SetCRT2ToTV) {
if (pVBInfo->SetFlag & RPLLDIV2XO)
VCLKIndex = TVCLKBASE_315_25 + TVVCLKDIV2;
else
VCLKIndex = TVCLKBASE_315_25 + TVVCLK;
} else { /* for CRT2 */
/* di+Ext_CRTVCLK */
VCLKIndex = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRTVCLK;
VCLKIndex &= IndexMask;
}
return VCLKIndex;
}
static void XGI_SetCRT1VCLK(unsigned short ModeIdIndex,
struct xgi_hw_device_info *HwDeviceExtension,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned char index, data;
unsigned short vclkindex;
if ((pVBInfo->IF_DEF_LVDS == 0) &&
(pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV |
VB_SIS302LV | VB_XGI301C)) &&
(pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)) {
vclkindex = XGI_GetVCLK2Ptr(ModeIdIndex, RefreshRateTableIndex,
pVBInfo);
data = xgifb_reg_get(pVBInfo->P3c4, 0x31) & 0xCF;
xgifb_reg_set(pVBInfo->P3c4, 0x31, data);
data = XGI_VBVCLKData[vclkindex].Part4_A;
xgifb_reg_set(pVBInfo->P3c4, 0x2B, data);
data = XGI_VBVCLKData[vclkindex].Part4_B;
xgifb_reg_set(pVBInfo->P3c4, 0x2C, data);
xgifb_reg_set(pVBInfo->P3c4, 0x2D, 0x01);
} else {
index = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRTVCLK;
data = xgifb_reg_get(pVBInfo->P3c4, 0x31) & 0xCF;
xgifb_reg_set(pVBInfo->P3c4, 0x31, data);
xgifb_reg_set(pVBInfo->P3c4, 0x2B, XGI_VCLKData[index].SR2B);
xgifb_reg_set(pVBInfo->P3c4, 0x2C, XGI_VCLKData[index].SR2C);
xgifb_reg_set(pVBInfo->P3c4, 0x2D, 0x01);
}
if (HwDeviceExtension->jChipType >= XG20) {
if (XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag &
HalfDCLK) {
data = xgifb_reg_get(pVBInfo->P3c4, 0x2B);
xgifb_reg_set(pVBInfo->P3c4, 0x2B, data);
data = xgifb_reg_get(pVBInfo->P3c4, 0x2C);
index = data;
index &= 0xE0;
data &= 0x1F;
data <<= 1;
data += 1;
data |= index;
xgifb_reg_set(pVBInfo->P3c4, 0x2C, data);
}
}
}
static void XGI_SetXG21FPBits(struct vb_device_info *pVBInfo)
{
unsigned char temp;
temp = xgifb_reg_get(pVBInfo->P3d4, 0x37); /* D[0] 1: 18bit */
temp = (temp & 1) << 6;
/* SR06[6] 18bit Dither */
xgifb_reg_and_or(pVBInfo->P3c4, 0x06, ~0x40, temp);
/* SR09[7] enable FP output, SR09[6] 1: sigle 18bits, 0: dual 12bits */
xgifb_reg_and_or(pVBInfo->P3c4, 0x09, ~0xc0, temp | 0x80);
}
static void XGI_SetCRT1FIFO(struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short data;
data = xgifb_reg_get(pVBInfo->P3c4, 0x3D);
data &= 0xfe;
xgifb_reg_set(pVBInfo->P3c4, 0x3D, data); /* disable auto-threshold */
xgifb_reg_set(pVBInfo->P3c4, 0x08, 0x34);
data = xgifb_reg_get(pVBInfo->P3c4, 0x09);
data &= 0xC0;
xgifb_reg_set(pVBInfo->P3c4, 0x09, data | 0x30);
data = xgifb_reg_get(pVBInfo->P3c4, 0x3D);
data |= 0x01;
xgifb_reg_set(pVBInfo->P3c4, 0x3D, data);
if (HwDeviceExtension->jChipType == XG21)
XGI_SetXG21FPBits(pVBInfo); /* Fix SR9[7:6] can't read back */
}
static void XGI_SetVCLKState(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short data, data2 = 0;
short VCLK;
unsigned char index;
index = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRTVCLK;
index &= IndexMask;
VCLK = XGI_VCLKData[index].CLOCK;
data = xgifb_reg_get(pVBInfo->P3c4, 0x32);
data &= 0xf3;
if (VCLK >= 200)
data |= 0x0c; /* VCLK > 200 */
if (HwDeviceExtension->jChipType >= XG20)
data &= ~0x04; /* 2 pixel mode */
xgifb_reg_set(pVBInfo->P3c4, 0x32, data);
if (HwDeviceExtension->jChipType < XG20) {
data = xgifb_reg_get(pVBInfo->P3c4, 0x1F);
data &= 0xE7;
if (VCLK < 200)
data |= 0x10;
xgifb_reg_set(pVBInfo->P3c4, 0x1F, data);
}
data2 = 0x00;
xgifb_reg_and_or(pVBInfo->P3c4, 0x07, 0xFC, data2);
if (HwDeviceExtension->jChipType >= XG27)
xgifb_reg_and_or(pVBInfo->P3c4, 0x40, 0xFC, data2 & 0x03);
}
static void XGI_SetCRT1ModeRegs(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short data, data2, data3, infoflag = 0, modeflag, resindex,
xres;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
infoflag = XGI330_RefIndex[RefreshRateTableIndex].Ext_InfoFlag;
if (xgifb_reg_get(pVBInfo->P3d4, 0x31) & 0x01)
xgifb_reg_and_or(pVBInfo->P3c4, 0x1F, 0x3F, 0x00);
data = infoflag;
data2 = 0;
data2 |= 0x02;
data3 = pVBInfo->ModeType - ModeVGA;
data3 <<= 2;
data2 |= data3;
data &= InterlaceMode;
if (data)
data2 |= 0x20;
xgifb_reg_and_or(pVBInfo->P3c4, 0x06, ~0x3F, data2);
resindex = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
xres = XGI330_ModeResInfo[resindex].HTotal; /* xres->ax */
data = 0x0000;
if (infoflag & InterlaceMode) {
if (xres == 1024)
data = 0x0035;
else if (xres == 1280)
data = 0x0048;
}
xgifb_reg_and_or(pVBInfo->P3d4, 0x19, 0xFF, data);
xgifb_reg_and_or(pVBInfo->P3d4, 0x19, 0xFC, 0);
if (modeflag & HalfDCLK)
xgifb_reg_and_or(pVBInfo->P3c4, 0x01, 0xF7, 0x08);
data2 = 0;
if (modeflag & LineCompareOff)
data2 |= 0x08;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0F, ~0x48, data2);
data = 0x60;
data = data ^ 0x60;
data = data ^ 0xA0;
xgifb_reg_and_or(pVBInfo->P3c4, 0x21, 0x1F, data);
XGI_SetVCLKState(HwDeviceExtension, RefreshRateTableIndex, pVBInfo);
data = xgifb_reg_get(pVBInfo->P3d4, 0x31);
if (HwDeviceExtension->jChipType == XG27) {
if (data & 0x40)
data = 0x2c;
else
data = 0x6c;
xgifb_reg_set(pVBInfo->P3d4, 0x52, data);
xgifb_reg_or(pVBInfo->P3d4, 0x51, 0x10);
} else if (HwDeviceExtension->jChipType >= XG20) {
if (data & 0x40)
data = 0x33;
else
data = 0x73;
xgifb_reg_set(pVBInfo->P3d4, 0x52, data);
xgifb_reg_set(pVBInfo->P3d4, 0x51, 0x02);
} else {
if (data & 0x40)
data = 0x2c;
else
data = 0x6c;
xgifb_reg_set(pVBInfo->P3d4, 0x52, data);
}
}
static void XGI_WriteDAC(unsigned short dl,
unsigned short ah,
unsigned short al,
unsigned short dh,
struct vb_device_info *pVBInfo)
{
unsigned short bh, bl;
bh = ah;
bl = al;
if (dl != 0) {
swap(bh, dh);
if (dl == 1)
swap(bl, dh);
else
swap(bl, bh);
}
outb((unsigned short) dh, pVBInfo->P3c9);
outb((unsigned short) bh, pVBInfo->P3c9);
outb((unsigned short) bl, pVBInfo->P3c9);
}
static void XGI_LoadDAC(struct vb_device_info *pVBInfo)
{
unsigned short data, data2, i, k, m, n, o, si, di, bx, dl, al, ah, dh;
const unsigned short *table = XGINew_VGA_DAC;
outb(0xFF, pVBInfo->P3c6);
outb(0x00, pVBInfo->P3c8);
for (i = 0; i < 16; i++) {
data = table[i];
for (k = 0; k < 3; k++) {
data2 = 0;
if (data & 0x01)
data2 = 0x2A;
if (data & 0x02)
data2 += 0x15;
outb(data2, pVBInfo->P3c9);
data >>= 2;
}
}
for (i = 16; i < 32; i++) {
data = table[i];
for (k = 0; k < 3; k++)
outb(data, pVBInfo->P3c9);
}
si = 32;
for (m = 0; m < 9; m++) {
di = si;
bx = si + 0x04;
dl = 0;
for (n = 0; n < 3; n++) {
for (o = 0; o < 5; o++) {
dh = table[si];
ah = table[di];
al = table[bx];
si++;
XGI_WriteDAC(dl, ah, al, dh, pVBInfo);
}
si -= 2;
for (o = 0; o < 3; o++) {
dh = table[bx];
ah = table[di];
al = table[si];
si--;
XGI_WriteDAC(dl, ah, al, dh, pVBInfo);
}
dl++;
}
si += 5;
}
}
static void XGI_GetLVDSResInfo(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short resindex, xres, yres, modeflag;
/* si+Ext_ResInfo */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
/* si+Ext_ResInfo */
resindex = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
xres = XGI330_ModeResInfo[resindex].HTotal;
yres = XGI330_ModeResInfo[resindex].VTotal;
if (modeflag & HalfDCLK)
xres <<= 1;
if (modeflag & DoubleScanMode)
yres <<= 1;
if (xres == 720)
xres = 640;
pVBInfo->VGAHDE = xres;
pVBInfo->HDE = xres;
pVBInfo->VGAVDE = yres;
pVBInfo->VDE = yres;
}
static void const *XGI_GetLcdPtr(struct XGI330_LCDDataTablStruct const *table,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short i, tempdx, tempbx, modeflag;
tempbx = 0;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
i = 0;
while (table[i].PANELID != 0xff) {
tempdx = pVBInfo->LCDResInfo;
if (tempbx & 0x0080) { /* OEMUtil */
tempbx &= (~0x0080);
tempdx = pVBInfo->LCDTypeInfo;
}
if (pVBInfo->LCDInfo & EnableScalingLCD)
tempdx &= (~PanelResInfo);
if (table[i].PANELID == tempdx) {
tempbx = table[i].MASK;
tempdx = pVBInfo->LCDInfo;
if (modeflag & HalfDCLK)
tempdx |= SetLCDLowResolution;
tempbx &= tempdx;
if (tempbx == table[i].CAP)
break;
}
i++;
}
return table[i].DATAPTR;
}
static struct SiS_TVData const *XGI_GetTVPtr(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short i, tempdx, tempal, modeflag;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
tempal = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC;
tempal = tempal & 0x3f;
tempdx = pVBInfo->TVInfo;
if (pVBInfo->VBInfo & SetInSlaveMode)
tempdx = tempdx | SetTVLockMode;
if (modeflag & HalfDCLK)
tempdx = tempdx | SetTVLowResolution;
i = 0;
while (XGI_TVDataTable[i].MASK != 0xffff) {
if ((tempdx & XGI_TVDataTable[i].MASK) ==
XGI_TVDataTable[i].CAP)
break;
i++;
}
return &XGI_TVDataTable[i].DATAPTR[tempal];
}
static void XGI_GetLVDSData(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
struct SiS_LVDSData const *LCDPtr;
if (!(pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)))
return;
LCDPtr = XGI_GetLcdPtr(XGI_EPLLCDDataPtr, ModeIdIndex, pVBInfo);
pVBInfo->VGAHT = LCDPtr->VGAHT;
pVBInfo->VGAVT = LCDPtr->VGAVT;
pVBInfo->HT = LCDPtr->LCDHT;
pVBInfo->VT = LCDPtr->LCDVT;
if (pVBInfo->LCDInfo & (SetLCDtoNonExpanding | EnableScalingLCD))
return;
if ((pVBInfo->LCDResInfo == Panel_1024x768) ||
(pVBInfo->LCDResInfo == Panel_1024x768x75)) {
pVBInfo->HDE = 1024;
pVBInfo->VDE = 768;
} else if ((pVBInfo->LCDResInfo == Panel_1280x1024) ||
(pVBInfo->LCDResInfo == Panel_1280x1024x75)) {
pVBInfo->HDE = 1280;
pVBInfo->VDE = 1024;
} else if (pVBInfo->LCDResInfo == Panel_1400x1050) {
pVBInfo->HDE = 1400;
pVBInfo->VDE = 1050;
} else {
pVBInfo->HDE = 1600;
pVBInfo->VDE = 1200;
}
}
static void XGI_ModCRT1Regs(unsigned short ModeIdIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short i;
struct XGI_LVDSCRT1HDataStruct const *LCDPtr = NULL;
struct XGI_LVDSCRT1VDataStruct const *LCDPtr1 = NULL;
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)) {
LCDPtr = XGI_GetLcdPtr(xgifb_epllcd_crt1_h, ModeIdIndex,
pVBInfo);
for (i = 0; i < 8; i++)
pVBInfo->TimingH.data[i] = LCDPtr[0].Reg[i];
}
XGI_SetCRT1Timing_H(pVBInfo, HwDeviceExtension);
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)) {
LCDPtr1 = XGI_GetLcdPtr(xgifb_epllcd_crt1_v, ModeIdIndex,
pVBInfo);
for (i = 0; i < 7; i++)
pVBInfo->TimingV.data[i] = LCDPtr1[0].Reg[i];
}
XGI_SetCRT1Timing_V(ModeIdIndex, pVBInfo);
}
static unsigned short XGI_GetLCDCapPtr(struct vb_device_info *pVBInfo)
{
unsigned char tempal, tempah, tempbl, i;
tempah = xgifb_reg_get(pVBInfo->P3d4, 0x36);
tempal = tempah & 0x0F;
tempah = tempah & 0xF0;
i = 0;
tempbl = pVBInfo->LCDCapList[i].LCD_ID;
while (tempbl != 0xFF) {
if (tempbl & 0x80) { /* OEMUtil */
tempal = tempah;
tempbl = tempbl & ~(0x80);
}
if (tempal == tempbl)
break;
i++;
tempbl = pVBInfo->LCDCapList[i].LCD_ID;
}
return i;
}
static unsigned short XGI_GetLCDCapPtr1(struct vb_device_info *pVBInfo)
{
unsigned short tempah, tempal, tempbl, i;
tempal = pVBInfo->LCDResInfo;
tempah = pVBInfo->LCDTypeInfo;
i = 0;
tempbl = pVBInfo->LCDCapList[i].LCD_ID;
while (tempbl != 0xFF) {
if ((tempbl & 0x80) && (tempbl != 0x80)) {
tempal = tempah;
tempbl &= ~0x80;
}
if (tempal == tempbl)
break;
i++;
tempbl = pVBInfo->LCDCapList[i].LCD_ID;
}
if (tempbl == 0xFF) {
pVBInfo->LCDResInfo = Panel_1024x768;
pVBInfo->LCDTypeInfo = 0;
i = 0;
}
return i;
}
static void XGI_GetLCDSync(unsigned short *HSyncWidth,
unsigned short *VSyncWidth,
struct vb_device_info *pVBInfo)
{
unsigned short Index;
Index = XGI_GetLCDCapPtr(pVBInfo);
*HSyncWidth = pVBInfo->LCDCapList[Index].LCD_HSyncWidth;
*VSyncWidth = pVBInfo->LCDCapList[Index].LCD_VSyncWidth;
}
static void XGI_SetLVDSRegs(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx, tempax, tempcx, tempdx, push1, push2, modeflag;
unsigned long temp, temp1, temp2, temp3, push3;
struct XGI330_LCDDataDesStruct2 const *LCDPtr1 = NULL;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
LCDPtr1 = XGI_GetLcdPtr(XGI_EPLLCDDesDataPtr, ModeIdIndex, pVBInfo);
XGI_GetLCDSync(&tempax, &tempbx, pVBInfo);
push1 = tempbx;
push2 = tempax;
/* GetLCDResInfo */
if ((pVBInfo->LCDResInfo == Panel_1024x768) ||
(pVBInfo->LCDResInfo == Panel_1024x768x75)) {
tempax = 1024;
tempbx = 768;
} else if ((pVBInfo->LCDResInfo == Panel_1280x1024) ||
(pVBInfo->LCDResInfo == Panel_1280x1024x75)) {
tempax = 1280;
tempbx = 1024;
} else if (pVBInfo->LCDResInfo == Panel_1400x1050) {
tempax = 1400;
tempbx = 1050;
} else {
tempax = 1600;
tempbx = 1200;
}
if (pVBInfo->LCDInfo & SetLCDtoNonExpanding) {
pVBInfo->HDE = tempax;
pVBInfo->VDE = tempbx;
pVBInfo->VGAHDE = tempax;
pVBInfo->VGAVDE = tempbx;
}
tempax = pVBInfo->HT;
tempbx = LCDPtr1->LCDHDES;
tempcx = pVBInfo->HDE;
tempbx = tempbx & 0x0fff;
tempcx += tempbx;
if (tempcx >= tempax)
tempcx -= tempax;
xgifb_reg_set(pVBInfo->Part1Port, 0x1A, tempbx & 0x07);
tempcx >>= 3;
tempbx >>= 3;
xgifb_reg_set(pVBInfo->Part1Port, 0x16,
(unsigned short) (tempbx & 0xff));
xgifb_reg_set(pVBInfo->Part1Port, 0x17,
(unsigned short) (tempcx & 0xff));
tempax = pVBInfo->HT;
tempbx = LCDPtr1->LCDHRS;
tempcx = push2;
if (pVBInfo->LCDInfo & EnableScalingLCD)
tempcx = LCDPtr1->LCDHSync;
tempcx += tempbx;
if (tempcx >= tempax)
tempcx -= tempax;
tempax = tempbx & 0x07;
tempax >>= 5;
tempcx >>= 3;
tempbx >>= 3;
tempcx &= 0x1f;
tempax |= tempcx;
xgifb_reg_set(pVBInfo->Part1Port, 0x15, tempax);
xgifb_reg_set(pVBInfo->Part1Port, 0x14,
(unsigned short) (tempbx & 0xff));
tempax = pVBInfo->VT;
tempbx = LCDPtr1->LCDVDES;
tempcx = pVBInfo->VDE;
tempbx = tempbx & 0x0fff;
tempcx += tempbx;
if (tempcx >= tempax)
tempcx -= tempax;
xgifb_reg_set(pVBInfo->Part1Port, 0x1b,
(unsigned short) (tempbx & 0xff));
xgifb_reg_set(pVBInfo->Part1Port, 0x1c,
(unsigned short) (tempcx & 0xff));
tempbx = (tempbx >> 8) & 0x07;
tempcx = (tempcx >> 8) & 0x07;
xgifb_reg_set(pVBInfo->Part1Port, 0x1d,
(unsigned short) ((tempcx << 3)
| tempbx));
tempax = pVBInfo->VT;
tempbx = LCDPtr1->LCDVRS;
tempcx = push1;
if (pVBInfo->LCDInfo & EnableScalingLCD)
tempcx = LCDPtr1->LCDVSync;
tempcx += tempbx;
if (tempcx >= tempax)
tempcx -= tempax;
xgifb_reg_set(pVBInfo->Part1Port, 0x18,
(unsigned short) (tempbx & 0xff));
xgifb_reg_and_or(pVBInfo->Part1Port, 0x19, ~0x0f,
(unsigned short) (tempcx & 0x0f));
tempax = ((tempbx >> 8) & 0x07) << 3;
tempbx = pVBInfo->VGAVDE;
if (tempbx != pVBInfo->VDE)
tempax |= 0x40;
if (pVBInfo->LCDInfo & XGI_EnableLVDSDDA)
tempax |= 0x40;
xgifb_reg_and_or(pVBInfo->Part1Port, 0x1a, 0x07,
tempax);
tempbx = pVBInfo->VDE;
tempax = pVBInfo->VGAVDE;
temp = tempax; /* 0430 ylshieh */
temp1 = (temp << 18) / tempbx;
tempdx = (unsigned short) ((temp << 18) % tempbx);
if (tempdx != 0)
temp1 += 1;
temp2 = temp1;
push3 = temp2;
xgifb_reg_set(pVBInfo->Part1Port, 0x37,
(unsigned short) (temp2 & 0xff));
xgifb_reg_set(pVBInfo->Part1Port, 0x36,
(unsigned short) ((temp2 >> 8) & 0xff));
tempbx = (unsigned short) (temp2 >> 16);
tempax = tempbx & 0x03;
tempbx = pVBInfo->VGAVDE;
if (tempbx == pVBInfo->VDE)
tempax |= 0x04;
xgifb_reg_set(pVBInfo->Part1Port, 0x35, tempax);
if (pVBInfo->VBType & VB_XGI301C) {
temp2 = push3;
xgifb_reg_set(pVBInfo->Part4Port,
0x3c,
(unsigned short) (temp2 & 0xff));
xgifb_reg_set(pVBInfo->Part4Port,
0x3b,
(unsigned short) ((temp2 >> 8) &
0xff));
tempbx = (unsigned short) (temp2 >> 16);
xgifb_reg_and_or(pVBInfo->Part4Port, 0x3a,
~0xc0,
(unsigned short) ((tempbx &
0xff) << 6));
tempcx = pVBInfo->VGAVDE;
if (tempcx == pVBInfo->VDE)
xgifb_reg_and_or(pVBInfo->Part4Port,
0x30, ~0x0c, 0x00);
else
xgifb_reg_and_or(pVBInfo->Part4Port,
0x30, ~0x0c, 0x08);
}
tempcx = pVBInfo->VGAHDE;
tempbx = pVBInfo->HDE;
temp1 = tempcx << 16;
tempax = (unsigned short) (temp1 / tempbx);
if ((tempbx & 0xffff) == (tempcx & 0xffff))
tempax = 65535;
temp3 = tempax;
temp1 = pVBInfo->VGAHDE << 16;
temp1 /= temp3;
temp3 <<= 16;
temp1 -= 1;
temp3 = (temp3 & 0xffff0000) + (temp1 & 0xffff);
tempax = (unsigned short) (temp3 & 0xff);
xgifb_reg_set(pVBInfo->Part1Port, 0x1f, tempax);
temp1 = pVBInfo->VGAVDE << 18;
temp1 = temp1 / push3;
tempbx = (unsigned short) (temp1 & 0xffff);
if (pVBInfo->LCDResInfo == Panel_1024x768)
tempbx -= 1;
tempax = ((tempbx >> 8) & 0xff) << 3;
tempax |= (unsigned short) ((temp3 >> 8) & 0x07);
xgifb_reg_set(pVBInfo->Part1Port, 0x20,
(unsigned short) (tempax & 0xff));
xgifb_reg_set(pVBInfo->Part1Port, 0x21,
(unsigned short) (tempbx & 0xff));
temp3 >>= 16;
if (modeflag & HalfDCLK)
temp3 >>= 1;
xgifb_reg_set(pVBInfo->Part1Port, 0x22,
(unsigned short) ((temp3 >> 8) & 0xff));
xgifb_reg_set(pVBInfo->Part1Port, 0x23,
(unsigned short) (temp3 & 0xff));
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GETLCDVCLKPtr */
/* Input : */
/* Output : al -> VCLK Index */
/* Description : */
/* --------------------------------------------------------------------- */
static void XGI_GetLCDVCLKPtr(unsigned char *di_0, unsigned char *di_1,
struct vb_device_info *pVBInfo)
{
unsigned short index;
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)) {
index = XGI_GetLCDCapPtr1(pVBInfo);
if (pVBInfo->VBInfo & SetCRT2ToLCD) { /* LCDB */
*di_0 = pVBInfo->LCDCapList[index].LCUCHAR_VCLKData1;
*di_1 = pVBInfo->LCDCapList[index].LCUCHAR_VCLKData2;
} else { /* LCDA */
*di_0 = pVBInfo->LCDCapList[index].LCDA_VCLKData1;
*di_1 = pVBInfo->LCDCapList[index].LCDA_VCLKData2;
}
}
}
static unsigned char XGI_GetVCLKPtr(unsigned short RefreshRateTableIndex,
unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned short index, modeflag;
unsigned char tempal;
/* si+Ext_ResInfo */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
if ((pVBInfo->SetFlag & ProgrammingCRT2) &&
(!(pVBInfo->LCDInfo & EnableScalingLCD))) { /* {LCDA/LCDB} */
index = XGI_GetLCDCapPtr(pVBInfo);
tempal = pVBInfo->LCDCapList[index].LCD_VCLK;
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA))
return tempal;
/* {TV} */
if (pVBInfo->VBType &
(VB_SIS301B |
VB_SIS302B |
VB_SIS301LV |
VB_SIS302LV |
VB_XGI301C)) {
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
tempal = TVCLKBASE_315 + HiTVVCLKDIV2;
if (!(pVBInfo->TVInfo & RPLLDIV2XO))
tempal = TVCLKBASE_315 + HiTVVCLK;
if (pVBInfo->TVInfo & TVSimuMode) {
tempal = TVCLKBASE_315 + HiTVSimuVCLK;
if (!(modeflag & Charx8Dot))
tempal = TVCLKBASE_315 +
HiTVTextVCLK;
}
return tempal;
}
if (pVBInfo->TVInfo & TVSetYPbPr750p) {
tempal = XGI_YPbPr750pVCLK;
return tempal;
}
if (pVBInfo->TVInfo & TVSetYPbPr525p) {
tempal = YPbPr525pVCLK;
return tempal;
}
tempal = NTSC1024VCLK;
if (!(pVBInfo->TVInfo & NTSC1024x768)) {
tempal = TVCLKBASE_315 + TVVCLKDIV2;
if (!(pVBInfo->TVInfo & RPLLDIV2XO))
tempal = TVCLKBASE_315 + TVVCLK;
}
if (pVBInfo->VBInfo & SetCRT2ToTV)
return tempal;
}
} /* {End of VB} */
inb((pVBInfo->P3ca + 0x02));
tempal = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRTVCLK;
return tempal;
}
static void XGI_GetVCLKLen(unsigned char tempal, unsigned char *di_0,
unsigned char *di_1, struct vb_device_info *pVBInfo)
{
if (pVBInfo->VBType & (VB_SIS301 | VB_SIS301B | VB_SIS302B
| VB_SIS301LV | VB_SIS302LV | VB_XGI301C)) {
if ((!(pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)) &&
(pVBInfo->SetFlag & ProgrammingCRT2)) {
*di_0 = XGI_VBVCLKData[tempal].Part4_A;
*di_1 = XGI_VBVCLKData[tempal].Part4_B;
}
} else {
*di_0 = XGI_VCLKData[tempal].SR2B;
*di_1 = XGI_VCLKData[tempal].SR2C;
}
}
static void XGI_SetCRT2ECLK(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned char di_0, di_1, tempal;
int i;
tempal = XGI_GetVCLKPtr(RefreshRateTableIndex, ModeIdIndex, pVBInfo);
XGI_GetVCLKLen(tempal, &di_0, &di_1, pVBInfo);
XGI_GetLCDVCLKPtr(&di_0, &di_1, pVBInfo);
for (i = 0; i < 4; i++) {
xgifb_reg_and_or(pVBInfo->P3d4, 0x31, ~0x30,
(unsigned short) (0x10 * i));
if ((!(pVBInfo->VBInfo & XGI_SetCRT2ToLCDA))
&& (!(pVBInfo->VBInfo & SetInSlaveMode))) {
xgifb_reg_set(pVBInfo->P3c4, 0x2e, di_0);
xgifb_reg_set(pVBInfo->P3c4, 0x2f, di_1);
} else {
xgifb_reg_set(pVBInfo->P3c4, 0x2b, di_0);
xgifb_reg_set(pVBInfo->P3c4, 0x2c, di_1);
}
}
}
static void XGI_UpdateModeInfo(struct vb_device_info *pVBInfo)
{
unsigned short tempcl, tempch, temp, tempbl, tempax;
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
tempcl = 0;
tempch = 0;
temp = xgifb_reg_get(pVBInfo->P3c4, 0x01);
if (!(temp & 0x20)) {
temp = xgifb_reg_get(pVBInfo->P3d4, 0x17);
if (temp & 0x80) {
temp = xgifb_reg_get(pVBInfo->P3d4, 0x53);
if (!(temp & 0x40))
tempcl |= ActiveCRT1;
}
}
temp = xgifb_reg_get(pVBInfo->Part1Port, 0x2e);
temp &= 0x0f;
if (!(temp == 0x08)) {
/* Check ChannelA */
tempax = xgifb_reg_get(pVBInfo->Part1Port, 0x13);
if (tempax & 0x04)
tempcl = tempcl | ActiveLCD;
temp &= 0x05;
if (!(tempcl & ActiveLCD))
if (temp == 0x01)
tempcl |= ActiveCRT2;
if (temp == 0x04)
tempcl |= ActiveLCD;
if (temp == 0x05) {
temp = xgifb_reg_get(pVBInfo->Part2Port, 0x00);
if (!(temp & 0x08))
tempch |= ActiveAVideo;
if (!(temp & 0x04))
tempch |= ActiveSVideo;
if (temp & 0x02)
tempch |= ActiveSCART;
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
if (temp & 0x01)
tempch |= ActiveHiTV;
}
if (pVBInfo->VBInfo & SetCRT2ToYPbPr525750) {
temp = xgifb_reg_get(
pVBInfo->Part2Port,
0x4d);
if (temp & 0x10)
tempch |= ActiveYPbPr;
}
if (tempch != 0)
tempcl |= ActiveTV;
}
}
temp = xgifb_reg_get(pVBInfo->P3d4, 0x3d);
if (tempcl & ActiveLCD) {
if ((pVBInfo->SetFlag & ReserveTVOption)) {
if (temp & ActiveTV)
tempcl |= ActiveTV;
}
}
temp = tempcl;
tempbl = ~XGI_ModeSwitchStatus;
xgifb_reg_and_or(pVBInfo->P3d4, 0x3d, tempbl, temp);
if (!(pVBInfo->SetFlag & ReserveTVOption))
xgifb_reg_set(pVBInfo->P3d4, 0x3e, tempch);
}
}
void XGI_GetVBType(struct vb_device_info *pVBInfo)
{
unsigned short flag, tempbx, tempah;
tempbx = VB_SIS302B;
flag = xgifb_reg_get(pVBInfo->Part4Port, 0x00);
if (flag == 0x02)
goto finish;
tempbx = VB_SIS301;
flag = xgifb_reg_get(pVBInfo->Part4Port, 0x01);
if (flag < 0xB0)
goto finish;
tempbx = VB_SIS301B;
if (flag < 0xC0)
goto bigger_than_0xB0;
tempbx = VB_XGI301C;
if (flag < 0xD0)
goto bigger_than_0xB0;
tempbx = VB_SIS301LV;
if (flag < 0xE0)
goto bigger_than_0xB0;
tempbx = VB_SIS302LV;
tempah = xgifb_reg_get(pVBInfo->Part4Port, 0x39);
if (tempah != 0xFF)
tempbx = VB_XGI301C;
bigger_than_0xB0:
if (tempbx & (VB_SIS301B | VB_SIS302B)) {
flag = xgifb_reg_get(pVBInfo->Part4Port, 0x23);
if (!(flag & 0x02))
tempbx = tempbx | VB_NoLCD;
}
finish:
pVBInfo->VBType = tempbx;
}
static void XGI_GetVBInfo(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempax, push, tempbx, temp, modeflag;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
pVBInfo->SetFlag = 0;
pVBInfo->ModeType = modeflag & ModeTypeMask;
tempbx = 0;
if (!(pVBInfo->VBType & 0xFFFF))
return;
/* Check Display Device */
temp = xgifb_reg_get(pVBInfo->P3d4, 0x30);
tempbx = tempbx | temp;
temp = xgifb_reg_get(pVBInfo->P3d4, 0x31);
push = temp;
push <<= 8;
tempax = temp << 8;
tempbx = tempbx | tempax;
temp = (SetCRT2ToDualEdge | SetCRT2ToYPbPr525750 | XGI_SetCRT2ToLCDA
| SetInSlaveMode | DisableCRT2Display);
temp = 0xFFFF ^ temp;
tempbx &= temp;
temp = xgifb_reg_get(pVBInfo->P3d4, 0x38);
if (pVBInfo->VBType & (VB_SIS302B | VB_SIS301LV | VB_SIS302LV |
VB_XGI301C)) {
if (temp & EnableDualEdge) {
tempbx |= SetCRT2ToDualEdge;
if (temp & SetToLCDA)
tempbx |= XGI_SetCRT2ToLCDA;
}
}
if (pVBInfo->VBType & (VB_SIS301LV|VB_SIS302LV|VB_XGI301C)) {
if (temp & SetYPbPr) {
/* shampoo add for new scratch */
temp = xgifb_reg_get(pVBInfo->P3d4, 0x35);
temp &= YPbPrMode;
tempbx |= SetCRT2ToHiVision;
if (temp != YPbPrMode1080i) {
tempbx &= (~SetCRT2ToHiVision);
tempbx |= SetCRT2ToYPbPr525750;
}
}
}
tempax = push; /* restore CR31 */
temp = 0x09FC;
if (!(tempbx & temp)) {
tempax |= DisableCRT2Display;
tempbx = 0;
}
if (!(pVBInfo->VBType & VB_NoLCD)) {
if (tempbx & XGI_SetCRT2ToLCDA) {
if (tempbx & SetSimuScanMode)
tempbx &= (~(SetCRT2ToLCD | SetCRT2ToRAMDAC |
SwitchCRT2));
else
tempbx &= (~(SetCRT2ToLCD | SetCRT2ToRAMDAC |
SetCRT2ToTV | SwitchCRT2));
}
}
/* shampoo add */
/* for driver abnormal */
if (!(tempbx & (SwitchCRT2 | SetSimuScanMode))) {
if (tempbx & SetCRT2ToRAMDAC) {
tempbx &= (0xFF00 | SetCRT2ToRAMDAC |
SwitchCRT2 | SetSimuScanMode);
tempbx &= (0x00FF | (~SetCRT2ToYPbPr525750));
}
}
if (!(pVBInfo->VBType & VB_NoLCD)) {
if (tempbx & SetCRT2ToLCD) {
tempbx &= (0xFF00 | SetCRT2ToLCD | SwitchCRT2 |
SetSimuScanMode);
tempbx &= (0x00FF | (~SetCRT2ToYPbPr525750));
}
}
if (tempbx & SetCRT2ToSCART) {
tempbx &= (0xFF00 | SetCRT2ToSCART | SwitchCRT2 |
SetSimuScanMode);
tempbx &= (0x00FF | (~SetCRT2ToYPbPr525750));
}
if (tempbx & SetCRT2ToYPbPr525750)
tempbx &= (0xFF00 | SwitchCRT2 | SetSimuScanMode);
if (tempbx & SetCRT2ToHiVision)
tempbx &= (0xFF00 | SetCRT2ToHiVision | SwitchCRT2 |
SetSimuScanMode);
if (tempax & DisableCRT2Display) { /* Set Display Device Info */
if (!(tempbx & (SwitchCRT2 | SetSimuScanMode)))
tempbx = DisableCRT2Display;
}
if (!(tempbx & DisableCRT2Display)) {
if ((!(tempbx & DriverMode)) || (!(modeflag & CRT2Mode))) {
if (!(tempbx & XGI_SetCRT2ToLCDA))
tempbx |= (SetInSlaveMode | SetSimuScanMode);
}
/* LCD+TV can't support in slave mode
* (Force LCDA+TV->LCDB) */
if ((tempbx & SetInSlaveMode) && (tempbx & XGI_SetCRT2ToLCDA)) {
tempbx ^= (SetCRT2ToLCD | XGI_SetCRT2ToLCDA |
SetCRT2ToDualEdge);
pVBInfo->SetFlag |= ReserveTVOption;
}
}
pVBInfo->VBInfo = tempbx;
}
static void XGI_GetTVInfo(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx = 0, resinfo = 0, modeflag, index1;
if (pVBInfo->VBInfo & SetCRT2ToTV) {
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
resinfo = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
tempbx = xgifb_reg_get(pVBInfo->P3d4, 0x35);
if (tempbx & TVSetPAL) {
tempbx &= (SetCHTVOverScan |
TVSetPALM |
TVSetPALN |
TVSetPAL);
if (tempbx & TVSetPALM)
/* set to NTSC if PAL-M */
tempbx &= ~TVSetPAL;
} else
tempbx &= (SetCHTVOverScan |
TVSetNTSCJ |
TVSetPAL);
if (pVBInfo->VBInfo & SetCRT2ToSCART)
tempbx |= TVSetPAL;
if (pVBInfo->VBInfo & SetCRT2ToYPbPr525750) {
index1 = xgifb_reg_get(pVBInfo->P3d4, 0x35);
index1 &= YPbPrMode;
if (index1 == YPbPrMode525i)
tempbx |= TVSetYPbPr525i;
if (index1 == YPbPrMode525p)
tempbx = tempbx | TVSetYPbPr525p;
if (index1 == YPbPrMode750p)
tempbx = tempbx | TVSetYPbPr750p;
}
if (pVBInfo->VBInfo & SetCRT2ToHiVision)
tempbx = tempbx | TVSetHiVision | TVSetPAL;
if ((pVBInfo->VBInfo & SetInSlaveMode) &&
(!(pVBInfo->VBInfo & SetNotSimuMode)))
tempbx |= TVSimuMode;
if (!(tempbx & TVSetPAL) && (modeflag > 13) && (resinfo == 8))
/* NTSC 1024x768, */
tempbx |= NTSC1024x768;
tempbx |= RPLLDIV2XO;
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
if (pVBInfo->VBInfo & SetInSlaveMode)
tempbx &= (~RPLLDIV2XO);
} else if (tempbx & (TVSetYPbPr525p | TVSetYPbPr750p)) {
tempbx &= (~RPLLDIV2XO);
} else if (!(pVBInfo->VBType & (VB_SIS301B | VB_SIS302B |
VB_SIS301LV | VB_SIS302LV |
VB_XGI301C))) {
if (tempbx & TVSimuMode)
tempbx &= (~RPLLDIV2XO);
}
}
pVBInfo->TVInfo = tempbx;
}
static unsigned char XGI_GetLCDInfo(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short temp, tempax, tempbx, resinfo = 0, LCDIdIndex;
pVBInfo->LCDResInfo = 0;
pVBInfo->LCDTypeInfo = 0;
pVBInfo->LCDInfo = 0;
/* si+Ext_ResInfo // */
resinfo = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
temp = xgifb_reg_get(pVBInfo->P3d4, 0x36); /* Get LCD Res.Info */
tempbx = temp & 0x0F;
if (tempbx == 0)
tempbx = Panel_1024x768; /* default */
/* LCD75 */
if ((tempbx == Panel_1024x768) || (tempbx == Panel_1280x1024)) {
if (pVBInfo->VBInfo & DriverMode) {
tempax = xgifb_reg_get(pVBInfo->P3d4, 0x33);
if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)
tempax &= 0x0F;
else
tempax >>= 4;
if ((resinfo == 6) || (resinfo == 9)) {
if (tempax >= 3)
tempbx |= PanelRef75Hz;
} else if ((resinfo == 7) || (resinfo == 8)) {
if (tempax >= 4)
tempbx |= PanelRef75Hz;
}
}
}
pVBInfo->LCDResInfo = tempbx;
/* End of LCD75 */
if (!(pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)))
return 0;
tempbx = 0;
temp = xgifb_reg_get(pVBInfo->P3d4, 0x37);
temp &= (ScalingLCD | LCDNonExpanding | LCDSyncBit | SetPWDEnable);
tempbx |= temp;
LCDIdIndex = XGI_GetLCDCapPtr1(pVBInfo);
tempax = pVBInfo->LCDCapList[LCDIdIndex].LCD_Capability;
if (((pVBInfo->VBType & VB_SIS302LV) ||
(pVBInfo->VBType & VB_XGI301C)) && (tempax & XGI_LCDDualLink))
tempbx |= SetLCDDualLink;
if ((pVBInfo->LCDResInfo == Panel_1400x1050) &&
(pVBInfo->VBInfo & SetCRT2ToLCD) && (resinfo == 9) &&
(!(tempbx & EnableScalingLCD)))
/*
* set to center in 1280x1024 LCDB
* for Panel_1400x1050
*/
tempbx |= SetLCDtoNonExpanding;
if (pVBInfo->VBInfo & SetInSlaveMode) {
if (pVBInfo->VBInfo & SetNotSimuMode)
tempbx |= XGI_LCDVESATiming;
} else {
tempbx |= XGI_LCDVESATiming;
}
pVBInfo->LCDInfo = tempbx;
return 1;
}
unsigned char XGI_SearchModeID(unsigned short ModeNo,
unsigned short *ModeIdIndex)
{
for (*ModeIdIndex = 0;; (*ModeIdIndex)++) {
if (XGI330_EModeIDTable[*ModeIdIndex].Ext_ModeID == ModeNo)
break;
if (XGI330_EModeIDTable[*ModeIdIndex].Ext_ModeID == 0xFF)
return 0;
}
return 1;
}
static unsigned char XG21GPIODataTransfer(unsigned char ujDate)
{
unsigned char ujRet = 0;
unsigned char i = 0;
for (i = 0; i < 8; i++) {
ujRet <<= 1;
ujRet |= (ujDate >> i) & 1;
}
return ujRet;
}
/*----------------------------------------------------------------------------*/
/* output */
/* bl[5] : LVDS signal */
/* bl[1] : LVDS backlight */
/* bl[0] : LVDS VDD */
/*----------------------------------------------------------------------------*/
static unsigned char XGI_XG21GetPSCValue(struct vb_device_info *pVBInfo)
{
unsigned char CR4A, temp;
CR4A = xgifb_reg_get(pVBInfo->P3d4, 0x4A);
xgifb_reg_and(pVBInfo->P3d4, 0x4A, ~0x23); /* enable GPIO write */
temp = xgifb_reg_get(pVBInfo->P3d4, 0x48);
temp = XG21GPIODataTransfer(temp);
temp &= 0x23;
xgifb_reg_set(pVBInfo->P3d4, 0x4A, CR4A);
return temp;
}
/*----------------------------------------------------------------------------*/
/* output */
/* bl[5] : LVDS signal */
/* bl[1] : LVDS backlight */
/* bl[0] : LVDS VDD */
/*----------------------------------------------------------------------------*/
static unsigned char XGI_XG27GetPSCValue(struct vb_device_info *pVBInfo)
{
unsigned char CR4A, CRB4, temp;
CR4A = xgifb_reg_get(pVBInfo->P3d4, 0x4A);
xgifb_reg_and(pVBInfo->P3d4, 0x4A, ~0x0C); /* enable GPIO write */
temp = xgifb_reg_get(pVBInfo->P3d4, 0x48);
temp &= 0x0C;
temp >>= 2;
xgifb_reg_set(pVBInfo->P3d4, 0x4A, CR4A);
CRB4 = xgifb_reg_get(pVBInfo->P3d4, 0xB4);
temp |= ((CRB4 & 0x04) << 3);
return temp;
}
/*----------------------------------------------------------------------------*/
/* input */
/* bl[5] : 1;LVDS signal on */
/* bl[1] : 1;LVDS backlight on */
/* bl[0] : 1:LVDS VDD on */
/* bh: 100000b : clear bit 5, to set bit5 */
/* 000010b : clear bit 1, to set bit1 */
/* 000001b : clear bit 0, to set bit0 */
/*----------------------------------------------------------------------------*/
static void XGI_XG21BLSignalVDD(unsigned short tempbh, unsigned short tempbl,
struct vb_device_info *pVBInfo)
{
unsigned char CR4A, temp;
CR4A = xgifb_reg_get(pVBInfo->P3d4, 0x4A);
tempbh &= 0x23;
tempbl &= 0x23;
xgifb_reg_and(pVBInfo->P3d4, 0x4A, ~tempbh); /* enable GPIO write */
if (tempbh & 0x20) {
temp = (tempbl >> 4) & 0x02;
/* CR B4[1] */
xgifb_reg_and_or(pVBInfo->P3d4, 0xB4, ~0x02, temp);
}
temp = xgifb_reg_get(pVBInfo->P3d4, 0x48);
temp = XG21GPIODataTransfer(temp);
temp &= ~tempbh;
temp |= tempbl;
xgifb_reg_set(pVBInfo->P3d4, 0x48, temp);
}
static void XGI_XG27BLSignalVDD(unsigned short tempbh, unsigned short tempbl,
struct vb_device_info *pVBInfo)
{
unsigned char CR4A, temp;
unsigned short tempbh0, tempbl0;
tempbh0 = tempbh;
tempbl0 = tempbl;
tempbh0 &= 0x20;
tempbl0 &= 0x20;
tempbh0 >>= 3;
tempbl0 >>= 3;
if (tempbh & 0x20) {
temp = (tempbl >> 4) & 0x02;
/* CR B4[1] */
xgifb_reg_and_or(pVBInfo->P3d4, 0xB4, ~0x02, temp);
}
xgifb_reg_and_or(pVBInfo->P3d4, 0xB4, ~tempbh0, tempbl0);
CR4A = xgifb_reg_get(pVBInfo->P3d4, 0x4A);
tempbh &= 0x03;
tempbl &= 0x03;
tempbh <<= 2;
tempbl <<= 2; /* GPIOC,GPIOD */
xgifb_reg_and(pVBInfo->P3d4, 0x4A, ~tempbh); /* enable GPIO write */
xgifb_reg_and_or(pVBInfo->P3d4, 0x48, ~tempbh, tempbl);
}
static void XGI_DisplayOn(struct xgifb_video_info *xgifb_info,
struct xgi_hw_device_info *pXGIHWDE,
struct vb_device_info *pVBInfo)
{
xgifb_reg_and_or(pVBInfo->P3c4, 0x01, 0xDF, 0x00);
if (pXGIHWDE->jChipType == XG21) {
if (pVBInfo->IF_DEF_LVDS == 1) {
if (!(XGI_XG21GetPSCValue(pVBInfo) & 0x1)) {
/* LVDS VDD on */
XGI_XG21BLSignalVDD(0x01, 0x01, pVBInfo);
mdelay(xgifb_info->lvds_data.PSC_S2);
}
if (!(XGI_XG21GetPSCValue(pVBInfo) & 0x20))
/* LVDS signal on */
XGI_XG21BLSignalVDD(0x20, 0x20, pVBInfo);
mdelay(xgifb_info->lvds_data.PSC_S3);
/* LVDS backlight on */
XGI_XG21BLSignalVDD(0x02, 0x02, pVBInfo);
} else {
/* DVO/DVI signal on */
XGI_XG21BLSignalVDD(0x20, 0x20, pVBInfo);
}
}
if (pXGIHWDE->jChipType == XG27) {
if (pVBInfo->IF_DEF_LVDS == 1) {
if (!(XGI_XG27GetPSCValue(pVBInfo) & 0x1)) {
/* LVDS VDD on */
XGI_XG27BLSignalVDD(0x01, 0x01, pVBInfo);
mdelay(xgifb_info->lvds_data.PSC_S2);
}
if (!(XGI_XG27GetPSCValue(pVBInfo) & 0x20))
/* LVDS signal on */
XGI_XG27BLSignalVDD(0x20, 0x20, pVBInfo);
mdelay(xgifb_info->lvds_data.PSC_S3);
/* LVDS backlight on */
XGI_XG27BLSignalVDD(0x02, 0x02, pVBInfo);
} else {
/* DVO/DVI signal on */
XGI_XG27BLSignalVDD(0x20, 0x20, pVBInfo);
}
}
}
void XGI_DisplayOff(struct xgifb_video_info *xgifb_info,
struct xgi_hw_device_info *pXGIHWDE,
struct vb_device_info *pVBInfo)
{
if (pXGIHWDE->jChipType == XG21) {
if (pVBInfo->IF_DEF_LVDS == 1) {
/* LVDS backlight off */
XGI_XG21BLSignalVDD(0x02, 0x00, pVBInfo);
mdelay(xgifb_info->lvds_data.PSC_S3);
} else {
/* DVO/DVI signal off */
XGI_XG21BLSignalVDD(0x20, 0x00, pVBInfo);
}
}
if (pXGIHWDE->jChipType == XG27) {
if ((XGI_XG27GetPSCValue(pVBInfo) & 0x2)) {
/* LVDS backlight off */
XGI_XG27BLSignalVDD(0x02, 0x00, pVBInfo);
mdelay(xgifb_info->lvds_data.PSC_S3);
}
if (pVBInfo->IF_DEF_LVDS == 0)
/* DVO/DVI signal off */
XGI_XG27BLSignalVDD(0x20, 0x00, pVBInfo);
}
xgifb_reg_and_or(pVBInfo->P3c4, 0x01, 0xDF, 0x20);
}
static void XGI_WaitDisply(struct vb_device_info *pVBInfo)
{
while ((inb(pVBInfo->P3da) & 0x01))
break;
while (!(inb(pVBInfo->P3da) & 0x01))
break;
}
static void XGI_AutoThreshold(struct vb_device_info *pVBInfo)
{
xgifb_reg_or(pVBInfo->Part1Port, 0x01, 0x40);
}
static void XGI_SaveCRT2Info(unsigned short ModeNo,
struct vb_device_info *pVBInfo)
{
unsigned short temp1, temp2;
/* reserve CR34 for CRT1 Mode No */
xgifb_reg_set(pVBInfo->P3d4, 0x34, ModeNo);
temp1 = (pVBInfo->VBInfo & SetInSlaveMode) >> 8;
temp2 = ~(SetInSlaveMode >> 8);
xgifb_reg_and_or(pVBInfo->P3d4, 0x31, temp2, temp1);
}
static void XGI_GetCRT2ResInfo(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short xres, yres, modeflag, resindex;
resindex = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
xres = XGI330_ModeResInfo[resindex].HTotal; /* xres->ax */
yres = XGI330_ModeResInfo[resindex].VTotal; /* yres->bx */
/* si+St_ModeFlag */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
if (modeflag & HalfDCLK)
xres *= 2;
if (modeflag & DoubleScanMode)
yres *= 2;
if (!(pVBInfo->VBInfo & SetCRT2ToLCD))
goto exit;
if (pVBInfo->LCDResInfo == Panel_1600x1200) {
if (!(pVBInfo->LCDInfo & XGI_LCDVESATiming)) {
if (yres == 1024)
yres = 1056;
}
}
if (pVBInfo->LCDResInfo == Panel_1280x1024) {
if (yres == 400)
yres = 405;
else if (yres == 350)
yres = 360;
if (pVBInfo->LCDInfo & XGI_LCDVESATiming) {
if (yres == 360)
yres = 375;
}
}
if (pVBInfo->LCDResInfo == Panel_1024x768) {
if (!(pVBInfo->LCDInfo & XGI_LCDVESATiming)) {
if (!(pVBInfo->LCDInfo & LCDNonExpanding)) {
if (yres == 350)
yres = 357;
else if (yres == 400)
yres = 420;
else if (yres == 480)
yres = 525;
}
}
}
if (xres == 720)
xres = 640;
exit:
pVBInfo->VGAHDE = xres;
pVBInfo->HDE = xres;
pVBInfo->VGAVDE = yres;
pVBInfo->VDE = yres;
}
static unsigned char XGI_IsLCDDualLink(struct vb_device_info *pVBInfo)
{
if ((pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)) &&
(pVBInfo->LCDInfo & SetLCDDualLink)) /* shampoo0129 */
return 1;
return 0;
}
static void XGI_GetRAMDAC2DATA(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempax, tempbx, temp1, temp2, modeflag = 0, tempcx,
CRT1Index;
pVBInfo->RVBHCMAX = 1;
pVBInfo->RVBHCFACT = 1;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
CRT1Index = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRT1CRTC;
CRT1Index &= IndexMask;
temp1 = (unsigned short) XGI_CRT1Table[CRT1Index].CR[0];
temp2 = (unsigned short) XGI_CRT1Table[CRT1Index].CR[5];
tempax = (temp1 & 0xFF) | ((temp2 & 0x03) << 8);
tempbx = (unsigned short) XGI_CRT1Table[CRT1Index].CR[8];
tempcx = (unsigned short)
XGI_CRT1Table[CRT1Index].CR[14] << 8;
tempcx &= 0x0100;
tempcx <<= 2;
tempbx |= tempcx;
temp1 = (unsigned short) XGI_CRT1Table[CRT1Index].CR[9];
if (temp1 & 0x01)
tempbx |= 0x0100;
if (temp1 & 0x20)
tempbx |= 0x0200;
tempax += 5;
if (modeflag & Charx8Dot)
tempax *= 8;
else
tempax *= 9;
pVBInfo->VGAHT = tempax;
pVBInfo->HT = tempax;
tempbx++;
pVBInfo->VGAVT = tempbx;
pVBInfo->VT = tempbx;
}
static void XGI_GetCRT2Data(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempax = 0, tempbx = 0, modeflag, resinfo;
struct SiS_LCDData const *LCDPtr = NULL;
/* si+Ext_ResInfo */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
resinfo = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
pVBInfo->NewFlickerMode = 0;
pVBInfo->RVBHRS = 50;
if (pVBInfo->VBInfo & SetCRT2ToRAMDAC) {
XGI_GetRAMDAC2DATA(ModeIdIndex, RefreshRateTableIndex, pVBInfo);
return;
}
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)) {
LCDPtr = XGI_GetLcdPtr(XGI_LCDDataTable, ModeIdIndex,
pVBInfo);
pVBInfo->RVBHCMAX = LCDPtr->RVBHCMAX;
pVBInfo->RVBHCFACT = LCDPtr->RVBHCFACT;
pVBInfo->VGAHT = LCDPtr->VGAHT;
pVBInfo->VGAVT = LCDPtr->VGAVT;
pVBInfo->HT = LCDPtr->LCDHT;
pVBInfo->VT = LCDPtr->LCDVT;
if (pVBInfo->LCDResInfo == Panel_1024x768) {
tempax = 1024;
tempbx = 768;
if (!(pVBInfo->LCDInfo & XGI_LCDVESATiming)) {
if (pVBInfo->VGAVDE == 357)
tempbx = 527;
else if (pVBInfo->VGAVDE == 420)
tempbx = 620;
else if (pVBInfo->VGAVDE == 525)
tempbx = 775;
else if (pVBInfo->VGAVDE == 600)
tempbx = 775;
}
} else if (pVBInfo->LCDResInfo == Panel_1024x768x75) {
tempax = 1024;
tempbx = 768;
} else if (pVBInfo->LCDResInfo == Panel_1280x1024) {
tempax = 1280;
if (pVBInfo->VGAVDE == 360)
tempbx = 768;
else if (pVBInfo->VGAVDE == 375)
tempbx = 800;
else if (pVBInfo->VGAVDE == 405)
tempbx = 864;
else
tempbx = 1024;
} else if (pVBInfo->LCDResInfo == Panel_1280x1024x75) {
tempax = 1280;
tempbx = 1024;
} else if (pVBInfo->LCDResInfo == Panel_1280x960) {
tempax = 1280;
if (pVBInfo->VGAVDE == 350)
tempbx = 700;
else if (pVBInfo->VGAVDE == 400)
tempbx = 800;
else if (pVBInfo->VGAVDE == 1024)
tempbx = 960;
else
tempbx = 960;
} else if (pVBInfo->LCDResInfo == Panel_1400x1050) {
tempax = 1400;
tempbx = 1050;
if (pVBInfo->VGAVDE == 1024) {
tempax = 1280;
tempbx = 1024;
}
} else if (pVBInfo->LCDResInfo == Panel_1600x1200) {
tempax = 1600;
tempbx = 1200; /* alan 10/14/2003 */
if (!(pVBInfo->LCDInfo & XGI_LCDVESATiming)) {
if (pVBInfo->VGAVDE == 350)
tempbx = 875;
else if (pVBInfo->VGAVDE == 400)
tempbx = 1000;
}
}
if (pVBInfo->LCDInfo & LCDNonExpanding) {
tempax = pVBInfo->VGAHDE;
tempbx = pVBInfo->VGAVDE;
}
pVBInfo->HDE = tempax;
pVBInfo->VDE = tempbx;
return;
}
if (pVBInfo->VBInfo & (SetCRT2ToTV)) {
struct SiS_TVData const *TVPtr;
TVPtr = XGI_GetTVPtr(ModeIdIndex, RefreshRateTableIndex,
pVBInfo);
pVBInfo->RVBHCMAX = TVPtr->RVBHCMAX;
pVBInfo->RVBHCFACT = TVPtr->RVBHCFACT;
pVBInfo->VGAHT = TVPtr->VGAHT;
pVBInfo->VGAVT = TVPtr->VGAVT;
pVBInfo->HDE = TVPtr->TVHDE;
pVBInfo->VDE = TVPtr->TVVDE;
pVBInfo->RVBHRS = TVPtr->RVBHRS;
pVBInfo->NewFlickerMode = TVPtr->FlickerMode;
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
if (resinfo == 0x08)
pVBInfo->NewFlickerMode = 0x40;
else if (resinfo == 0x09)
pVBInfo->NewFlickerMode = 0x40;
else if (resinfo == 0x12)
pVBInfo->NewFlickerMode = 0x40;
if (pVBInfo->VGAVDE == 350)
pVBInfo->TVInfo |= TVSimuMode;
tempax = ExtHiTVHT;
tempbx = ExtHiTVVT;
if (pVBInfo->VBInfo & SetInSlaveMode) {
if (pVBInfo->TVInfo & TVSimuMode) {
tempax = StHiTVHT;
tempbx = StHiTVVT;
if (!(modeflag & Charx8Dot)) {
tempax = StHiTextTVHT;
tempbx = StHiTextTVVT;
}
}
}
} else if (pVBInfo->VBInfo & SetCRT2ToYPbPr525750) {
if (pVBInfo->TVInfo & TVSetYPbPr750p) {
tempax = YPbPrTV750pHT; /* Ext750pTVHT */
tempbx = YPbPrTV750pVT; /* Ext750pTVVT */
}
if (pVBInfo->TVInfo & TVSetYPbPr525p) {
tempax = YPbPrTV525pHT; /* Ext525pTVHT */
tempbx = YPbPrTV525pVT; /* Ext525pTVVT */
} else if (pVBInfo->TVInfo & TVSetYPbPr525i) {
tempax = YPbPrTV525iHT; /* Ext525iTVHT */
tempbx = YPbPrTV525iVT; /* Ext525iTVVT */
if (pVBInfo->TVInfo & NTSC1024x768)
tempax = NTSC1024x768HT;
}
} else {
tempax = PALHT;
tempbx = PALVT;
if (!(pVBInfo->TVInfo & TVSetPAL)) {
tempax = NTSCHT;
tempbx = NTSCVT;
if (pVBInfo->TVInfo & NTSC1024x768)
tempax = NTSC1024x768HT;
}
}
pVBInfo->HT = tempax;
pVBInfo->VT = tempbx;
}
}
static void XGI_SetCRT2VCLK(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned char di_0, di_1, tempal;
tempal = XGI_GetVCLKPtr(RefreshRateTableIndex, ModeIdIndex, pVBInfo);
XGI_GetVCLKLen(tempal, &di_0, &di_1, pVBInfo);
XGI_GetLCDVCLKPtr(&di_0, &di_1, pVBInfo);
if (pVBInfo->VBType & VB_SIS301) { /* shampoo 0129 */
/* 301 */
xgifb_reg_set(pVBInfo->Part4Port, 0x0A, 0x10);
xgifb_reg_set(pVBInfo->Part4Port, 0x0B, di_1);
xgifb_reg_set(pVBInfo->Part4Port, 0x0A, di_0);
} else { /* 301b/302b/301lv/302lv */
xgifb_reg_set(pVBInfo->Part4Port, 0x0A, di_0);
xgifb_reg_set(pVBInfo->Part4Port, 0x0B, di_1);
}
xgifb_reg_set(pVBInfo->Part4Port, 0x00, 0x12);
if (pVBInfo->VBInfo & SetCRT2ToRAMDAC)
xgifb_reg_or(pVBInfo->Part4Port, 0x12, 0x28);
else
xgifb_reg_or(pVBInfo->Part4Port, 0x12, 0x08);
}
static unsigned short XGI_GetColorDepth(unsigned short ModeIdIndex)
{
unsigned short ColorDepth[6] = { 1, 2, 4, 4, 6, 8 };
short index;
unsigned short modeflag;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
index = (modeflag & ModeTypeMask) - ModeEGA;
if (index < 0)
index = 0;
return ColorDepth[index];
}
static unsigned short XGI_GetOffset(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex)
{
unsigned short temp, colordepth, modeinfo, index, infoflag,
ColorDepth[] = { 0x01, 0x02, 0x04 };
modeinfo = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeInfo;
infoflag = XGI330_RefIndex[RefreshRateTableIndex].Ext_InfoFlag;
index = (modeinfo >> 8) & 0xFF;
temp = XGI330_ScreenOffset[index];
if (infoflag & InterlaceMode)
temp <<= 1;
colordepth = XGI_GetColorDepth(ModeIdIndex);
if ((ModeNo >= 0x7C) && (ModeNo <= 0x7E)) {
temp = ModeNo - 0x7C;
colordepth = ColorDepth[temp];
temp = 0x6B;
if (infoflag & InterlaceMode)
temp <<= 1;
}
return temp * colordepth;
}
static void XGI_SetCRT2Offset(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short offset;
unsigned char temp;
if (pVBInfo->VBInfo & SetInSlaveMode)
return;
offset = XGI_GetOffset(ModeNo, ModeIdIndex, RefreshRateTableIndex);
temp = (unsigned char) (offset & 0xFF);
xgifb_reg_set(pVBInfo->Part1Port, 0x07, temp);
temp = (unsigned char) ((offset & 0xFF00) >> 8);
xgifb_reg_set(pVBInfo->Part1Port, 0x09, temp);
temp = (unsigned char) (((offset >> 3) & 0xFF) + 1);
xgifb_reg_set(pVBInfo->Part1Port, 0x03, temp);
}
static void XGI_SetCRT2FIFO(struct vb_device_info *pVBInfo)
{
/* threshold high ,disable auto threshold */
xgifb_reg_set(pVBInfo->Part1Port, 0x01, 0x3B);
/* threshold low default 04h */
xgifb_reg_and_or(pVBInfo->Part1Port, 0x02, ~(0x3F), 0x04);
}
static void XGI_PreSetGroup1(unsigned short ModeNo, unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
u8 tempcx;
XGI_SetCRT2Offset(ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
XGI_SetCRT2FIFO(pVBInfo);
for (tempcx = 4; tempcx < 7; tempcx++)
xgifb_reg_set(pVBInfo->Part1Port, tempcx, 0x0);
xgifb_reg_set(pVBInfo->Part1Port, 0x50, 0x00);
xgifb_reg_set(pVBInfo->Part1Port, 0x02, 0x44); /* temp 0206 */
}
static void XGI_SetGroup1(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short temp = 0, tempax = 0, tempbx = 0, tempcx = 0,
pushbx = 0, CRT1Index, modeflag;
CRT1Index = XGI330_RefIndex[RefreshRateTableIndex].Ext_CRT1CRTC;
CRT1Index &= IndexMask;
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
/* bainy change table name */
if (modeflag & HalfDCLK) {
/* BTVGA2HT 0x08,0x09 */
temp = (pVBInfo->VGAHT / 2 - 1) & 0x0FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x08, temp);
temp = (((pVBInfo->VGAHT / 2 - 1) & 0xFF00) >> 8) << 4;
xgifb_reg_and_or(pVBInfo->Part1Port, 0x09, ~0x0F0, temp);
/* BTVGA2HDEE 0x0A,0x0C */
temp = (pVBInfo->VGAHDE / 2 + 16) & 0x0FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0A, temp);
tempcx = ((pVBInfo->VGAHT - pVBInfo->VGAHDE) / 2) >> 2;
pushbx = pVBInfo->VGAHDE / 2 + 16;
tempcx >>= 1;
tempbx = pushbx + tempcx; /* bx BTVGA@HRS 0x0B,0x0C */
tempcx += tempbx;
if (pVBInfo->VBInfo & SetCRT2ToRAMDAC) {
tempbx = XGI_CRT1Table[CRT1Index].CR[4];
tempbx |= ((XGI_CRT1Table[CRT1Index].CR[14] &
0xC0) << 2);
tempbx = (tempbx - 3) << 3; /* (VGAHRS-3)*8 */
tempcx = XGI_CRT1Table[CRT1Index].CR[5];
tempcx &= 0x1F;
temp = XGI_CRT1Table[CRT1Index].CR[15];
temp = (temp & 0x04) << (5 - 2); /* VGAHRE D[5] */
tempcx = ((tempcx | temp) - 3) << 3; /* (VGAHRE-3)*8 */
}
tempbx += 4;
tempcx += 4;
if (tempcx > (pVBInfo->VGAHT / 2))
tempcx = pVBInfo->VGAHT / 2;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0B, temp);
} else {
temp = (pVBInfo->VGAHT - 1) & 0x0FF; /* BTVGA2HT 0x08,0x09 */
xgifb_reg_set(pVBInfo->Part1Port, 0x08, temp);
temp = (((pVBInfo->VGAHT - 1) & 0xFF00) >> 8) << 4;
xgifb_reg_and_or(pVBInfo->Part1Port, 0x09, ~0x0F0, temp);
/* BTVGA2HDEE 0x0A,0x0C */
temp = (pVBInfo->VGAHDE + 16) & 0x0FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0A, temp);
tempcx = (pVBInfo->VGAHT - pVBInfo->VGAHDE) >> 2; /* cx */
pushbx = pVBInfo->VGAHDE + 16;
tempcx >>= 1;
tempbx = pushbx + tempcx; /* bx BTVGA@HRS 0x0B,0x0C */
tempcx += tempbx;
if (pVBInfo->VBInfo & SetCRT2ToRAMDAC) {
tempbx = XGI_CRT1Table[CRT1Index].CR[3];
tempbx |= ((XGI_CRT1Table[CRT1Index].CR[5] &
0xC0) << 2);
tempbx = (tempbx - 3) << 3; /* (VGAHRS-3)*8 */
tempcx = XGI_CRT1Table[CRT1Index].CR[4];
tempcx &= 0x1F;
temp = XGI_CRT1Table[CRT1Index].CR[6];
temp = (temp & 0x04) << (5 - 2); /* VGAHRE D[5] */
tempcx = ((tempcx | temp) - 3) << 3; /* (VGAHRE-3)*8 */
tempbx += 16;
tempcx += 16;
}
if (tempcx > pVBInfo->VGAHT)
tempcx = pVBInfo->VGAHT;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0B, temp);
}
tempax = (tempax & 0x00FF) | (tempbx & 0xFF00);
tempbx = pushbx;
tempbx = (tempbx & 0x00FF) | ((tempbx & 0xFF00) << 4);
tempax |= (tempbx & 0xFF00);
temp = (tempax & 0xFF00) >> 8;
xgifb_reg_set(pVBInfo->Part1Port, 0x0C, temp);
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0D, temp);
tempcx = (pVBInfo->VGAVT - 1);
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0E, temp);
tempbx = pVBInfo->VGAVDE - 1;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0F, temp);
temp = ((tempbx & 0xFF00) << 3) >> 8;
temp |= ((tempcx & 0xFF00) >> 8);
xgifb_reg_set(pVBInfo->Part1Port, 0x12, temp);
/* BTVGA2VRS 0x10,0x11 */
tempbx = (pVBInfo->VGAVT + pVBInfo->VGAVDE) >> 1;
/* BTVGA2VRE 0x11 */
tempcx = ((pVBInfo->VGAVT - pVBInfo->VGAVDE) >> 4) + tempbx + 1;
if (pVBInfo->VBInfo & SetCRT2ToRAMDAC) {
tempbx = XGI_CRT1Table[CRT1Index].CR[10];
temp = XGI_CRT1Table[CRT1Index].CR[9];
if (temp & 0x04)
tempbx |= 0x0100;
if (temp & 0x080)
tempbx |= 0x0200;
temp = XGI_CRT1Table[CRT1Index].CR[14];
if (temp & 0x08)
tempbx |= 0x0400;
temp = XGI_CRT1Table[CRT1Index].CR[11];
tempcx = (tempcx & 0xFF00) | (temp & 0x00FF);
}
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x10, temp);
temp = ((tempbx & 0xFF00) >> 8) << 4;
temp = ((tempcx & 0x000F) | (temp));
xgifb_reg_set(pVBInfo->Part1Port, 0x11, temp);
tempax = 0;
if (modeflag & DoubleScanMode)
tempax |= 0x80;
if (modeflag & HalfDCLK)
tempax |= 0x40;
xgifb_reg_and_or(pVBInfo->Part1Port, 0x2C, ~0x0C0, tempax);
}
static unsigned short XGI_GetVGAHT2(struct vb_device_info *pVBInfo)
{
unsigned long tempax, tempbx;
tempbx = ((pVBInfo->VGAVT - pVBInfo->VGAVDE) * pVBInfo->RVBHCMAX)
& 0xFFFF;
tempax = (pVBInfo->VT - pVBInfo->VDE) * pVBInfo->RVBHCFACT;
tempax = (tempax * pVBInfo->HT) / tempbx;
return (unsigned short) tempax;
}
static void XGI_SetLockRegs(unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short push1, push2, tempax, tempbx = 0, tempcx, temp, resinfo,
modeflag;
/* si+Ext_ResInfo */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
resinfo = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
if (!(pVBInfo->VBInfo & SetInSlaveMode))
return;
temp = 0xFF; /* set MAX HT */
xgifb_reg_set(pVBInfo->Part1Port, 0x03, temp);
tempcx = 0x08;
if (pVBInfo->VBType & (VB_SIS301LV | VB_SIS302LV | VB_XGI301C))
modeflag |= Charx8Dot;
tempax = pVBInfo->VGAHDE; /* 0x04 Horizontal Display End */
if (modeflag & HalfDCLK)
tempax >>= 1;
tempax = (tempax / tempcx) - 1;
tempbx |= ((tempax & 0x00FF) << 8);
temp = tempax & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x04, temp);
temp = (tempbx & 0xFF00) >> 8;
if (pVBInfo->VBInfo & SetCRT2ToTV) {
if (!(pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)))
temp += 2;
if ((pVBInfo->VBInfo & SetCRT2ToHiVision) &&
!(pVBInfo->VBType & VB_SIS301LV) && (resinfo == 7))
temp -= 2;
}
/* 0x05 Horizontal Display Start */
xgifb_reg_set(pVBInfo->Part1Port, 0x05, temp);
/* 0x06 Horizontal Blank end */
xgifb_reg_set(pVBInfo->Part1Port, 0x06, 0x03);
if (!(pVBInfo->VBInfo & DisableCRT2Display)) { /* 030226 bainy */
if (pVBInfo->VBInfo & SetCRT2ToTV)
tempax = pVBInfo->VGAHT;
else
tempax = XGI_GetVGAHT2(pVBInfo);
}
if (tempax >= pVBInfo->VGAHT)
tempax = pVBInfo->VGAHT;
if (modeflag & HalfDCLK)
tempax >>= 1;
tempax = (tempax / tempcx) - 5;
tempcx = tempax; /* 20030401 0x07 horizontal Retrace Start */
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
temp = (tempbx & 0x00FF) - 1;
if (!(modeflag & HalfDCLK)) {
temp -= 6;
if (pVBInfo->TVInfo & TVSimuMode) {
temp -= 4;
temp -= 10;
}
}
} else {
tempbx = (tempbx & 0xFF00) >> 8;
tempcx = (tempcx + tempbx) >> 1;
temp = (tempcx & 0x00FF) + 2;
if (pVBInfo->VBInfo & SetCRT2ToTV) {
temp -= 1;
if (!(modeflag & HalfDCLK)) {
if ((modeflag & Charx8Dot)) {
temp += 4;
if (pVBInfo->VGAHDE >= 800)
temp -= 6;
}
}
} else if (!(modeflag & HalfDCLK)) {
temp -= 4;
if (pVBInfo->LCDResInfo != Panel_1280x960 &&
pVBInfo->VGAHDE >= 800) {
temp -= 7;
if (pVBInfo->VGAHDE >= 1280 &&
pVBInfo->LCDResInfo != Panel_1280x960 &&
(pVBInfo->LCDInfo & LCDNonExpanding))
temp += 28;
}
}
}
/* 0x07 Horizontal Retrace Start */
xgifb_reg_set(pVBInfo->Part1Port, 0x07, temp);
/* 0x08 Horizontal Retrace End */
xgifb_reg_set(pVBInfo->Part1Port, 0x08, 0);
if (pVBInfo->VBInfo & SetCRT2ToTV) {
if (pVBInfo->TVInfo & TVSimuMode) {
if (ModeNo == 0x50) {
if (pVBInfo->TVInfo == SetNTSCTV) {
xgifb_reg_set(pVBInfo->Part1Port,
0x07, 0x30);
xgifb_reg_set(pVBInfo->Part1Port,
0x08, 0x03);
} else {
xgifb_reg_set(pVBInfo->Part1Port,
0x07, 0x2f);
xgifb_reg_set(pVBInfo->Part1Port,
0x08, 0x02);
}
}
}
}
xgifb_reg_set(pVBInfo->Part1Port, 0x18, 0x03); /* 0x18 SR0B */
xgifb_reg_and_or(pVBInfo->Part1Port, 0x19, 0xF0, 0x00);
xgifb_reg_set(pVBInfo->Part1Port, 0x09, 0xFF); /* 0x09 Set Max VT */
tempbx = pVBInfo->VGAVT;
push1 = tempbx;
tempcx = 0x121;
tempbx = pVBInfo->VGAVDE; /* 0x0E Virtical Display End */
if (tempbx == 357)
tempbx = 350;
if (tempbx == 360)
tempbx = 350;
if (tempbx == 375)
tempbx = 350;
if (tempbx == 405)
tempbx = 400;
if (tempbx == 525)
tempbx = 480;
push2 = tempbx;
if (pVBInfo->VBInfo & SetCRT2ToLCD) {
if (pVBInfo->LCDResInfo == Panel_1024x768) {
if (!(pVBInfo->LCDInfo & XGI_LCDVESATiming)) {
if (tempbx == 350)
tempbx += 5;
if (tempbx == 480)
tempbx += 5;
}
}
}
tempbx--;
tempbx--;
temp = tempbx & 0x00FF;
/* 0x10 vertical Blank Start */
xgifb_reg_set(pVBInfo->Part1Port, 0x10, temp);
tempbx = push2;
tempbx--;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0E, temp);
if (tempbx & 0x0100)
tempcx |= 0x0002;
tempax = 0x000B;
if (modeflag & DoubleScanMode)
tempax |= 0x08000;
if (tempbx & 0x0200)
tempcx |= 0x0040;
temp = (tempax & 0xFF00) >> 8;
xgifb_reg_set(pVBInfo->Part1Port, 0x0B, temp);
if (tempbx & 0x0400)
tempcx |= 0x0600;
/* 0x11 Vertival Blank End */
xgifb_reg_set(pVBInfo->Part1Port, 0x11, 0x00);
tempax = push1;
tempax -= tempbx; /* 0x0C Vertical Retrace Start */
tempax >>= 2;
push1 = tempax; /* push ax */
if (resinfo != 0x09) {
tempax <<= 1;
tempbx += tempax;
}
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
if ((pVBInfo->VBType & VB_SIS301LV) &&
!(pVBInfo->TVInfo & TVSetHiVision)) {
if ((pVBInfo->TVInfo & TVSimuMode) &&
(pVBInfo->TVInfo & TVSetPAL)) {
if (!(pVBInfo->VBType & VB_SIS301LV) ||
!(pVBInfo->TVInfo &
(TVSetYPbPr525p |
TVSetYPbPr750p |
TVSetHiVision)))
tempbx += 40;
}
} else {
tempbx -= 10;
}
} else if (pVBInfo->TVInfo & TVSimuMode) {
if (pVBInfo->TVInfo & TVSetPAL) {
if (pVBInfo->VBType & VB_SIS301LV) {
if (!(pVBInfo->TVInfo &
(TVSetYPbPr525p |
TVSetYPbPr750p |
TVSetHiVision)))
tempbx += 40;
} else {
tempbx += 40;
}
}
}
tempax = push1;
tempax >>= 2;
tempax++;
tempax += tempbx;
push1 = tempax; /* push ax */
if ((pVBInfo->TVInfo & TVSetPAL)) {
if (tempbx <= 513) {
if (tempax >= 513)
tempbx = 513;
}
}
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0C, temp);
tempbx--;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x10, temp);
if (tempbx & 0x0100)
tempcx |= 0x0008;
if (tempbx & 0x0200)
xgifb_reg_and_or(pVBInfo->Part1Port, 0x0B, 0x0FF, 0x20);
tempbx++;
if (tempbx & 0x0100)
tempcx |= 0x0004;
if (tempbx & 0x0200)
tempcx |= 0x0080;
if (tempbx & 0x0400)
tempcx |= 0x0C00;
tempbx = push1; /* pop ax */
temp = tempbx & 0x00FF;
temp &= 0x0F;
/* 0x0D vertical Retrace End */
xgifb_reg_set(pVBInfo->Part1Port, 0x0D, temp);
if (tempbx & 0x0010)
tempcx |= 0x2000;
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part1Port, 0x0A, temp); /* 0x0A CR07 */
temp = (tempcx & 0x0FF00) >> 8;
xgifb_reg_set(pVBInfo->Part1Port, 0x17, temp); /* 0x17 SR0A */
tempax = modeflag;
temp = (tempax & 0xFF00) >> 8;
temp = (temp >> 1) & 0x09;
if (pVBInfo->VBType & (VB_SIS301LV | VB_SIS302LV | VB_XGI301C))
temp |= 0x01;
xgifb_reg_set(pVBInfo->Part1Port, 0x16, temp); /* 0x16 SR01 */
xgifb_reg_set(pVBInfo->Part1Port, 0x0F, 0); /* 0x0F CR14 */
xgifb_reg_set(pVBInfo->Part1Port, 0x12, 0); /* 0x12 CR17 */
if (pVBInfo->LCDInfo & LCDRGB18Bit)
temp = 0x80;
else
temp = 0x00;
xgifb_reg_set(pVBInfo->Part1Port, 0x1A, temp); /* 0x1A SR0E */
}
static void XGI_SetGroup2(unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short i, j, tempax, tempbx, tempcx, temp, push1, push2,
modeflag;
unsigned char const *TimingPoint;
unsigned long longtemp, tempeax, tempebx, temp2, tempecx;
/* si+Ext_ResInfo */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
tempax = 0;
if (!(pVBInfo->VBInfo & SetCRT2ToAVIDEO))
tempax |= 0x0800;
if (!(pVBInfo->VBInfo & SetCRT2ToSVIDEO))
tempax |= 0x0400;
if (pVBInfo->VBInfo & SetCRT2ToSCART)
tempax |= 0x0200;
if (!(pVBInfo->TVInfo & TVSetPAL))
tempax |= 0x1000;
if (pVBInfo->VBInfo & SetCRT2ToHiVision)
tempax |= 0x0100;
if (pVBInfo->TVInfo & (TVSetYPbPr525p | TVSetYPbPr750p))
tempax &= 0xfe00;
tempax = (tempax & 0xff00) >> 8;
xgifb_reg_set(pVBInfo->Part2Port, 0x0, tempax);
TimingPoint = XGI330_NTSCTiming;
if (pVBInfo->TVInfo & TVSetPAL)
TimingPoint = XGI330_PALTiming;
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
TimingPoint = XGI330_HiTVExtTiming;
if (pVBInfo->VBInfo & SetInSlaveMode)
TimingPoint = XGI330_HiTVSt2Timing;
if (pVBInfo->SetFlag & TVSimuMode)
TimingPoint = XGI330_HiTVSt1Timing;
if (!(modeflag & Charx8Dot))
TimingPoint = XGI330_HiTVTextTiming;
}
if (pVBInfo->VBInfo & SetCRT2ToYPbPr525750) {
if (pVBInfo->TVInfo & TVSetYPbPr525i)
TimingPoint = XGI330_YPbPr525iTiming;
if (pVBInfo->TVInfo & TVSetYPbPr525p)
TimingPoint = XGI330_YPbPr525pTiming;
if (pVBInfo->TVInfo & TVSetYPbPr750p)
TimingPoint = XGI330_YPbPr750pTiming;
}
for (i = 0x01, j = 0; i <= 0x2D; i++, j++)
xgifb_reg_set(pVBInfo->Part2Port, i, TimingPoint[j]);
for (i = 0x39; i <= 0x45; i++, j++)
/* di->temp2[j] */
xgifb_reg_set(pVBInfo->Part2Port, i, TimingPoint[j]);
if (pVBInfo->VBInfo & SetCRT2ToTV)
xgifb_reg_and_or(pVBInfo->Part2Port, 0x3A, 0x1F, 0x00);
temp = pVBInfo->NewFlickerMode;
temp &= 0x80;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x0A, 0xFF, temp);
if (pVBInfo->TVInfo & TVSetPAL)
tempax = 520;
else
tempax = 440;
if (pVBInfo->VDE <= tempax) {
tempax -= pVBInfo->VDE;
tempax >>= 2;
tempax = (tempax & 0x00FF) | ((tempax & 0x00FF) << 8);
push1 = tempax;
temp = (tempax & 0xFF00) >> 8;
temp += (unsigned short) TimingPoint[0];
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
if (pVBInfo->VBInfo & (SetCRT2ToAVIDEO
| SetCRT2ToSVIDEO | SetCRT2ToSCART
| SetCRT2ToYPbPr525750)) {
tempcx = pVBInfo->VGAHDE;
if (tempcx >= 1024) {
temp = 0x17; /* NTSC */
if (pVBInfo->TVInfo & TVSetPAL)
temp = 0x19; /* PAL */
}
}
}
xgifb_reg_set(pVBInfo->Part2Port, 0x01, temp);
tempax = push1;
temp = (tempax & 0xFF00) >> 8;
temp += TimingPoint[1];
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
if ((pVBInfo->VBInfo & (SetCRT2ToAVIDEO
| SetCRT2ToSVIDEO | SetCRT2ToSCART
| SetCRT2ToYPbPr525750))) {
tempcx = pVBInfo->VGAHDE;
if (tempcx >= 1024) {
temp = 0x1D; /* NTSC */
if (pVBInfo->TVInfo & TVSetPAL)
temp = 0x52; /* PAL */
}
}
}
xgifb_reg_set(pVBInfo->Part2Port, 0x02, temp);
}
/* 301b */
tempcx = pVBInfo->HT;
if (XGI_IsLCDDualLink(pVBInfo))
tempcx >>= 1;
tempcx -= 2;
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x1B, temp);
temp = (tempcx & 0xFF00) >> 8;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x1D, ~0x0F, temp);
tempcx = pVBInfo->HT >> 1;
push1 = tempcx; /* push cx */
tempcx += 7;
if (pVBInfo->VBInfo & SetCRT2ToHiVision)
tempcx -= 4;
temp = tempcx & 0x00FF;
temp <<= 4;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x22, 0x0F, temp);
tempbx = TimingPoint[j] | ((TimingPoint[j + 1]) << 8);
tempbx += tempcx;
push2 = tempbx;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x24, temp);
temp = (tempbx & 0xFF00) >> 8;
temp <<= 4;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x25, 0x0F, temp);
tempbx = push2;
tempbx = tempbx + 8;
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
tempbx = tempbx - 4;
tempcx = tempbx;
}
temp = (tempbx & 0x00FF) << 4;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x29, 0x0F, temp);
j += 2;
tempcx += (TimingPoint[j] | ((TimingPoint[j + 1]) << 8));
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x27, temp);
temp = ((tempcx & 0xFF00) >> 8) << 4;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x28, 0x0F, temp);
tempcx += 8;
if (pVBInfo->VBInfo & SetCRT2ToHiVision)
tempcx -= 4;
temp = tempcx & 0xFF;
temp <<= 4;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x2A, 0x0F, temp);
tempcx = push1; /* pop cx */
j += 2;
temp = TimingPoint[j] | ((TimingPoint[j + 1]) << 8);
tempcx -= temp;
temp = tempcx & 0x00FF;
temp <<= 4;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x2D, 0x0F, temp);
tempcx -= 11;
if (!(pVBInfo->VBInfo & SetCRT2ToTV)) {
tempax = XGI_GetVGAHT2(pVBInfo);
tempcx = tempax - 1;
}
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x2E, temp);
tempbx = pVBInfo->VDE;
if (pVBInfo->VGAVDE == 360)
tempbx = 746;
if (pVBInfo->VGAVDE == 375)
tempbx = 746;
if (pVBInfo->VGAVDE == 405)
tempbx = 853;
if (pVBInfo->VBInfo & SetCRT2ToTV) {
if (pVBInfo->VBType &
(VB_SIS301LV | VB_SIS302LV | VB_XGI301C)) {
if (!(pVBInfo->TVInfo &
(TVSetYPbPr525p | TVSetYPbPr750p)))
tempbx >>= 1;
} else
tempbx >>= 1;
}
tempbx -= 2;
temp = tempbx & 0x00FF;
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
if (pVBInfo->VBType & VB_SIS301LV) {
if (pVBInfo->TVInfo & TVSetHiVision) {
if (pVBInfo->VBInfo & SetInSlaveMode) {
if (ModeNo == 0x2f)
temp += 1;
}
}
} else if (pVBInfo->VBInfo & SetInSlaveMode) {
if (ModeNo == 0x2f)
temp += 1;
}
}
xgifb_reg_set(pVBInfo->Part2Port, 0x2F, temp);
temp = (tempcx & 0xFF00) >> 8;
temp |= ((tempbx & 0xFF00) >> 8) << 6;
if (!(pVBInfo->VBInfo & SetCRT2ToHiVision)) {
if (pVBInfo->VBType & VB_SIS301LV) {
if (pVBInfo->TVInfo & TVSetHiVision) {
temp |= 0x10;
if (!(pVBInfo->VBInfo & SetCRT2ToSVIDEO))
temp |= 0x20;
}
} else {
temp |= 0x10;
if (!(pVBInfo->VBInfo & SetCRT2ToSVIDEO))
temp |= 0x20;
}
}
xgifb_reg_set(pVBInfo->Part2Port, 0x30, temp);
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) { /* TV gatingno */
tempbx = pVBInfo->VDE;
tempcx = tempbx - 2;
if (pVBInfo->VBInfo & SetCRT2ToTV) {
if (!(pVBInfo->TVInfo & (TVSetYPbPr525p
| TVSetYPbPr750p)))
tempbx >>= 1;
}
if (pVBInfo->VBType & (VB_SIS302LV | VB_XGI301C)) {
temp = 0;
if (tempcx & 0x0400)
temp |= 0x20;
if (tempbx & 0x0400)
temp |= 0x40;
xgifb_reg_set(pVBInfo->Part4Port, 0x10, temp);
}
temp = (((tempbx - 3) & 0x0300) >> 8) << 5;
xgifb_reg_set(pVBInfo->Part2Port, 0x46, temp);
temp = (tempbx - 3) & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x47, temp);
}
tempbx = tempbx & 0x00FF;
if (!(modeflag & HalfDCLK)) {
tempcx = pVBInfo->VGAHDE;
if (tempcx >= pVBInfo->HDE) {
tempbx |= 0x2000;
tempax &= 0x00FF;
}
}
tempcx = 0x0101;
if (pVBInfo->VBInfo & SetCRT2ToTV) { /*301b*/
if (pVBInfo->VGAHDE >= 1024) {
tempcx = 0x1920;
if (pVBInfo->VGAHDE >= 1280) {
tempcx = 0x1420;
tempbx = tempbx & 0xDFFF;
}
}
}
if (!(tempbx & 0x2000)) {
if (modeflag & HalfDCLK)
tempcx = (tempcx & 0xFF00) | ((tempcx & 0x00FF) << 1);
push1 = tempbx;
tempeax = pVBInfo->VGAHDE;
tempebx = (tempcx & 0xFF00) >> 8;
longtemp = tempeax * tempebx;
tempecx = tempcx & 0x00FF;
longtemp = longtemp / tempecx;
/* 301b */
tempecx = 8 * 1024;
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
tempecx = tempecx * 8;
}
longtemp = longtemp * tempecx;
tempecx = pVBInfo->HDE;
temp2 = longtemp % tempecx;
tempeax = longtemp / tempecx;
if (temp2 != 0)
tempeax += 1;
tempax = (unsigned short) tempeax;
/* 301b */
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
tempcx = ((tempax & 0xFF00) >> 5) >> 8;
}
/* end 301b */
tempbx = push1;
tempbx = (unsigned short) (((tempeax & 0x0000FF00) & 0x1F00)
| (tempbx & 0x00FF));
tempax = (unsigned short) (((tempeax & 0x000000FF) << 8)
| (tempax & 0x00FF));
temp = (tempax & 0xFF00) >> 8;
} else {
temp = (tempax & 0x00FF) >> 8;
}
xgifb_reg_set(pVBInfo->Part2Port, 0x44, temp);
temp = (tempbx & 0xFF00) >> 8;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x45, ~0x03F, temp);
temp = tempcx & 0x00FF;
if (tempbx & 0x2000)
temp = 0;
if (!(pVBInfo->VBInfo & SetCRT2ToLCD))
temp |= 0x18;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x46, ~0x1F, temp);
if (pVBInfo->TVInfo & TVSetPAL) {
tempbx = 0x0382;
tempcx = 0x007e;
} else {
tempbx = 0x0369;
tempcx = 0x0061;
}
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x4b, temp);
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x4c, temp);
temp = ((tempcx & 0xFF00) >> 8) & 0x03;
temp <<= 2;
temp |= ((tempbx & 0xFF00) >> 8) & 0x03;
if (pVBInfo->VBInfo & SetCRT2ToYPbPr525750) {
temp |= 0x10;
if (pVBInfo->TVInfo & TVSetYPbPr525p)
temp |= 0x20;
if (pVBInfo->TVInfo & TVSetYPbPr750p)
temp |= 0x60;
}
xgifb_reg_set(pVBInfo->Part2Port, 0x4d, temp);
temp = xgifb_reg_get(pVBInfo->Part2Port, 0x43); /* 301b change */
xgifb_reg_set(pVBInfo->Part2Port, 0x43, (unsigned short) (temp - 3));
if (!(pVBInfo->TVInfo & (TVSetYPbPr525p | TVSetYPbPr750p))) {
if (pVBInfo->TVInfo & NTSC1024x768) {
TimingPoint = XGI_NTSC1024AdjTime;
for (i = 0x1c, j = 0; i <= 0x30; i++, j++) {
xgifb_reg_set(pVBInfo->Part2Port, i,
TimingPoint[j]);
}
xgifb_reg_set(pVBInfo->Part2Port, 0x43, 0x72);
}
}
/* Modify for 301C PALM Support */
if (pVBInfo->VBType & VB_XGI301C) {
if (pVBInfo->TVInfo & TVSetPALM)
xgifb_reg_and_or(pVBInfo->Part2Port, 0x4E, ~0x08,
0x08); /* PALM Mode */
}
if (pVBInfo->TVInfo & TVSetPALM) {
tempax = xgifb_reg_get(pVBInfo->Part2Port, 0x01);
tempax--;
xgifb_reg_and(pVBInfo->Part2Port, 0x01, tempax);
xgifb_reg_and(pVBInfo->Part2Port, 0x00, 0xEF);
}
if (pVBInfo->VBInfo & SetCRT2ToHiVision) {
if (!(pVBInfo->VBInfo & SetInSlaveMode))
xgifb_reg_set(pVBInfo->Part2Port, 0x0B, 0x00);
}
}
static void XGI_SetLCDRegs(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short pushbx, tempax, tempbx, tempcx, temp, tempah,
tempbh, tempch;
struct XGI_LCDDesStruct const *LCDBDesPtr = NULL;
/* si+Ext_ResInfo */
if (!(pVBInfo->VBInfo & SetCRT2ToLCD))
return;
tempbx = pVBInfo->HDE; /* RHACTE=HDE-1 */
if (XGI_IsLCDDualLink(pVBInfo))
tempbx >>= 1;
tempbx -= 1;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x2C, temp);
temp = (tempbx & 0xFF00) >> 8;
temp <<= 4;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x2B, 0x0F, temp);
temp = 0x01;
xgifb_reg_set(pVBInfo->Part2Port, 0x0B, temp);
tempbx = pVBInfo->VDE; /* RTVACTEO=(VDE-1)&0xFF */
tempbx--;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x03, temp);
temp = ((tempbx & 0xFF00) >> 8) & 0x07;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x0C, ~0x07, temp);
tempcx = pVBInfo->VT - 1;
temp = tempcx & 0x00FF; /* RVTVT=VT-1 */
xgifb_reg_set(pVBInfo->Part2Port, 0x19, temp);
temp = (tempcx & 0xFF00) >> 8;
temp <<= 5;
xgifb_reg_set(pVBInfo->Part2Port, 0x1A, temp);
xgifb_reg_and_or(pVBInfo->Part2Port, 0x09, 0xF0, 0x00);
xgifb_reg_and_or(pVBInfo->Part2Port, 0x0A, 0xF0, 0x00);
xgifb_reg_and_or(pVBInfo->Part2Port, 0x17, 0xFB, 0x00);
xgifb_reg_and_or(pVBInfo->Part2Port, 0x18, 0xDF, 0x00);
/* Customized LCDB Does not add */
if ((pVBInfo->VBType & VB_SIS301LV) || (pVBInfo->VBType & VB_SIS302LV))
LCDBDesPtr = XGI_GetLcdPtr(xgifb_lcddldes, ModeIdIndex,
pVBInfo);
else
LCDBDesPtr = XGI_GetLcdPtr(XGI_LCDDesDataTable, ModeIdIndex,
pVBInfo);
tempah = pVBInfo->LCDResInfo;
tempah &= PanelResInfo;
if ((tempah == Panel_1024x768) || (tempah == Panel_1024x768x75)) {
tempbx = 1024;
tempcx = 768;
} else if ((tempah == Panel_1280x1024) ||
(tempah == Panel_1280x1024x75)) {
tempbx = 1280;
tempcx = 1024;
} else if (tempah == Panel_1400x1050) {
tempbx = 1400;
tempcx = 1050;
} else {
tempbx = 1600;
tempcx = 1200;
}
if (pVBInfo->LCDInfo & EnableScalingLCD) {
tempbx = pVBInfo->HDE;
tempcx = pVBInfo->VDE;
}
pushbx = tempbx;
tempax = pVBInfo->VT;
pVBInfo->LCDHDES = LCDBDesPtr->LCDHDES;
pVBInfo->LCDHRS = LCDBDesPtr->LCDHRS;
pVBInfo->LCDVDES = LCDBDesPtr->LCDVDES;
pVBInfo->LCDVRS = LCDBDesPtr->LCDVRS;
tempbx = pVBInfo->LCDVDES;
tempcx += tempbx;
if (tempcx >= tempax)
tempcx -= tempax; /* lcdvdes */
temp = tempbx & 0x00FF; /* RVEQ1EQ=lcdvdes */
xgifb_reg_set(pVBInfo->Part2Port, 0x05, temp);
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x06, temp);
tempch = ((tempcx & 0xFF00) >> 8) & 0x07;
tempbh = ((tempbx & 0xFF00) >> 8) & 0x07;
tempah = tempch;
tempah <<= 3;
tempah |= tempbh;
xgifb_reg_set(pVBInfo->Part2Port, 0x02, tempah);
/* getlcdsync() */
XGI_GetLCDSync(&tempax, &tempbx, pVBInfo);
tempcx = tempbx;
tempax = pVBInfo->VT;
tempbx = pVBInfo->LCDVRS;
tempcx += tempbx;
if (tempcx >= tempax)
tempcx -= tempax;
temp = tempbx & 0x00FF; /* RTVACTEE=lcdvrs */
xgifb_reg_set(pVBInfo->Part2Port, 0x04, temp);
temp = (tempbx & 0xFF00) >> 8;
temp <<= 4;
temp |= (tempcx & 0x000F);
xgifb_reg_set(pVBInfo->Part2Port, 0x01, temp);
tempcx = pushbx;
tempax = pVBInfo->HT;
tempbx = pVBInfo->LCDHDES;
tempbx &= 0x0FFF;
if (XGI_IsLCDDualLink(pVBInfo)) {
tempax >>= 1;
tempbx >>= 1;
tempcx >>= 1;
}
if (pVBInfo->VBType & VB_SIS302LV)
tempbx += 1;
if (pVBInfo->VBType & VB_XGI301C) /* tap4 */
tempbx += 1;
tempcx += tempbx;
if (tempcx >= tempax)
tempcx -= tempax;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x1F, temp); /* RHBLKE=lcdhdes */
temp = ((tempbx & 0xFF00) >> 8) << 4;
xgifb_reg_set(pVBInfo->Part2Port, 0x20, temp);
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part2Port, 0x23, temp); /* RHEQPLE=lcdhdee */
temp = (tempcx & 0xFF00) >> 8;
xgifb_reg_set(pVBInfo->Part2Port, 0x25, temp);
XGI_GetLCDSync(&tempax, &tempbx, pVBInfo);
tempcx = tempax;
tempax = pVBInfo->HT;
tempbx = pVBInfo->LCDHRS;
if (XGI_IsLCDDualLink(pVBInfo)) {
tempax >>= 1;
tempbx >>= 1;
tempcx >>= 1;
}
if (pVBInfo->VBType & VB_SIS302LV)
tempbx += 1;
tempcx += tempbx;
if (tempcx >= tempax)
tempcx -= tempax;
temp = tempbx & 0x00FF; /* RHBURSTS=lcdhrs */
xgifb_reg_set(pVBInfo->Part2Port, 0x1C, temp);
temp = (tempbx & 0xFF00) >> 8;
temp <<= 4;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x1D, ~0x0F0, temp);
temp = tempcx & 0x00FF; /* RHSYEXP2S=lcdhre */
xgifb_reg_set(pVBInfo->Part2Port, 0x21, temp);
if (!(pVBInfo->LCDInfo & XGI_LCDVESATiming)) {
if (pVBInfo->VGAVDE == 525) {
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B
| VB_SIS301LV | VB_SIS302LV
| VB_XGI301C)) {
temp = 0xC6;
} else
temp = 0xC4;
xgifb_reg_set(pVBInfo->Part2Port, 0x2f, temp);
xgifb_reg_set(pVBInfo->Part2Port, 0x30, 0xB3);
}
if (pVBInfo->VGAVDE == 420) {
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B
| VB_SIS301LV | VB_SIS302LV
| VB_XGI301C)) {
temp = 0x4F;
} else
temp = 0x4E;
xgifb_reg_set(pVBInfo->Part2Port, 0x2f, temp);
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetTap4Ptr */
/* Input : */
/* Output : di -> Tap4 Reg. Setting Pointer */
/* Description : */
/* --------------------------------------------------------------------- */
static struct XGI301C_Tap4TimingStruct const
*XGI_GetTap4Ptr(unsigned short tempcx, struct vb_device_info *pVBInfo)
{
unsigned short tempax, tempbx, i;
struct XGI301C_Tap4TimingStruct const *Tap4TimingPtr;
if (tempcx == 0) {
tempax = pVBInfo->VGAHDE;
tempbx = pVBInfo->HDE;
} else {
tempax = pVBInfo->VGAVDE;
tempbx = pVBInfo->VDE;
}
if (tempax <= tempbx)
return &xgifb_tap4_timing[0];
Tap4TimingPtr = xgifb_ntsc_525_tap4_timing; /* NTSC */
if (pVBInfo->TVInfo & TVSetPAL)
Tap4TimingPtr = PALTap4Timing;
if (pVBInfo->VBInfo & SetCRT2ToYPbPr525750) {
if ((pVBInfo->TVInfo & TVSetYPbPr525i) ||
(pVBInfo->TVInfo & TVSetYPbPr525p))
Tap4TimingPtr = xgifb_ntsc_525_tap4_timing;
if (pVBInfo->TVInfo & TVSetYPbPr750p)
Tap4TimingPtr = YPbPr750pTap4Timing;
}
if (pVBInfo->VBInfo & SetCRT2ToHiVision)
Tap4TimingPtr = xgifb_tap4_timing;
i = 0;
while (Tap4TimingPtr[i].DE != 0xFFFF) {
if (Tap4TimingPtr[i].DE == tempax)
break;
i++;
}
return &Tap4TimingPtr[i];
}
static void XGI_SetTap4Regs(struct vb_device_info *pVBInfo)
{
unsigned short i, j;
struct XGI301C_Tap4TimingStruct const *Tap4TimingPtr;
if (!(pVBInfo->VBType & VB_XGI301C))
return;
Tap4TimingPtr = XGI_GetTap4Ptr(0, pVBInfo); /* Set Horizontal Scaling */
for (i = 0x80, j = 0; i <= 0xBF; i++, j++)
xgifb_reg_set(pVBInfo->Part2Port, i, Tap4TimingPtr->Reg[j]);
if ((pVBInfo->VBInfo & SetCRT2ToTV) &&
(!(pVBInfo->VBInfo & SetCRT2ToHiVision))) {
/* Set Vertical Scaling */
Tap4TimingPtr = XGI_GetTap4Ptr(1, pVBInfo);
for (i = 0xC0, j = 0; i < 0xFF; i++, j++)
xgifb_reg_set(pVBInfo->Part2Port,
i,
Tap4TimingPtr->Reg[j]);
}
if ((pVBInfo->VBInfo & SetCRT2ToTV) &&
(!(pVBInfo->VBInfo & SetCRT2ToHiVision)))
/* Enable V.Scaling */
xgifb_reg_and_or(pVBInfo->Part2Port, 0x4E, ~0x14, 0x04);
else
/* Enable H.Scaling */
xgifb_reg_and_or(pVBInfo->Part2Port, 0x4E, ~0x14, 0x10);
}
static void XGI_SetGroup3(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short i;
unsigned char const *tempdi;
unsigned short modeflag;
/* si+Ext_ResInfo */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
xgifb_reg_set(pVBInfo->Part3Port, 0x00, 0x00);
if (pVBInfo->TVInfo & TVSetPAL) {
xgifb_reg_set(pVBInfo->Part3Port, 0x13, 0xFA);
xgifb_reg_set(pVBInfo->Part3Port, 0x14, 0xC8);
} else {
xgifb_reg_set(pVBInfo->Part3Port, 0x13, 0xF5);
xgifb_reg_set(pVBInfo->Part3Port, 0x14, 0xB7);
}
if (!(pVBInfo->VBInfo & SetCRT2ToTV))
return;
if (pVBInfo->TVInfo & TVSetPALM) {
xgifb_reg_set(pVBInfo->Part3Port, 0x13, 0xFA);
xgifb_reg_set(pVBInfo->Part3Port, 0x14, 0xC8);
xgifb_reg_set(pVBInfo->Part3Port, 0x3D, 0xA8);
}
if ((pVBInfo->VBInfo & SetCRT2ToHiVision) || (pVBInfo->VBInfo
& SetCRT2ToYPbPr525750)) {
if (pVBInfo->TVInfo & TVSetYPbPr525i)
return;
tempdi = XGI330_HiTVGroup3Data;
if (pVBInfo->SetFlag & TVSimuMode) {
tempdi = XGI330_HiTVGroup3Simu;
if (!(modeflag & Charx8Dot))
tempdi = XGI330_HiTVGroup3Text;
}
if (pVBInfo->TVInfo & TVSetYPbPr525p)
tempdi = XGI330_Ren525pGroup3;
if (pVBInfo->TVInfo & TVSetYPbPr750p)
tempdi = XGI330_Ren750pGroup3;
for (i = 0; i <= 0x3E; i++)
xgifb_reg_set(pVBInfo->Part3Port, i, tempdi[i]);
if (pVBInfo->VBType & VB_XGI301C) { /* Marcovision */
if (pVBInfo->TVInfo & TVSetYPbPr525p)
xgifb_reg_set(pVBInfo->Part3Port, 0x28, 0x3f);
}
}
}
static void XGI_SetGroup4(unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempax, tempcx, tempbx, modeflag, temp, temp2;
unsigned long tempebx, tempeax, templong;
/* si+Ext_ResInfo */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
temp = pVBInfo->RVBHCFACT;
xgifb_reg_set(pVBInfo->Part4Port, 0x13, temp);
tempbx = pVBInfo->RVBHCMAX;
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part4Port, 0x14, temp);
temp2 = ((tempbx & 0xFF00) >> 8) << 7;
tempcx = pVBInfo->VGAHT - 1;
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part4Port, 0x16, temp);
temp = ((tempcx & 0xFF00) >> 8) << 3;
temp2 |= temp;
tempcx = pVBInfo->VGAVT - 1;
if (!(pVBInfo->VBInfo & SetCRT2ToTV))
tempcx -= 5;
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part4Port, 0x17, temp);
temp = temp2 | ((tempcx & 0xFF00) >> 8);
xgifb_reg_set(pVBInfo->Part4Port, 0x15, temp);
xgifb_reg_or(pVBInfo->Part4Port, 0x0D, 0x08);
tempcx = pVBInfo->VBInfo;
tempbx = pVBInfo->VGAHDE;
if (modeflag & HalfDCLK)
tempbx >>= 1;
if (XGI_IsLCDDualLink(pVBInfo))
tempbx >>= 1;
if (tempcx & SetCRT2ToHiVision) {
temp = 0;
if (tempbx <= 1024)
temp = 0xA0;
if (tempbx == 1280)
temp = 0xC0;
} else if (tempcx & SetCRT2ToTV) {
temp = 0xA0;
if (tempbx <= 800)
temp = 0x80;
} else {
temp = 0x80;
if (pVBInfo->VBInfo & SetCRT2ToLCD) {
temp = 0;
if (tempbx > 800)
temp = 0x60;
}
}
if (pVBInfo->TVInfo & (TVSetYPbPr525p | TVSetYPbPr750p)) {
temp = 0x00;
if (pVBInfo->VGAHDE == 1280)
temp = 0x40;
if (pVBInfo->VGAHDE == 1024)
temp = 0x20;
}
xgifb_reg_and_or(pVBInfo->Part4Port, 0x0E, ~0xEF, temp);
tempebx = pVBInfo->VDE;
tempcx = pVBInfo->RVBHRS;
temp = tempcx & 0x00FF;
xgifb_reg_set(pVBInfo->Part4Port, 0x18, temp);
tempeax = pVBInfo->VGAVDE;
tempcx |= 0x04000;
if (tempeax <= tempebx) {
tempcx = (tempcx & (~0x4000));
tempeax = pVBInfo->VGAVDE;
} else {
tempeax -= tempebx;
}
templong = (tempeax * 256 * 1024) % tempebx;
tempeax = (tempeax * 256 * 1024) / tempebx;
tempebx = tempeax;
if (templong != 0)
tempebx++;
temp = (unsigned short) (tempebx & 0x000000FF);
xgifb_reg_set(pVBInfo->Part4Port, 0x1B, temp);
temp = (unsigned short) ((tempebx & 0x0000FF00) >> 8);
xgifb_reg_set(pVBInfo->Part4Port, 0x1A, temp);
tempbx = (unsigned short) (tempebx >> 16);
temp = tempbx & 0x00FF;
temp <<= 4;
temp |= ((tempcx & 0xFF00) >> 8);
xgifb_reg_set(pVBInfo->Part4Port, 0x19, temp);
/* 301b */
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
temp = 0x0028;
xgifb_reg_set(pVBInfo->Part4Port, 0x1C, temp);
tempax = pVBInfo->VGAHDE;
if (modeflag & HalfDCLK)
tempax >>= 1;
if (XGI_IsLCDDualLink(pVBInfo))
tempax >>= 1;
if (pVBInfo->VBInfo & SetCRT2ToLCD) {
if (tempax > 800)
tempax -= 800;
} else if (pVBInfo->VGAHDE > 800) {
if (pVBInfo->VGAHDE == 1024)
tempax = (tempax * 25 / 32) - 1;
else
tempax = (tempax * 20 / 32) - 1;
}
tempax -= 1;
temp = (tempax & 0xFF00) >> 8;
temp = (temp & 0x0003) << 4;
xgifb_reg_set(pVBInfo->Part4Port, 0x1E, temp);
temp = (tempax & 0x00FF);
xgifb_reg_set(pVBInfo->Part4Port, 0x1D, temp);
if (pVBInfo->VBInfo & (SetCRT2ToTV | SetCRT2ToHiVision)) {
if (pVBInfo->VGAHDE > 800)
xgifb_reg_or(pVBInfo->Part4Port, 0x1E, 0x08);
}
temp = 0x0036;
if (pVBInfo->VBInfo & SetCRT2ToTV) {
if (!(pVBInfo->TVInfo & (NTSC1024x768
| TVSetYPbPr525p | TVSetYPbPr750p
| TVSetHiVision))) {
temp |= 0x0001;
if ((pVBInfo->VBInfo & SetInSlaveMode)
&& (!(pVBInfo->TVInfo
& TVSimuMode)))
temp &= (~0x0001);
}
}
xgifb_reg_and_or(pVBInfo->Part4Port, 0x1F, 0x00C0, temp);
tempbx = pVBInfo->HT;
if (XGI_IsLCDDualLink(pVBInfo))
tempbx >>= 1;
tempbx = (tempbx >> 1) - 2;
temp = ((tempbx & 0x0700) >> 8) << 3;
xgifb_reg_and_or(pVBInfo->Part4Port, 0x21, 0x00C0, temp);
temp = tempbx & 0x00FF;
xgifb_reg_set(pVBInfo->Part4Port, 0x22, temp);
}
/* end 301b */
XGI_SetCRT2VCLK(ModeIdIndex, RefreshRateTableIndex, pVBInfo);
}
static void XGINew_EnableCRT2(struct vb_device_info *pVBInfo)
{
xgifb_reg_and_or(pVBInfo->P3c4, 0x1E, 0xFF, 0x20);
}
static void XGI_SetGroup5(struct vb_device_info *pVBInfo)
{
if (pVBInfo->ModeType == ModeVGA) {
if (!(pVBInfo->VBInfo & (SetInSlaveMode | LoadDACFlag
| DisableCRT2Display))) {
XGINew_EnableCRT2(pVBInfo);
}
}
}
static void XGI_DisableGatingCRT(struct vb_device_info *pVBInfo)
{
xgifb_reg_and_or(pVBInfo->P3d4, 0x63, 0xBF, 0x00);
}
static unsigned char XGI_XG21CheckLVDSMode(struct xgifb_video_info *xgifb_info,
unsigned short ModeNo, unsigned short ModeIdIndex)
{
unsigned short xres, yres, colordepth, modeflag, resindex;
resindex = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
xres = XGI330_ModeResInfo[resindex].HTotal; /* xres->ax */
yres = XGI330_ModeResInfo[resindex].VTotal; /* yres->bx */
/* si+St_ModeFlag */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
if (!(modeflag & Charx8Dot)) {
xres /= 9;
xres *= 8;
}
if ((ModeNo > 0x13) && (modeflag & HalfDCLK))
xres *= 2;
if ((ModeNo > 0x13) && (modeflag & DoubleScanMode))
yres *= 2;
if (xres > xgifb_info->lvds_data.LVDSHDE)
return 0;
if (yres > xgifb_info->lvds_data.LVDSVDE)
return 0;
if (xres != xgifb_info->lvds_data.LVDSHDE ||
yres != xgifb_info->lvds_data.LVDSVDE) {
colordepth = XGI_GetColorDepth(ModeIdIndex);
if (colordepth > 2)
return 0;
}
return 1;
}
static void xgifb_set_lvds(struct xgifb_video_info *xgifb_info,
int chip_id,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned char temp, Miscdata;
unsigned short xres, yres, modeflag, resindex;
unsigned short LVDSHT, LVDSHBS, LVDSHRS, LVDSHRE, LVDSHBE;
unsigned short LVDSVT, LVDSVBS, LVDSVRS, LVDSVRE, LVDSVBE;
unsigned short value;
temp = (unsigned char) ((xgifb_info->lvds_data.LVDS_Capability &
(LCDPolarity << 8)) >> 8);
temp &= LCDPolarity;
Miscdata = inb(pVBInfo->P3cc);
outb((Miscdata & 0x3F) | temp, pVBInfo->P3c2);
temp = xgifb_info->lvds_data.LVDS_Capability & LCDPolarity;
/* SR35[7] FP VSync polarity */
xgifb_reg_and_or(pVBInfo->P3c4, 0x35, ~0x80, temp & 0x80);
/* SR30[5] FP HSync polarity */
xgifb_reg_and_or(pVBInfo->P3c4, 0x30, ~0x20, (temp & 0x40) >> 1);
if (chip_id == XG27)
XGI_SetXG27FPBits(pVBInfo);
else
XGI_SetXG21FPBits(pVBInfo);
resindex = XGI330_EModeIDTable[ModeIdIndex].Ext_RESINFO;
xres = XGI330_ModeResInfo[resindex].HTotal; /* xres->ax */
yres = XGI330_ModeResInfo[resindex].VTotal; /* yres->bx */
/* si+St_ModeFlag */
modeflag = XGI330_EModeIDTable[ModeIdIndex].Ext_ModeFlag;
if (!(modeflag & Charx8Dot))
xres = xres * 8 / 9;
LVDSHT = xgifb_info->lvds_data.LVDSHT;
LVDSHBS = xres + (xgifb_info->lvds_data.LVDSHDE - xres) / 2;
if (LVDSHBS > LVDSHT)
LVDSHBS -= LVDSHT;
LVDSHRS = LVDSHBS + xgifb_info->lvds_data.LVDSHFP;
if (LVDSHRS > LVDSHT)
LVDSHRS -= LVDSHT;
LVDSHRE = LVDSHRS + xgifb_info->lvds_data.LVDSHSYNC;
if (LVDSHRE > LVDSHT)
LVDSHRE -= LVDSHT;
LVDSHBE = LVDSHBS + LVDSHT - xgifb_info->lvds_data.LVDSHDE;
LVDSVT = xgifb_info->lvds_data.LVDSVT;
LVDSVBS = yres + (xgifb_info->lvds_data.LVDSVDE - yres) / 2;
if (modeflag & DoubleScanMode)
LVDSVBS += yres / 2;
if (LVDSVBS > LVDSVT)
LVDSVBS -= LVDSVT;
LVDSVRS = LVDSVBS + xgifb_info->lvds_data.LVDSVFP;
if (LVDSVRS > LVDSVT)
LVDSVRS -= LVDSVT;
LVDSVRE = LVDSVRS + xgifb_info->lvds_data.LVDSVSYNC;
if (LVDSVRE > LVDSVT)
LVDSVRE -= LVDSVT;
LVDSVBE = LVDSVBS + LVDSVT - xgifb_info->lvds_data.LVDSVDE;
temp = xgifb_reg_get(pVBInfo->P3d4, 0x11);
xgifb_reg_set(pVBInfo->P3d4, 0x11, temp & 0x7f); /* Unlock CRTC */
if (!(modeflag & Charx8Dot))
xgifb_reg_or(pVBInfo->P3c4, 0x1, 0x1);
/* HT SR0B[1:0] CR00 */
value = (LVDSHT >> 3) - 5;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0B, ~0x03, (value & 0x300) >> 8);
xgifb_reg_set(pVBInfo->P3d4, 0x0, (value & 0xFF));
/* HBS SR0B[5:4] CR02 */
value = (LVDSHBS >> 3) - 1;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0B, ~0x30, (value & 0x300) >> 4);
xgifb_reg_set(pVBInfo->P3d4, 0x2, (value & 0xFF));
/* HBE SR0C[1:0] CR05[7] CR03[4:0] */
value = (LVDSHBE >> 3) - 1;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0C, ~0x03, (value & 0xC0) >> 6);
xgifb_reg_and_or(pVBInfo->P3d4, 0x05, ~0x80, (value & 0x20) << 2);
xgifb_reg_and_or(pVBInfo->P3d4, 0x03, ~0x1F, value & 0x1F);
/* HRS SR0B[7:6] CR04 */
value = (LVDSHRS >> 3) + 2;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0B, ~0xC0, (value & 0x300) >> 2);
xgifb_reg_set(pVBInfo->P3d4, 0x4, (value & 0xFF));
/* Panel HRS SR2F[1:0] SR2E[7:0] */
value--;
xgifb_reg_and_or(pVBInfo->P3c4, 0x2F, ~0x03, (value & 0x300) >> 8);
xgifb_reg_set(pVBInfo->P3c4, 0x2E, (value & 0xFF));
/* HRE SR0C[2] CR05[4:0] */
value = (LVDSHRE >> 3) + 2;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0C, ~0x04, (value & 0x20) >> 3);
xgifb_reg_and_or(pVBInfo->P3d4, 0x05, ~0x1F, value & 0x1F);
/* Panel HRE SR2F[7:2] */
value--;
xgifb_reg_and_or(pVBInfo->P3c4, 0x2F, ~0xFC, value << 2);
/* VT SR0A[0] CR07[5][0] CR06 */
value = LVDSVT - 2;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0A, ~0x01, (value & 0x400) >> 10);
xgifb_reg_and_or(pVBInfo->P3d4, 0x07, ~0x20, (value & 0x200) >> 4);
xgifb_reg_and_or(pVBInfo->P3d4, 0x07, ~0x01, (value & 0x100) >> 8);
xgifb_reg_set(pVBInfo->P3d4, 0x06, (value & 0xFF));
/* VBS SR0A[2] CR09[5] CR07[3] CR15 */
value = LVDSVBS - 1;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0A, ~0x04, (value & 0x400) >> 8);
xgifb_reg_and_or(pVBInfo->P3d4, 0x09, ~0x20, (value & 0x200) >> 4);
xgifb_reg_and_or(pVBInfo->P3d4, 0x07, ~0x08, (value & 0x100) >> 5);
xgifb_reg_set(pVBInfo->P3d4, 0x15, (value & 0xFF));
/* VBE SR0A[4] CR16 */
value = LVDSVBE - 1;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0A, ~0x10, (value & 0x100) >> 4);
xgifb_reg_set(pVBInfo->P3d4, 0x16, (value & 0xFF));
/* VRS SR0A[3] CR7[7][2] CR10 */
value = LVDSVRS - 1;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0A, ~0x08, (value & 0x400) >> 7);
xgifb_reg_and_or(pVBInfo->P3d4, 0x07, ~0x80, (value & 0x200) >> 2);
xgifb_reg_and_or(pVBInfo->P3d4, 0x07, ~0x04, (value & 0x100) >> 6);
xgifb_reg_set(pVBInfo->P3d4, 0x10, (value & 0xFF));
if (chip_id == XG27) {
/* Panel VRS SR35[2:0] SR34[7:0] */
xgifb_reg_and_or(pVBInfo->P3c4, 0x35, ~0x07,
(value & 0x700) >> 8);
xgifb_reg_set(pVBInfo->P3c4, 0x34, value & 0xFF);
} else {
/* Panel VRS SR3F[1:0] SR34[7:0] SR33[0] */
xgifb_reg_and_or(pVBInfo->P3c4, 0x3F, ~0x03,
(value & 0x600) >> 9);
xgifb_reg_set(pVBInfo->P3c4, 0x34, (value >> 1) & 0xFF);
xgifb_reg_and_or(pVBInfo->P3d4, 0x33, ~0x01, value & 0x01);
}
/* VRE SR0A[5] CR11[3:0] */
value = LVDSVRE - 1;
xgifb_reg_and_or(pVBInfo->P3c4, 0x0A, ~0x20, (value & 0x10) << 1);
xgifb_reg_and_or(pVBInfo->P3d4, 0x11, ~0x0F, value & 0x0F);
/* Panel VRE SR3F[7:2] */
if (chip_id == XG27)
xgifb_reg_and_or(pVBInfo->P3c4, 0x3F, ~0xFC,
(value << 2) & 0xFC);
else
/* SR3F[7] has to be 0, h/w bug */
xgifb_reg_and_or(pVBInfo->P3c4, 0x3F, ~0xFC,
(value << 2) & 0x7C);
for (temp = 0, value = 0; temp < 3; temp++) {
xgifb_reg_and_or(pVBInfo->P3c4, 0x31, ~0x30, value);
xgifb_reg_set(pVBInfo->P3c4,
0x2B, xgifb_info->lvds_data.VCLKData1);
xgifb_reg_set(pVBInfo->P3c4,
0x2C, xgifb_info->lvds_data.VCLKData2);
value += 0x10;
}
if (!(modeflag & Charx8Dot)) {
inb(pVBInfo->P3da); /* reset 3da */
outb(0x13, pVBInfo->P3c0); /* set index */
/* set data, panning = 0, shift left 1 dot*/
outb(0x00, pVBInfo->P3c0);
inb(pVBInfo->P3da); /* Enable Attribute */
outb(0x20, pVBInfo->P3c0);
inb(pVBInfo->P3da); /* reset 3da */
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_IsLCDON */
/* Input : */
/* Output : 0 : Skip PSC Control */
/* 1: Disable PSC */
/* Description : */
/* --------------------------------------------------------------------- */
static unsigned char XGI_IsLCDON(struct vb_device_info *pVBInfo)
{
unsigned short tempax;
tempax = pVBInfo->VBInfo;
if (tempax & SetCRT2ToDualEdge)
return 0;
else if (tempax & (DisableCRT2Display | SwitchCRT2 | SetSimuScanMode))
return 1;
return 0;
}
static void XGI_DisableBridge(struct xgifb_video_info *xgifb_info,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short tempah = 0;
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
tempah = 0x3F;
if (!(pVBInfo->VBInfo &
(DisableCRT2Display | SetSimuScanMode))) {
if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA) {
if (pVBInfo->VBInfo & SetCRT2ToDualEdge)
tempah = 0x7F; /* Disable Channel A */
}
}
/* disable part4_1f */
xgifb_reg_and(pVBInfo->Part4Port, 0x1F, tempah);
if (pVBInfo->VBType & (VB_SIS302LV | VB_XGI301C)) {
if (((pVBInfo->VBInfo &
(SetCRT2ToLCD | XGI_SetCRT2ToLCDA))) ||
(XGI_IsLCDON(pVBInfo)))
/* LVDS Driver power down */
xgifb_reg_or(pVBInfo->Part4Port, 0x30, 0x80);
}
if (pVBInfo->VBInfo & (DisableCRT2Display | XGI_SetCRT2ToLCDA |
SetSimuScanMode))
XGI_DisplayOff(xgifb_info, HwDeviceExtension, pVBInfo);
if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)
/* Power down */
xgifb_reg_and(pVBInfo->Part1Port, 0x1e, 0xdf);
/* disable TV as primary VGA swap */
xgifb_reg_and(pVBInfo->P3c4, 0x32, 0xdf);
if ((pVBInfo->VBInfo & (SetSimuScanMode | SetCRT2ToDualEdge)))
xgifb_reg_and(pVBInfo->Part2Port, 0x00, 0xdf);
if ((pVBInfo->VBInfo &
(DisableCRT2Display | SetSimuScanMode)) ||
((!(pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)) &&
(pVBInfo->VBInfo &
(SetCRT2ToRAMDAC | SetCRT2ToLCD | SetCRT2ToTV))))
xgifb_reg_or(pVBInfo->Part1Port, 0x00, 0x80);
if ((pVBInfo->VBInfo &
(DisableCRT2Display | SetSimuScanMode)) ||
(!(pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)) ||
(pVBInfo->VBInfo &
(SetCRT2ToRAMDAC | SetCRT2ToLCD | SetCRT2ToTV))) {
/* save Part1 index 0 */
tempah = xgifb_reg_get(pVBInfo->Part1Port, 0x00);
/* BTDAC = 1, avoid VB reset */
xgifb_reg_or(pVBInfo->Part1Port, 0x00, 0x10);
/* disable CRT2 */
xgifb_reg_and(pVBInfo->Part1Port, 0x1E, 0xDF);
/* restore Part1 index 0 */
xgifb_reg_set(pVBInfo->Part1Port, 0x00, tempah);
}
} else { /* {301} */
if (pVBInfo->VBInfo & (SetCRT2ToLCD | SetCRT2ToTV)) {
xgifb_reg_or(pVBInfo->Part1Port, 0x00, 0x80);
/* Disable CRT2 */
xgifb_reg_and(pVBInfo->Part1Port, 0x1E, 0xDF);
/* Disable TV asPrimary VGA swap */
xgifb_reg_and(pVBInfo->P3c4, 0x32, 0xDF);
}
if (pVBInfo->VBInfo & (DisableCRT2Display | XGI_SetCRT2ToLCDA
| SetSimuScanMode))
XGI_DisplayOff(xgifb_info, HwDeviceExtension, pVBInfo);
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetTVPtrIndex */
/* Input : */
/* Output : */
/* Description : bx 0 : ExtNTSC */
/* 1 : StNTSC */
/* 2 : ExtPAL */
/* 3 : StPAL */
/* 4 : ExtHiTV */
/* 5 : StHiTV */
/* 6 : Ext525i */
/* 7 : St525i */
/* 8 : Ext525p */
/* 9 : St525p */
/* A : Ext750p */
/* B : St750p */
/* --------------------------------------------------------------------- */
static unsigned short XGI_GetTVPtrIndex(struct vb_device_info *pVBInfo)
{
unsigned short tempbx = 0;
if (pVBInfo->TVInfo & TVSetPAL)
tempbx = 2;
if (pVBInfo->TVInfo & TVSetHiVision)
tempbx = 4;
if (pVBInfo->TVInfo & TVSetYPbPr525i)
tempbx = 6;
if (pVBInfo->TVInfo & TVSetYPbPr525p)
tempbx = 8;
if (pVBInfo->TVInfo & TVSetYPbPr750p)
tempbx = 10;
if (pVBInfo->TVInfo & TVSimuMode)
tempbx++;
return tempbx;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetTVPtrIndex2 */
/* Input : */
/* Output : bx 0 : NTSC */
/* 1 : PAL */
/* 2 : PALM */
/* 3 : PALN */
/* 4 : NTSC1024x768 */
/* 5 : PAL-M 1024x768 */
/* 6-7: reserved */
/* cl 0 : YFilter1 */
/* 1 : YFilter2 */
/* ch 0 : 301A */
/* 1 : 301B/302B/301LV/302LV */
/* Description : */
/* --------------------------------------------------------------------- */
static void XGI_GetTVPtrIndex2(unsigned short *tempbx, unsigned char *tempcl,
unsigned char *tempch, struct vb_device_info *pVBInfo)
{
*tempbx = 0;
*tempcl = 0;
*tempch = 0;
if (pVBInfo->TVInfo & TVSetPAL)
*tempbx = 1;
if (pVBInfo->TVInfo & TVSetPALM)
*tempbx = 2;
if (pVBInfo->TVInfo & TVSetPALN)
*tempbx = 3;
if (pVBInfo->TVInfo & NTSC1024x768) {
*tempbx = 4;
if (pVBInfo->TVInfo & TVSetPALM)
*tempbx = 5;
}
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
if ((!(pVBInfo->VBInfo & SetInSlaveMode)) || (pVBInfo->TVInfo
& TVSimuMode)) {
*tempbx += 8;
*tempcl += 1;
}
}
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C))
(*tempch)++;
}
static void XGI_SetDelayComp(struct vb_device_info *pVBInfo)
{
unsigned char tempah, tempbl, tempbh;
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA
| SetCRT2ToTV | SetCRT2ToRAMDAC)) {
tempbh = 0;
tempbl = XGI301TVDelay;
if (pVBInfo->VBInfo & SetCRT2ToDualEdge)
tempbl >>= 4;
if (pVBInfo->VBInfo &
(SetCRT2ToLCD | XGI_SetCRT2ToLCDA)) {
tempbh = XGI301LCDDelay;
if (!(pVBInfo->VBInfo & XGI_SetCRT2ToLCDA))
tempbl = tempbh;
}
tempbl &= 0x0F;
tempbh &= 0xF0;
tempah = xgifb_reg_get(pVBInfo->Part1Port, 0x2D);
if (pVBInfo->VBInfo & (SetCRT2ToRAMDAC | SetCRT2ToLCD
| SetCRT2ToTV)) { /* Channel B */
tempah &= 0xF0;
tempah |= tempbl;
}
if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA) {
/* Channel A */
tempah &= 0x0F;
tempah |= tempbh;
}
xgifb_reg_set(pVBInfo->Part1Port, 0x2D, tempah);
}
}
}
static void XGI_SetLCDCap_A(unsigned short tempcx,
struct vb_device_info *pVBInfo)
{
unsigned short temp;
temp = xgifb_reg_get(pVBInfo->P3d4, 0x37);
if (temp & LCDRGB18Bit) {
xgifb_reg_and_or(pVBInfo->Part1Port, 0x19, 0x0F,
/* Enable Dither */
(unsigned short) (0x20 | (tempcx & 0x00C0)));
xgifb_reg_and_or(pVBInfo->Part1Port, 0x1A, 0x7F, 0x80);
} else {
xgifb_reg_and_or(pVBInfo->Part1Port, 0x19, 0x0F,
(unsigned short) (0x30 | (tempcx & 0x00C0)));
xgifb_reg_and_or(pVBInfo->Part1Port, 0x1A, 0x7F, 0x00);
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetLCDCap_B */
/* Input : cx -> LCD Capability */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
static void XGI_SetLCDCap_B(unsigned short tempcx,
struct vb_device_info *pVBInfo)
{
if (tempcx & EnableLCD24bpp) /* 24bits */
xgifb_reg_and_or(pVBInfo->Part2Port, 0x1A, 0xE0,
(unsigned short) (((tempcx & 0x00ff) >> 6)
| 0x0c));
else
xgifb_reg_and_or(pVBInfo->Part2Port, 0x1A, 0xE0,
(unsigned short) (((tempcx & 0x00ff) >> 6)
| 0x18)); /* Enable Dither */
}
static void XGI_LongWait(struct vb_device_info *pVBInfo)
{
unsigned short i;
i = xgifb_reg_get(pVBInfo->P3c4, 0x1F);
if (!(i & 0xC0)) {
for (i = 0; i < 0xFFFF; i++) {
if (!(inb(pVBInfo->P3da) & 0x08))
break;
}
for (i = 0; i < 0xFFFF; i++) {
if ((inb(pVBInfo->P3da) & 0x08))
break;
}
}
}
static void SetSpectrum(struct vb_device_info *pVBInfo)
{
unsigned short index;
index = XGI_GetLCDCapPtr(pVBInfo);
/* disable down spectrum D[4] */
xgifb_reg_and(pVBInfo->Part4Port, 0x30, 0x8F);
XGI_LongWait(pVBInfo);
xgifb_reg_or(pVBInfo->Part4Port, 0x30, 0x20); /* reset spectrum */
XGI_LongWait(pVBInfo);
xgifb_reg_set(pVBInfo->Part4Port, 0x31,
pVBInfo->LCDCapList[index].Spectrum_31);
xgifb_reg_set(pVBInfo->Part4Port, 0x32,
pVBInfo->LCDCapList[index].Spectrum_32);
xgifb_reg_set(pVBInfo->Part4Port, 0x33,
pVBInfo->LCDCapList[index].Spectrum_33);
xgifb_reg_set(pVBInfo->Part4Port, 0x34,
pVBInfo->LCDCapList[index].Spectrum_34);
XGI_LongWait(pVBInfo);
xgifb_reg_or(pVBInfo->Part4Port, 0x30, 0x40); /* enable spectrum */
}
static void XGI_SetLCDCap(struct vb_device_info *pVBInfo)
{
unsigned short tempcx;
tempcx = pVBInfo->LCDCapList[XGI_GetLCDCapPtr(pVBInfo)].LCD_Capability;
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV |
VB_SIS302LV | VB_XGI301C)) {
if (pVBInfo->VBType &
(VB_SIS301LV | VB_SIS302LV | VB_XGI301C)) {
/* Set 301LV Capability */
xgifb_reg_set(pVBInfo->Part4Port, 0x24,
(unsigned char) (tempcx & 0x1F));
}
/* VB Driving */
xgifb_reg_and_or(pVBInfo->Part4Port, 0x0D,
~((EnableVBCLKDRVLOW | EnablePLLSPLOW) >> 8),
(unsigned short) ((tempcx & (EnableVBCLKDRVLOW
| EnablePLLSPLOW)) >> 8));
if (pVBInfo->VBInfo & SetCRT2ToLCD)
XGI_SetLCDCap_B(tempcx, pVBInfo);
else if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)
XGI_SetLCDCap_A(tempcx, pVBInfo);
if (pVBInfo->VBType & (VB_SIS302LV | VB_XGI301C)) {
if (tempcx & EnableSpectrum)
SetSpectrum(pVBInfo);
}
} else {
/* LVDS,CH7017 */
XGI_SetLCDCap_A(tempcx, pVBInfo);
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetAntiFlicker */
/* Input : */
/* Output : */
/* Description : Set TV Customized Param. */
/* --------------------------------------------------------------------- */
static void XGI_SetAntiFlicker(struct vb_device_info *pVBInfo)
{
unsigned short tempbx;
unsigned char tempah;
if (pVBInfo->TVInfo & (TVSetYPbPr525p | TVSetYPbPr750p))
return;
tempbx = XGI_GetTVPtrIndex(pVBInfo);
tempbx &= 0xFE;
tempah = TVAntiFlickList[tempbx];
tempah <<= 4;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x0A, 0x8F, tempah);
}
static void XGI_SetEdgeEnhance(struct vb_device_info *pVBInfo)
{
unsigned short tempbx;
unsigned char tempah;
tempbx = XGI_GetTVPtrIndex(pVBInfo);
tempbx &= 0xFE;
tempah = TVEdgeList[tempbx];
tempah <<= 5;
xgifb_reg_and_or(pVBInfo->Part2Port, 0x3A, 0x1F, tempah);
}
static void XGI_SetPhaseIncr(struct vb_device_info *pVBInfo)
{
unsigned short tempbx;
unsigned char tempcl, tempch;
unsigned long tempData;
XGI_GetTVPtrIndex2(&tempbx, &tempcl, &tempch, pVBInfo); /* bx, cl, ch */
tempData = TVPhaseList[tempbx];
xgifb_reg_set(pVBInfo->Part2Port, 0x31, (unsigned short) (tempData
& 0x000000FF));
xgifb_reg_set(pVBInfo->Part2Port, 0x32, (unsigned short) ((tempData
& 0x0000FF00) >> 8));
xgifb_reg_set(pVBInfo->Part2Port, 0x33, (unsigned short) ((tempData
& 0x00FF0000) >> 16));
xgifb_reg_set(pVBInfo->Part2Port, 0x34, (unsigned short) ((tempData
& 0xFF000000) >> 24));
}
static void XGI_SetYFilter(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx, index;
unsigned char const *filterPtr;
unsigned char tempcl, tempch, tempal;
XGI_GetTVPtrIndex2(&tempbx, &tempcl, &tempch, pVBInfo); /* bx, cl, ch */
switch (tempbx) {
case 0x00:
case 0x04:
filterPtr = NTSCYFilter1;
break;
case 0x01:
filterPtr = PALYFilter1;
break;
case 0x02:
case 0x05:
case 0x0D:
case 0x03:
filterPtr = xgifb_palmn_yfilter1;
break;
case 0x08:
case 0x0C:
case 0x0A:
case 0x0B:
case 0x09:
filterPtr = xgifb_yfilter2;
break;
default:
return;
}
tempal = XGI330_EModeIDTable[ModeIdIndex].VB_ExtTVYFilterIndex;
if (tempcl == 0)
index = tempal * 4;
else
index = tempal * 7;
if ((tempcl == 0) && (tempch == 1)) {
xgifb_reg_set(pVBInfo->Part2Port, 0x35, 0);
xgifb_reg_set(pVBInfo->Part2Port, 0x36, 0);
xgifb_reg_set(pVBInfo->Part2Port, 0x37, 0);
xgifb_reg_set(pVBInfo->Part2Port, 0x38, filterPtr[index++]);
} else {
xgifb_reg_set(pVBInfo->Part2Port, 0x35, filterPtr[index++]);
xgifb_reg_set(pVBInfo->Part2Port, 0x36, filterPtr[index++]);
xgifb_reg_set(pVBInfo->Part2Port, 0x37, filterPtr[index++]);
xgifb_reg_set(pVBInfo->Part2Port, 0x38, filterPtr[index++]);
}
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
xgifb_reg_set(pVBInfo->Part2Port, 0x48, filterPtr[index++]);
xgifb_reg_set(pVBInfo->Part2Port, 0x49, filterPtr[index++]);
xgifb_reg_set(pVBInfo->Part2Port, 0x4A, filterPtr[index++]);
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_OEM310Setting */
/* Input : */
/* Output : */
/* Description : Customized Param. for 301 */
/* --------------------------------------------------------------------- */
static void XGI_OEM310Setting(unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
XGI_SetDelayComp(pVBInfo);
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA))
XGI_SetLCDCap(pVBInfo);
if (pVBInfo->VBInfo & SetCRT2ToTV) {
XGI_SetPhaseIncr(pVBInfo);
XGI_SetYFilter(ModeIdIndex, pVBInfo);
XGI_SetAntiFlicker(pVBInfo);
if (pVBInfo->VBType & VB_SIS301)
XGI_SetEdgeEnhance(pVBInfo);
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT2ModeRegs */
/* Input : */
/* Output : */
/* Description : Origin code for crt2group */
/* --------------------------------------------------------------------- */
static void XGI_SetCRT2ModeRegs(struct vb_device_info *pVBInfo)
{
unsigned short tempbl;
short tempcl;
unsigned char tempah;
tempah = 0;
if (!(pVBInfo->VBInfo & DisableCRT2Display)) {
tempah = xgifb_reg_get(pVBInfo->Part1Port, 0x00);
tempah &= ~0x10; /* BTRAMDAC */
tempah |= 0x40; /* BTRAM */
if (pVBInfo->VBInfo & (SetCRT2ToRAMDAC | SetCRT2ToTV
| SetCRT2ToLCD)) {
tempah = 0x40; /* BTDRAM */
tempcl = pVBInfo->ModeType;
tempcl -= ModeVGA;
if (tempcl >= 0) {
/* BT Color */
tempah = (0x008 >> tempcl);
if (tempah == 0)
tempah = 1;
tempah |= 0x040;
}
if (pVBInfo->VBInfo & SetInSlaveMode)
tempah ^= 0x50; /* BTDAC */
}
}
xgifb_reg_set(pVBInfo->Part1Port, 0x00, tempah);
tempah = 0x08;
tempbl = 0xf0;
if (pVBInfo->VBInfo & DisableCRT2Display)
goto reg_and_or;
tempah = 0x00;
tempbl = 0xff;
if (!(pVBInfo->VBInfo & (SetCRT2ToRAMDAC | SetCRT2ToTV |
SetCRT2ToLCD | XGI_SetCRT2ToLCDA)))
goto reg_and_or;
if ((pVBInfo->VBInfo & XGI_SetCRT2ToLCDA) &&
(!(pVBInfo->VBInfo & SetSimuScanMode))) {
tempbl &= 0xf7;
tempah |= 0x01;
goto reg_and_or;
}
if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA) {
tempbl &= 0xf7;
tempah |= 0x01;
}
if (!(pVBInfo->VBInfo & (SetCRT2ToRAMDAC | SetCRT2ToTV | SetCRT2ToLCD)))
goto reg_and_or;
tempbl &= 0xf8;
tempah = 0x01;
if (!(pVBInfo->VBInfo & SetInSlaveMode))
tempah |= 0x02;
if (!(pVBInfo->VBInfo & SetCRT2ToRAMDAC)) {
tempah = tempah ^ 0x05;
if (!(pVBInfo->VBInfo & SetCRT2ToLCD))
tempah = tempah ^ 0x01;
}
if (!(pVBInfo->VBInfo & SetCRT2ToDualEdge))
tempah |= 0x08;
reg_and_or:
xgifb_reg_and_or(pVBInfo->Part1Port, 0x2e, tempbl, tempah);
if (pVBInfo->VBInfo & (SetCRT2ToRAMDAC | SetCRT2ToTV | SetCRT2ToLCD
| XGI_SetCRT2ToLCDA)) {
tempah &= (~0x08);
if ((pVBInfo->ModeType == ModeVGA) && (!(pVBInfo->VBInfo
& SetInSlaveMode))) {
tempah |= 0x010;
}
tempah |= 0x080;
if (pVBInfo->VBInfo & SetCRT2ToTV) {
tempah |= 0x020;
if (pVBInfo->VBInfo & DriverMode)
tempah = tempah ^ 0x20;
}
xgifb_reg_and_or(pVBInfo->Part4Port, 0x0D, ~0x0BF, tempah);
tempah = 0;
if (pVBInfo->LCDInfo & SetLCDDualLink)
tempah |= 0x40;
if (pVBInfo->VBInfo & SetCRT2ToTV) {
if (pVBInfo->TVInfo & RPLLDIV2XO)
tempah |= 0x40;
}
if ((pVBInfo->LCDResInfo == Panel_1280x1024)
|| (pVBInfo->LCDResInfo == Panel_1280x1024x75))
tempah |= 0x80;
if (pVBInfo->LCDResInfo == Panel_1280x960)
tempah |= 0x80;
xgifb_reg_set(pVBInfo->Part4Port, 0x0C, tempah);
}
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
tempah = 0;
tempbl = 0xfb;
if (pVBInfo->VBInfo & SetCRT2ToDualEdge) {
tempbl = 0xff;
if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)
tempah |= 0x04; /* shampoo 0129 */
}
xgifb_reg_and_or(pVBInfo->Part1Port, 0x13, tempbl, tempah);
tempah = 0x00;
tempbl = 0xcf;
if (!(pVBInfo->VBInfo & DisableCRT2Display)) {
if (pVBInfo->VBInfo & SetCRT2ToDualEdge)
tempah |= 0x30;
}
xgifb_reg_and_or(pVBInfo->Part1Port, 0x2c, tempbl, tempah);
tempah = 0;
tempbl = 0x3f;
if (!(pVBInfo->VBInfo & DisableCRT2Display)) {
if (pVBInfo->VBInfo & SetCRT2ToDualEdge)
tempah |= 0xc0;
}
xgifb_reg_and_or(pVBInfo->Part4Port, 0x21, tempbl, tempah);
}
tempah = 0;
tempbl = 0x7f;
if (!(pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)) {
tempbl = 0xff;
if (!(pVBInfo->VBInfo & SetCRT2ToDualEdge))
tempah |= 0x80;
}
xgifb_reg_and_or(pVBInfo->Part4Port, 0x23, tempbl, tempah);
if (pVBInfo->VBType & (VB_SIS302LV | VB_XGI301C)) {
if (pVBInfo->LCDInfo & SetLCDDualLink) {
xgifb_reg_or(pVBInfo->Part4Port, 0x27, 0x20);
xgifb_reg_or(pVBInfo->Part4Port, 0x34, 0x10);
}
}
}
void XGI_UnLockCRT2(struct vb_device_info *pVBInfo)
{
xgifb_reg_and_or(pVBInfo->Part1Port, 0x2f, 0xFF, 0x01);
}
void XGI_LockCRT2(struct vb_device_info *pVBInfo)
{
xgifb_reg_and_or(pVBInfo->Part1Port, 0x2F, 0xFE, 0x00);
}
unsigned short XGI_GetRatePtrCRT2(struct xgi_hw_device_info *pXGIHWDE,
unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
const u8 LCDARefreshIndex[] = {
0x00, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x00 };
unsigned short RefreshRateTableIndex, i, index, temp;
index = xgifb_reg_get(pVBInfo->P3d4, 0x33);
index >>= pVBInfo->SelectCRT2Rate;
index &= 0x0F;
if (pVBInfo->LCDInfo & LCDNonExpanding)
index = 0;
if (index > 0)
index--;
if (pVBInfo->SetFlag & ProgrammingCRT2) {
if (pVBInfo->VBInfo & (SetCRT2ToLCD | XGI_SetCRT2ToLCDA)) {
temp = LCDARefreshIndex[pVBInfo->LCDResInfo & 0x07];
if (index > temp)
index = temp;
}
}
RefreshRateTableIndex = XGI330_EModeIDTable[ModeIdIndex].REFindex;
ModeNo = XGI330_RefIndex[RefreshRateTableIndex].ModeID;
if (pXGIHWDE->jChipType >= XG20) { /* for XG20, XG21, XG27 */
if ((XGI330_RefIndex[RefreshRateTableIndex].XRes == 800) &&
(XGI330_RefIndex[RefreshRateTableIndex].YRes == 600)) {
index++;
}
/* do the similar adjustment like XGISearchCRT1Rate() */
if ((XGI330_RefIndex[RefreshRateTableIndex].XRes == 1024) &&
(XGI330_RefIndex[RefreshRateTableIndex].YRes == 768)) {
index++;
}
if ((XGI330_RefIndex[RefreshRateTableIndex].XRes == 1280) &&
(XGI330_RefIndex[RefreshRateTableIndex].YRes == 1024)) {
index++;
}
}
i = 0;
do {
if (XGI330_RefIndex[RefreshRateTableIndex + i].
ModeID != ModeNo)
break;
temp = XGI330_RefIndex[RefreshRateTableIndex + i].Ext_InfoFlag;
temp &= ModeTypeMask;
if (temp < pVBInfo->ModeType)
break;
i++;
index--;
} while (index != 0xFFFF);
if (!(pVBInfo->VBInfo & SetCRT2ToRAMDAC)) {
if (pVBInfo->VBInfo & SetInSlaveMode) {
temp = XGI330_RefIndex[RefreshRateTableIndex + i - 1].
Ext_InfoFlag;
if (temp & InterlaceMode)
i++;
}
}
i--;
if ((pVBInfo->SetFlag & ProgrammingCRT2)) {
temp = XGI_AjustCRT2Rate(ModeIdIndex, RefreshRateTableIndex,
&i, pVBInfo);
}
return RefreshRateTableIndex + i;
}
static void XGI_SetLCDAGroup(unsigned short ModeNo, unsigned short ModeIdIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short RefreshRateTableIndex;
pVBInfo->SetFlag |= ProgrammingCRT2;
RefreshRateTableIndex = XGI_GetRatePtrCRT2(HwDeviceExtension, ModeNo,
ModeIdIndex, pVBInfo);
XGI_GetLVDSResInfo(ModeIdIndex, pVBInfo);
XGI_GetLVDSData(ModeIdIndex, pVBInfo);
XGI_ModCRT1Regs(ModeIdIndex, HwDeviceExtension, pVBInfo);
XGI_SetLVDSRegs(ModeIdIndex, pVBInfo);
XGI_SetCRT2ECLK(ModeIdIndex, RefreshRateTableIndex, pVBInfo);
}
static unsigned char XGI_SetCRT2Group301(unsigned short ModeNo,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short ModeIdIndex, RefreshRateTableIndex;
pVBInfo->SetFlag |= ProgrammingCRT2;
XGI_SearchModeID(ModeNo, &ModeIdIndex);
pVBInfo->SelectCRT2Rate = 4;
RefreshRateTableIndex = XGI_GetRatePtrCRT2(HwDeviceExtension, ModeNo,
ModeIdIndex, pVBInfo);
XGI_SaveCRT2Info(ModeNo, pVBInfo);
XGI_GetCRT2ResInfo(ModeIdIndex, pVBInfo);
XGI_GetCRT2Data(ModeIdIndex, RefreshRateTableIndex, pVBInfo);
XGI_PreSetGroup1(ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
XGI_SetGroup1(ModeIdIndex, RefreshRateTableIndex, pVBInfo);
XGI_SetLockRegs(ModeNo, ModeIdIndex, pVBInfo);
XGI_SetGroup2(ModeNo, ModeIdIndex, pVBInfo);
XGI_SetLCDRegs(ModeIdIndex, pVBInfo);
XGI_SetTap4Regs(pVBInfo);
XGI_SetGroup3(ModeIdIndex, pVBInfo);
XGI_SetGroup4(ModeIdIndex, RefreshRateTableIndex, pVBInfo);
XGI_SetCRT2VCLK(ModeIdIndex, RefreshRateTableIndex, pVBInfo);
XGI_SetGroup5(pVBInfo);
XGI_AutoThreshold(pVBInfo);
return 1;
}
void XGI_SenseCRT1(struct vb_device_info *pVBInfo)
{
unsigned char CRTCData[17] = { 0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81,
0x0B, 0x3E, 0xE9, 0x0B, 0xDF, 0xE7, 0x04, 0x00, 0x00,
0x05, 0x00 };
unsigned char SR01 = 0, SR1F = 0, SR07 = 0, SR06 = 0;
unsigned char CR17, CR63, SR31;
unsigned short temp;
int i;
xgifb_reg_set(pVBInfo->P3c4, 0x05, 0x86);
/* to fix XG42 single LCD sense to CRT+LCD */
xgifb_reg_set(pVBInfo->P3d4, 0x57, 0x4A);
xgifb_reg_set(pVBInfo->P3d4, 0x53, (xgifb_reg_get(
pVBInfo->P3d4, 0x53) | 0x02));
SR31 = xgifb_reg_get(pVBInfo->P3c4, 0x31);
CR63 = xgifb_reg_get(pVBInfo->P3d4, 0x63);
SR01 = xgifb_reg_get(pVBInfo->P3c4, 0x01);
xgifb_reg_set(pVBInfo->P3c4, 0x01, (unsigned char) (SR01 & 0xDF));
xgifb_reg_set(pVBInfo->P3d4, 0x63, (unsigned char) (CR63 & 0xBF));
CR17 = xgifb_reg_get(pVBInfo->P3d4, 0x17);
xgifb_reg_set(pVBInfo->P3d4, 0x17, (unsigned char) (CR17 | 0x80));
SR1F = xgifb_reg_get(pVBInfo->P3c4, 0x1F);
xgifb_reg_set(pVBInfo->P3c4, 0x1F, (unsigned char) (SR1F | 0x04));
SR07 = xgifb_reg_get(pVBInfo->P3c4, 0x07);
xgifb_reg_set(pVBInfo->P3c4, 0x07, (unsigned char) (SR07 & 0xFB));
SR06 = xgifb_reg_get(pVBInfo->P3c4, 0x06);
xgifb_reg_set(pVBInfo->P3c4, 0x06, (unsigned char) (SR06 & 0xC3));
xgifb_reg_set(pVBInfo->P3d4, 0x11, 0x00);
for (i = 0; i < 8; i++)
xgifb_reg_set(pVBInfo->P3d4, (unsigned short) i, CRTCData[i]);
for (i = 8; i < 11; i++)
xgifb_reg_set(pVBInfo->P3d4, (unsigned short) (i + 8),
CRTCData[i]);
for (i = 11; i < 13; i++)
xgifb_reg_set(pVBInfo->P3d4, (unsigned short) (i + 4),
CRTCData[i]);
for (i = 13; i < 16; i++)
xgifb_reg_set(pVBInfo->P3c4, (unsigned short) (i - 3),
CRTCData[i]);
xgifb_reg_set(pVBInfo->P3c4, 0x0E, (unsigned char) (CRTCData[16]
& 0xE0));
xgifb_reg_set(pVBInfo->P3c4, 0x31, 0x00);
xgifb_reg_set(pVBInfo->P3c4, 0x2B, 0x1B);
xgifb_reg_set(pVBInfo->P3c4, 0x2C, 0xE1);
outb(0x00, pVBInfo->P3c8);
for (i = 0; i < 256 * 3; i++)
outb(0x0F, (pVBInfo->P3c8 + 1)); /* DAC_TEST_PARMS */
mdelay(1);
XGI_WaitDisply(pVBInfo);
temp = inb(pVBInfo->P3c2);
if (temp & 0x10)
xgifb_reg_and_or(pVBInfo->P3d4, 0x32, 0xDF, 0x20);
else
xgifb_reg_and_or(pVBInfo->P3d4, 0x32, 0xDF, 0x00);
/* avoid display something, set BLACK DAC if not restore DAC */
outb(0x00, pVBInfo->P3c8);
for (i = 0; i < 256 * 3; i++)
outb(0, (pVBInfo->P3c8 + 1));
xgifb_reg_set(pVBInfo->P3c4, 0x01, SR01);
xgifb_reg_set(pVBInfo->P3d4, 0x63, CR63);
xgifb_reg_set(pVBInfo->P3c4, 0x31, SR31);
xgifb_reg_set(pVBInfo->P3d4, 0x53, (xgifb_reg_get(
pVBInfo->P3d4, 0x53) & 0xFD));
xgifb_reg_set(pVBInfo->P3c4, 0x1F, (unsigned char) SR1F);
}
static void XGI_EnableBridge(struct xgifb_video_info *xgifb_info,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short tempah;
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
if (pVBInfo->VBInfo & SetCRT2ToDualEdge)
/* Power on */
xgifb_reg_set(pVBInfo->Part1Port, 0x1E, 0x20);
if (pVBInfo->VBInfo & (SetCRT2ToLCD | SetCRT2ToTV |
SetCRT2ToRAMDAC)) {
tempah = xgifb_reg_get(pVBInfo->P3c4, 0x32);
tempah &= 0xDF;
if (pVBInfo->VBInfo & SetInSlaveMode) {
if (!(pVBInfo->VBInfo & SetCRT2ToRAMDAC))
tempah |= 0x20;
}
xgifb_reg_set(pVBInfo->P3c4, 0x32, tempah);
xgifb_reg_or(pVBInfo->P3c4, 0x1E, 0x20);
tempah = xgifb_reg_get(pVBInfo->Part1Port, 0x2E);
if (!(tempah & 0x80))
xgifb_reg_or(pVBInfo->Part1Port, 0x2E, 0x80);
xgifb_reg_and(pVBInfo->Part1Port, 0x00, 0x7F);
}
if (!(pVBInfo->VBInfo & DisableCRT2Display)) {
xgifb_reg_and_or(pVBInfo->Part2Port, 0x00, ~0xE0,
0x20); /* shampoo 0129 */
if (pVBInfo->VBType & (VB_SIS302LV | VB_XGI301C)) {
if (pVBInfo->VBInfo &
(SetCRT2ToLCD | XGI_SetCRT2ToLCDA))
/* LVDS PLL power on */
xgifb_reg_and(pVBInfo->Part4Port, 0x2A,
0x7F);
/* LVDS Driver power on */
xgifb_reg_and(pVBInfo->Part4Port, 0x30, 0x7F);
}
}
tempah = 0x00;
if (!(pVBInfo->VBInfo & DisableCRT2Display)) {
tempah = 0xc0;
if (!(pVBInfo->VBInfo & SetSimuScanMode) &&
(pVBInfo->VBInfo & XGI_SetCRT2ToLCDA) &&
(pVBInfo->VBInfo & SetCRT2ToDualEdge)) {
tempah = tempah & 0x40;
if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA)
tempah = tempah ^ 0xC0;
}
}
/* EnablePart4_1F */
xgifb_reg_or(pVBInfo->Part4Port, 0x1F, tempah);
XGI_DisableGatingCRT(pVBInfo);
XGI_DisplayOn(xgifb_info, HwDeviceExtension, pVBInfo);
} /* 301 */
else { /* LVDS */
if (pVBInfo->VBInfo & (SetCRT2ToTV | SetCRT2ToLCD
| XGI_SetCRT2ToLCDA))
/* enable CRT2 */
xgifb_reg_or(pVBInfo->Part1Port, 0x1E, 0x20);
tempah = xgifb_reg_get(pVBInfo->Part1Port, 0x2E);
if (!(tempah & 0x80))
xgifb_reg_or(pVBInfo->Part1Port, 0x2E, 0x80);
xgifb_reg_and(pVBInfo->Part1Port, 0x00, 0x7F);
XGI_DisplayOn(xgifb_info, HwDeviceExtension, pVBInfo);
} /* End of VB */
}
static void XGI_SetCRT1Group(struct xgifb_video_info *xgifb_info,
struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short RefreshRateTableIndex, temp;
XGI_SetSeqRegs(pVBInfo);
outb(XGI330_StandTable.MISC, pVBInfo->P3c2);
XGI_SetCRTCRegs(pVBInfo);
XGI_SetATTRegs(ModeIdIndex, pVBInfo);
XGI_SetGRCRegs(pVBInfo);
XGI_ClearExt1Regs(pVBInfo);
if (HwDeviceExtension->jChipType == XG27) {
if (pVBInfo->IF_DEF_LVDS == 0)
XGI_SetDefaultVCLK(pVBInfo);
}
temp = ~ProgrammingCRT2;
pVBInfo->SetFlag &= temp;
pVBInfo->SelectCRT2Rate = 0;
if (pVBInfo->VBType & (VB_SIS301B | VB_SIS302B | VB_SIS301LV
| VB_SIS302LV | VB_XGI301C)) {
if (pVBInfo->VBInfo & (SetSimuScanMode | XGI_SetCRT2ToLCDA
| SetInSlaveMode)) {
pVBInfo->SetFlag |= ProgrammingCRT2;
}
}
RefreshRateTableIndex = XGI_GetRatePtrCRT2(HwDeviceExtension, ModeNo,
ModeIdIndex, pVBInfo);
if (RefreshRateTableIndex != 0xFFFF) {
XGI_SetSync(RefreshRateTableIndex, pVBInfo);
XGI_SetCRT1CRTC(ModeIdIndex, RefreshRateTableIndex,
pVBInfo, HwDeviceExtension);
XGI_SetCRT1DE(ModeIdIndex, RefreshRateTableIndex, pVBInfo);
XGI_SetCRT1Offset(ModeNo, ModeIdIndex, RefreshRateTableIndex,
HwDeviceExtension, pVBInfo);
XGI_SetCRT1VCLK(ModeIdIndex, HwDeviceExtension,
RefreshRateTableIndex, pVBInfo);
}
if (HwDeviceExtension->jChipType >= XG21) {
temp = xgifb_reg_get(pVBInfo->P3d4, 0x38);
if (temp & 0xA0) {
if (HwDeviceExtension->jChipType == XG27)
XGI_SetXG27CRTC(RefreshRateTableIndex, pVBInfo);
else
XGI_SetXG21CRTC(RefreshRateTableIndex, pVBInfo);
XGI_UpdateXG21CRTC(ModeNo, pVBInfo,
RefreshRateTableIndex);
xgifb_set_lcd(HwDeviceExtension->jChipType,
pVBInfo, RefreshRateTableIndex);
if (pVBInfo->IF_DEF_LVDS == 1)
xgifb_set_lvds(xgifb_info,
HwDeviceExtension->jChipType,
ModeIdIndex, pVBInfo);
}
}
pVBInfo->SetFlag &= (~ProgrammingCRT2);
XGI_SetCRT1FIFO(HwDeviceExtension, pVBInfo);
XGI_SetCRT1ModeRegs(HwDeviceExtension, ModeIdIndex,
RefreshRateTableIndex, pVBInfo);
XGI_LoadDAC(pVBInfo);
}
unsigned char XGISetModeNew(struct xgifb_video_info *xgifb_info,
struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeNo)
{
unsigned short ModeIdIndex;
struct vb_device_info VBINF;
struct vb_device_info *pVBInfo = &VBINF;
pVBInfo->IF_DEF_LVDS = 0;
if (HwDeviceExtension->jChipType >= XG20)
pVBInfo->VBType = 0; /*set VBType default 0*/
XGIRegInit(pVBInfo, xgifb_info->vga_base);
/* for x86 Linux, XG21 LVDS */
if (HwDeviceExtension->jChipType == XG21) {
if ((xgifb_reg_get(pVBInfo->P3d4, 0x38) & 0xE0) == 0xC0)
pVBInfo->IF_DEF_LVDS = 1;
}
if (HwDeviceExtension->jChipType == XG27) {
if ((xgifb_reg_get(pVBInfo->P3d4, 0x38) & 0xE0) == 0xC0) {
if (xgifb_reg_get(pVBInfo->P3d4, 0x30) & 0x20)
pVBInfo->IF_DEF_LVDS = 1;
}
}
InitTo330Pointer(HwDeviceExtension->jChipType, pVBInfo);
if (ModeNo & 0x80)
ModeNo = ModeNo & 0x7F;
xgifb_reg_set(pVBInfo->P3c4, 0x05, 0x86);
if (HwDeviceExtension->jChipType < XG20)
XGI_UnLockCRT2(pVBInfo);
XGI_SearchModeID(ModeNo, &ModeIdIndex);
if (HwDeviceExtension->jChipType < XG20) {
XGI_GetVBInfo(ModeIdIndex, pVBInfo);
XGI_GetTVInfo(ModeIdIndex, pVBInfo);
XGI_GetLCDInfo(ModeIdIndex, pVBInfo);
XGI_DisableBridge(xgifb_info, HwDeviceExtension, pVBInfo);
if (pVBInfo->VBInfo & (SetSimuScanMode | XGI_SetCRT2ToLCDA) ||
(!(pVBInfo->VBInfo & SwitchCRT2))) {
XGI_SetCRT1Group(xgifb_info, HwDeviceExtension, ModeNo,
ModeIdIndex, pVBInfo);
if (pVBInfo->VBInfo & XGI_SetCRT2ToLCDA) {
XGI_SetLCDAGroup(ModeNo, ModeIdIndex,
HwDeviceExtension, pVBInfo);
}
}
if (pVBInfo->VBInfo & (SetSimuScanMode | SwitchCRT2)) {
switch (HwDeviceExtension->ujVBChipID) {
case VB_CHIP_301: /* fall through */
case VB_CHIP_302:
XGI_SetCRT2Group301(ModeNo, HwDeviceExtension,
pVBInfo); /*add for CRT2 */
break;
default:
break;
}
}
XGI_SetCRT2ModeRegs(pVBInfo);
XGI_OEM310Setting(ModeIdIndex, pVBInfo); /*0212*/
XGI_EnableBridge(xgifb_info, HwDeviceExtension, pVBInfo);
} /* !XG20 */
else {
if (pVBInfo->IF_DEF_LVDS == 1)
if (!XGI_XG21CheckLVDSMode(xgifb_info, ModeNo,
ModeIdIndex))
return 0;
pVBInfo->ModeType = XGI330_EModeIDTable[ModeIdIndex].
Ext_ModeFlag & ModeTypeMask;
pVBInfo->SetFlag = 0;
pVBInfo->VBInfo = DisableCRT2Display;
XGI_DisplayOff(xgifb_info, HwDeviceExtension, pVBInfo);
XGI_SetCRT1Group(xgifb_info, HwDeviceExtension, ModeNo,
ModeIdIndex, pVBInfo);
XGI_DisplayOn(xgifb_info, HwDeviceExtension, pVBInfo);
}
XGI_UpdateModeInfo(pVBInfo);
if (HwDeviceExtension->jChipType < XG20)
XGI_LockCRT2(pVBInfo);
return 1;
}
| gpl-2.0 |
ambikadash/linux-fqt | drivers/s390/scsi/zfcp_unit.c | 586 | 6400 | /*
* zfcp device driver
*
* Tracking of manually configured LUNs and helper functions to
* register the LUNs with the SCSI midlayer.
*
* Copyright IBM Corp. 2010
*/
#include "zfcp_def.h"
#include "zfcp_ext.h"
/**
* zfcp_unit_scsi_scan - Register LUN with SCSI midlayer
* @unit: The zfcp LUN/unit to register
*
* When the SCSI midlayer is not allowed to automatically scan and
* attach SCSI devices, zfcp has to register the single devices with
* the SCSI midlayer.
*/
void zfcp_unit_scsi_scan(struct zfcp_unit *unit)
{
struct fc_rport *rport = unit->port->rport;
unsigned int lun;
lun = scsilun_to_int((struct scsi_lun *) &unit->fcp_lun);
if (rport && rport->port_state == FC_PORTSTATE_ONLINE)
scsi_scan_target(&rport->dev, 0, rport->scsi_target_id, lun, 1);
}
static void zfcp_unit_scsi_scan_work(struct work_struct *work)
{
struct zfcp_unit *unit = container_of(work, struct zfcp_unit,
scsi_work);
zfcp_unit_scsi_scan(unit);
put_device(&unit->dev);
}
/**
* zfcp_unit_queue_scsi_scan - Register configured units on port
* @port: The zfcp_port where to register units
*
* After opening a port, all units configured on this port have to be
* registered with the SCSI midlayer. This function should be called
* after calling fc_remote_port_add, so that the fc_rport is already
* ONLINE and the call to scsi_scan_target runs the same way as the
* call in the FC transport class.
*/
void zfcp_unit_queue_scsi_scan(struct zfcp_port *port)
{
struct zfcp_unit *unit;
read_lock_irq(&port->unit_list_lock);
list_for_each_entry(unit, &port->unit_list, list) {
get_device(&unit->dev);
if (scsi_queue_work(port->adapter->scsi_host,
&unit->scsi_work) <= 0)
put_device(&unit->dev);
}
read_unlock_irq(&port->unit_list_lock);
}
static struct zfcp_unit *_zfcp_unit_find(struct zfcp_port *port, u64 fcp_lun)
{
struct zfcp_unit *unit;
list_for_each_entry(unit, &port->unit_list, list)
if (unit->fcp_lun == fcp_lun) {
get_device(&unit->dev);
return unit;
}
return NULL;
}
/**
* zfcp_unit_find - Find and return zfcp_unit with specified FCP LUN
* @port: zfcp_port where to look for the unit
* @fcp_lun: 64 Bit FCP LUN used to identify the zfcp_unit
*
* If zfcp_unit is found, a reference is acquired that has to be
* released later.
*
* Returns: Pointer to the zfcp_unit, or NULL if there is no zfcp_unit
* with the specified FCP LUN.
*/
struct zfcp_unit *zfcp_unit_find(struct zfcp_port *port, u64 fcp_lun)
{
struct zfcp_unit *unit;
read_lock_irq(&port->unit_list_lock);
unit = _zfcp_unit_find(port, fcp_lun);
read_unlock_irq(&port->unit_list_lock);
return unit;
}
/**
* zfcp_unit_release - Drop reference to zfcp_port and free memory of zfcp_unit.
* @dev: pointer to device in zfcp_unit
*/
static void zfcp_unit_release(struct device *dev)
{
struct zfcp_unit *unit = container_of(dev, struct zfcp_unit, dev);
atomic_dec(&unit->port->units);
kfree(unit);
}
/**
* zfcp_unit_enqueue - enqueue unit to unit list of a port.
* @port: pointer to port where unit is added
* @fcp_lun: FCP LUN of unit to be enqueued
* Returns: 0 success
*
* Sets up some unit internal structures and creates sysfs entry.
*/
int zfcp_unit_add(struct zfcp_port *port, u64 fcp_lun)
{
struct zfcp_unit *unit;
int retval = 0;
mutex_lock(&zfcp_sysfs_port_units_mutex);
if (atomic_read(&port->units) == -1) {
/* port is already gone */
retval = -ENODEV;
goto out;
}
unit = zfcp_unit_find(port, fcp_lun);
if (unit) {
put_device(&unit->dev);
retval = -EEXIST;
goto out;
}
unit = kzalloc(sizeof(struct zfcp_unit), GFP_KERNEL);
if (!unit) {
retval = -ENOMEM;
goto out;
}
unit->port = port;
unit->fcp_lun = fcp_lun;
unit->dev.parent = &port->dev;
unit->dev.release = zfcp_unit_release;
unit->dev.groups = zfcp_unit_attr_groups;
INIT_WORK(&unit->scsi_work, zfcp_unit_scsi_scan_work);
if (dev_set_name(&unit->dev, "0x%016llx",
(unsigned long long) fcp_lun)) {
kfree(unit);
retval = -ENOMEM;
goto out;
}
if (device_register(&unit->dev)) {
put_device(&unit->dev);
retval = -ENOMEM;
goto out;
}
atomic_inc(&port->units); /* under zfcp_sysfs_port_units_mutex ! */
write_lock_irq(&port->unit_list_lock);
list_add_tail(&unit->list, &port->unit_list);
write_unlock_irq(&port->unit_list_lock);
zfcp_unit_scsi_scan(unit);
out:
mutex_unlock(&zfcp_sysfs_port_units_mutex);
return retval;
}
/**
* zfcp_unit_sdev - Return SCSI device for zfcp_unit
* @unit: The zfcp_unit where to get the SCSI device for
*
* Returns: scsi_device pointer on success, NULL if there is no SCSI
* device for this zfcp_unit
*
* On success, the caller also holds a reference to the SCSI device
* that must be released with scsi_device_put.
*/
struct scsi_device *zfcp_unit_sdev(struct zfcp_unit *unit)
{
struct Scsi_Host *shost;
struct zfcp_port *port;
unsigned int lun;
lun = scsilun_to_int((struct scsi_lun *) &unit->fcp_lun);
port = unit->port;
shost = port->adapter->scsi_host;
return scsi_device_lookup(shost, 0, port->starget_id, lun);
}
/**
* zfcp_unit_sdev_status - Return zfcp LUN status for SCSI device
* @unit: The unit to lookup the SCSI device for
*
* Returns the zfcp LUN status field of the SCSI device if the SCSI device
* for the zfcp_unit exists, 0 otherwise.
*/
unsigned int zfcp_unit_sdev_status(struct zfcp_unit *unit)
{
unsigned int status = 0;
struct scsi_device *sdev;
struct zfcp_scsi_dev *zfcp_sdev;
sdev = zfcp_unit_sdev(unit);
if (sdev) {
zfcp_sdev = sdev_to_zfcp(sdev);
status = atomic_read(&zfcp_sdev->status);
scsi_device_put(sdev);
}
return status;
}
/**
* zfcp_unit_remove - Remove entry from list of configured units
* @port: The port where to remove the unit from the configuration
* @fcp_lun: The 64 bit LUN of the unit to remove
*
* Returns: -EINVAL if a unit with the specified LUN does not exist,
* 0 on success.
*/
int zfcp_unit_remove(struct zfcp_port *port, u64 fcp_lun)
{
struct zfcp_unit *unit;
struct scsi_device *sdev;
write_lock_irq(&port->unit_list_lock);
unit = _zfcp_unit_find(port, fcp_lun);
if (unit)
list_del(&unit->list);
write_unlock_irq(&port->unit_list_lock);
if (!unit)
return -EINVAL;
sdev = zfcp_unit_sdev(unit);
if (sdev) {
scsi_remove_device(sdev);
scsi_device_put(sdev);
}
put_device(&unit->dev);
device_unregister(&unit->dev);
return 0;
}
| gpl-2.0 |
keiranFTW/semc-kernel-msm7x30 | tools/perf/util/help.c | 586 | 8251 | #include "cache.h"
#include "../builtin.h"
#include "exec_cmd.h"
#include "levenshtein.h"
#include "help.h"
/* most GUI terminals set COLUMNS (although some don't export it) */
static int term_columns(void)
{
char *col_string = getenv("COLUMNS");
int n_cols;
if (col_string && (n_cols = atoi(col_string)) > 0)
return n_cols;
#ifdef TIOCGWINSZ
{
struct winsize ws;
if (!ioctl(1, TIOCGWINSZ, &ws)) {
if (ws.ws_col)
return ws.ws_col;
}
}
#endif
return 80;
}
void add_cmdname(struct cmdnames *cmds, const char *name, size_t len)
{
struct cmdname *ent = malloc(sizeof(*ent) + len + 1);
ent->len = len;
memcpy(ent->name, name, len);
ent->name[len] = 0;
ALLOC_GROW(cmds->names, cmds->cnt + 1, cmds->alloc);
cmds->names[cmds->cnt++] = ent;
}
static void clean_cmdnames(struct cmdnames *cmds)
{
unsigned int i;
for (i = 0; i < cmds->cnt; ++i)
free(cmds->names[i]);
free(cmds->names);
cmds->cnt = 0;
cmds->alloc = 0;
}
static int cmdname_compare(const void *a_, const void *b_)
{
struct cmdname *a = *(struct cmdname **)a_;
struct cmdname *b = *(struct cmdname **)b_;
return strcmp(a->name, b->name);
}
static void uniq(struct cmdnames *cmds)
{
unsigned int i, j;
if (!cmds->cnt)
return;
for (i = j = 1; i < cmds->cnt; i++)
if (strcmp(cmds->names[i]->name, cmds->names[i-1]->name))
cmds->names[j++] = cmds->names[i];
cmds->cnt = j;
}
void exclude_cmds(struct cmdnames *cmds, struct cmdnames *excludes)
{
size_t ci, cj, ei;
int cmp;
ci = cj = ei = 0;
while (ci < cmds->cnt && ei < excludes->cnt) {
cmp = strcmp(cmds->names[ci]->name, excludes->names[ei]->name);
if (cmp < 0)
cmds->names[cj++] = cmds->names[ci++];
else if (cmp == 0)
ci++, ei++;
else if (cmp > 0)
ei++;
}
while (ci < cmds->cnt)
cmds->names[cj++] = cmds->names[ci++];
cmds->cnt = cj;
}
static void pretty_print_string_list(struct cmdnames *cmds, int longest)
{
int cols = 1, rows;
int space = longest + 1; /* min 1 SP between words */
int max_cols = term_columns() - 1; /* don't print *on* the edge */
int i, j;
if (space < max_cols)
cols = max_cols / space;
rows = (cmds->cnt + cols - 1) / cols;
for (i = 0; i < rows; i++) {
printf(" ");
for (j = 0; j < cols; j++) {
unsigned int n = j * rows + i;
unsigned int size = space;
if (n >= cmds->cnt)
break;
if (j == cols-1 || n + rows >= cmds->cnt)
size = 1;
printf("%-*s", size, cmds->names[n]->name);
}
putchar('\n');
}
}
static int is_executable(const char *name)
{
struct stat st;
if (stat(name, &st) || /* stat, not lstat */
!S_ISREG(st.st_mode))
return 0;
return st.st_mode & S_IXUSR;
}
static void list_commands_in_dir(struct cmdnames *cmds,
const char *path,
const char *prefix)
{
int prefix_len;
DIR *dir = opendir(path);
struct dirent *de;
struct strbuf buf = STRBUF_INIT;
int len;
if (!dir)
return;
if (!prefix)
prefix = "perf-";
prefix_len = strlen(prefix);
strbuf_addf(&buf, "%s/", path);
len = buf.len;
while ((de = readdir(dir)) != NULL) {
int entlen;
if (prefixcmp(de->d_name, prefix))
continue;
strbuf_setlen(&buf, len);
strbuf_addstr(&buf, de->d_name);
if (!is_executable(buf.buf))
continue;
entlen = strlen(de->d_name) - prefix_len;
if (has_extension(de->d_name, ".exe"))
entlen -= 4;
add_cmdname(cmds, de->d_name + prefix_len, entlen);
}
closedir(dir);
strbuf_release(&buf);
}
void load_command_list(const char *prefix,
struct cmdnames *main_cmds,
struct cmdnames *other_cmds)
{
const char *env_path = getenv("PATH");
const char *exec_path = perf_exec_path();
if (exec_path) {
list_commands_in_dir(main_cmds, exec_path, prefix);
qsort(main_cmds->names, main_cmds->cnt,
sizeof(*main_cmds->names), cmdname_compare);
uniq(main_cmds);
}
if (env_path) {
char *paths, *path, *colon;
path = paths = strdup(env_path);
while (1) {
if ((colon = strchr(path, PATH_SEP)))
*colon = 0;
if (!exec_path || strcmp(path, exec_path))
list_commands_in_dir(other_cmds, path, prefix);
if (!colon)
break;
path = colon + 1;
}
free(paths);
qsort(other_cmds->names, other_cmds->cnt,
sizeof(*other_cmds->names), cmdname_compare);
uniq(other_cmds);
}
exclude_cmds(other_cmds, main_cmds);
}
void list_commands(const char *title, struct cmdnames *main_cmds,
struct cmdnames *other_cmds)
{
unsigned int i, longest = 0;
for (i = 0; i < main_cmds->cnt; i++)
if (longest < main_cmds->names[i]->len)
longest = main_cmds->names[i]->len;
for (i = 0; i < other_cmds->cnt; i++)
if (longest < other_cmds->names[i]->len)
longest = other_cmds->names[i]->len;
if (main_cmds->cnt) {
const char *exec_path = perf_exec_path();
printf("available %s in '%s'\n", title, exec_path);
printf("----------------");
mput_char('-', strlen(title) + strlen(exec_path));
putchar('\n');
pretty_print_string_list(main_cmds, longest);
putchar('\n');
}
if (other_cmds->cnt) {
printf("%s available from elsewhere on your $PATH\n", title);
printf("---------------------------------------");
mput_char('-', strlen(title));
putchar('\n');
pretty_print_string_list(other_cmds, longest);
putchar('\n');
}
}
int is_in_cmdlist(struct cmdnames *c, const char *s)
{
unsigned int i;
for (i = 0; i < c->cnt; i++)
if (!strcmp(s, c->names[i]->name))
return 1;
return 0;
}
static int autocorrect;
static struct cmdnames aliases;
static int perf_unknown_cmd_config(const char *var, const char *value, void *cb)
{
if (!strcmp(var, "help.autocorrect"))
autocorrect = perf_config_int(var,value);
/* Also use aliases for command lookup */
if (!prefixcmp(var, "alias."))
add_cmdname(&aliases, var + 6, strlen(var + 6));
return perf_default_config(var, value, cb);
}
static int levenshtein_compare(const void *p1, const void *p2)
{
const struct cmdname *const *c1 = p1, *const *c2 = p2;
const char *s1 = (*c1)->name, *s2 = (*c2)->name;
int l1 = (*c1)->len;
int l2 = (*c2)->len;
return l1 != l2 ? l1 - l2 : strcmp(s1, s2);
}
static void add_cmd_list(struct cmdnames *cmds, struct cmdnames *old)
{
unsigned int i;
ALLOC_GROW(cmds->names, cmds->cnt + old->cnt, cmds->alloc);
for (i = 0; i < old->cnt; i++)
cmds->names[cmds->cnt++] = old->names[i];
free(old->names);
old->cnt = 0;
old->names = NULL;
}
const char *help_unknown_cmd(const char *cmd)
{
unsigned int i, n = 0, best_similarity = 0;
struct cmdnames main_cmds, other_cmds;
memset(&main_cmds, 0, sizeof(main_cmds));
memset(&other_cmds, 0, sizeof(main_cmds));
memset(&aliases, 0, sizeof(aliases));
perf_config(perf_unknown_cmd_config, NULL);
load_command_list("perf-", &main_cmds, &other_cmds);
add_cmd_list(&main_cmds, &aliases);
add_cmd_list(&main_cmds, &other_cmds);
qsort(main_cmds.names, main_cmds.cnt,
sizeof(main_cmds.names), cmdname_compare);
uniq(&main_cmds);
if (main_cmds.cnt) {
/* This reuses cmdname->len for similarity index */
for (i = 0; i < main_cmds.cnt; ++i)
main_cmds.names[i]->len =
levenshtein(cmd, main_cmds.names[i]->name, 0, 2, 1, 4);
qsort(main_cmds.names, main_cmds.cnt,
sizeof(*main_cmds.names), levenshtein_compare);
best_similarity = main_cmds.names[0]->len;
n = 1;
while (n < main_cmds.cnt && best_similarity == main_cmds.names[n]->len)
++n;
}
if (autocorrect && n == 1) {
const char *assumed = main_cmds.names[0]->name;
main_cmds.names[0] = NULL;
clean_cmdnames(&main_cmds);
fprintf(stderr, "WARNING: You called a Git program named '%s', "
"which does not exist.\n"
"Continuing under the assumption that you meant '%s'\n",
cmd, assumed);
if (autocorrect > 0) {
fprintf(stderr, "in %0.1f seconds automatically...\n",
(float)autocorrect/10.0);
poll(NULL, 0, autocorrect * 100);
}
return assumed;
}
fprintf(stderr, "perf: '%s' is not a perf-command. See 'perf --help'.\n", cmd);
if (main_cmds.cnt && best_similarity < 6) {
fprintf(stderr, "\nDid you mean %s?\n",
n < 2 ? "this": "one of these");
for (i = 0; i < n; i++)
fprintf(stderr, "\t%s\n", main_cmds.names[i]->name);
}
exit(1);
}
int cmd_version(int argc __used, const char **argv __used, const char *prefix __used)
{
printf("perf version %s\n", perf_version_string);
return 0;
}
| gpl-2.0 |
maz-1/firefly-rk3288-kernel | drivers/media/pci/cx18/cx18-driver.c | 842 | 40250 | /*
* cx18 driver initialization and card probing
*
* Derived from ivtv-driver.c
*
* Copyright (C) 2007 Hans Verkuil <hverkuil@xs4all.nl>
* Copyright (C) 2008 Andy Walls <awalls@md.metrocast.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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
#include "cx18-driver.h"
#include "cx18-io.h"
#include "cx18-version.h"
#include "cx18-cards.h"
#include "cx18-i2c.h"
#include "cx18-irq.h"
#include "cx18-gpio.h"
#include "cx18-firmware.h"
#include "cx18-queue.h"
#include "cx18-streams.h"
#include "cx18-av-core.h"
#include "cx18-scb.h"
#include "cx18-mailbox.h"
#include "cx18-ioctl.h"
#include "cx18-controls.h"
#include "tuner-xc2028.h"
#include <linux/dma-mapping.h>
#include <media/tveeprom.h>
/* If you have already X v4l cards, then set this to X. This way
the device numbers stay matched. Example: you have a WinTV card
without radio and a Compro H900 with. Normally this would give a
video1 device together with a radio0 device for the Compro. By
setting this to 1 you ensure that radio0 is now also radio1. */
int cx18_first_minor;
/* Callback for registering extensions */
int (*cx18_ext_init)(struct cx18 *);
EXPORT_SYMBOL(cx18_ext_init);
/* add your revision and whatnot here */
static struct pci_device_id cx18_pci_tbl[] = {
{PCI_VENDOR_ID_CX, PCI_DEVICE_ID_CX23418,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{0,}
};
MODULE_DEVICE_TABLE(pci, cx18_pci_tbl);
static atomic_t cx18_instance = ATOMIC_INIT(0);
/* Parameter declarations */
static int cardtype[CX18_MAX_CARDS];
static int tuner[CX18_MAX_CARDS] = { -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static int radio[CX18_MAX_CARDS] = { -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1 };
static unsigned cardtype_c = 1;
static unsigned tuner_c = 1;
static unsigned radio_c = 1;
static char pal[] = "--";
static char secam[] = "--";
static char ntsc[] = "-";
/* Buffers */
static int enc_ts_buffers = CX18_DEFAULT_ENC_TS_BUFFERS;
static int enc_mpg_buffers = CX18_DEFAULT_ENC_MPG_BUFFERS;
static int enc_idx_buffers = CX18_DEFAULT_ENC_IDX_BUFFERS;
static int enc_yuv_buffers = CX18_DEFAULT_ENC_YUV_BUFFERS;
static int enc_vbi_buffers = CX18_DEFAULT_ENC_VBI_BUFFERS;
static int enc_pcm_buffers = CX18_DEFAULT_ENC_PCM_BUFFERS;
static int enc_ts_bufsize = CX18_DEFAULT_ENC_TS_BUFSIZE;
static int enc_mpg_bufsize = CX18_DEFAULT_ENC_MPG_BUFSIZE;
static int enc_idx_bufsize = CX18_DEFAULT_ENC_IDX_BUFSIZE;
static int enc_yuv_bufsize = CX18_DEFAULT_ENC_YUV_BUFSIZE;
static int enc_pcm_bufsize = CX18_DEFAULT_ENC_PCM_BUFSIZE;
static int enc_ts_bufs = -1;
static int enc_mpg_bufs = -1;
static int enc_idx_bufs = CX18_MAX_FW_MDLS_PER_STREAM;
static int enc_yuv_bufs = -1;
static int enc_vbi_bufs = -1;
static int enc_pcm_bufs = -1;
static int cx18_pci_latency = 1;
static int mmio_ndelay;
static int retry_mmio = 1;
int cx18_debug;
module_param_array(tuner, int, &tuner_c, 0644);
module_param_array(radio, int, &radio_c, 0644);
module_param_array(cardtype, int, &cardtype_c, 0644);
module_param_string(pal, pal, sizeof(pal), 0644);
module_param_string(secam, secam, sizeof(secam), 0644);
module_param_string(ntsc, ntsc, sizeof(ntsc), 0644);
module_param_named(debug, cx18_debug, int, 0644);
module_param(mmio_ndelay, int, 0644);
module_param(retry_mmio, int, 0644);
module_param(cx18_pci_latency, int, 0644);
module_param(cx18_first_minor, int, 0644);
module_param(enc_ts_buffers, int, 0644);
module_param(enc_mpg_buffers, int, 0644);
module_param(enc_idx_buffers, int, 0644);
module_param(enc_yuv_buffers, int, 0644);
module_param(enc_vbi_buffers, int, 0644);
module_param(enc_pcm_buffers, int, 0644);
module_param(enc_ts_bufsize, int, 0644);
module_param(enc_mpg_bufsize, int, 0644);
module_param(enc_idx_bufsize, int, 0644);
module_param(enc_yuv_bufsize, int, 0644);
module_param(enc_pcm_bufsize, int, 0644);
module_param(enc_ts_bufs, int, 0644);
module_param(enc_mpg_bufs, int, 0644);
module_param(enc_idx_bufs, int, 0644);
module_param(enc_yuv_bufs, int, 0644);
module_param(enc_vbi_bufs, int, 0644);
module_param(enc_pcm_bufs, int, 0644);
MODULE_PARM_DESC(tuner, "Tuner type selection,\n"
"\t\t\tsee tuner.h for values");
MODULE_PARM_DESC(radio,
"Enable or disable the radio. Use only if autodetection\n"
"\t\t\tfails. 0 = disable, 1 = enable");
MODULE_PARM_DESC(cardtype,
"Only use this option if your card is not detected properly.\n"
"\t\tSpecify card type:\n"
"\t\t\t 1 = Hauppauge HVR 1600 (ESMT memory)\n"
"\t\t\t 2 = Hauppauge HVR 1600 (Samsung memory)\n"
"\t\t\t 3 = Compro VideoMate H900\n"
"\t\t\t 4 = Yuan MPC718\n"
"\t\t\t 5 = Conexant Raptor PAL/SECAM\n"
"\t\t\t 6 = Toshiba Qosmio DVB-T/Analog\n"
"\t\t\t 7 = Leadtek WinFast PVR2100\n"
"\t\t\t 8 = Leadtek WinFast DVR3100 H\n"
"\t\t\t 9 = GoTView PCI DVD3 Hybrid\n"
"\t\t\t 10 = Hauppauge HVR 1600 (S5H1411)\n"
"\t\t\t 0 = Autodetect (default)\n"
"\t\t\t-1 = Ignore this card\n\t\t");
MODULE_PARM_DESC(pal, "Set PAL standard: B, G, H, D, K, I, M, N, Nc, 60");
MODULE_PARM_DESC(secam, "Set SECAM standard: B, G, H, D, K, L, LC");
MODULE_PARM_DESC(ntsc, "Set NTSC standard: M, J, K");
MODULE_PARM_DESC(debug,
"Debug level (bitmask). Default: 0\n"
"\t\t\t 1/0x0001: warning\n"
"\t\t\t 2/0x0002: info\n"
"\t\t\t 4/0x0004: mailbox\n"
"\t\t\t 8/0x0008: dma\n"
"\t\t\t 16/0x0010: ioctl\n"
"\t\t\t 32/0x0020: file\n"
"\t\t\t 64/0x0040: i2c\n"
"\t\t\t128/0x0080: irq\n"
"\t\t\t256/0x0100: high volume\n");
MODULE_PARM_DESC(cx18_pci_latency,
"Change the PCI latency to 64 if lower: 0 = No, 1 = Yes,\n"
"\t\t\tDefault: Yes");
MODULE_PARM_DESC(retry_mmio,
"(Deprecated) MMIO writes are now always checked and retried\n"
"\t\t\tEffectively: 1 [Yes]");
MODULE_PARM_DESC(mmio_ndelay,
"(Deprecated) MMIO accesses are now never purposely delayed\n"
"\t\t\tEffectively: 0 ns");
MODULE_PARM_DESC(enc_ts_buffers,
"Encoder TS buffer memory (MB). (enc_ts_bufs can override)\n"
"\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_TS_BUFFERS));
MODULE_PARM_DESC(enc_ts_bufsize,
"Size of an encoder TS buffer (kB)\n"
"\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_TS_BUFSIZE));
MODULE_PARM_DESC(enc_ts_bufs,
"Number of encoder TS buffers\n"
"\t\t\tDefault is computed from other enc_ts_* parameters");
MODULE_PARM_DESC(enc_mpg_buffers,
"Encoder MPG buffer memory (MB). (enc_mpg_bufs can override)\n"
"\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_MPG_BUFFERS));
MODULE_PARM_DESC(enc_mpg_bufsize,
"Size of an encoder MPG buffer (kB)\n"
"\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_MPG_BUFSIZE));
MODULE_PARM_DESC(enc_mpg_bufs,
"Number of encoder MPG buffers\n"
"\t\t\tDefault is computed from other enc_mpg_* parameters");
MODULE_PARM_DESC(enc_idx_buffers,
"(Deprecated) Encoder IDX buffer memory (MB)\n"
"\t\t\tIgnored, except 0 disables IDX buffer allocations\n"
"\t\t\tDefault: 1 [Enabled]");
MODULE_PARM_DESC(enc_idx_bufsize,
"Size of an encoder IDX buffer (kB)\n"
"\t\t\tAllowed values are multiples of 1.5 kB rounded up\n"
"\t\t\t(multiples of size required for 64 index entries)\n"
"\t\t\tDefault: 2");
MODULE_PARM_DESC(enc_idx_bufs,
"Number of encoder IDX buffers\n"
"\t\t\tDefault: " __stringify(CX18_MAX_FW_MDLS_PER_STREAM));
MODULE_PARM_DESC(enc_yuv_buffers,
"Encoder YUV buffer memory (MB). (enc_yuv_bufs can override)\n"
"\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_YUV_BUFFERS));
MODULE_PARM_DESC(enc_yuv_bufsize,
"Size of an encoder YUV buffer (kB)\n"
"\t\t\tAllowed values are multiples of 33.75 kB rounded up\n"
"\t\t\t(multiples of size required for 32 screen lines)\n"
"\t\t\tDefault: 102");
MODULE_PARM_DESC(enc_yuv_bufs,
"Number of encoder YUV buffers\n"
"\t\t\tDefault is computed from other enc_yuv_* parameters");
MODULE_PARM_DESC(enc_vbi_buffers,
"Encoder VBI buffer memory (MB). (enc_vbi_bufs can override)\n"
"\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_VBI_BUFFERS));
MODULE_PARM_DESC(enc_vbi_bufs,
"Number of encoder VBI buffers\n"
"\t\t\tDefault is computed from enc_vbi_buffers");
MODULE_PARM_DESC(enc_pcm_buffers,
"Encoder PCM buffer memory (MB). (enc_pcm_bufs can override)\n"
"\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_PCM_BUFFERS));
MODULE_PARM_DESC(enc_pcm_bufsize,
"Size of an encoder PCM buffer (kB)\n"
"\t\t\tDefault: " __stringify(CX18_DEFAULT_ENC_PCM_BUFSIZE));
MODULE_PARM_DESC(enc_pcm_bufs,
"Number of encoder PCM buffers\n"
"\t\t\tDefault is computed from other enc_pcm_* parameters");
MODULE_PARM_DESC(cx18_first_minor,
"Set device node number assigned to first card");
MODULE_AUTHOR("Hans Verkuil");
MODULE_DESCRIPTION("CX23418 driver");
MODULE_SUPPORTED_DEVICE("CX23418 MPEG2 encoder");
MODULE_LICENSE("GPL");
MODULE_VERSION(CX18_VERSION);
#if defined(CONFIG_MODULES) && defined(MODULE)
static void request_module_async(struct work_struct *work)
{
struct cx18 *dev = container_of(work, struct cx18, request_module_wk);
/* Make sure cx18-alsa module is loaded */
request_module("cx18-alsa");
/* Initialize cx18-alsa for this instance of the cx18 device */
if (cx18_ext_init != NULL)
cx18_ext_init(dev);
}
static void request_modules(struct cx18 *dev)
{
INIT_WORK(&dev->request_module_wk, request_module_async);
schedule_work(&dev->request_module_wk);
}
static void flush_request_modules(struct cx18 *dev)
{
flush_work(&dev->request_module_wk);
}
#else
#define request_modules(dev)
#define flush_request_modules(dev)
#endif /* CONFIG_MODULES */
/* Generic utility functions */
int cx18_msleep_timeout(unsigned int msecs, int intr)
{
long int timeout = msecs_to_jiffies(msecs);
int sig;
do {
set_current_state(intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
timeout = schedule_timeout(timeout);
sig = intr ? signal_pending(current) : 0;
} while (!sig && timeout);
return sig;
}
/* Release ioremapped memory */
static void cx18_iounmap(struct cx18 *cx)
{
if (cx == NULL)
return;
/* Release io memory */
if (cx->enc_mem != NULL) {
CX18_DEBUG_INFO("releasing enc_mem\n");
iounmap(cx->enc_mem);
cx->enc_mem = NULL;
}
}
static void cx18_eeprom_dump(struct cx18 *cx, unsigned char *eedata, int len)
{
int i;
CX18_INFO("eeprom dump:\n");
for (i = 0; i < len; i++) {
if (0 == (i % 16))
CX18_INFO("eeprom %02x:", i);
printk(KERN_CONT " %02x", eedata[i]);
if (15 == (i % 16))
printk(KERN_CONT "\n");
}
}
/* Hauppauge card? get values from tveeprom */
void cx18_read_eeprom(struct cx18 *cx, struct tveeprom *tv)
{
struct i2c_client *c;
u8 eedata[256];
memset(tv, 0, sizeof(*tv));
c = kzalloc(sizeof(*c), GFP_KERNEL);
if (!c)
return;
strlcpy(c->name, "cx18 tveeprom tmp", sizeof(c->name));
c->adapter = &cx->i2c_adap[0];
c->addr = 0xa0 >> 1;
if (tveeprom_read(c, eedata, sizeof(eedata)))
goto ret;
switch (cx->card->type) {
case CX18_CARD_HVR_1600_ESMT:
case CX18_CARD_HVR_1600_SAMSUNG:
case CX18_CARD_HVR_1600_S5H1411:
tveeprom_hauppauge_analog(c, tv, eedata);
break;
case CX18_CARD_YUAN_MPC718:
case CX18_CARD_GOTVIEW_PCI_DVD3:
tv->model = 0x718;
cx18_eeprom_dump(cx, eedata, sizeof(eedata));
CX18_INFO("eeprom PCI ID: %02x%02x:%02x%02x\n",
eedata[2], eedata[1], eedata[4], eedata[3]);
break;
default:
tv->model = 0xffffffff;
cx18_eeprom_dump(cx, eedata, sizeof(eedata));
break;
}
ret:
kfree(c);
}
static void cx18_process_eeprom(struct cx18 *cx)
{
struct tveeprom tv;
cx18_read_eeprom(cx, &tv);
/* Many thanks to Steven Toth from Hauppauge for providing the
model numbers */
/* Note: the Samsung memory models cannot be reliably determined
from the model number. Use the cardtype module option if you
have one of these preproduction models. */
switch (tv.model) {
case 74301: /* Retail models */
case 74321:
case 74351: /* OEM models */
case 74361:
/* Digital side is s5h1411/tda18271 */
cx->card = cx18_get_card(CX18_CARD_HVR_1600_S5H1411);
break;
case 74021: /* Retail models */
case 74031:
case 74041:
case 74141:
case 74541: /* OEM models */
case 74551:
case 74591:
case 74651:
case 74691:
case 74751:
case 74891:
/* Digital side is s5h1409/mxl5005s */
cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
break;
case 0x718:
return;
case 0xffffffff:
CX18_INFO("Unknown EEPROM encoding\n");
return;
case 0:
CX18_ERR("Invalid EEPROM\n");
return;
default:
CX18_ERR("Unknown model %d, defaulting to original HVR-1600 "
"(cardtype=1)\n", tv.model);
cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
break;
}
cx->v4l2_cap = cx->card->v4l2_capabilities;
cx->card_name = cx->card->name;
cx->card_i2c = cx->card->i2c;
CX18_INFO("Autodetected %s\n", cx->card_name);
if (tv.tuner_type == TUNER_ABSENT)
CX18_ERR("tveeprom cannot autodetect tuner!\n");
if (cx->options.tuner == -1)
cx->options.tuner = tv.tuner_type;
if (cx->options.radio == -1)
cx->options.radio = (tv.has_radio != 0);
if (cx->std != 0)
/* user specified tuner standard */
return;
/* autodetect tuner standard */
#define TVEEPROM_TUNER_FORMAT_ALL (V4L2_STD_B | V4L2_STD_GH | \
V4L2_STD_MN | \
V4L2_STD_PAL_I | \
V4L2_STD_SECAM_L | V4L2_STD_SECAM_LC | \
V4L2_STD_DK)
if ((tv.tuner_formats & TVEEPROM_TUNER_FORMAT_ALL)
== TVEEPROM_TUNER_FORMAT_ALL) {
CX18_DEBUG_INFO("Worldwide tuner detected\n");
cx->std = V4L2_STD_ALL;
} else if (tv.tuner_formats & V4L2_STD_PAL) {
CX18_DEBUG_INFO("PAL tuner detected\n");
cx->std |= V4L2_STD_PAL_BG | V4L2_STD_PAL_H;
} else if (tv.tuner_formats & V4L2_STD_NTSC) {
CX18_DEBUG_INFO("NTSC tuner detected\n");
cx->std |= V4L2_STD_NTSC_M;
} else if (tv.tuner_formats & V4L2_STD_SECAM) {
CX18_DEBUG_INFO("SECAM tuner detected\n");
cx->std |= V4L2_STD_SECAM_L;
} else {
CX18_INFO("No tuner detected, default to NTSC-M\n");
cx->std |= V4L2_STD_NTSC_M;
}
}
static v4l2_std_id cx18_parse_std(struct cx18 *cx)
{
switch (pal[0]) {
case '6':
return V4L2_STD_PAL_60;
case 'b':
case 'B':
case 'g':
case 'G':
return V4L2_STD_PAL_BG;
case 'h':
case 'H':
return V4L2_STD_PAL_H;
case 'n':
case 'N':
if (pal[1] == 'c' || pal[1] == 'C')
return V4L2_STD_PAL_Nc;
return V4L2_STD_PAL_N;
case 'i':
case 'I':
return V4L2_STD_PAL_I;
case 'd':
case 'D':
case 'k':
case 'K':
return V4L2_STD_PAL_DK;
case 'M':
case 'm':
return V4L2_STD_PAL_M;
case '-':
break;
default:
CX18_WARN("pal= argument not recognised\n");
return 0;
}
switch (secam[0]) {
case 'b':
case 'B':
case 'g':
case 'G':
case 'h':
case 'H':
return V4L2_STD_SECAM_B | V4L2_STD_SECAM_G | V4L2_STD_SECAM_H;
case 'd':
case 'D':
case 'k':
case 'K':
return V4L2_STD_SECAM_DK;
case 'l':
case 'L':
if (secam[1] == 'C' || secam[1] == 'c')
return V4L2_STD_SECAM_LC;
return V4L2_STD_SECAM_L;
case '-':
break;
default:
CX18_WARN("secam= argument not recognised\n");
return 0;
}
switch (ntsc[0]) {
case 'm':
case 'M':
return V4L2_STD_NTSC_M;
case 'j':
case 'J':
return V4L2_STD_NTSC_M_JP;
case 'k':
case 'K':
return V4L2_STD_NTSC_M_KR;
case '-':
break;
default:
CX18_WARN("ntsc= argument not recognised\n");
return 0;
}
/* no match found */
return 0;
}
static void cx18_process_options(struct cx18 *cx)
{
int i, j;
cx->options.megabytes[CX18_ENC_STREAM_TYPE_TS] = enc_ts_buffers;
cx->options.megabytes[CX18_ENC_STREAM_TYPE_MPG] = enc_mpg_buffers;
cx->options.megabytes[CX18_ENC_STREAM_TYPE_IDX] = enc_idx_buffers;
cx->options.megabytes[CX18_ENC_STREAM_TYPE_YUV] = enc_yuv_buffers;
cx->options.megabytes[CX18_ENC_STREAM_TYPE_VBI] = enc_vbi_buffers;
cx->options.megabytes[CX18_ENC_STREAM_TYPE_PCM] = enc_pcm_buffers;
cx->options.megabytes[CX18_ENC_STREAM_TYPE_RAD] = 0; /* control only */
cx->stream_buffers[CX18_ENC_STREAM_TYPE_TS] = enc_ts_bufs;
cx->stream_buffers[CX18_ENC_STREAM_TYPE_MPG] = enc_mpg_bufs;
cx->stream_buffers[CX18_ENC_STREAM_TYPE_IDX] = enc_idx_bufs;
cx->stream_buffers[CX18_ENC_STREAM_TYPE_YUV] = enc_yuv_bufs;
cx->stream_buffers[CX18_ENC_STREAM_TYPE_VBI] = enc_vbi_bufs;
cx->stream_buffers[CX18_ENC_STREAM_TYPE_PCM] = enc_pcm_bufs;
cx->stream_buffers[CX18_ENC_STREAM_TYPE_RAD] = 0; /* control, no data */
cx->stream_buf_size[CX18_ENC_STREAM_TYPE_TS] = enc_ts_bufsize;
cx->stream_buf_size[CX18_ENC_STREAM_TYPE_MPG] = enc_mpg_bufsize;
cx->stream_buf_size[CX18_ENC_STREAM_TYPE_IDX] = enc_idx_bufsize;
cx->stream_buf_size[CX18_ENC_STREAM_TYPE_YUV] = enc_yuv_bufsize;
cx->stream_buf_size[CX18_ENC_STREAM_TYPE_VBI] = vbi_active_samples * 36;
cx->stream_buf_size[CX18_ENC_STREAM_TYPE_PCM] = enc_pcm_bufsize;
cx->stream_buf_size[CX18_ENC_STREAM_TYPE_RAD] = 0; /* control no data */
/* Ensure stream_buffers & stream_buf_size are valid */
for (i = 0; i < CX18_MAX_STREAMS; i++) {
if (cx->stream_buffers[i] == 0 || /* User said 0 buffers */
cx->options.megabytes[i] <= 0 || /* User said 0 MB total */
cx->stream_buf_size[i] <= 0) { /* User said buf size 0 */
cx->options.megabytes[i] = 0;
cx->stream_buffers[i] = 0;
cx->stream_buf_size[i] = 0;
continue;
}
/*
* YUV is a special case where the stream_buf_size needs to be
* an integral multiple of 33.75 kB (storage for 32 screens
* lines to maintain alignment in case of lost buffers).
*
* IDX is a special case where the stream_buf_size should be
* an integral multiple of 1.5 kB (storage for 64 index entries
* to maintain alignment in case of lost buffers).
*
*/
if (i == CX18_ENC_STREAM_TYPE_YUV) {
cx->stream_buf_size[i] *= 1024;
cx->stream_buf_size[i] -=
(cx->stream_buf_size[i] % CX18_UNIT_ENC_YUV_BUFSIZE);
if (cx->stream_buf_size[i] < CX18_UNIT_ENC_YUV_BUFSIZE)
cx->stream_buf_size[i] =
CX18_UNIT_ENC_YUV_BUFSIZE;
} else if (i == CX18_ENC_STREAM_TYPE_IDX) {
cx->stream_buf_size[i] *= 1024;
cx->stream_buf_size[i] -=
(cx->stream_buf_size[i] % CX18_UNIT_ENC_IDX_BUFSIZE);
if (cx->stream_buf_size[i] < CX18_UNIT_ENC_IDX_BUFSIZE)
cx->stream_buf_size[i] =
CX18_UNIT_ENC_IDX_BUFSIZE;
}
/*
* YUV and IDX are special cases where the stream_buf_size is
* now in bytes.
* VBI is a special case where the stream_buf_size is fixed
* and already in bytes
*/
if (i == CX18_ENC_STREAM_TYPE_VBI ||
i == CX18_ENC_STREAM_TYPE_YUV ||
i == CX18_ENC_STREAM_TYPE_IDX) {
if (cx->stream_buffers[i] < 0) {
cx->stream_buffers[i] =
cx->options.megabytes[i] * 1024 * 1024
/ cx->stream_buf_size[i];
} else {
/* N.B. This might round down to 0 */
cx->options.megabytes[i] =
cx->stream_buffers[i]
* cx->stream_buf_size[i]/(1024 * 1024);
}
} else {
/* All other streams have stream_buf_size in kB here */
if (cx->stream_buffers[i] < 0) {
cx->stream_buffers[i] =
cx->options.megabytes[i] * 1024
/ cx->stream_buf_size[i];
} else {
/* N.B. This might round down to 0 */
cx->options.megabytes[i] =
cx->stream_buffers[i]
* cx->stream_buf_size[i] / 1024;
}
/* convert from kB to bytes */
cx->stream_buf_size[i] *= 1024;
}
CX18_DEBUG_INFO("Stream type %d options: %d MB, %d buffers, "
"%d bytes\n", i, cx->options.megabytes[i],
cx->stream_buffers[i], cx->stream_buf_size[i]);
}
cx->options.cardtype = cardtype[cx->instance];
cx->options.tuner = tuner[cx->instance];
cx->options.radio = radio[cx->instance];
cx->std = cx18_parse_std(cx);
if (cx->options.cardtype == -1) {
CX18_INFO("Ignore card\n");
return;
}
cx->card = cx18_get_card(cx->options.cardtype - 1);
if (cx->card)
CX18_INFO("User specified %s card\n", cx->card->name);
else if (cx->options.cardtype != 0)
CX18_ERR("Unknown user specified type, trying to autodetect card\n");
if (cx->card == NULL) {
if (cx->pci_dev->subsystem_vendor == CX18_PCI_ID_HAUPPAUGE) {
cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
CX18_INFO("Autodetected Hauppauge card\n");
}
}
if (cx->card == NULL) {
for (i = 0; (cx->card = cx18_get_card(i)); i++) {
if (cx->card->pci_list == NULL)
continue;
for (j = 0; cx->card->pci_list[j].device; j++) {
if (cx->pci_dev->device !=
cx->card->pci_list[j].device)
continue;
if (cx->pci_dev->subsystem_vendor !=
cx->card->pci_list[j].subsystem_vendor)
continue;
if (cx->pci_dev->subsystem_device !=
cx->card->pci_list[j].subsystem_device)
continue;
CX18_INFO("Autodetected %s card\n", cx->card->name);
goto done;
}
}
}
done:
if (cx->card == NULL) {
cx->card = cx18_get_card(CX18_CARD_HVR_1600_ESMT);
CX18_ERR("Unknown card: vendor/device: [%04x:%04x]\n",
cx->pci_dev->vendor, cx->pci_dev->device);
CX18_ERR(" subsystem vendor/device: [%04x:%04x]\n",
cx->pci_dev->subsystem_vendor,
cx->pci_dev->subsystem_device);
CX18_ERR("Defaulting to %s card\n", cx->card->name);
CX18_ERR("Please mail the vendor/device and subsystem vendor/device IDs and what kind of\n");
CX18_ERR("card you have to the ivtv-devel mailinglist (www.ivtvdriver.org)\n");
CX18_ERR("Prefix your subject line with [UNKNOWN CX18 CARD].\n");
}
cx->v4l2_cap = cx->card->v4l2_capabilities;
cx->card_name = cx->card->name;
cx->card_i2c = cx->card->i2c;
}
static int cx18_create_in_workq(struct cx18 *cx)
{
snprintf(cx->in_workq_name, sizeof(cx->in_workq_name), "%s-in",
cx->v4l2_dev.name);
cx->in_work_queue = alloc_ordered_workqueue(cx->in_workq_name, 0);
if (cx->in_work_queue == NULL) {
CX18_ERR("Unable to create incoming mailbox handler thread\n");
return -ENOMEM;
}
return 0;
}
static void cx18_init_in_work_orders(struct cx18 *cx)
{
int i;
for (i = 0; i < CX18_MAX_IN_WORK_ORDERS; i++) {
cx->in_work_order[i].cx = cx;
cx->in_work_order[i].str = cx->epu_debug_str;
INIT_WORK(&cx->in_work_order[i].work, cx18_in_work_handler);
}
}
/* Precondition: the cx18 structure has been memset to 0. Only
the dev and instance fields have been filled in.
No assumptions on the card type may be made here (see cx18_init_struct2
for that).
*/
static int cx18_init_struct1(struct cx18 *cx)
{
int ret;
cx->base_addr = pci_resource_start(cx->pci_dev, 0);
mutex_init(&cx->serialize_lock);
mutex_init(&cx->gpio_lock);
mutex_init(&cx->epu2apu_mb_lock);
mutex_init(&cx->epu2cpu_mb_lock);
ret = cx18_create_in_workq(cx);
if (ret)
return ret;
cx18_init_in_work_orders(cx);
/* start counting open_id at 1 */
cx->open_id = 1;
/* Initial settings */
cx->cxhdl.port = CX2341X_PORT_MEMORY;
cx->cxhdl.capabilities = CX2341X_CAP_HAS_TS | CX2341X_CAP_HAS_SLICED_VBI;
cx->cxhdl.ops = &cx18_cxhdl_ops;
cx->cxhdl.func = cx18_api_func;
cx->cxhdl.priv = &cx->streams[CX18_ENC_STREAM_TYPE_MPG];
ret = cx2341x_handler_init(&cx->cxhdl, 50);
if (ret)
return ret;
cx->v4l2_dev.ctrl_handler = &cx->cxhdl.hdl;
cx->temporal_strength = cx->cxhdl.video_temporal_filter->cur.val;
cx->spatial_strength = cx->cxhdl.video_spatial_filter->cur.val;
cx->filter_mode = cx->cxhdl.video_spatial_filter_mode->cur.val |
(cx->cxhdl.video_temporal_filter_mode->cur.val << 1) |
(cx->cxhdl.video_median_filter_type->cur.val << 2);
init_waitqueue_head(&cx->cap_w);
init_waitqueue_head(&cx->mb_apu_waitq);
init_waitqueue_head(&cx->mb_cpu_waitq);
init_waitqueue_head(&cx->dma_waitq);
/* VBI */
cx->vbi.in.type = V4L2_BUF_TYPE_VBI_CAPTURE;
cx->vbi.sliced_in = &cx->vbi.in.fmt.sliced;
/* IVTV style VBI insertion into MPEG streams */
INIT_LIST_HEAD(&cx->vbi.sliced_mpeg_buf.list);
INIT_LIST_HEAD(&cx->vbi.sliced_mpeg_mdl.list);
INIT_LIST_HEAD(&cx->vbi.sliced_mpeg_mdl.buf_list);
list_add(&cx->vbi.sliced_mpeg_buf.list,
&cx->vbi.sliced_mpeg_mdl.buf_list);
return 0;
}
/* Second initialization part. Here the card type has been
autodetected. */
static void cx18_init_struct2(struct cx18 *cx)
{
int i;
for (i = 0; i < CX18_CARD_MAX_VIDEO_INPUTS; i++)
if (cx->card->video_inputs[i].video_type == 0)
break;
cx->nof_inputs = i;
for (i = 0; i < CX18_CARD_MAX_AUDIO_INPUTS; i++)
if (cx->card->audio_inputs[i].audio_type == 0)
break;
cx->nof_audio_inputs = i;
/* Find tuner input */
for (i = 0; i < cx->nof_inputs; i++) {
if (cx->card->video_inputs[i].video_type ==
CX18_CARD_INPUT_VID_TUNER)
break;
}
if (i == cx->nof_inputs)
i = 0;
cx->active_input = i;
cx->audio_input = cx->card->video_inputs[i].audio_index;
}
static int cx18_setup_pci(struct cx18 *cx, struct pci_dev *pci_dev,
const struct pci_device_id *pci_id)
{
u16 cmd;
unsigned char pci_latency;
CX18_DEBUG_INFO("Enabling pci device\n");
if (pci_enable_device(pci_dev)) {
CX18_ERR("Can't enable device %d!\n", cx->instance);
return -EIO;
}
if (pci_set_dma_mask(pci_dev, DMA_BIT_MASK(32))) {
CX18_ERR("No suitable DMA available, card %d\n", cx->instance);
return -EIO;
}
if (!request_mem_region(cx->base_addr, CX18_MEM_SIZE, "cx18 encoder")) {
CX18_ERR("Cannot request encoder memory region, card %d\n",
cx->instance);
return -EIO;
}
/* Enable bus mastering and memory mapped IO for the CX23418 */
pci_read_config_word(pci_dev, PCI_COMMAND, &cmd);
cmd |= PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER;
pci_write_config_word(pci_dev, PCI_COMMAND, cmd);
cx->card_rev = pci_dev->revision;
pci_read_config_byte(pci_dev, PCI_LATENCY_TIMER, &pci_latency);
if (pci_latency < 64 && cx18_pci_latency) {
CX18_INFO("Unreasonably low latency timer, "
"setting to 64 (was %d)\n", pci_latency);
pci_write_config_byte(pci_dev, PCI_LATENCY_TIMER, 64);
pci_read_config_byte(pci_dev, PCI_LATENCY_TIMER, &pci_latency);
}
CX18_DEBUG_INFO("cx%d (rev %d) at %02x:%02x.%x, "
"irq: %d, latency: %d, memory: 0x%llx\n",
cx->pci_dev->device, cx->card_rev, pci_dev->bus->number,
PCI_SLOT(pci_dev->devfn), PCI_FUNC(pci_dev->devfn),
cx->pci_dev->irq, pci_latency, (u64)cx->base_addr);
return 0;
}
static void cx18_init_subdevs(struct cx18 *cx)
{
u32 hw = cx->card->hw_all;
u32 device;
int i;
for (i = 0, device = 1; i < 32; i++, device <<= 1) {
if (!(device & hw))
continue;
switch (device) {
case CX18_HW_DVB:
case CX18_HW_TVEEPROM:
/* These subordinate devices do not use probing */
cx->hw_flags |= device;
break;
case CX18_HW_418_AV:
/* The A/V decoder gets probed earlier to set PLLs */
/* Just note that the card uses it (i.e. has analog) */
cx->hw_flags |= device;
break;
case CX18_HW_GPIO_RESET_CTRL:
/*
* The Reset Controller gets probed and added to
* hw_flags earlier for i2c adapter/bus initialization
*/
break;
case CX18_HW_GPIO_MUX:
if (cx18_gpio_register(cx, device) == 0)
cx->hw_flags |= device;
break;
default:
if (cx18_i2c_register(cx, i) == 0)
cx->hw_flags |= device;
break;
}
}
if (cx->hw_flags & CX18_HW_418_AV)
cx->sd_av = cx18_find_hw(cx, CX18_HW_418_AV);
if (cx->card->hw_muxer != 0)
cx->sd_extmux = cx18_find_hw(cx, cx->card->hw_muxer);
}
static int cx18_probe(struct pci_dev *pci_dev,
const struct pci_device_id *pci_id)
{
int retval = 0;
int i;
u32 devtype;
struct cx18 *cx;
/* FIXME - module parameter arrays constrain max instances */
i = atomic_inc_return(&cx18_instance) - 1;
if (i >= CX18_MAX_CARDS) {
printk(KERN_ERR "cx18: cannot manage card %d, driver has a "
"limit of 0 - %d\n", i, CX18_MAX_CARDS - 1);
return -ENOMEM;
}
cx = kzalloc(sizeof(struct cx18), GFP_ATOMIC);
if (cx == NULL) {
printk(KERN_ERR "cx18: cannot manage card %d, out of memory\n",
i);
return -ENOMEM;
}
cx->pci_dev = pci_dev;
cx->instance = i;
retval = v4l2_device_register(&pci_dev->dev, &cx->v4l2_dev);
if (retval) {
printk(KERN_ERR "cx18: v4l2_device_register of card %d failed"
"\n", cx->instance);
kfree(cx);
return retval;
}
snprintf(cx->v4l2_dev.name, sizeof(cx->v4l2_dev.name), "cx18-%d",
cx->instance);
CX18_INFO("Initializing card %d\n", cx->instance);
cx18_process_options(cx);
if (cx->options.cardtype == -1) {
retval = -ENODEV;
goto err;
}
retval = cx18_init_struct1(cx);
if (retval)
goto err;
CX18_DEBUG_INFO("base addr: 0x%llx\n", (u64)cx->base_addr);
/* PCI Device Setup */
retval = cx18_setup_pci(cx, pci_dev, pci_id);
if (retval != 0)
goto free_workqueues;
/* map io memory */
CX18_DEBUG_INFO("attempting ioremap at 0x%llx len 0x%08x\n",
(u64)cx->base_addr + CX18_MEM_OFFSET, CX18_MEM_SIZE);
cx->enc_mem = ioremap_nocache(cx->base_addr + CX18_MEM_OFFSET,
CX18_MEM_SIZE);
if (!cx->enc_mem) {
CX18_ERR("ioremap failed. Can't get a window into CX23418 "
"memory and register space\n");
CX18_ERR("Each capture card with a CX23418 needs 64 MB of "
"vmalloc address space for the window\n");
CX18_ERR("Check the output of 'grep Vmalloc /proc/meminfo'\n");
CX18_ERR("Use the vmalloc= kernel command line option to set "
"VmallocTotal to a larger value\n");
retval = -ENOMEM;
goto free_mem;
}
cx->reg_mem = cx->enc_mem + CX18_REG_OFFSET;
devtype = cx18_read_reg(cx, 0xC72028);
switch (devtype & 0xff000000) {
case 0xff000000:
CX18_INFO("cx23418 revision %08x (A)\n", devtype);
break;
case 0x01000000:
CX18_INFO("cx23418 revision %08x (B)\n", devtype);
break;
default:
CX18_INFO("cx23418 revision %08x (Unknown)\n", devtype);
break;
}
cx18_init_power(cx, 1);
cx18_init_memory(cx);
cx->scb = (struct cx18_scb __iomem *)(cx->enc_mem + SCB_OFFSET);
cx18_init_scb(cx);
cx18_gpio_init(cx);
/* Initialize integrated A/V decoder early to set PLLs, just in case */
retval = cx18_av_probe(cx);
if (retval) {
CX18_ERR("Could not register A/V decoder subdevice\n");
goto free_map;
}
/* Initialize GPIO Reset Controller to do chip resets during i2c init */
if (cx->card->hw_all & CX18_HW_GPIO_RESET_CTRL) {
if (cx18_gpio_register(cx, CX18_HW_GPIO_RESET_CTRL) != 0)
CX18_WARN("Could not register GPIO reset controller"
"subdevice; proceeding anyway.\n");
else
cx->hw_flags |= CX18_HW_GPIO_RESET_CTRL;
}
/* active i2c */
CX18_DEBUG_INFO("activating i2c...\n");
retval = init_cx18_i2c(cx);
if (retval) {
CX18_ERR("Could not initialize i2c\n");
goto free_map;
}
if (cx->card->hw_all & CX18_HW_TVEEPROM) {
/* Based on the model number the cardtype may be changed.
The PCI IDs are not always reliable. */
const struct cx18_card *orig_card = cx->card;
cx18_process_eeprom(cx);
if (cx->card != orig_card) {
/* Changed the cardtype; re-reset the I2C chips */
cx18_gpio_init(cx);
cx18_call_hw(cx, CX18_HW_GPIO_RESET_CTRL,
core, reset, (u32) CX18_GPIO_RESET_I2C);
}
}
if (cx->card->comment)
CX18_INFO("%s", cx->card->comment);
if (cx->card->v4l2_capabilities == 0) {
retval = -ENODEV;
goto free_i2c;
}
cx18_init_memory(cx);
cx18_init_scb(cx);
/* Register IRQ */
retval = request_irq(cx->pci_dev->irq, cx18_irq_handler,
IRQF_SHARED | IRQF_DISABLED,
cx->v4l2_dev.name, (void *)cx);
if (retval) {
CX18_ERR("Failed to register irq %d\n", retval);
goto free_i2c;
}
if (cx->std == 0)
cx->std = V4L2_STD_NTSC_M;
if (cx->options.tuner == -1) {
for (i = 0; i < CX18_CARD_MAX_TUNERS; i++) {
if ((cx->std & cx->card->tuners[i].std) == 0)
continue;
cx->options.tuner = cx->card->tuners[i].tuner;
break;
}
}
/* if no tuner was found, then pick the first tuner in the card list */
if (cx->options.tuner == -1 && cx->card->tuners[0].std) {
cx->std = cx->card->tuners[0].std;
if (cx->std & V4L2_STD_PAL)
cx->std = V4L2_STD_PAL_BG | V4L2_STD_PAL_H;
else if (cx->std & V4L2_STD_NTSC)
cx->std = V4L2_STD_NTSC_M;
else if (cx->std & V4L2_STD_SECAM)
cx->std = V4L2_STD_SECAM_L;
cx->options.tuner = cx->card->tuners[0].tuner;
}
if (cx->options.radio == -1)
cx->options.radio = (cx->card->radio_input.audio_type != 0);
/* The card is now fully identified, continue with card-specific
initialization. */
cx18_init_struct2(cx);
cx18_init_subdevs(cx);
if (cx->std & V4L2_STD_525_60)
cx->is_60hz = 1;
else
cx->is_50hz = 1;
cx2341x_handler_set_50hz(&cx->cxhdl, !cx->is_60hz);
if (cx->options.radio > 0)
cx->v4l2_cap |= V4L2_CAP_RADIO;
if (cx->options.tuner > -1) {
struct tuner_setup setup;
setup.addr = ADDR_UNSET;
setup.type = cx->options.tuner;
setup.mode_mask = T_ANALOG_TV; /* matches TV tuners */
setup.config = NULL;
if (cx->options.radio > 0)
setup.mode_mask |= T_RADIO;
setup.tuner_callback = (setup.type == TUNER_XC2028) ?
cx18_reset_tuner_gpio : NULL;
cx18_call_all(cx, tuner, s_type_addr, &setup);
if (setup.type == TUNER_XC2028) {
static struct xc2028_ctrl ctrl = {
.fname = XC2028_DEFAULT_FIRMWARE,
.max_len = 64,
};
struct v4l2_priv_tun_config cfg = {
.tuner = cx->options.tuner,
.priv = &ctrl,
};
cx18_call_all(cx, tuner, s_config, &cfg);
}
}
/* The tuner is fixed to the standard. The other inputs (e.g. S-Video)
are not. */
cx->tuner_std = cx->std;
if (cx->std == V4L2_STD_ALL)
cx->std = V4L2_STD_NTSC_M;
retval = cx18_streams_setup(cx);
if (retval) {
CX18_ERR("Error %d setting up streams\n", retval);
goto free_irq;
}
retval = cx18_streams_register(cx);
if (retval) {
CX18_ERR("Error %d registering devices\n", retval);
goto free_streams;
}
CX18_INFO("Initialized card: %s\n", cx->card_name);
/* Load cx18 submodules (cx18-alsa) */
request_modules(cx);
return 0;
free_streams:
cx18_streams_cleanup(cx, 1);
free_irq:
free_irq(cx->pci_dev->irq, (void *)cx);
free_i2c:
exit_cx18_i2c(cx);
free_map:
cx18_iounmap(cx);
free_mem:
release_mem_region(cx->base_addr, CX18_MEM_SIZE);
free_workqueues:
destroy_workqueue(cx->in_work_queue);
err:
if (retval == 0)
retval = -ENODEV;
CX18_ERR("Error %d on initialization\n", retval);
v4l2_device_unregister(&cx->v4l2_dev);
kfree(cx);
return retval;
}
int cx18_init_on_first_open(struct cx18 *cx)
{
int video_input;
int fw_retry_count = 3;
struct v4l2_frequency vf;
struct cx18_open_id fh;
v4l2_std_id std;
fh.cx = cx;
if (test_bit(CX18_F_I_FAILED, &cx->i_flags))
return -ENXIO;
if (test_and_set_bit(CX18_F_I_INITED, &cx->i_flags))
return 0;
while (--fw_retry_count > 0) {
/* load firmware */
if (cx18_firmware_init(cx) == 0)
break;
if (fw_retry_count > 1)
CX18_WARN("Retry loading firmware\n");
}
if (fw_retry_count == 0) {
set_bit(CX18_F_I_FAILED, &cx->i_flags);
return -ENXIO;
}
set_bit(CX18_F_I_LOADED_FW, &cx->i_flags);
/*
* Init the firmware twice to work around a silicon bug
* with the digital TS.
*
* The second firmware load requires us to normalize the APU state,
* or the audio for the first analog capture will be badly incorrect.
*
* I can't seem to call APU_RESETAI and have it succeed without the
* APU capturing audio, so we start and stop it here to do the reset
*/
/* MPEG Encoding, 224 kbps, MPEG Layer II, 48 ksps */
cx18_vapi(cx, CX18_APU_START, 2, CX18_APU_ENCODING_METHOD_MPEG|0xb9, 0);
cx18_vapi(cx, CX18_APU_RESETAI, 0);
cx18_vapi(cx, CX18_APU_STOP, 1, CX18_APU_ENCODING_METHOD_MPEG);
fw_retry_count = 3;
while (--fw_retry_count > 0) {
/* load firmware */
if (cx18_firmware_init(cx) == 0)
break;
if (fw_retry_count > 1)
CX18_WARN("Retry loading firmware\n");
}
if (fw_retry_count == 0) {
set_bit(CX18_F_I_FAILED, &cx->i_flags);
return -ENXIO;
}
/*
* The second firmware load requires us to normalize the APU state,
* or the audio for the first analog capture will be badly incorrect.
*
* I can't seem to call APU_RESETAI and have it succeed without the
* APU capturing audio, so we start and stop it here to do the reset
*/
/* MPEG Encoding, 224 kbps, MPEG Layer II, 48 ksps */
cx18_vapi(cx, CX18_APU_START, 2, CX18_APU_ENCODING_METHOD_MPEG|0xb9, 0);
cx18_vapi(cx, CX18_APU_RESETAI, 0);
cx18_vapi(cx, CX18_APU_STOP, 1, CX18_APU_ENCODING_METHOD_MPEG);
/* Init the A/V decoder, if it hasn't been already */
v4l2_subdev_call(cx->sd_av, core, load_fw);
vf.tuner = 0;
vf.type = V4L2_TUNER_ANALOG_TV;
vf.frequency = 6400; /* the tuner 'baseline' frequency */
/* Set initial frequency. For PAL/SECAM broadcasts no
'default' channel exists AFAIK. */
if (cx->std == V4L2_STD_NTSC_M_JP)
vf.frequency = 1460; /* ch. 1 91250*16/1000 */
else if (cx->std & V4L2_STD_NTSC_M)
vf.frequency = 1076; /* ch. 4 67250*16/1000 */
video_input = cx->active_input;
cx->active_input++; /* Force update of input */
cx18_s_input(NULL, &fh, video_input);
/* Let the VIDIOC_S_STD ioctl do all the work, keeps the code
in one place. */
cx->std++; /* Force full standard initialization */
std = (cx->tuner_std == V4L2_STD_ALL) ? V4L2_STD_NTSC_M : cx->tuner_std;
cx18_s_std(NULL, &fh, std);
cx18_s_frequency(NULL, &fh, &vf);
return 0;
}
static void cx18_cancel_in_work_orders(struct cx18 *cx)
{
int i;
for (i = 0; i < CX18_MAX_IN_WORK_ORDERS; i++)
cancel_work_sync(&cx->in_work_order[i].work);
}
static void cx18_cancel_out_work_orders(struct cx18 *cx)
{
int i;
for (i = 0; i < CX18_MAX_STREAMS; i++)
if (&cx->streams[i].video_dev != NULL)
cancel_work_sync(&cx->streams[i].out_work_order);
}
static void cx18_remove(struct pci_dev *pci_dev)
{
struct v4l2_device *v4l2_dev = pci_get_drvdata(pci_dev);
struct cx18 *cx = to_cx18(v4l2_dev);
int i;
CX18_DEBUG_INFO("Removing Card\n");
flush_request_modules(cx);
/* Stop all captures */
CX18_DEBUG_INFO("Stopping all streams\n");
if (atomic_read(&cx->tot_capturing) > 0)
cx18_stop_all_captures(cx);
/* Stop interrupts that cause incoming work to be queued */
cx18_sw1_irq_disable(cx, IRQ_CPU_TO_EPU | IRQ_APU_TO_EPU);
/* Incoming work can cause outgoing work, so clean up incoming first */
cx18_cancel_in_work_orders(cx);
cx18_cancel_out_work_orders(cx);
/* Stop ack interrupts that may have been needed for work to finish */
cx18_sw2_irq_disable(cx, IRQ_CPU_TO_EPU_ACK | IRQ_APU_TO_EPU_ACK);
cx18_halt_firmware(cx);
destroy_workqueue(cx->in_work_queue);
cx18_streams_cleanup(cx, 1);
exit_cx18_i2c(cx);
free_irq(cx->pci_dev->irq, (void *)cx);
cx18_iounmap(cx);
release_mem_region(cx->base_addr, CX18_MEM_SIZE);
pci_disable_device(cx->pci_dev);
if (cx->vbi.sliced_mpeg_data[0] != NULL)
for (i = 0; i < CX18_VBI_FRAMES; i++)
kfree(cx->vbi.sliced_mpeg_data[i]);
v4l2_ctrl_handler_free(&cx->av_state.hdl);
CX18_INFO("Removed %s\n", cx->card_name);
v4l2_device_unregister(v4l2_dev);
kfree(cx);
}
/* define a pci_driver for card detection */
static struct pci_driver cx18_pci_driver = {
.name = "cx18",
.id_table = cx18_pci_tbl,
.probe = cx18_probe,
.remove = cx18_remove,
};
static int __init module_start(void)
{
printk(KERN_INFO "cx18: Start initialization, version %s\n",
CX18_VERSION);
/* Validate parameters */
if (cx18_first_minor < 0 || cx18_first_minor >= CX18_MAX_CARDS) {
printk(KERN_ERR "cx18: Exiting, cx18_first_minor must be between 0 and %d\n",
CX18_MAX_CARDS - 1);
return -1;
}
if (cx18_debug < 0 || cx18_debug > 511) {
cx18_debug = 0;
printk(KERN_INFO "cx18: Debug value must be >= 0 and <= 511!\n");
}
if (pci_register_driver(&cx18_pci_driver)) {
printk(KERN_ERR "cx18: Error detecting PCI card\n");
return -ENODEV;
}
printk(KERN_INFO "cx18: End initialization\n");
return 0;
}
static void __exit module_cleanup(void)
{
pci_unregister_driver(&cx18_pci_driver);
}
module_init(module_start);
module_exit(module_cleanup);
MODULE_FIRMWARE(XC2028_DEFAULT_FIRMWARE);
| gpl-2.0 |
rlnelson-git/linux-nvme | drivers/video/sh_mobile_meram.c | 842 | 20783 | /*
* SuperH Mobile MERAM Driver for SuperH Mobile LCDC Driver
*
* Copyright (c) 2011 Damian Hobson-Garcia <dhobsong@igel.co.jp>
* Takanari Hayama <taki@igel.co.jp>
*
* 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/device.h>
#include <linux/err.h>
#include <linux/export.h>
#include <linux/genalloc.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <video/sh_mobile_meram.h>
/* -----------------------------------------------------------------------------
* MERAM registers
*/
#define MEVCR1 0x4
#define MEVCR1_RST (1 << 31)
#define MEVCR1_WD (1 << 30)
#define MEVCR1_AMD1 (1 << 29)
#define MEVCR1_AMD0 (1 << 28)
#define MEQSEL1 0x40
#define MEQSEL2 0x44
#define MExxCTL 0x400
#define MExxCTL_BV (1 << 31)
#define MExxCTL_BSZ_SHIFT 28
#define MExxCTL_MSAR_MASK (0x7ff << MExxCTL_MSAR_SHIFT)
#define MExxCTL_MSAR_SHIFT 16
#define MExxCTL_NXT_MASK (0x1f << MExxCTL_NXT_SHIFT)
#define MExxCTL_NXT_SHIFT 11
#define MExxCTL_WD1 (1 << 10)
#define MExxCTL_WD0 (1 << 9)
#define MExxCTL_WS (1 << 8)
#define MExxCTL_CB (1 << 7)
#define MExxCTL_WBF (1 << 6)
#define MExxCTL_WF (1 << 5)
#define MExxCTL_RF (1 << 4)
#define MExxCTL_CM (1 << 3)
#define MExxCTL_MD_READ (1 << 0)
#define MExxCTL_MD_WRITE (2 << 0)
#define MExxCTL_MD_ICB_WB (3 << 0)
#define MExxCTL_MD_ICB (4 << 0)
#define MExxCTL_MD_FB (7 << 0)
#define MExxCTL_MD_MASK (7 << 0)
#define MExxBSIZE 0x404
#define MExxBSIZE_RCNT_SHIFT 28
#define MExxBSIZE_YSZM1_SHIFT 16
#define MExxBSIZE_XSZM1_SHIFT 0
#define MExxMNCF 0x408
#define MExxMNCF_KWBNM_SHIFT 28
#define MExxMNCF_KRBNM_SHIFT 24
#define MExxMNCF_BNM_SHIFT 16
#define MExxMNCF_XBV (1 << 15)
#define MExxMNCF_CPL_YCBCR444 (1 << 12)
#define MExxMNCF_CPL_YCBCR420 (2 << 12)
#define MExxMNCF_CPL_YCBCR422 (3 << 12)
#define MExxMNCF_CPL_MSK (3 << 12)
#define MExxMNCF_BL (1 << 2)
#define MExxMNCF_LNM_SHIFT 0
#define MExxSARA 0x410
#define MExxSARB 0x414
#define MExxSBSIZE 0x418
#define MExxSBSIZE_HDV (1 << 31)
#define MExxSBSIZE_HSZ16 (0 << 28)
#define MExxSBSIZE_HSZ32 (1 << 28)
#define MExxSBSIZE_HSZ64 (2 << 28)
#define MExxSBSIZE_HSZ128 (3 << 28)
#define MExxSBSIZE_SBSIZZ_SHIFT 0
#define MERAM_MExxCTL_VAL(next, addr) \
((((next) << MExxCTL_NXT_SHIFT) & MExxCTL_NXT_MASK) | \
(((addr) << MExxCTL_MSAR_SHIFT) & MExxCTL_MSAR_MASK))
#define MERAM_MExxBSIZE_VAL(rcnt, yszm1, xszm1) \
(((rcnt) << MExxBSIZE_RCNT_SHIFT) | \
((yszm1) << MExxBSIZE_YSZM1_SHIFT) | \
((xszm1) << MExxBSIZE_XSZM1_SHIFT))
static const unsigned long common_regs[] = {
MEVCR1,
MEQSEL1,
MEQSEL2,
};
#define MERAM_REGS_SIZE ARRAY_SIZE(common_regs)
static const unsigned long icb_regs[] = {
MExxCTL,
MExxBSIZE,
MExxMNCF,
MExxSARA,
MExxSARB,
MExxSBSIZE,
};
#define ICB_REGS_SIZE ARRAY_SIZE(icb_regs)
/*
* sh_mobile_meram_icb - MERAM ICB information
* @regs: Registers cache
* @index: ICB index
* @offset: MERAM block offset
* @size: MERAM block size in KiB
* @cache_unit: Bytes to cache per ICB
* @pixelformat: Video pixel format of the data stored in the ICB
* @current_reg: Which of Start Address Register A (0) or B (1) is in use
*/
struct sh_mobile_meram_icb {
unsigned long regs[ICB_REGS_SIZE];
unsigned int index;
unsigned long offset;
unsigned int size;
unsigned int cache_unit;
unsigned int pixelformat;
unsigned int current_reg;
};
#define MERAM_ICB_NUM 32
struct sh_mobile_meram_fb_plane {
struct sh_mobile_meram_icb *marker;
struct sh_mobile_meram_icb *cache;
};
struct sh_mobile_meram_fb_cache {
unsigned int nplanes;
struct sh_mobile_meram_fb_plane planes[2];
};
/*
* sh_mobile_meram_priv - MERAM device
* @base: Registers base address
* @meram: MERAM physical address
* @regs: Registers cache
* @lock: Protects used_icb and icbs
* @used_icb: Bitmask of used ICBs
* @icbs: ICBs
* @pool: Allocation pool to manage the MERAM
*/
struct sh_mobile_meram_priv {
void __iomem *base;
unsigned long meram;
unsigned long regs[MERAM_REGS_SIZE];
struct mutex lock;
unsigned long used_icb;
struct sh_mobile_meram_icb icbs[MERAM_ICB_NUM];
struct gen_pool *pool;
};
/* settings */
#define MERAM_GRANULARITY 1024
#define MERAM_SEC_LINE 15
#define MERAM_LINE_WIDTH 2048
/* -----------------------------------------------------------------------------
* Registers access
*/
#define MERAM_ICB_OFFSET(base, idx, off) ((base) + (off) + (idx) * 0x20)
static inline void meram_write_icb(void __iomem *base, unsigned int idx,
unsigned int off, unsigned long val)
{
iowrite32(val, MERAM_ICB_OFFSET(base, idx, off));
}
static inline unsigned long meram_read_icb(void __iomem *base, unsigned int idx,
unsigned int off)
{
return ioread32(MERAM_ICB_OFFSET(base, idx, off));
}
static inline void meram_write_reg(void __iomem *base, unsigned int off,
unsigned long val)
{
iowrite32(val, base + off);
}
static inline unsigned long meram_read_reg(void __iomem *base, unsigned int off)
{
return ioread32(base + off);
}
/* -----------------------------------------------------------------------------
* MERAM allocation and free
*/
static unsigned long meram_alloc(struct sh_mobile_meram_priv *priv, size_t size)
{
return gen_pool_alloc(priv->pool, size);
}
static void meram_free(struct sh_mobile_meram_priv *priv, unsigned long mem,
size_t size)
{
gen_pool_free(priv->pool, mem, size);
}
/* -----------------------------------------------------------------------------
* LCDC cache planes allocation, init, cleanup and free
*/
/* Allocate ICBs and MERAM for a plane. */
static int meram_plane_alloc(struct sh_mobile_meram_priv *priv,
struct sh_mobile_meram_fb_plane *plane,
size_t size)
{
unsigned long mem;
unsigned long idx;
idx = find_first_zero_bit(&priv->used_icb, 28);
if (idx == 28)
return -ENOMEM;
plane->cache = &priv->icbs[idx];
idx = find_next_zero_bit(&priv->used_icb, 32, 28);
if (idx == 32)
return -ENOMEM;
plane->marker = &priv->icbs[idx];
mem = meram_alloc(priv, size * 1024);
if (mem == 0)
return -ENOMEM;
__set_bit(plane->marker->index, &priv->used_icb);
__set_bit(plane->cache->index, &priv->used_icb);
plane->marker->offset = mem - priv->meram;
plane->marker->size = size;
return 0;
}
/* Free ICBs and MERAM for a plane. */
static void meram_plane_free(struct sh_mobile_meram_priv *priv,
struct sh_mobile_meram_fb_plane *plane)
{
meram_free(priv, priv->meram + plane->marker->offset,
plane->marker->size * 1024);
__clear_bit(plane->marker->index, &priv->used_icb);
__clear_bit(plane->cache->index, &priv->used_icb);
}
/* Is this a YCbCr(NV12, NV16 or NV24) colorspace? */
static int is_nvcolor(int cspace)
{
if (cspace == SH_MOBILE_MERAM_PF_NV ||
cspace == SH_MOBILE_MERAM_PF_NV24)
return 1;
return 0;
}
/* Set the next address to fetch. */
static void meram_set_next_addr(struct sh_mobile_meram_priv *priv,
struct sh_mobile_meram_fb_cache *cache,
unsigned long base_addr_y,
unsigned long base_addr_c)
{
struct sh_mobile_meram_icb *icb = cache->planes[0].marker;
unsigned long target;
icb->current_reg ^= 1;
target = icb->current_reg ? MExxSARB : MExxSARA;
/* set the next address to fetch */
meram_write_icb(priv->base, cache->planes[0].cache->index, target,
base_addr_y);
meram_write_icb(priv->base, cache->planes[0].marker->index, target,
base_addr_y + cache->planes[0].marker->cache_unit);
if (cache->nplanes == 2) {
meram_write_icb(priv->base, cache->planes[1].cache->index,
target, base_addr_c);
meram_write_icb(priv->base, cache->planes[1].marker->index,
target, base_addr_c +
cache->planes[1].marker->cache_unit);
}
}
/* Get the next ICB address. */
static void
meram_get_next_icb_addr(struct sh_mobile_meram_info *pdata,
struct sh_mobile_meram_fb_cache *cache,
unsigned long *icb_addr_y, unsigned long *icb_addr_c)
{
struct sh_mobile_meram_icb *icb = cache->planes[0].marker;
unsigned long icb_offset;
if (pdata->addr_mode == SH_MOBILE_MERAM_MODE0)
icb_offset = 0x80000000 | (icb->current_reg << 29);
else
icb_offset = 0xc0000000 | (icb->current_reg << 23);
*icb_addr_y = icb_offset | (cache->planes[0].marker->index << 24);
if (cache->nplanes == 2)
*icb_addr_c = icb_offset
| (cache->planes[1].marker->index << 24);
}
#define MERAM_CALC_BYTECOUNT(x, y) \
(((x) * (y) + (MERAM_LINE_WIDTH - 1)) & ~(MERAM_LINE_WIDTH - 1))
/* Initialize MERAM. */
static int meram_plane_init(struct sh_mobile_meram_priv *priv,
struct sh_mobile_meram_fb_plane *plane,
unsigned int xres, unsigned int yres,
unsigned int *out_pitch)
{
struct sh_mobile_meram_icb *marker = plane->marker;
unsigned long total_byte_count = MERAM_CALC_BYTECOUNT(xres, yres);
unsigned long bnm;
unsigned int lcdc_pitch;
unsigned int xpitch;
unsigned int line_cnt;
unsigned int save_lines;
/* adjust pitch to 1024, 2048, 4096 or 8192 */
lcdc_pitch = (xres - 1) | 1023;
lcdc_pitch = lcdc_pitch | (lcdc_pitch >> 1);
lcdc_pitch = lcdc_pitch | (lcdc_pitch >> 2);
lcdc_pitch += 1;
/* derive settings */
if (lcdc_pitch == 8192 && yres >= 1024) {
lcdc_pitch = xpitch = MERAM_LINE_WIDTH;
line_cnt = total_byte_count >> 11;
*out_pitch = xres;
save_lines = plane->marker->size / 16 / MERAM_SEC_LINE;
save_lines *= MERAM_SEC_LINE;
} else {
xpitch = xres;
line_cnt = yres;
*out_pitch = lcdc_pitch;
save_lines = plane->marker->size / (lcdc_pitch >> 10) / 2;
save_lines &= 0xff;
}
bnm = (save_lines - 1) << 16;
/* TODO: we better to check if we have enough MERAM buffer size */
/* set up ICB */
meram_write_icb(priv->base, plane->cache->index, MExxBSIZE,
MERAM_MExxBSIZE_VAL(0x0, line_cnt - 1, xpitch - 1));
meram_write_icb(priv->base, plane->marker->index, MExxBSIZE,
MERAM_MExxBSIZE_VAL(0xf, line_cnt - 1, xpitch - 1));
meram_write_icb(priv->base, plane->cache->index, MExxMNCF, bnm);
meram_write_icb(priv->base, plane->marker->index, MExxMNCF, bnm);
meram_write_icb(priv->base, plane->cache->index, MExxSBSIZE, xpitch);
meram_write_icb(priv->base, plane->marker->index, MExxSBSIZE, xpitch);
/* save a cache unit size */
plane->cache->cache_unit = xres * save_lines;
plane->marker->cache_unit = xres * save_lines;
/*
* Set MERAM for framebuffer
*
* we also chain the cache_icb and the marker_icb.
* we also split the allocated MERAM buffer between two ICBs.
*/
meram_write_icb(priv->base, plane->cache->index, MExxCTL,
MERAM_MExxCTL_VAL(plane->marker->index, marker->offset)
| MExxCTL_WD1 | MExxCTL_WD0 | MExxCTL_WS | MExxCTL_CM |
MExxCTL_MD_FB);
meram_write_icb(priv->base, plane->marker->index, MExxCTL,
MERAM_MExxCTL_VAL(plane->cache->index, marker->offset +
plane->marker->size / 2) |
MExxCTL_WD1 | MExxCTL_WD0 | MExxCTL_WS | MExxCTL_CM |
MExxCTL_MD_FB);
return 0;
}
static void meram_plane_cleanup(struct sh_mobile_meram_priv *priv,
struct sh_mobile_meram_fb_plane *plane)
{
/* disable ICB */
meram_write_icb(priv->base, plane->cache->index, MExxCTL,
MExxCTL_WBF | MExxCTL_WF | MExxCTL_RF);
meram_write_icb(priv->base, plane->marker->index, MExxCTL,
MExxCTL_WBF | MExxCTL_WF | MExxCTL_RF);
plane->cache->cache_unit = 0;
plane->marker->cache_unit = 0;
}
/* -----------------------------------------------------------------------------
* MERAM operations
*/
unsigned long sh_mobile_meram_alloc(struct sh_mobile_meram_info *pdata,
size_t size)
{
struct sh_mobile_meram_priv *priv = pdata->priv;
return meram_alloc(priv, size);
}
EXPORT_SYMBOL_GPL(sh_mobile_meram_alloc);
void sh_mobile_meram_free(struct sh_mobile_meram_info *pdata, unsigned long mem,
size_t size)
{
struct sh_mobile_meram_priv *priv = pdata->priv;
meram_free(priv, mem, size);
}
EXPORT_SYMBOL_GPL(sh_mobile_meram_free);
/* Allocate memory for the ICBs and mark them as used. */
static struct sh_mobile_meram_fb_cache *
meram_cache_alloc(struct sh_mobile_meram_priv *priv,
const struct sh_mobile_meram_cfg *cfg,
int pixelformat)
{
unsigned int nplanes = is_nvcolor(pixelformat) ? 2 : 1;
struct sh_mobile_meram_fb_cache *cache;
int ret;
cache = kzalloc(sizeof(*cache), GFP_KERNEL);
if (cache == NULL)
return ERR_PTR(-ENOMEM);
cache->nplanes = nplanes;
ret = meram_plane_alloc(priv, &cache->planes[0],
cfg->icb[0].meram_size);
if (ret < 0)
goto error;
cache->planes[0].marker->current_reg = 1;
cache->planes[0].marker->pixelformat = pixelformat;
if (cache->nplanes == 1)
return cache;
ret = meram_plane_alloc(priv, &cache->planes[1],
cfg->icb[1].meram_size);
if (ret < 0) {
meram_plane_free(priv, &cache->planes[0]);
goto error;
}
return cache;
error:
kfree(cache);
return ERR_PTR(-ENOMEM);
}
void *sh_mobile_meram_cache_alloc(struct sh_mobile_meram_info *pdata,
const struct sh_mobile_meram_cfg *cfg,
unsigned int xres, unsigned int yres,
unsigned int pixelformat, unsigned int *pitch)
{
struct sh_mobile_meram_fb_cache *cache;
struct sh_mobile_meram_priv *priv = pdata->priv;
struct platform_device *pdev = pdata->pdev;
unsigned int nplanes = is_nvcolor(pixelformat) ? 2 : 1;
unsigned int out_pitch;
if (priv == NULL)
return ERR_PTR(-ENODEV);
if (pixelformat != SH_MOBILE_MERAM_PF_NV &&
pixelformat != SH_MOBILE_MERAM_PF_NV24 &&
pixelformat != SH_MOBILE_MERAM_PF_RGB)
return ERR_PTR(-EINVAL);
dev_dbg(&pdev->dev, "registering %dx%d (%s)", xres, yres,
!pixelformat ? "yuv" : "rgb");
/* we can't handle wider than 8192px */
if (xres > 8192) {
dev_err(&pdev->dev, "width exceeding the limit (> 8192).");
return ERR_PTR(-EINVAL);
}
if (cfg->icb[0].meram_size == 0)
return ERR_PTR(-EINVAL);
if (nplanes == 2 && cfg->icb[1].meram_size == 0)
return ERR_PTR(-EINVAL);
mutex_lock(&priv->lock);
/* We now register the ICBs and allocate the MERAM regions. */
cache = meram_cache_alloc(priv, cfg, pixelformat);
if (IS_ERR(cache)) {
dev_err(&pdev->dev, "MERAM allocation failed (%ld).",
PTR_ERR(cache));
goto err;
}
/* initialize MERAM */
meram_plane_init(priv, &cache->planes[0], xres, yres, &out_pitch);
*pitch = out_pitch;
if (pixelformat == SH_MOBILE_MERAM_PF_NV)
meram_plane_init(priv, &cache->planes[1],
xres, (yres + 1) / 2, &out_pitch);
else if (pixelformat == SH_MOBILE_MERAM_PF_NV24)
meram_plane_init(priv, &cache->planes[1],
2 * xres, (yres + 1) / 2, &out_pitch);
err:
mutex_unlock(&priv->lock);
return cache;
}
EXPORT_SYMBOL_GPL(sh_mobile_meram_cache_alloc);
void
sh_mobile_meram_cache_free(struct sh_mobile_meram_info *pdata, void *data)
{
struct sh_mobile_meram_fb_cache *cache = data;
struct sh_mobile_meram_priv *priv = pdata->priv;
mutex_lock(&priv->lock);
/* Cleanup and free. */
meram_plane_cleanup(priv, &cache->planes[0]);
meram_plane_free(priv, &cache->planes[0]);
if (cache->nplanes == 2) {
meram_plane_cleanup(priv, &cache->planes[1]);
meram_plane_free(priv, &cache->planes[1]);
}
kfree(cache);
mutex_unlock(&priv->lock);
}
EXPORT_SYMBOL_GPL(sh_mobile_meram_cache_free);
void
sh_mobile_meram_cache_update(struct sh_mobile_meram_info *pdata, void *data,
unsigned long base_addr_y,
unsigned long base_addr_c,
unsigned long *icb_addr_y,
unsigned long *icb_addr_c)
{
struct sh_mobile_meram_fb_cache *cache = data;
struct sh_mobile_meram_priv *priv = pdata->priv;
mutex_lock(&priv->lock);
meram_set_next_addr(priv, cache, base_addr_y, base_addr_c);
meram_get_next_icb_addr(pdata, cache, icb_addr_y, icb_addr_c);
mutex_unlock(&priv->lock);
}
EXPORT_SYMBOL_GPL(sh_mobile_meram_cache_update);
/* -----------------------------------------------------------------------------
* Power management
*/
#if defined(CONFIG_PM_SLEEP) || defined(CONFIG_PM_RUNTIME)
static int sh_mobile_meram_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct sh_mobile_meram_priv *priv = platform_get_drvdata(pdev);
unsigned int i, j;
for (i = 0; i < MERAM_REGS_SIZE; i++)
priv->regs[i] = meram_read_reg(priv->base, common_regs[i]);
for (i = 0; i < 32; i++) {
if (!test_bit(i, &priv->used_icb))
continue;
for (j = 0; j < ICB_REGS_SIZE; j++) {
priv->icbs[i].regs[j] =
meram_read_icb(priv->base, i, icb_regs[j]);
/* Reset ICB on resume */
if (icb_regs[j] == MExxCTL)
priv->icbs[i].regs[j] |=
MExxCTL_WBF | MExxCTL_WF | MExxCTL_RF;
}
}
return 0;
}
static int sh_mobile_meram_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct sh_mobile_meram_priv *priv = platform_get_drvdata(pdev);
unsigned int i, j;
for (i = 0; i < 32; i++) {
if (!test_bit(i, &priv->used_icb))
continue;
for (j = 0; j < ICB_REGS_SIZE; j++)
meram_write_icb(priv->base, i, icb_regs[j],
priv->icbs[i].regs[j]);
}
for (i = 0; i < MERAM_REGS_SIZE; i++)
meram_write_reg(priv->base, common_regs[i], priv->regs[i]);
return 0;
}
#endif /* CONFIG_PM_SLEEP || CONFIG_PM_RUNTIME */
static UNIVERSAL_DEV_PM_OPS(sh_mobile_meram_dev_pm_ops,
sh_mobile_meram_suspend,
sh_mobile_meram_resume, NULL);
/* -----------------------------------------------------------------------------
* Probe/remove and driver init/exit
*/
static int sh_mobile_meram_probe(struct platform_device *pdev)
{
struct sh_mobile_meram_priv *priv;
struct sh_mobile_meram_info *pdata = pdev->dev.platform_data;
struct resource *regs;
struct resource *meram;
unsigned int i;
int error;
if (!pdata) {
dev_err(&pdev->dev, "no platform data defined\n");
return -EINVAL;
}
regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
meram = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (regs == NULL || meram == NULL) {
dev_err(&pdev->dev, "cannot get platform resources\n");
return -ENOENT;
}
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv) {
dev_err(&pdev->dev, "cannot allocate device data\n");
return -ENOMEM;
}
/* Initialize private data. */
mutex_init(&priv->lock);
priv->used_icb = pdata->reserved_icbs;
for (i = 0; i < MERAM_ICB_NUM; ++i)
priv->icbs[i].index = i;
pdata->priv = priv;
pdata->pdev = pdev;
/* Request memory regions and remap the registers. */
if (!request_mem_region(regs->start, resource_size(regs), pdev->name)) {
dev_err(&pdev->dev, "MERAM registers region already claimed\n");
error = -EBUSY;
goto err_req_regs;
}
if (!request_mem_region(meram->start, resource_size(meram),
pdev->name)) {
dev_err(&pdev->dev, "MERAM memory region already claimed\n");
error = -EBUSY;
goto err_req_meram;
}
priv->base = ioremap_nocache(regs->start, resource_size(regs));
if (!priv->base) {
dev_err(&pdev->dev, "ioremap failed\n");
error = -EFAULT;
goto err_ioremap;
}
priv->meram = meram->start;
/* Create and initialize the MERAM memory pool. */
priv->pool = gen_pool_create(ilog2(MERAM_GRANULARITY), -1);
if (priv->pool == NULL) {
error = -ENOMEM;
goto err_genpool;
}
error = gen_pool_add(priv->pool, meram->start, resource_size(meram),
-1);
if (error < 0)
goto err_genpool;
/* initialize ICB addressing mode */
if (pdata->addr_mode == SH_MOBILE_MERAM_MODE1)
meram_write_reg(priv->base, MEVCR1, MEVCR1_AMD1);
platform_set_drvdata(pdev, priv);
pm_runtime_enable(&pdev->dev);
dev_info(&pdev->dev, "sh_mobile_meram initialized.");
return 0;
err_genpool:
if (priv->pool)
gen_pool_destroy(priv->pool);
iounmap(priv->base);
err_ioremap:
release_mem_region(meram->start, resource_size(meram));
err_req_meram:
release_mem_region(regs->start, resource_size(regs));
err_req_regs:
mutex_destroy(&priv->lock);
kfree(priv);
return error;
}
static int sh_mobile_meram_remove(struct platform_device *pdev)
{
struct sh_mobile_meram_priv *priv = platform_get_drvdata(pdev);
struct resource *regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
struct resource *meram = platform_get_resource(pdev, IORESOURCE_MEM, 1);
pm_runtime_disable(&pdev->dev);
gen_pool_destroy(priv->pool);
iounmap(priv->base);
release_mem_region(meram->start, resource_size(meram));
release_mem_region(regs->start, resource_size(regs));
mutex_destroy(&priv->lock);
kfree(priv);
return 0;
}
static struct platform_driver sh_mobile_meram_driver = {
.driver = {
.name = "sh_mobile_meram",
.owner = THIS_MODULE,
.pm = &sh_mobile_meram_dev_pm_ops,
},
.probe = sh_mobile_meram_probe,
.remove = sh_mobile_meram_remove,
};
module_platform_driver(sh_mobile_meram_driver);
MODULE_DESCRIPTION("SuperH Mobile MERAM driver");
MODULE_AUTHOR("Damian Hobson-Garcia / Takanari Hayama");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
FreeProjectAce/i8160-kernel | drivers/rtc/rtc-pcap.c | 1098 | 5736 | /*
* pcap rtc code for Motorola EZX phones
*
* Copyright (c) 2008 guiming zhuo <gmzhuo@gmail.com>
* Copyright (c) 2009 Daniel Ribeiro <drwyrm@gmail.com>
*
* Based on Motorola's rtc.c Copyright (c) 2003-2005 Motorola
*
* 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/init.h>
#include <linux/mfd/ezx-pcap.h>
#include <linux/rtc.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
struct pcap_rtc {
struct pcap_chip *pcap;
struct rtc_device *rtc;
};
static irqreturn_t pcap_rtc_irq(int irq, void *_pcap_rtc)
{
struct pcap_rtc *pcap_rtc = _pcap_rtc;
unsigned long rtc_events;
if (irq == pcap_to_irq(pcap_rtc->pcap, PCAP_IRQ_1HZ))
rtc_events = RTC_IRQF | RTC_UF;
else if (irq == pcap_to_irq(pcap_rtc->pcap, PCAP_IRQ_TODA))
rtc_events = RTC_IRQF | RTC_AF;
else
rtc_events = 0;
rtc_update_irq(pcap_rtc->rtc, 1, rtc_events);
return IRQ_HANDLED;
}
static int pcap_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct platform_device *pdev = to_platform_device(dev);
struct pcap_rtc *pcap_rtc = platform_get_drvdata(pdev);
struct rtc_time *tm = &alrm->time;
unsigned long secs;
u32 tod; /* time of day, seconds since midnight */
u32 days; /* days since 1/1/1970 */
ezx_pcap_read(pcap_rtc->pcap, PCAP_REG_RTC_TODA, &tod);
secs = tod & PCAP_RTC_TOD_MASK;
ezx_pcap_read(pcap_rtc->pcap, PCAP_REG_RTC_DAYA, &days);
secs += (days & PCAP_RTC_DAY_MASK) * SEC_PER_DAY;
rtc_time_to_tm(secs, tm);
return 0;
}
static int pcap_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct platform_device *pdev = to_platform_device(dev);
struct pcap_rtc *pcap_rtc = platform_get_drvdata(pdev);
struct rtc_time *tm = &alrm->time;
unsigned long secs;
u32 tod, days;
rtc_tm_to_time(tm, &secs);
tod = secs % SEC_PER_DAY;
ezx_pcap_write(pcap_rtc->pcap, PCAP_REG_RTC_TODA, tod);
days = secs / SEC_PER_DAY;
ezx_pcap_write(pcap_rtc->pcap, PCAP_REG_RTC_DAYA, days);
return 0;
}
static int pcap_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
struct platform_device *pdev = to_platform_device(dev);
struct pcap_rtc *pcap_rtc = platform_get_drvdata(pdev);
unsigned long secs;
u32 tod, days;
ezx_pcap_read(pcap_rtc->pcap, PCAP_REG_RTC_TOD, &tod);
secs = tod & PCAP_RTC_TOD_MASK;
ezx_pcap_read(pcap_rtc->pcap, PCAP_REG_RTC_DAY, &days);
secs += (days & PCAP_RTC_DAY_MASK) * SEC_PER_DAY;
rtc_time_to_tm(secs, tm);
return rtc_valid_tm(tm);
}
static int pcap_rtc_set_mmss(struct device *dev, unsigned long secs)
{
struct platform_device *pdev = to_platform_device(dev);
struct pcap_rtc *pcap_rtc = platform_get_drvdata(pdev);
u32 tod, days;
tod = secs % SEC_PER_DAY;
ezx_pcap_write(pcap_rtc->pcap, PCAP_REG_RTC_TOD, tod);
days = secs / SEC_PER_DAY;
ezx_pcap_write(pcap_rtc->pcap, PCAP_REG_RTC_DAY, days);
return 0;
}
static int pcap_rtc_irq_enable(struct device *dev, int pirq, unsigned int en)
{
struct platform_device *pdev = to_platform_device(dev);
struct pcap_rtc *pcap_rtc = platform_get_drvdata(pdev);
if (en)
enable_irq(pcap_to_irq(pcap_rtc->pcap, pirq));
else
disable_irq(pcap_to_irq(pcap_rtc->pcap, pirq));
return 0;
}
static int pcap_rtc_alarm_irq_enable(struct device *dev, unsigned int en)
{
return pcap_rtc_irq_enable(dev, PCAP_IRQ_TODA, en);
}
static int pcap_rtc_update_irq_enable(struct device *dev, unsigned int en)
{
return pcap_rtc_irq_enable(dev, PCAP_IRQ_1HZ, en);
}
static const struct rtc_class_ops pcap_rtc_ops = {
.read_time = pcap_rtc_read_time,
.read_alarm = pcap_rtc_read_alarm,
.set_alarm = pcap_rtc_set_alarm,
.set_mmss = pcap_rtc_set_mmss,
.alarm_irq_enable = pcap_rtc_alarm_irq_enable,
.update_irq_enable = pcap_rtc_update_irq_enable,
};
static int __devinit pcap_rtc_probe(struct platform_device *pdev)
{
struct pcap_rtc *pcap_rtc;
int timer_irq, alarm_irq;
int err = -ENOMEM;
pcap_rtc = kmalloc(sizeof(struct pcap_rtc), GFP_KERNEL);
if (!pcap_rtc)
return err;
pcap_rtc->pcap = dev_get_drvdata(pdev->dev.parent);
pcap_rtc->rtc = rtc_device_register("pcap", &pdev->dev,
&pcap_rtc_ops, THIS_MODULE);
if (IS_ERR(pcap_rtc->rtc)) {
err = PTR_ERR(pcap_rtc->rtc);
goto fail_rtc;
}
platform_set_drvdata(pdev, pcap_rtc);
timer_irq = pcap_to_irq(pcap_rtc->pcap, PCAP_IRQ_1HZ);
alarm_irq = pcap_to_irq(pcap_rtc->pcap, PCAP_IRQ_TODA);
err = request_irq(timer_irq, pcap_rtc_irq, 0, "RTC Timer", pcap_rtc);
if (err)
goto fail_timer;
err = request_irq(alarm_irq, pcap_rtc_irq, 0, "RTC Alarm", pcap_rtc);
if (err)
goto fail_alarm;
return 0;
fail_alarm:
free_irq(timer_irq, pcap_rtc);
fail_timer:
rtc_device_unregister(pcap_rtc->rtc);
fail_rtc:
kfree(pcap_rtc);
return err;
}
static int __devexit pcap_rtc_remove(struct platform_device *pdev)
{
struct pcap_rtc *pcap_rtc = platform_get_drvdata(pdev);
free_irq(pcap_to_irq(pcap_rtc->pcap, PCAP_IRQ_1HZ), pcap_rtc);
free_irq(pcap_to_irq(pcap_rtc->pcap, PCAP_IRQ_TODA), pcap_rtc);
rtc_device_unregister(pcap_rtc->rtc);
kfree(pcap_rtc);
return 0;
}
static struct platform_driver pcap_rtc_driver = {
.remove = __devexit_p(pcap_rtc_remove),
.driver = {
.name = "pcap-rtc",
.owner = THIS_MODULE,
},
};
static int __init rtc_pcap_init(void)
{
return platform_driver_probe(&pcap_rtc_driver, pcap_rtc_probe);
}
static void __exit rtc_pcap_exit(void)
{
platform_driver_unregister(&pcap_rtc_driver);
}
module_init(rtc_pcap_init);
module_exit(rtc_pcap_exit);
MODULE_DESCRIPTION("Motorola pcap rtc driver");
MODULE_AUTHOR("guiming zhuo <gmzhuo@gmail.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ryanli/kernel_huawei_c8650 | drivers/media/dvb/ngene/ngene-cards.c | 1098 | 10659 | /*
* ngene-cards.c: nGene PCIe bridge driver - card specific info
*
* 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/pci.h>
#include <linux/pci_ids.h>
#include "ngene.h"
/* demods/tuners */
#include "stv6110x.h"
#include "stv090x.h"
#include "lnbh24.h"
#include "lgdt330x.h"
#include "mt2131.h"
/****************************************************************************/
/* Demod/tuner attachment ***************************************************/
/****************************************************************************/
static int tuner_attach_stv6110(struct ngene_channel *chan)
{
struct stv090x_config *feconf = (struct stv090x_config *)
chan->dev->card_info->fe_config[chan->number];
struct stv6110x_config *tunerconf = (struct stv6110x_config *)
chan->dev->card_info->tuner_config[chan->number];
struct stv6110x_devctl *ctl;
ctl = dvb_attach(stv6110x_attach, chan->fe, tunerconf,
&chan->i2c_adapter);
if (ctl == NULL) {
printk(KERN_ERR DEVICE_NAME ": No STV6110X found!\n");
return -ENODEV;
}
feconf->tuner_init = ctl->tuner_init;
feconf->tuner_set_mode = ctl->tuner_set_mode;
feconf->tuner_set_frequency = ctl->tuner_set_frequency;
feconf->tuner_get_frequency = ctl->tuner_get_frequency;
feconf->tuner_set_bandwidth = ctl->tuner_set_bandwidth;
feconf->tuner_get_bandwidth = ctl->tuner_get_bandwidth;
feconf->tuner_set_bbgain = ctl->tuner_set_bbgain;
feconf->tuner_get_bbgain = ctl->tuner_get_bbgain;
feconf->tuner_set_refclk = ctl->tuner_set_refclk;
feconf->tuner_get_status = ctl->tuner_get_status;
return 0;
}
static int demod_attach_stv0900(struct ngene_channel *chan)
{
struct stv090x_config *feconf = (struct stv090x_config *)
chan->dev->card_info->fe_config[chan->number];
chan->fe = dvb_attach(stv090x_attach,
feconf,
&chan->i2c_adapter,
chan->number == 0 ? STV090x_DEMODULATOR_0 :
STV090x_DEMODULATOR_1);
if (chan->fe == NULL) {
printk(KERN_ERR DEVICE_NAME ": No STV0900 found!\n");
return -ENODEV;
}
if (!dvb_attach(lnbh24_attach, chan->fe, &chan->i2c_adapter, 0,
0, chan->dev->card_info->lnb[chan->number])) {
printk(KERN_ERR DEVICE_NAME ": No LNBH24 found!\n");
dvb_frontend_detach(chan->fe);
return -ENODEV;
}
return 0;
}
static struct lgdt330x_config aver_m780 = {
.demod_address = 0xb2 >> 1,
.demod_chip = LGDT3303,
.serial_mpeg = 0x00, /* PARALLEL */
.clock_polarity_flip = 1,
};
static struct mt2131_config m780_tunerconfig = {
0xc0 >> 1
};
/* A single func to attach the demo and tuner, rather than
* use two sep funcs like the current design mandates.
*/
static int demod_attach_lg330x(struct ngene_channel *chan)
{
chan->fe = dvb_attach(lgdt330x_attach, &aver_m780, &chan->i2c_adapter);
if (chan->fe == NULL) {
printk(KERN_ERR DEVICE_NAME ": No LGDT330x found!\n");
return -ENODEV;
}
dvb_attach(mt2131_attach, chan->fe, &chan->i2c_adapter,
&m780_tunerconfig, 0);
return (chan->fe) ? 0 : -ENODEV;
}
/****************************************************************************/
/* Switch control (I2C gates, etc.) *****************************************/
/****************************************************************************/
static struct stv090x_config fe_cineS2 = {
.device = STV0900,
.demod_mode = STV090x_DUAL,
.clk_mode = STV090x_CLK_EXT,
.xtal = 27000000,
.address = 0x68,
.ts1_mode = STV090x_TSMODE_SERIAL_PUNCTURED,
.ts2_mode = STV090x_TSMODE_SERIAL_PUNCTURED,
.repeater_level = STV090x_RPTLEVEL_16,
.adc1_range = STV090x_ADC_1Vpp,
.adc2_range = STV090x_ADC_1Vpp,
.diseqc_envelope_mode = true,
};
static struct stv6110x_config tuner_cineS2_0 = {
.addr = 0x60,
.refclk = 27000000,
.clk_div = 1,
};
static struct stv6110x_config tuner_cineS2_1 = {
.addr = 0x63,
.refclk = 27000000,
.clk_div = 1,
};
static struct ngene_info ngene_info_cineS2 = {
.type = NGENE_SIDEWINDER,
.name = "Linux4Media cineS2 DVB-S2 Twin Tuner",
.io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN},
.demod_attach = {demod_attach_stv0900, demod_attach_stv0900},
.tuner_attach = {tuner_attach_stv6110, tuner_attach_stv6110},
.fe_config = {&fe_cineS2, &fe_cineS2},
.tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1},
.lnb = {0x0b, 0x08},
.tsf = {3, 3},
.fw_version = 15,
};
static struct ngene_info ngene_info_satixS2 = {
.type = NGENE_SIDEWINDER,
.name = "Mystique SaTiX-S2 Dual",
.io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN},
.demod_attach = {demod_attach_stv0900, demod_attach_stv0900},
.tuner_attach = {tuner_attach_stv6110, tuner_attach_stv6110},
.fe_config = {&fe_cineS2, &fe_cineS2},
.tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1},
.lnb = {0x0b, 0x08},
.tsf = {3, 3},
.fw_version = 15,
};
static struct ngene_info ngene_info_satixS2v2 = {
.type = NGENE_SIDEWINDER,
.name = "Mystique SaTiX-S2 Dual (v2)",
.io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN},
.demod_attach = {demod_attach_stv0900, demod_attach_stv0900},
.tuner_attach = {tuner_attach_stv6110, tuner_attach_stv6110},
.fe_config = {&fe_cineS2, &fe_cineS2},
.tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1},
.lnb = {0x0a, 0x08},
.tsf = {3, 3},
.fw_version = 15,
};
static struct ngene_info ngene_info_cineS2v5 = {
.type = NGENE_SIDEWINDER,
.name = "Linux4Media cineS2 DVB-S2 Twin Tuner (v5)",
.io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN},
.demod_attach = {demod_attach_stv0900, demod_attach_stv0900},
.tuner_attach = {tuner_attach_stv6110, tuner_attach_stv6110},
.fe_config = {&fe_cineS2, &fe_cineS2},
.tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1},
.lnb = {0x0a, 0x08},
.tsf = {3, 3},
.fw_version = 15,
};
static struct ngene_info ngene_info_duoFlexS2 = {
.type = NGENE_SIDEWINDER,
.name = "Digital Devices DuoFlex S2 miniPCIe",
.io_type = {NGENE_IO_TSIN, NGENE_IO_TSIN},
.demod_attach = {demod_attach_stv0900, demod_attach_stv0900},
.tuner_attach = {tuner_attach_stv6110, tuner_attach_stv6110},
.fe_config = {&fe_cineS2, &fe_cineS2},
.tuner_config = {&tuner_cineS2_0, &tuner_cineS2_1},
.lnb = {0x0a, 0x08},
.tsf = {3, 3},
.fw_version = 15,
};
static struct ngene_info ngene_info_m780 = {
.type = NGENE_APP,
.name = "Aver M780 ATSC/QAM-B",
/* Channel 0 is analog, which is currently unsupported */
.io_type = { NGENE_IO_NONE, NGENE_IO_TSIN },
.demod_attach = { NULL, demod_attach_lg330x },
/* Ensure these are NULL else the frame will call them (as funcs) */
.tuner_attach = { 0, 0, 0, 0 },
.fe_config = { NULL, &aver_m780 },
.avf = { 0 },
/* A custom electrical interface config for the demod to bridge */
.tsf = { 4, 4 },
.fw_version = 15,
};
/****************************************************************************/
/****************************************************************************/
/* PCI Subsystem ID *********************************************************/
/****************************************************************************/
#define NGENE_ID(_subvend, _subdev, _driverdata) { \
.vendor = NGENE_VID, .device = NGENE_PID, \
.subvendor = _subvend, .subdevice = _subdev, \
.driver_data = (unsigned long) &_driverdata }
/****************************************************************************/
static const struct pci_device_id ngene_id_tbl[] __devinitdata = {
NGENE_ID(0x18c3, 0xabc3, ngene_info_cineS2),
NGENE_ID(0x18c3, 0xabc4, ngene_info_cineS2),
NGENE_ID(0x18c3, 0xdb01, ngene_info_satixS2),
NGENE_ID(0x18c3, 0xdb02, ngene_info_satixS2v2),
NGENE_ID(0x18c3, 0xdd00, ngene_info_cineS2v5),
NGENE_ID(0x18c3, 0xdd10, ngene_info_duoFlexS2),
NGENE_ID(0x18c3, 0xdd20, ngene_info_duoFlexS2),
NGENE_ID(0x1461, 0x062e, ngene_info_m780),
{0}
};
MODULE_DEVICE_TABLE(pci, ngene_id_tbl);
/****************************************************************************/
/* Init/Exit ****************************************************************/
/****************************************************************************/
static pci_ers_result_t ngene_error_detected(struct pci_dev *dev,
enum pci_channel_state state)
{
printk(KERN_ERR DEVICE_NAME ": PCI error\n");
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (state == pci_channel_io_frozen)
return PCI_ERS_RESULT_NEED_RESET;
return PCI_ERS_RESULT_CAN_RECOVER;
}
static pci_ers_result_t ngene_link_reset(struct pci_dev *dev)
{
printk(KERN_INFO DEVICE_NAME ": link reset\n");
return 0;
}
static pci_ers_result_t ngene_slot_reset(struct pci_dev *dev)
{
printk(KERN_INFO DEVICE_NAME ": slot reset\n");
return 0;
}
static void ngene_resume(struct pci_dev *dev)
{
printk(KERN_INFO DEVICE_NAME ": resume\n");
}
static struct pci_error_handlers ngene_errors = {
.error_detected = ngene_error_detected,
.link_reset = ngene_link_reset,
.slot_reset = ngene_slot_reset,
.resume = ngene_resume,
};
static struct pci_driver ngene_pci_driver = {
.name = "ngene",
.id_table = ngene_id_tbl,
.probe = ngene_probe,
.remove = __devexit_p(ngene_remove),
.err_handler = &ngene_errors,
};
static __init int module_init_ngene(void)
{
printk(KERN_INFO
"nGene PCIE bridge driver, Copyright (C) 2005-2007 Micronas\n");
return pci_register_driver(&ngene_pci_driver);
}
static __exit void module_exit_ngene(void)
{
pci_unregister_driver(&ngene_pci_driver);
}
module_init(module_init_ngene);
module_exit(module_exit_ngene);
MODULE_DESCRIPTION("nGene");
MODULE_AUTHOR("Micronas, Ralph Metzler, Manfred Voelkel");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jxxhwy/Thunder-Kenel-JB-N719 | drivers/staging/ft1000/ft1000-pcmcia/ft1000_cs.c | 2378 | 9219 | /*---------------------------------------------------------------------------
FT1000 driver for Flarion Flash OFDM NIC Device
Copyright (C) 1999 David A. Hinds. All Rights Reserved.
Copyright (C) 2002 Flarion Technologies, All rights reserved.
Copyright (C) 2006 Patrik Ostrihon, All rights reserved.
Copyright (C) 2006 ProWeb Consulting, a.s, All rights reserved.
The initial developer of the original code is David A. Hinds
<dahinds@users.sourceforge.net>. Portions created by David A. Hinds.
This file was modified to support the Flarion Flash OFDM NIC Device
by Wai Chan (w.chan@flarion.com).
Port for kernel 2.6 created by Patrik Ostrihon (patrik.ostrihon@pwc.sk)
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/module.h>
#include <linux/init.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/byteorder.h>
#include <asm/uaccess.h>
/*====================================================================*/
/* Module parameters */
#define INT_MODULE_PARM(n, v) static int n = v; MODULE_PARM(n, "i")
MODULE_AUTHOR("Wai Chan");
MODULE_DESCRIPTION("FT1000 PCMCIA driver");
MODULE_LICENSE("GPL");
/* Newer, simpler way of listing specific interrupts */
/* The old way: bit map of interrupts to choose from */
/* This means pick from 15, 14, 12, 11, 10, 9, 7, 5, 4, and 3 */
/*
All the PCMCIA modules use PCMCIA_DEBUG to control debugging. If
you do not define PCMCIA_DEBUG at all, all the debug code will be
left out. If you compile with PCMCIA_DEBUG=0, the debug code will
be present but disabled.
*/
#ifdef FT_DEBUG
#define DEBUG(n, args...) printk(KERN_DEBUG args)
#else
#define DEBUG(n, args...)
#endif
/*====================================================================*/
struct net_device *init_ft1000_card(struct pcmcia_device *link,
void *ft1000_reset);
void stop_ft1000_card(struct net_device *);
static int ft1000_config(struct pcmcia_device *link);
static void ft1000_release(struct pcmcia_device *link);
/*
The attach() and detach() entry points are used to create and destroy
"instances" of the driver, where each instance represents everything
needed to manage one actual PCMCIA card.
*/
static void ft1000_detach(struct pcmcia_device *link);
static int ft1000_attach(struct pcmcia_device *link);
typedef struct local_info_t {
struct pcmcia_device *link;
struct net_device *dev;
} local_info_t;
#define MAX_ASIC_RESET_CNT 10
#define COR_DEFAULT 0x55
/*====================================================================*/
static void ft1000_reset(struct pcmcia_device * link)
{
pcmcia_reset_card(link->socket);
}
/*======================================================================
======================================================================*/
static int ft1000_attach(struct pcmcia_device *link)
{
local_info_t *local;
DEBUG(0, "ft1000_cs: ft1000_attach()\n");
local = kzalloc(sizeof(local_info_t), GFP_KERNEL);
if (!local) {
return -ENOMEM;
}
local->link = link;
link->priv = local;
local->dev = NULL;
link->config_flags |= CONF_ENABLE_IRQ | CONF_AUTO_SET_IO;
return ft1000_config(link);
} /* ft1000_attach */
/*======================================================================
This deletes a driver "instance". The device is de-registered
with Card Services. If it has been released, all local data
structures are freed. Otherwise, the structures will be freed
when the device is released.
======================================================================*/
static void ft1000_detach(struct pcmcia_device *link)
{
struct net_device *dev = ((local_info_t *) link->priv)->dev;
DEBUG(0, "ft1000_cs: ft1000_detach(0x%p)\n", link);
if (link == NULL) {
DEBUG(0,"ft1000_cs:ft1000_detach: Got a NULL pointer\n");
return;
}
if (dev) {
stop_ft1000_card(dev);
}
pcmcia_disable_device(link);
/* This points to the parent local_info_t struct */
free_netdev(dev);
} /* ft1000_detach */
/*======================================================================
Check if the io window is configured
======================================================================*/
int ft1000_confcheck(struct pcmcia_device *link, void *priv_data)
{
return pcmcia_request_io(link);
} /* ft1000_confcheck */
/*======================================================================
ft1000_config() is scheduled to run after a CARD_INSERTION event
is received, to configure the PCMCIA socket, and to make the
device available to the system.
======================================================================*/
static int ft1000_config(struct pcmcia_device *link)
{
int ret;
dev_dbg(&link->dev, "ft1000_cs: ft1000_config(0x%p)\n", link);
/* setup IO window */
ret = pcmcia_loop_config(link, ft1000_confcheck, NULL);
if (ret) {
printk(KERN_INFO "ft1000: Could not configure pcmcia\n");
return -ENODEV;
}
/* configure device */
ret = pcmcia_enable_device(link);
if (ret) {
printk(KERN_INFO "ft1000: could not enable pcmcia\n");
goto failed;
}
((local_info_t *) link->priv)->dev = init_ft1000_card(link,
&ft1000_reset);
if (((local_info_t *) link->priv)->dev == NULL) {
printk(KERN_INFO "ft1000: Could not register as network device\n");
goto failed;
}
/* Finally, report what we've done */
return 0;
failed:
ft1000_release(link);
return -ENODEV;
} /* ft1000_config */
/*======================================================================
After a card is removed, ft1000_release() will unregister the
device, and release the PCMCIA configuration. If the device is
still open, this will be postponed until it is closed.
======================================================================*/
static void ft1000_release(struct pcmcia_device * link)
{
DEBUG(0, "ft1000_cs: ft1000_release(0x%p)\n", link);
/*
If the device is currently in use, we won't release until it
is actually closed, because until then, we can't be sure that
no one will try to access the device or its data structures.
*/
/*
In a normal driver, additional code may be needed to release
other kernel data structures associated with this device.
*/
kfree((local_info_t *) link->priv);
/* Don't bother checking to see if these succeed or not */
pcmcia_disable_device(link);
} /* ft1000_release */
/*======================================================================
The card status event handler. Mostly, this schedules other
stuff to run after an event is received.
When a CARD_REMOVAL event is received, we immediately set a
private flag to block future accesses to this device. All the
functions that actually access the device should check this flag
to make sure the card is still present.
======================================================================*/
static int ft1000_suspend(struct pcmcia_device *link)
{
struct net_device *dev = ((local_info_t *) link->priv)->dev;
DEBUG(1, "ft1000_cs: ft1000_event(0x%06x)\n", event);
if (link->open)
netif_device_detach(dev);
return 0;
}
static int ft1000_resume(struct pcmcia_device *link)
{
/* struct net_device *dev = link->priv;
*/
return 0;
}
/*====================================================================*/
static const struct pcmcia_device_id ft1000_ids[] = {
PCMCIA_DEVICE_MANF_CARD(0x02cc, 0x0100),
PCMCIA_DEVICE_MANF_CARD(0x02cc, 0x1000),
PCMCIA_DEVICE_MANF_CARD(0x02cc, 0x1300),
PCMCIA_DEVICE_NULL,
};
MODULE_DEVICE_TABLE(pcmcia, ft1000_ids);
static struct pcmcia_driver ft1000_cs_driver = {
.owner = THIS_MODULE,
.drv = {
.name = "ft1000_cs",
},
.probe = ft1000_attach,
.remove = ft1000_detach,
.id_table = ft1000_ids,
.suspend = ft1000_suspend,
.resume = ft1000_resume,
};
static int __init init_ft1000_cs(void)
{
DEBUG(0, "ft1000_cs: loading\n");
return pcmcia_register_driver(&ft1000_cs_driver);
}
static void __exit exit_ft1000_cs(void)
{
DEBUG(0, "ft1000_cs: unloading\n");
pcmcia_unregister_driver(&ft1000_cs_driver);
}
module_init(init_ft1000_cs);
module_exit(exit_ft1000_cs);
| gpl-2.0 |
AnguisCaptor/PwnKernel_Shamu | drivers/spmi/spmi-dbgfs.c | 2378 | 20308 | /* Copyright (c) 2012-2014, 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.
*/
/**
* SPMI Debug-fs support.
*
* Hierarchy schema:
* /sys/kernel/debug/spmi
* /help -- static help text
* /spmi-0
* /spmi-0/address -- Starting register address for reads or writes
* /spmi-0/count -- number of registers to read (only on read)
* /spmi-0/data -- Triggers the SPMI formatted read.
* /spmi-0/data_raw -- Triggers the SPMI raw read or write
* /spmi-#
*/
#define pr_fmt(fmt) "%s:%d: " fmt, __func__, __LINE__
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/debugfs.h>
#include <linux/spmi.h>
#include <linux/ctype.h>
#include "spmi-dbgfs.h"
#define ADDR_LEN 6 /* 5 byte address + 1 space character */
#define CHARS_PER_ITEM 3 /* Format is 'XX ' */
#define ITEMS_PER_LINE 16 /* 16 data items per line */
#define MAX_LINE_LENGTH (ADDR_LEN + (ITEMS_PER_LINE * CHARS_PER_ITEM) + 1)
#define MAX_REG_PER_TRANSACTION (8)
static const char *DFS_ROOT_NAME = "spmi";
static const mode_t DFS_MODE = S_IRUSR | S_IWUSR;
/* Log buffer */
struct spmi_log_buffer {
size_t rpos; /* Current 'read' position in buffer */
size_t wpos; /* Current 'write' position in buffer */
size_t len; /* Length of the buffer */
char data[0]; /* Log buffer */
};
/* SPMI controller specific data */
struct spmi_ctrl_data {
u32 cnt;
u32 addr;
struct dentry *dir;
struct list_head node;
struct spmi_controller *ctrl;
};
/* SPMI transaction parameters */
struct spmi_trans {
u32 cnt; /* Number of bytes to read */
u32 addr; /* 20-bit address: SID + PID + Register offset */
u32 offset; /* Offset of last read data */
bool raw_data; /* Set to true for raw data dump */
struct spmi_controller *ctrl;
struct spmi_log_buffer *log; /* log buffer */
};
struct spmi_dbgfs {
struct dentry *root;
struct mutex lock;
struct list_head ctrl; /* List of spmi_ctrl_data nodes */
struct debugfs_blob_wrapper help_msg;
};
static struct spmi_dbgfs dbgfs_data = {
.lock = __MUTEX_INITIALIZER(dbgfs_data.lock),
.ctrl = LIST_HEAD_INIT(dbgfs_data.ctrl),
.help_msg = {
.data =
"SPMI Debug-FS support\n"
"\n"
"Hierarchy schema:\n"
"/sys/kernel/debug/spmi\n"
" /help -- Static help text\n"
" /spmi-0 -- Directory for SPMI bus 0\n"
" /spmi-0/address -- Starting register address for reads or writes\n"
" /spmi-0/count -- Number of registers to read (only used for reads)\n"
" /spmi-0/data -- Initiates the SPMI read (formatted output)\n"
" /spmi-0/data_raw -- Initiates the SPMI raw read or write\n"
" /spmi-n -- Directory for SPMI bus n\n"
"\n"
"To perform SPMI read or write transactions, you need to first write the\n"
"address of the slave device register to the 'address' file. For read\n"
"transactions, the number of bytes to be read needs to be written to the\n"
"'count' file.\n"
"\n"
"The 'address' file specifies the 20-bit address of a slave device register.\n"
"The upper 4 bits 'address[19..16]' specify the slave identifier (SID) for\n"
"the slave device. The lower 16 bits specify the slave register address.\n"
"\n"
"Reading from the 'data' file will initiate a SPMI read transaction starting\n"
"from slave register 'address' for 'count' number of bytes.\n"
"\n"
"Writing to the 'data' file will initiate a SPMI write transaction starting\n"
"from slave register 'address'. The number of registers written to will\n"
"match the number of bytes written to the 'data' file.\n"
"\n"
"Example: Read 4 bytes starting at register address 0x1234 for SID 2\n"
"\n"
"echo 0x21234 > address\n"
"echo 4 > count\n"
"cat data\n"
"\n"
"Example: Write 3 bytes starting at register address 0x1008 for SID 1\n"
"\n"
"echo 0x11008 > address\n"
"echo 0x01 0x02 0x03 > data\n"
"\n"
"Note that the count file is not used for writes. Since 3 bytes are\n"
"written to the 'data' file, then 3 bytes will be written across the\n"
"SPMI bus.\n\n",
},
};
static int spmi_dfs_open(struct spmi_ctrl_data *ctrl_data, struct file *file)
{
struct spmi_log_buffer *log;
struct spmi_trans *trans;
size_t logbufsize = SZ_4K;
if (!ctrl_data) {
pr_err("No SPMI controller data\n");
return -EINVAL;
}
/* Per file "transaction" data */
trans = kzalloc(sizeof(*trans), GFP_KERNEL);
if (!trans) {
pr_err("Unable to allocate memory for transaction data\n");
return -ENOMEM;
}
/* Allocate log buffer */
log = kzalloc(logbufsize, GFP_KERNEL);
if (!log) {
kfree(trans);
pr_err("Unable to allocate memory for log buffer\n");
return -ENOMEM;
}
log->rpos = 0;
log->wpos = 0;
log->len = logbufsize - sizeof(*log);
trans->log = log;
trans->cnt = ctrl_data->cnt;
trans->addr = ctrl_data->addr;
trans->ctrl = ctrl_data->ctrl;
trans->offset = trans->addr;
file->private_data = trans;
return 0;
}
static int spmi_dfs_data_open(struct inode *inode, struct file *file)
{
struct spmi_ctrl_data *ctrl_data = inode->i_private;
return spmi_dfs_open(ctrl_data, file);
}
static int spmi_dfs_raw_data_open(struct inode *inode, struct file *file)
{
int rc;
struct spmi_trans *trans;
struct spmi_ctrl_data *ctrl_data = inode->i_private;
rc = spmi_dfs_open(ctrl_data, file);
trans = file->private_data;
trans->raw_data = true;
return rc;
}
static int spmi_dfs_close(struct inode *inode, struct file *file)
{
struct spmi_trans *trans = file->private_data;
if (trans && trans->log) {
file->private_data = NULL;
kfree(trans->log);
kfree(trans);
}
return 0;
}
/**
* spmi_read_data: reads data across the SPMI bus
* @ctrl: The SPMI controller
* @buf: buffer to store the data read.
* @offset: SPMI address offset to start reading from.
* @cnt: The number of bytes to read.
*
* Returns 0 on success, otherwise returns error code from SPMI driver.
*/
static int
spmi_read_data(struct spmi_controller *ctrl, uint8_t *buf, int offset, int cnt)
{
int ret = 0;
int len;
uint8_t sid;
uint16_t addr;
while (cnt > 0) {
sid = (offset >> 16) & 0xF;
addr = offset & 0xFFFF;
len = min(cnt, MAX_REG_PER_TRANSACTION);
ret = spmi_ext_register_readl(ctrl, sid, addr, buf, len);
if (ret < 0) {
pr_err("SPMI read failed, err = %d\n", ret);
goto done;
}
cnt -= len;
buf += len;
offset += len;
}
done:
return ret;
}
/**
* spmi_write_data: writes data across the SPMI bus
* @ctrl: The SPMI controller
* @buf: data to be written.
* @offset: SPMI address offset to start writing to.
* @cnt: The number of bytes to write.
*
* Returns 0 on success, otherwise returns error code from SPMI driver.
*/
static int
spmi_write_data(struct spmi_controller *ctrl, uint8_t *buf, int offset, int cnt)
{
int ret = 0;
int len;
uint8_t sid;
uint16_t addr;
while (cnt > 0) {
sid = (offset >> 16) & 0xF;
addr = offset & 0xFFFF;
len = min(cnt, MAX_REG_PER_TRANSACTION);
ret = spmi_ext_register_writel(ctrl, sid, addr, buf, len);
if (ret < 0) {
pr_err("SPMI write failed, err = %d\n", ret);
goto done;
}
cnt -= len;
buf += len;
offset += len;
}
done:
return ret;
}
/**
* print_to_log: format a string and place into the log buffer
* @log: The log buffer to place the result into.
* @fmt: The format string to use.
* @...: The arguments for the format string.
*
* The return value is the number of characters written to @log buffer
* not including the trailing '\0'.
*/
static int print_to_log(struct spmi_log_buffer *log, const char *fmt, ...)
{
va_list args;
int cnt;
char *buf = &log->data[log->wpos];
size_t size = log->len - log->wpos;
va_start(args, fmt);
cnt = vscnprintf(buf, size, fmt, args);
va_end(args);
log->wpos += cnt;
return cnt;
}
/**
* write_next_line_to_log: Writes a single "line" of data into the log buffer
* @trans: Pointer to SPMI transaction data.
* @offset: SPMI address offset to start reading from.
* @pcnt: Pointer to 'cnt' variable. Indicates the number of bytes to read.
*
* The 'offset' is a 20-bits SPMI address which includes a 4-bit slave id (SID),
* an 8-bit peripheral id (PID), and an 8-bit peripheral register address.
*
* On a successful read, the pcnt is decremented by the number of data
* bytes read across the SPMI bus. When the cnt reaches 0, all requested
* bytes have been read.
*/
static int
write_next_line_to_log(struct spmi_trans *trans, int offset, size_t *pcnt)
{
int i, j;
u8 data[ITEMS_PER_LINE];
struct spmi_log_buffer *log = trans->log;
int cnt = 0;
int padding = offset % ITEMS_PER_LINE;
int items_to_read = min(ARRAY_SIZE(data) - padding, *pcnt);
int items_to_log = min(ITEMS_PER_LINE, padding + items_to_read);
/* Buffer needs enough space for an entire line */
if ((log->len - log->wpos) < MAX_LINE_LENGTH)
goto done;
/* Read the desired number of "items" */
if (spmi_read_data(trans->ctrl, data, offset, items_to_read))
goto done;
*pcnt -= items_to_read;
/* Each line starts with the aligned offset (20-bit address) */
cnt = print_to_log(log, "%5.5X ", offset & 0xffff0);
if (cnt == 0)
goto done;
/* If the offset is unaligned, add padding to right justify items */
for (i = 0; i < padding; ++i) {
cnt = print_to_log(log, "-- ");
if (cnt == 0)
goto done;
}
/* Log the data items */
for (j = 0; i < items_to_log; ++i, ++j) {
cnt = print_to_log(log, "%2.2X ", data[j]);
if (cnt == 0)
goto done;
}
/* If the last character was a space, then replace it with a newline */
if (log->wpos > 0 && log->data[log->wpos - 1] == ' ')
log->data[log->wpos - 1] = '\n';
done:
return cnt;
}
/**
* write_raw_data_to_log: Writes a single "line" of data into the log buffer
* @trans: Pointer to SPMI transaction data.
* @offset: SPMI address offset to start reading from.
* @pcnt: Pointer to 'cnt' variable. Indicates the number of bytes to read.
*
* The 'offset' is a 20-bits SPMI address which includes a 4-bit slave id (SID),
* an 8-bit peripheral id (PID), and an 8-bit peripheral register address.
*
* On a successful read, the pcnt is decremented by the number of data
* bytes read across the SPMI bus. When the cnt reaches 0, all requested
* bytes have been read.
*/
static int
write_raw_data_to_log(struct spmi_trans *trans, int offset, size_t *pcnt)
{
u8 data[16];
struct spmi_log_buffer *log = trans->log;
int i;
int cnt = 0;
int items_to_read = min(ARRAY_SIZE(data), *pcnt);
/* Buffer needs enough space for an entire line */
if ((log->len - log->wpos) < 80)
goto done;
/* Read the desired number of "items" */
if (spmi_read_data(trans->ctrl, data, offset, items_to_read))
goto done;
*pcnt -= items_to_read;
/* Log the data items */
for (i = 0; i < items_to_read; ++i) {
cnt = print_to_log(log, "0x%2.2X ", data[i]);
if (cnt == 0)
goto done;
}
/* If the last character was a space, then replace it with a newline */
if (log->wpos > 0 && log->data[log->wpos - 1] == ' ')
log->data[log->wpos - 1] = '\n';
done:
return cnt;
}
/**
* get_log_data - reads data across the SPMI bus and saves to the log buffer
* @trans: Pointer to SPMI transaction data.
*
* Returns the number of "items" read or SPMI error code for read failures.
*/
static int get_log_data(struct spmi_trans *trans)
{
int cnt;
int last_cnt;
int items_read;
int total_items_read = 0;
u32 offset = trans->offset;
size_t item_cnt = trans->cnt;
struct spmi_log_buffer *log = trans->log;
int (*write_to_log)(struct spmi_trans *, int, size_t *);
if (item_cnt == 0)
return 0;
if (trans->raw_data)
write_to_log = write_raw_data_to_log;
else
write_to_log = write_next_line_to_log;
/* Reset the log buffer 'pointers' */
log->wpos = log->rpos = 0;
/* Keep reading data until the log is full */
do {
last_cnt = item_cnt;
cnt = write_to_log(trans, offset, &item_cnt);
items_read = last_cnt - item_cnt;
offset += items_read;
total_items_read += items_read;
} while (cnt && item_cnt > 0);
/* Adjust the transaction offset and count */
trans->cnt = item_cnt;
trans->offset += total_items_read;
return total_items_read;
}
/**
* spmi_dfs_reg_write: write user's byte array (coded as string) over SPMI.
* @file: file pointer
* @buf: user data to be written.
* @count: maximum space available in @buf
* @ppos: starting position
* @return number of user byte written, or negative error value
*/
static ssize_t spmi_dfs_reg_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int bytes_read;
int data;
int pos = 0;
int cnt = 0;
u8 *values;
size_t ret = 0;
struct spmi_trans *trans = file->private_data;
u32 offset = trans->offset;
/* Make a copy of the user data */
char *kbuf = kmalloc(count + 1, GFP_KERNEL);
if (!kbuf)
return -ENOMEM;
ret = copy_from_user(kbuf, buf, count);
if (ret == count) {
pr_err("failed to copy data from user\n");
ret = -EFAULT;
goto free_buf;
}
count -= ret;
*ppos += count;
kbuf[count] = '\0';
/* Override the text buffer with the raw data */
values = kbuf;
/* Parse the data in the buffer. It should be a string of numbers */
while (sscanf(kbuf + pos, "%i%n", &data, &bytes_read) == 1) {
pos += bytes_read;
values[cnt++] = data & 0xff;
}
if (!cnt)
goto free_buf;
/* Perform the SPMI write(s) */
ret = spmi_write_data(trans->ctrl, values, offset, cnt);
if (ret) {
pr_err("SPMI write failed, err = %zu\n", ret);
} else {
ret = count;
trans->offset += cnt;
}
free_buf:
kfree(kbuf);
return ret;
}
/**
* spmi_dfs_reg_read: reads value(s) over SPMI and fill user's buffer a
* byte array (coded as string)
* @file: file pointer
* @buf: where to put the result
* @count: maximum space available in @buf
* @ppos: starting position
* @return number of user bytes read, or negative error value
*/
static ssize_t spmi_dfs_reg_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct spmi_trans *trans = file->private_data;
struct spmi_log_buffer *log = trans->log;
size_t ret;
size_t len;
/* Is the the log buffer empty */
if (log->rpos >= log->wpos) {
if (get_log_data(trans) <= 0)
return 0;
}
len = min(count, log->wpos - log->rpos);
ret = copy_to_user(buf, &log->data[log->rpos], len);
if (ret == len) {
pr_err("error copy SPMI register values to user\n");
return -EFAULT;
}
/* 'ret' is the number of bytes not copied */
len -= ret;
*ppos += len;
log->rpos += len;
return len;
}
static const struct file_operations spmi_dfs_reg_fops = {
.open = spmi_dfs_data_open,
.release = spmi_dfs_close,
.read = spmi_dfs_reg_read,
.write = spmi_dfs_reg_write,
};
static const struct file_operations spmi_dfs_raw_data_fops = {
.open = spmi_dfs_raw_data_open,
.release = spmi_dfs_close,
.read = spmi_dfs_reg_read,
.write = spmi_dfs_reg_write,
};
/**
* spmi_dfs_create_fs: create debugfs file system.
* @return pointer to root directory or NULL if failed to create fs
*/
static struct dentry *spmi_dfs_create_fs(void)
{
struct dentry *root, *file;
pr_debug("Creating SPMI debugfs file-system\n");
root = debugfs_create_dir(DFS_ROOT_NAME, NULL);
if (IS_ERR_OR_NULL(root)) {
pr_err("Error creating top level directory err:%ld",
(long)root);
if (PTR_ERR(root) == -ENODEV)
pr_err("debugfs is not enabled in the kernel");
return NULL;
}
dbgfs_data.help_msg.size = strlen(dbgfs_data.help_msg.data);
file = debugfs_create_blob("help", S_IRUGO, root, &dbgfs_data.help_msg);
if (!file) {
pr_err("error creating help entry\n");
goto err_remove_fs;
}
return root;
err_remove_fs:
debugfs_remove_recursive(root);
return NULL;
}
/**
* spmi_dfs_get_root: return a pointer to SPMI debugfs root directory.
* @brief return a pointer to the existing directory, or if no root
* directory exists then create one. Directory is created with file that
* configures SPMI transaction, namely: sid, address, and count.
* @returns valid pointer on success or NULL
*/
struct dentry *spmi_dfs_get_root(void)
{
if (dbgfs_data.root)
return dbgfs_data.root;
if (mutex_lock_interruptible(&dbgfs_data.lock) < 0)
return NULL;
/* critical section */
if (!dbgfs_data.root) { /* double checking idiom */
dbgfs_data.root = spmi_dfs_create_fs();
}
mutex_unlock(&dbgfs_data.lock);
return dbgfs_data.root;
}
/*
* spmi_dfs_add_controller: adds new spmi controller entry
* @return zero on success
*/
int spmi_dfs_add_controller(struct spmi_controller *ctrl)
{
struct dentry *dir;
struct dentry *root;
struct dentry *file;
struct spmi_ctrl_data *ctrl_data;
pr_debug("Adding controller %s\n", ctrl->dev.kobj.name);
root = spmi_dfs_get_root();
if (!root)
return -ENOENT;
/* Allocate transaction data for the controller */
ctrl_data = kzalloc(sizeof(*ctrl_data), GFP_KERNEL);
if (!ctrl_data)
return -ENOMEM;
dir = debugfs_create_dir(ctrl->dev.kobj.name, root);
if (!dir) {
pr_err("Error creating entry for spmi controller %s\n",
ctrl->dev.kobj.name);
goto err_create_dir_failed;
}
ctrl_data->cnt = 1;
ctrl_data->dir = dir;
ctrl_data->ctrl = ctrl;
file = debugfs_create_u32("count", DFS_MODE, dir, &ctrl_data->cnt);
if (!file) {
pr_err("error creating 'count' entry\n");
goto err_remove_fs;
}
file = debugfs_create_x32("address", DFS_MODE, dir, &ctrl_data->addr);
if (!file) {
pr_err("error creating 'address' entry\n");
goto err_remove_fs;
}
file = debugfs_create_file("data", DFS_MODE, dir, ctrl_data,
&spmi_dfs_reg_fops);
if (!file) {
pr_err("error creating 'data' entry\n");
goto err_remove_fs;
}
file = debugfs_create_file("data_raw", DFS_MODE, dir, ctrl_data,
&spmi_dfs_raw_data_fops);
if (!file) {
pr_err("error creating 'data' entry\n");
goto err_remove_fs;
}
list_add(&ctrl_data->node, &dbgfs_data.ctrl);
return 0;
err_remove_fs:
debugfs_remove_recursive(dir);
err_create_dir_failed:
kfree(ctrl_data);
return -ENOMEM;
}
/*
* spmi_dfs_del_controller: deletes spmi controller entry
* @return zero on success
*/
int spmi_dfs_del_controller(struct spmi_controller *ctrl)
{
int rc;
struct list_head *pos, *tmp;
struct spmi_ctrl_data *ctrl_data;
pr_debug("Deleting controller %s\n", ctrl->dev.kobj.name);
rc = mutex_lock_interruptible(&dbgfs_data.lock);
if (rc)
return rc;
list_for_each_safe(pos, tmp, &dbgfs_data.ctrl) {
ctrl_data = list_entry(pos, struct spmi_ctrl_data, node);
if (ctrl_data->ctrl == ctrl) {
debugfs_remove_recursive(ctrl_data->dir);
list_del(pos);
kfree(ctrl_data);
rc = 0;
goto done;
}
}
rc = -EINVAL;
pr_debug("Unknown controller %s\n", ctrl->dev.kobj.name);
done:
mutex_unlock(&dbgfs_data.lock);
return rc;
}
/*
* spmi_dfs_create_file: creates a new file in the SPMI debugfs
* @returns valid dentry pointer on success or NULL
*/
struct dentry *spmi_dfs_create_file(struct spmi_controller *ctrl,
const char *name, void *data,
const struct file_operations *fops)
{
struct spmi_ctrl_data *ctrl_data;
list_for_each_entry(ctrl_data, &dbgfs_data.ctrl, node) {
if (ctrl_data->ctrl == ctrl)
return debugfs_create_file(name,
DFS_MODE, ctrl_data->dir, data, fops);
}
return NULL;
}
static void __exit spmi_dfs_delete_all_ctrl(struct list_head *head)
{
struct list_head *pos, *tmp;
list_for_each_safe(pos, tmp, head) {
struct spmi_ctrl_data *ctrl_data;
ctrl_data = list_entry(pos, struct spmi_ctrl_data, node);
list_del(pos);
kfree(ctrl_data);
}
}
static void __exit spmi_dfs_destroy(void)
{
pr_debug("de-initializing spmi debugfs ...");
if (mutex_lock_interruptible(&dbgfs_data.lock) < 0)
return;
if (dbgfs_data.root) {
debugfs_remove_recursive(dbgfs_data.root);
dbgfs_data.root = NULL;
spmi_dfs_delete_all_ctrl(&dbgfs_data.ctrl);
}
mutex_unlock(&dbgfs_data.lock);
}
module_exit(spmi_dfs_destroy);
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:spmi_debug_fs");
| gpl-2.0 |
chonix/trinity | drivers/net/forcedeth.c | 2378 | 182686 | /*
* forcedeth: Ethernet driver for NVIDIA nForce media access controllers.
*
* Note: This driver is a cleanroom reimplementation based on reverse
* engineered documentation written by Carl-Daniel Hailfinger
* and Andrew de Quincey.
*
* NVIDIA, nForce and other NVIDIA marks are trademarks or registered
* trademarks of NVIDIA Corporation in the United States and other
* countries.
*
* Copyright (C) 2003,4,5 Manfred Spraul
* Copyright (C) 2004 Andrew de Quincey (wol support)
* Copyright (C) 2004 Carl-Daniel Hailfinger (invalid MAC handling, insane
* IRQ rate fixes, bigendian fixes, cleanups, verification)
* Copyright (c) 2004,2005,2006,2007,2008,2009 NVIDIA Corporation
*
* 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
*
* Known bugs:
* We suspect that on some hardware no TX done interrupts are generated.
* This means recovery from netif_stop_queue only happens if the hw timer
* interrupt fires (100 times/second, configurable with NVREG_POLL_DEFAULT)
* and the timer is active in the IRQMask, or if a rx packet arrives by chance.
* If your hardware reliably generates tx done interrupts, then you can remove
* DEV_NEED_TIMERIRQ from the driver_data flags.
* DEV_NEED_TIMERIRQ will not harm you on sane hardware, only generating a few
* superfluous timer interrupts from the nic.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define FORCEDETH_VERSION "0.64"
#define DRV_NAME "forcedeth"
#include <linux/module.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/ethtool.h>
#include <linux/timer.h>
#include <linux/skbuff.h>
#include <linux/mii.h>
#include <linux/random.h>
#include <linux/init.h>
#include <linux/if_vlan.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/prefetch.h>
#include <linux/io.h>
#include <asm/irq.h>
#include <asm/system.h>
#define TX_WORK_PER_LOOP 64
#define RX_WORK_PER_LOOP 64
/*
* Hardware access:
*/
#define DEV_NEED_TIMERIRQ 0x0000001 /* set the timer irq flag in the irq mask */
#define DEV_NEED_LINKTIMER 0x0000002 /* poll link settings. Relies on the timer irq */
#define DEV_HAS_LARGEDESC 0x0000004 /* device supports jumbo frames and needs packet format 2 */
#define DEV_HAS_HIGH_DMA 0x0000008 /* device supports 64bit dma */
#define DEV_HAS_CHECKSUM 0x0000010 /* device supports tx and rx checksum offloads */
#define DEV_HAS_VLAN 0x0000020 /* device supports vlan tagging and striping */
#define DEV_HAS_MSI 0x0000040 /* device supports MSI */
#define DEV_HAS_MSI_X 0x0000080 /* device supports MSI-X */
#define DEV_HAS_POWER_CNTRL 0x0000100 /* device supports power savings */
#define DEV_HAS_STATISTICS_V1 0x0000200 /* device supports hw statistics version 1 */
#define DEV_HAS_STATISTICS_V2 0x0000400 /* device supports hw statistics version 2 */
#define DEV_HAS_STATISTICS_V3 0x0000800 /* device supports hw statistics version 3 */
#define DEV_HAS_STATISTICS_V12 0x0000600 /* device supports hw statistics version 1 and 2 */
#define DEV_HAS_STATISTICS_V123 0x0000e00 /* device supports hw statistics version 1, 2, and 3 */
#define DEV_HAS_TEST_EXTENDED 0x0001000 /* device supports extended diagnostic test */
#define DEV_HAS_MGMT_UNIT 0x0002000 /* device supports management unit */
#define DEV_HAS_CORRECT_MACADDR 0x0004000 /* device supports correct mac address order */
#define DEV_HAS_COLLISION_FIX 0x0008000 /* device supports tx collision fix */
#define DEV_HAS_PAUSEFRAME_TX_V1 0x0010000 /* device supports tx pause frames version 1 */
#define DEV_HAS_PAUSEFRAME_TX_V2 0x0020000 /* device supports tx pause frames version 2 */
#define DEV_HAS_PAUSEFRAME_TX_V3 0x0040000 /* device supports tx pause frames version 3 */
#define DEV_NEED_TX_LIMIT 0x0080000 /* device needs to limit tx */
#define DEV_NEED_TX_LIMIT2 0x0180000 /* device needs to limit tx, expect for some revs */
#define DEV_HAS_GEAR_MODE 0x0200000 /* device supports gear mode */
#define DEV_NEED_PHY_INIT_FIX 0x0400000 /* device needs specific phy workaround */
#define DEV_NEED_LOW_POWER_FIX 0x0800000 /* device needs special power up workaround */
#define DEV_NEED_MSI_FIX 0x1000000 /* device needs msi workaround */
enum {
NvRegIrqStatus = 0x000,
#define NVREG_IRQSTAT_MIIEVENT 0x040
#define NVREG_IRQSTAT_MASK 0x83ff
NvRegIrqMask = 0x004,
#define NVREG_IRQ_RX_ERROR 0x0001
#define NVREG_IRQ_RX 0x0002
#define NVREG_IRQ_RX_NOBUF 0x0004
#define NVREG_IRQ_TX_ERR 0x0008
#define NVREG_IRQ_TX_OK 0x0010
#define NVREG_IRQ_TIMER 0x0020
#define NVREG_IRQ_LINK 0x0040
#define NVREG_IRQ_RX_FORCED 0x0080
#define NVREG_IRQ_TX_FORCED 0x0100
#define NVREG_IRQ_RECOVER_ERROR 0x8200
#define NVREG_IRQMASK_THROUGHPUT 0x00df
#define NVREG_IRQMASK_CPU 0x0060
#define NVREG_IRQ_TX_ALL (NVREG_IRQ_TX_ERR|NVREG_IRQ_TX_OK|NVREG_IRQ_TX_FORCED)
#define NVREG_IRQ_RX_ALL (NVREG_IRQ_RX_ERROR|NVREG_IRQ_RX|NVREG_IRQ_RX_NOBUF|NVREG_IRQ_RX_FORCED)
#define NVREG_IRQ_OTHER (NVREG_IRQ_TIMER|NVREG_IRQ_LINK|NVREG_IRQ_RECOVER_ERROR)
NvRegUnknownSetupReg6 = 0x008,
#define NVREG_UNKSETUP6_VAL 3
/*
* NVREG_POLL_DEFAULT is the interval length of the timer source on the nic
* NVREG_POLL_DEFAULT=97 would result in an interval length of 1 ms
*/
NvRegPollingInterval = 0x00c,
#define NVREG_POLL_DEFAULT_THROUGHPUT 65535 /* backup tx cleanup if loop max reached */
#define NVREG_POLL_DEFAULT_CPU 13
NvRegMSIMap0 = 0x020,
NvRegMSIMap1 = 0x024,
NvRegMSIIrqMask = 0x030,
#define NVREG_MSI_VECTOR_0_ENABLED 0x01
NvRegMisc1 = 0x080,
#define NVREG_MISC1_PAUSE_TX 0x01
#define NVREG_MISC1_HD 0x02
#define NVREG_MISC1_FORCE 0x3b0f3c
NvRegMacReset = 0x34,
#define NVREG_MAC_RESET_ASSERT 0x0F3
NvRegTransmitterControl = 0x084,
#define NVREG_XMITCTL_START 0x01
#define NVREG_XMITCTL_MGMT_ST 0x40000000
#define NVREG_XMITCTL_SYNC_MASK 0x000f0000
#define NVREG_XMITCTL_SYNC_NOT_READY 0x0
#define NVREG_XMITCTL_SYNC_PHY_INIT 0x00040000
#define NVREG_XMITCTL_MGMT_SEMA_MASK 0x00000f00
#define NVREG_XMITCTL_MGMT_SEMA_FREE 0x0
#define NVREG_XMITCTL_HOST_SEMA_MASK 0x0000f000
#define NVREG_XMITCTL_HOST_SEMA_ACQ 0x0000f000
#define NVREG_XMITCTL_HOST_LOADED 0x00004000
#define NVREG_XMITCTL_TX_PATH_EN 0x01000000
#define NVREG_XMITCTL_DATA_START 0x00100000
#define NVREG_XMITCTL_DATA_READY 0x00010000
#define NVREG_XMITCTL_DATA_ERROR 0x00020000
NvRegTransmitterStatus = 0x088,
#define NVREG_XMITSTAT_BUSY 0x01
NvRegPacketFilterFlags = 0x8c,
#define NVREG_PFF_PAUSE_RX 0x08
#define NVREG_PFF_ALWAYS 0x7F0000
#define NVREG_PFF_PROMISC 0x80
#define NVREG_PFF_MYADDR 0x20
#define NVREG_PFF_LOOPBACK 0x10
NvRegOffloadConfig = 0x90,
#define NVREG_OFFLOAD_HOMEPHY 0x601
#define NVREG_OFFLOAD_NORMAL RX_NIC_BUFSIZE
NvRegReceiverControl = 0x094,
#define NVREG_RCVCTL_START 0x01
#define NVREG_RCVCTL_RX_PATH_EN 0x01000000
NvRegReceiverStatus = 0x98,
#define NVREG_RCVSTAT_BUSY 0x01
NvRegSlotTime = 0x9c,
#define NVREG_SLOTTIME_LEGBF_ENABLED 0x80000000
#define NVREG_SLOTTIME_10_100_FULL 0x00007f00
#define NVREG_SLOTTIME_1000_FULL 0x0003ff00
#define NVREG_SLOTTIME_HALF 0x0000ff00
#define NVREG_SLOTTIME_DEFAULT 0x00007f00
#define NVREG_SLOTTIME_MASK 0x000000ff
NvRegTxDeferral = 0xA0,
#define NVREG_TX_DEFERRAL_DEFAULT 0x15050f
#define NVREG_TX_DEFERRAL_RGMII_10_100 0x16070f
#define NVREG_TX_DEFERRAL_RGMII_1000 0x14050f
#define NVREG_TX_DEFERRAL_RGMII_STRETCH_10 0x16190f
#define NVREG_TX_DEFERRAL_RGMII_STRETCH_100 0x16300f
#define NVREG_TX_DEFERRAL_MII_STRETCH 0x152000
NvRegRxDeferral = 0xA4,
#define NVREG_RX_DEFERRAL_DEFAULT 0x16
NvRegMacAddrA = 0xA8,
NvRegMacAddrB = 0xAC,
NvRegMulticastAddrA = 0xB0,
#define NVREG_MCASTADDRA_FORCE 0x01
NvRegMulticastAddrB = 0xB4,
NvRegMulticastMaskA = 0xB8,
#define NVREG_MCASTMASKA_NONE 0xffffffff
NvRegMulticastMaskB = 0xBC,
#define NVREG_MCASTMASKB_NONE 0xffff
NvRegPhyInterface = 0xC0,
#define PHY_RGMII 0x10000000
NvRegBackOffControl = 0xC4,
#define NVREG_BKOFFCTRL_DEFAULT 0x70000000
#define NVREG_BKOFFCTRL_SEED_MASK 0x000003ff
#define NVREG_BKOFFCTRL_SELECT 24
#define NVREG_BKOFFCTRL_GEAR 12
NvRegTxRingPhysAddr = 0x100,
NvRegRxRingPhysAddr = 0x104,
NvRegRingSizes = 0x108,
#define NVREG_RINGSZ_TXSHIFT 0
#define NVREG_RINGSZ_RXSHIFT 16
NvRegTransmitPoll = 0x10c,
#define NVREG_TRANSMITPOLL_MAC_ADDR_REV 0x00008000
NvRegLinkSpeed = 0x110,
#define NVREG_LINKSPEED_FORCE 0x10000
#define NVREG_LINKSPEED_10 1000
#define NVREG_LINKSPEED_100 100
#define NVREG_LINKSPEED_1000 50
#define NVREG_LINKSPEED_MASK (0xFFF)
NvRegUnknownSetupReg5 = 0x130,
#define NVREG_UNKSETUP5_BIT31 (1<<31)
NvRegTxWatermark = 0x13c,
#define NVREG_TX_WM_DESC1_DEFAULT 0x0200010
#define NVREG_TX_WM_DESC2_3_DEFAULT 0x1e08000
#define NVREG_TX_WM_DESC2_3_1000 0xfe08000
NvRegTxRxControl = 0x144,
#define NVREG_TXRXCTL_KICK 0x0001
#define NVREG_TXRXCTL_BIT1 0x0002
#define NVREG_TXRXCTL_BIT2 0x0004
#define NVREG_TXRXCTL_IDLE 0x0008
#define NVREG_TXRXCTL_RESET 0x0010
#define NVREG_TXRXCTL_RXCHECK 0x0400
#define NVREG_TXRXCTL_DESC_1 0
#define NVREG_TXRXCTL_DESC_2 0x002100
#define NVREG_TXRXCTL_DESC_3 0xc02200
#define NVREG_TXRXCTL_VLANSTRIP 0x00040
#define NVREG_TXRXCTL_VLANINS 0x00080
NvRegTxRingPhysAddrHigh = 0x148,
NvRegRxRingPhysAddrHigh = 0x14C,
NvRegTxPauseFrame = 0x170,
#define NVREG_TX_PAUSEFRAME_DISABLE 0x0fff0080
#define NVREG_TX_PAUSEFRAME_ENABLE_V1 0x01800010
#define NVREG_TX_PAUSEFRAME_ENABLE_V2 0x056003f0
#define NVREG_TX_PAUSEFRAME_ENABLE_V3 0x09f00880
NvRegTxPauseFrameLimit = 0x174,
#define NVREG_TX_PAUSEFRAMELIMIT_ENABLE 0x00010000
NvRegMIIStatus = 0x180,
#define NVREG_MIISTAT_ERROR 0x0001
#define NVREG_MIISTAT_LINKCHANGE 0x0008
#define NVREG_MIISTAT_MASK_RW 0x0007
#define NVREG_MIISTAT_MASK_ALL 0x000f
NvRegMIIMask = 0x184,
#define NVREG_MII_LINKCHANGE 0x0008
NvRegAdapterControl = 0x188,
#define NVREG_ADAPTCTL_START 0x02
#define NVREG_ADAPTCTL_LINKUP 0x04
#define NVREG_ADAPTCTL_PHYVALID 0x40000
#define NVREG_ADAPTCTL_RUNNING 0x100000
#define NVREG_ADAPTCTL_PHYSHIFT 24
NvRegMIISpeed = 0x18c,
#define NVREG_MIISPEED_BIT8 (1<<8)
#define NVREG_MIIDELAY 5
NvRegMIIControl = 0x190,
#define NVREG_MIICTL_INUSE 0x08000
#define NVREG_MIICTL_WRITE 0x00400
#define NVREG_MIICTL_ADDRSHIFT 5
NvRegMIIData = 0x194,
NvRegTxUnicast = 0x1a0,
NvRegTxMulticast = 0x1a4,
NvRegTxBroadcast = 0x1a8,
NvRegWakeUpFlags = 0x200,
#define NVREG_WAKEUPFLAGS_VAL 0x7770
#define NVREG_WAKEUPFLAGS_BUSYSHIFT 24
#define NVREG_WAKEUPFLAGS_ENABLESHIFT 16
#define NVREG_WAKEUPFLAGS_D3SHIFT 12
#define NVREG_WAKEUPFLAGS_D2SHIFT 8
#define NVREG_WAKEUPFLAGS_D1SHIFT 4
#define NVREG_WAKEUPFLAGS_D0SHIFT 0
#define NVREG_WAKEUPFLAGS_ACCEPT_MAGPAT 0x01
#define NVREG_WAKEUPFLAGS_ACCEPT_WAKEUPPAT 0x02
#define NVREG_WAKEUPFLAGS_ACCEPT_LINKCHANGE 0x04
#define NVREG_WAKEUPFLAGS_ENABLE 0x1111
NvRegMgmtUnitGetVersion = 0x204,
#define NVREG_MGMTUNITGETVERSION 0x01
NvRegMgmtUnitVersion = 0x208,
#define NVREG_MGMTUNITVERSION 0x08
NvRegPowerCap = 0x268,
#define NVREG_POWERCAP_D3SUPP (1<<30)
#define NVREG_POWERCAP_D2SUPP (1<<26)
#define NVREG_POWERCAP_D1SUPP (1<<25)
NvRegPowerState = 0x26c,
#define NVREG_POWERSTATE_POWEREDUP 0x8000
#define NVREG_POWERSTATE_VALID 0x0100
#define NVREG_POWERSTATE_MASK 0x0003
#define NVREG_POWERSTATE_D0 0x0000
#define NVREG_POWERSTATE_D1 0x0001
#define NVREG_POWERSTATE_D2 0x0002
#define NVREG_POWERSTATE_D3 0x0003
NvRegMgmtUnitControl = 0x278,
#define NVREG_MGMTUNITCONTROL_INUSE 0x20000
NvRegTxCnt = 0x280,
NvRegTxZeroReXmt = 0x284,
NvRegTxOneReXmt = 0x288,
NvRegTxManyReXmt = 0x28c,
NvRegTxLateCol = 0x290,
NvRegTxUnderflow = 0x294,
NvRegTxLossCarrier = 0x298,
NvRegTxExcessDef = 0x29c,
NvRegTxRetryErr = 0x2a0,
NvRegRxFrameErr = 0x2a4,
NvRegRxExtraByte = 0x2a8,
NvRegRxLateCol = 0x2ac,
NvRegRxRunt = 0x2b0,
NvRegRxFrameTooLong = 0x2b4,
NvRegRxOverflow = 0x2b8,
NvRegRxFCSErr = 0x2bc,
NvRegRxFrameAlignErr = 0x2c0,
NvRegRxLenErr = 0x2c4,
NvRegRxUnicast = 0x2c8,
NvRegRxMulticast = 0x2cc,
NvRegRxBroadcast = 0x2d0,
NvRegTxDef = 0x2d4,
NvRegTxFrame = 0x2d8,
NvRegRxCnt = 0x2dc,
NvRegTxPause = 0x2e0,
NvRegRxPause = 0x2e4,
NvRegRxDropFrame = 0x2e8,
NvRegVlanControl = 0x300,
#define NVREG_VLANCONTROL_ENABLE 0x2000
NvRegMSIXMap0 = 0x3e0,
NvRegMSIXMap1 = 0x3e4,
NvRegMSIXIrqStatus = 0x3f0,
NvRegPowerState2 = 0x600,
#define NVREG_POWERSTATE2_POWERUP_MASK 0x0F15
#define NVREG_POWERSTATE2_POWERUP_REV_A3 0x0001
#define NVREG_POWERSTATE2_PHY_RESET 0x0004
#define NVREG_POWERSTATE2_GATE_CLOCKS 0x0F00
};
/* Big endian: should work, but is untested */
struct ring_desc {
__le32 buf;
__le32 flaglen;
};
struct ring_desc_ex {
__le32 bufhigh;
__le32 buflow;
__le32 txvlan;
__le32 flaglen;
};
union ring_type {
struct ring_desc *orig;
struct ring_desc_ex *ex;
};
#define FLAG_MASK_V1 0xffff0000
#define FLAG_MASK_V2 0xffffc000
#define LEN_MASK_V1 (0xffffffff ^ FLAG_MASK_V1)
#define LEN_MASK_V2 (0xffffffff ^ FLAG_MASK_V2)
#define NV_TX_LASTPACKET (1<<16)
#define NV_TX_RETRYERROR (1<<19)
#define NV_TX_RETRYCOUNT_MASK (0xF<<20)
#define NV_TX_FORCED_INTERRUPT (1<<24)
#define NV_TX_DEFERRED (1<<26)
#define NV_TX_CARRIERLOST (1<<27)
#define NV_TX_LATECOLLISION (1<<28)
#define NV_TX_UNDERFLOW (1<<29)
#define NV_TX_ERROR (1<<30)
#define NV_TX_VALID (1<<31)
#define NV_TX2_LASTPACKET (1<<29)
#define NV_TX2_RETRYERROR (1<<18)
#define NV_TX2_RETRYCOUNT_MASK (0xF<<19)
#define NV_TX2_FORCED_INTERRUPT (1<<30)
#define NV_TX2_DEFERRED (1<<25)
#define NV_TX2_CARRIERLOST (1<<26)
#define NV_TX2_LATECOLLISION (1<<27)
#define NV_TX2_UNDERFLOW (1<<28)
/* error and valid are the same for both */
#define NV_TX2_ERROR (1<<30)
#define NV_TX2_VALID (1<<31)
#define NV_TX2_TSO (1<<28)
#define NV_TX2_TSO_SHIFT 14
#define NV_TX2_TSO_MAX_SHIFT 14
#define NV_TX2_TSO_MAX_SIZE (1<<NV_TX2_TSO_MAX_SHIFT)
#define NV_TX2_CHECKSUM_L3 (1<<27)
#define NV_TX2_CHECKSUM_L4 (1<<26)
#define NV_TX3_VLAN_TAG_PRESENT (1<<18)
#define NV_RX_DESCRIPTORVALID (1<<16)
#define NV_RX_MISSEDFRAME (1<<17)
#define NV_RX_SUBSTRACT1 (1<<18)
#define NV_RX_ERROR1 (1<<23)
#define NV_RX_ERROR2 (1<<24)
#define NV_RX_ERROR3 (1<<25)
#define NV_RX_ERROR4 (1<<26)
#define NV_RX_CRCERR (1<<27)
#define NV_RX_OVERFLOW (1<<28)
#define NV_RX_FRAMINGERR (1<<29)
#define NV_RX_ERROR (1<<30)
#define NV_RX_AVAIL (1<<31)
#define NV_RX_ERROR_MASK (NV_RX_ERROR1|NV_RX_ERROR2|NV_RX_ERROR3|NV_RX_ERROR4|NV_RX_CRCERR|NV_RX_OVERFLOW|NV_RX_FRAMINGERR)
#define NV_RX2_CHECKSUMMASK (0x1C000000)
#define NV_RX2_CHECKSUM_IP (0x10000000)
#define NV_RX2_CHECKSUM_IP_TCP (0x14000000)
#define NV_RX2_CHECKSUM_IP_UDP (0x18000000)
#define NV_RX2_DESCRIPTORVALID (1<<29)
#define NV_RX2_SUBSTRACT1 (1<<25)
#define NV_RX2_ERROR1 (1<<18)
#define NV_RX2_ERROR2 (1<<19)
#define NV_RX2_ERROR3 (1<<20)
#define NV_RX2_ERROR4 (1<<21)
#define NV_RX2_CRCERR (1<<22)
#define NV_RX2_OVERFLOW (1<<23)
#define NV_RX2_FRAMINGERR (1<<24)
/* error and avail are the same for both */
#define NV_RX2_ERROR (1<<30)
#define NV_RX2_AVAIL (1<<31)
#define NV_RX2_ERROR_MASK (NV_RX2_ERROR1|NV_RX2_ERROR2|NV_RX2_ERROR3|NV_RX2_ERROR4|NV_RX2_CRCERR|NV_RX2_OVERFLOW|NV_RX2_FRAMINGERR)
#define NV_RX3_VLAN_TAG_PRESENT (1<<16)
#define NV_RX3_VLAN_TAG_MASK (0x0000FFFF)
/* Miscellaneous hardware related defines: */
#define NV_PCI_REGSZ_VER1 0x270
#define NV_PCI_REGSZ_VER2 0x2d4
#define NV_PCI_REGSZ_VER3 0x604
#define NV_PCI_REGSZ_MAX 0x604
/* various timeout delays: all in usec */
#define NV_TXRX_RESET_DELAY 4
#define NV_TXSTOP_DELAY1 10
#define NV_TXSTOP_DELAY1MAX 500000
#define NV_TXSTOP_DELAY2 100
#define NV_RXSTOP_DELAY1 10
#define NV_RXSTOP_DELAY1MAX 500000
#define NV_RXSTOP_DELAY2 100
#define NV_SETUP5_DELAY 5
#define NV_SETUP5_DELAYMAX 50000
#define NV_POWERUP_DELAY 5
#define NV_POWERUP_DELAYMAX 5000
#define NV_MIIBUSY_DELAY 50
#define NV_MIIPHY_DELAY 10
#define NV_MIIPHY_DELAYMAX 10000
#define NV_MAC_RESET_DELAY 64
#define NV_WAKEUPPATTERNS 5
#define NV_WAKEUPMASKENTRIES 4
/* General driver defaults */
#define NV_WATCHDOG_TIMEO (5*HZ)
#define RX_RING_DEFAULT 512
#define TX_RING_DEFAULT 256
#define RX_RING_MIN 128
#define TX_RING_MIN 64
#define RING_MAX_DESC_VER_1 1024
#define RING_MAX_DESC_VER_2_3 16384
/* rx/tx mac addr + type + vlan + align + slack*/
#define NV_RX_HEADERS (64)
/* even more slack. */
#define NV_RX_ALLOC_PAD (64)
/* maximum mtu size */
#define NV_PKTLIMIT_1 ETH_DATA_LEN /* hard limit not known */
#define NV_PKTLIMIT_2 9100 /* Actual limit according to NVidia: 9202 */
#define OOM_REFILL (1+HZ/20)
#define POLL_WAIT (1+HZ/100)
#define LINK_TIMEOUT (3*HZ)
#define STATS_INTERVAL (10*HZ)
/*
* desc_ver values:
* The nic supports three different descriptor types:
* - DESC_VER_1: Original
* - DESC_VER_2: support for jumbo frames.
* - DESC_VER_3: 64-bit format.
*/
#define DESC_VER_1 1
#define DESC_VER_2 2
#define DESC_VER_3 3
/* PHY defines */
#define PHY_OUI_MARVELL 0x5043
#define PHY_OUI_CICADA 0x03f1
#define PHY_OUI_VITESSE 0x01c1
#define PHY_OUI_REALTEK 0x0732
#define PHY_OUI_REALTEK2 0x0020
#define PHYID1_OUI_MASK 0x03ff
#define PHYID1_OUI_SHFT 6
#define PHYID2_OUI_MASK 0xfc00
#define PHYID2_OUI_SHFT 10
#define PHYID2_MODEL_MASK 0x03f0
#define PHY_MODEL_REALTEK_8211 0x0110
#define PHY_REV_MASK 0x0001
#define PHY_REV_REALTEK_8211B 0x0000
#define PHY_REV_REALTEK_8211C 0x0001
#define PHY_MODEL_REALTEK_8201 0x0200
#define PHY_MODEL_MARVELL_E3016 0x0220
#define PHY_MARVELL_E3016_INITMASK 0x0300
#define PHY_CICADA_INIT1 0x0f000
#define PHY_CICADA_INIT2 0x0e00
#define PHY_CICADA_INIT3 0x01000
#define PHY_CICADA_INIT4 0x0200
#define PHY_CICADA_INIT5 0x0004
#define PHY_CICADA_INIT6 0x02000
#define PHY_VITESSE_INIT_REG1 0x1f
#define PHY_VITESSE_INIT_REG2 0x10
#define PHY_VITESSE_INIT_REG3 0x11
#define PHY_VITESSE_INIT_REG4 0x12
#define PHY_VITESSE_INIT_MSK1 0xc
#define PHY_VITESSE_INIT_MSK2 0x0180
#define PHY_VITESSE_INIT1 0x52b5
#define PHY_VITESSE_INIT2 0xaf8a
#define PHY_VITESSE_INIT3 0x8
#define PHY_VITESSE_INIT4 0x8f8a
#define PHY_VITESSE_INIT5 0xaf86
#define PHY_VITESSE_INIT6 0x8f86
#define PHY_VITESSE_INIT7 0xaf82
#define PHY_VITESSE_INIT8 0x0100
#define PHY_VITESSE_INIT9 0x8f82
#define PHY_VITESSE_INIT10 0x0
#define PHY_REALTEK_INIT_REG1 0x1f
#define PHY_REALTEK_INIT_REG2 0x19
#define PHY_REALTEK_INIT_REG3 0x13
#define PHY_REALTEK_INIT_REG4 0x14
#define PHY_REALTEK_INIT_REG5 0x18
#define PHY_REALTEK_INIT_REG6 0x11
#define PHY_REALTEK_INIT_REG7 0x01
#define PHY_REALTEK_INIT1 0x0000
#define PHY_REALTEK_INIT2 0x8e00
#define PHY_REALTEK_INIT3 0x0001
#define PHY_REALTEK_INIT4 0xad17
#define PHY_REALTEK_INIT5 0xfb54
#define PHY_REALTEK_INIT6 0xf5c7
#define PHY_REALTEK_INIT7 0x1000
#define PHY_REALTEK_INIT8 0x0003
#define PHY_REALTEK_INIT9 0x0008
#define PHY_REALTEK_INIT10 0x0005
#define PHY_REALTEK_INIT11 0x0200
#define PHY_REALTEK_INIT_MSK1 0x0003
#define PHY_GIGABIT 0x0100
#define PHY_TIMEOUT 0x1
#define PHY_ERROR 0x2
#define PHY_100 0x1
#define PHY_1000 0x2
#define PHY_HALF 0x100
#define NV_PAUSEFRAME_RX_CAPABLE 0x0001
#define NV_PAUSEFRAME_TX_CAPABLE 0x0002
#define NV_PAUSEFRAME_RX_ENABLE 0x0004
#define NV_PAUSEFRAME_TX_ENABLE 0x0008
#define NV_PAUSEFRAME_RX_REQ 0x0010
#define NV_PAUSEFRAME_TX_REQ 0x0020
#define NV_PAUSEFRAME_AUTONEG 0x0040
/* MSI/MSI-X defines */
#define NV_MSI_X_MAX_VECTORS 8
#define NV_MSI_X_VECTORS_MASK 0x000f
#define NV_MSI_CAPABLE 0x0010
#define NV_MSI_X_CAPABLE 0x0020
#define NV_MSI_ENABLED 0x0040
#define NV_MSI_X_ENABLED 0x0080
#define NV_MSI_X_VECTOR_ALL 0x0
#define NV_MSI_X_VECTOR_RX 0x0
#define NV_MSI_X_VECTOR_TX 0x1
#define NV_MSI_X_VECTOR_OTHER 0x2
#define NV_MSI_PRIV_OFFSET 0x68
#define NV_MSI_PRIV_VALUE 0xffffffff
#define NV_RESTART_TX 0x1
#define NV_RESTART_RX 0x2
#define NV_TX_LIMIT_COUNT 16
#define NV_DYNAMIC_THRESHOLD 4
#define NV_DYNAMIC_MAX_QUIET_COUNT 2048
/* statistics */
struct nv_ethtool_str {
char name[ETH_GSTRING_LEN];
};
static const struct nv_ethtool_str nv_estats_str[] = {
{ "tx_bytes" },
{ "tx_zero_rexmt" },
{ "tx_one_rexmt" },
{ "tx_many_rexmt" },
{ "tx_late_collision" },
{ "tx_fifo_errors" },
{ "tx_carrier_errors" },
{ "tx_excess_deferral" },
{ "tx_retry_error" },
{ "rx_frame_error" },
{ "rx_extra_byte" },
{ "rx_late_collision" },
{ "rx_runt" },
{ "rx_frame_too_long" },
{ "rx_over_errors" },
{ "rx_crc_errors" },
{ "rx_frame_align_error" },
{ "rx_length_error" },
{ "rx_unicast" },
{ "rx_multicast" },
{ "rx_broadcast" },
{ "rx_packets" },
{ "rx_errors_total" },
{ "tx_errors_total" },
/* version 2 stats */
{ "tx_deferral" },
{ "tx_packets" },
{ "rx_bytes" },
{ "tx_pause" },
{ "rx_pause" },
{ "rx_drop_frame" },
/* version 3 stats */
{ "tx_unicast" },
{ "tx_multicast" },
{ "tx_broadcast" }
};
struct nv_ethtool_stats {
u64 tx_bytes;
u64 tx_zero_rexmt;
u64 tx_one_rexmt;
u64 tx_many_rexmt;
u64 tx_late_collision;
u64 tx_fifo_errors;
u64 tx_carrier_errors;
u64 tx_excess_deferral;
u64 tx_retry_error;
u64 rx_frame_error;
u64 rx_extra_byte;
u64 rx_late_collision;
u64 rx_runt;
u64 rx_frame_too_long;
u64 rx_over_errors;
u64 rx_crc_errors;
u64 rx_frame_align_error;
u64 rx_length_error;
u64 rx_unicast;
u64 rx_multicast;
u64 rx_broadcast;
u64 rx_packets;
u64 rx_errors_total;
u64 tx_errors_total;
/* version 2 stats */
u64 tx_deferral;
u64 tx_packets;
u64 rx_bytes;
u64 tx_pause;
u64 rx_pause;
u64 rx_drop_frame;
/* version 3 stats */
u64 tx_unicast;
u64 tx_multicast;
u64 tx_broadcast;
};
#define NV_DEV_STATISTICS_V3_COUNT (sizeof(struct nv_ethtool_stats)/sizeof(u64))
#define NV_DEV_STATISTICS_V2_COUNT (NV_DEV_STATISTICS_V3_COUNT - 3)
#define NV_DEV_STATISTICS_V1_COUNT (NV_DEV_STATISTICS_V2_COUNT - 6)
/* diagnostics */
#define NV_TEST_COUNT_BASE 3
#define NV_TEST_COUNT_EXTENDED 4
static const struct nv_ethtool_str nv_etests_str[] = {
{ "link (online/offline)" },
{ "register (offline) " },
{ "interrupt (offline) " },
{ "loopback (offline) " }
};
struct register_test {
__u32 reg;
__u32 mask;
};
static const struct register_test nv_registers_test[] = {
{ NvRegUnknownSetupReg6, 0x01 },
{ NvRegMisc1, 0x03c },
{ NvRegOffloadConfig, 0x03ff },
{ NvRegMulticastAddrA, 0xffffffff },
{ NvRegTxWatermark, 0x0ff },
{ NvRegWakeUpFlags, 0x07777 },
{ 0, 0 }
};
struct nv_skb_map {
struct sk_buff *skb;
dma_addr_t dma;
unsigned int dma_len:31;
unsigned int dma_single:1;
struct ring_desc_ex *first_tx_desc;
struct nv_skb_map *next_tx_ctx;
};
/*
* SMP locking:
* All hardware access under netdev_priv(dev)->lock, except the performance
* critical parts:
* - rx is (pseudo-) lockless: it relies on the single-threading provided
* by the arch code for interrupts.
* - tx setup is lockless: it relies on netif_tx_lock. Actual submission
* needs netdev_priv(dev)->lock :-(
* - set_multicast_list: preparation lockless, relies on netif_tx_lock.
*/
/* in dev: base, irq */
struct fe_priv {
spinlock_t lock;
struct net_device *dev;
struct napi_struct napi;
/* General data:
* Locking: spin_lock(&np->lock); */
struct nv_ethtool_stats estats;
int in_shutdown;
u32 linkspeed;
int duplex;
int autoneg;
int fixed_mode;
int phyaddr;
int wolenabled;
unsigned int phy_oui;
unsigned int phy_model;
unsigned int phy_rev;
u16 gigabit;
int intr_test;
int recover_error;
int quiet_count;
/* General data: RO fields */
dma_addr_t ring_addr;
struct pci_dev *pci_dev;
u32 orig_mac[2];
u32 events;
u32 irqmask;
u32 desc_ver;
u32 txrxctl_bits;
u32 vlanctl_bits;
u32 driver_data;
u32 device_id;
u32 register_size;
u32 mac_in_use;
int mgmt_version;
int mgmt_sema;
void __iomem *base;
/* rx specific fields.
* Locking: Within irq hander or disable_irq+spin_lock(&np->lock);
*/
union ring_type get_rx, put_rx, first_rx, last_rx;
struct nv_skb_map *get_rx_ctx, *put_rx_ctx;
struct nv_skb_map *first_rx_ctx, *last_rx_ctx;
struct nv_skb_map *rx_skb;
union ring_type rx_ring;
unsigned int rx_buf_sz;
unsigned int pkt_limit;
struct timer_list oom_kick;
struct timer_list nic_poll;
struct timer_list stats_poll;
u32 nic_poll_irq;
int rx_ring_size;
/* media detection workaround.
* Locking: Within irq hander or disable_irq+spin_lock(&np->lock);
*/
int need_linktimer;
unsigned long link_timeout;
/*
* tx specific fields.
*/
union ring_type get_tx, put_tx, first_tx, last_tx;
struct nv_skb_map *get_tx_ctx, *put_tx_ctx;
struct nv_skb_map *first_tx_ctx, *last_tx_ctx;
struct nv_skb_map *tx_skb;
union ring_type tx_ring;
u32 tx_flags;
int tx_ring_size;
int tx_limit;
u32 tx_pkts_in_progress;
struct nv_skb_map *tx_change_owner;
struct nv_skb_map *tx_end_flip;
int tx_stop;
/* vlan fields */
struct vlan_group *vlangrp;
/* msi/msi-x fields */
u32 msi_flags;
struct msix_entry msi_x_entry[NV_MSI_X_MAX_VECTORS];
/* flow control */
u32 pause_flags;
/* power saved state */
u32 saved_config_space[NV_PCI_REGSZ_MAX/4];
/* for different msi-x irq type */
char name_rx[IFNAMSIZ + 3]; /* -rx */
char name_tx[IFNAMSIZ + 3]; /* -tx */
char name_other[IFNAMSIZ + 6]; /* -other */
};
/*
* Maximum number of loops until we assume that a bit in the irq mask
* is stuck. Overridable with module param.
*/
static int max_interrupt_work = 4;
/*
* Optimization can be either throuput mode or cpu mode
*
* Throughput Mode: Every tx and rx packet will generate an interrupt.
* CPU Mode: Interrupts are controlled by a timer.
*/
enum {
NV_OPTIMIZATION_MODE_THROUGHPUT,
NV_OPTIMIZATION_MODE_CPU,
NV_OPTIMIZATION_MODE_DYNAMIC
};
static int optimization_mode = NV_OPTIMIZATION_MODE_DYNAMIC;
/*
* Poll interval for timer irq
*
* This interval determines how frequent an interrupt is generated.
* The is value is determined by [(time_in_micro_secs * 100) / (2^10)]
* Min = 0, and Max = 65535
*/
static int poll_interval = -1;
/*
* MSI interrupts
*/
enum {
NV_MSI_INT_DISABLED,
NV_MSI_INT_ENABLED
};
static int msi = NV_MSI_INT_ENABLED;
/*
* MSIX interrupts
*/
enum {
NV_MSIX_INT_DISABLED,
NV_MSIX_INT_ENABLED
};
static int msix = NV_MSIX_INT_ENABLED;
/*
* DMA 64bit
*/
enum {
NV_DMA_64BIT_DISABLED,
NV_DMA_64BIT_ENABLED
};
static int dma_64bit = NV_DMA_64BIT_ENABLED;
/*
* Crossover Detection
* Realtek 8201 phy + some OEM boards do not work properly.
*/
enum {
NV_CROSSOVER_DETECTION_DISABLED,
NV_CROSSOVER_DETECTION_ENABLED
};
static int phy_cross = NV_CROSSOVER_DETECTION_DISABLED;
/*
* Power down phy when interface is down (persists through reboot;
* older Linux and other OSes may not power it up again)
*/
static int phy_power_down;
static inline struct fe_priv *get_nvpriv(struct net_device *dev)
{
return netdev_priv(dev);
}
static inline u8 __iomem *get_hwbase(struct net_device *dev)
{
return ((struct fe_priv *)netdev_priv(dev))->base;
}
static inline void pci_push(u8 __iomem *base)
{
/* force out pending posted writes */
readl(base);
}
static inline u32 nv_descr_getlength(struct ring_desc *prd, u32 v)
{
return le32_to_cpu(prd->flaglen)
& ((v == DESC_VER_1) ? LEN_MASK_V1 : LEN_MASK_V2);
}
static inline u32 nv_descr_getlength_ex(struct ring_desc_ex *prd, u32 v)
{
return le32_to_cpu(prd->flaglen) & LEN_MASK_V2;
}
static bool nv_optimized(struct fe_priv *np)
{
if (np->desc_ver == DESC_VER_1 || np->desc_ver == DESC_VER_2)
return false;
return true;
}
static int reg_delay(struct net_device *dev, int offset, u32 mask, u32 target,
int delay, int delaymax)
{
u8 __iomem *base = get_hwbase(dev);
pci_push(base);
do {
udelay(delay);
delaymax -= delay;
if (delaymax < 0)
return 1;
} while ((readl(base + offset) & mask) != target);
return 0;
}
#define NV_SETUP_RX_RING 0x01
#define NV_SETUP_TX_RING 0x02
static inline u32 dma_low(dma_addr_t addr)
{
return addr;
}
static inline u32 dma_high(dma_addr_t addr)
{
return addr>>31>>1; /* 0 if 32bit, shift down by 32 if 64bit */
}
static void setup_hw_rings(struct net_device *dev, int rxtx_flags)
{
struct fe_priv *np = get_nvpriv(dev);
u8 __iomem *base = get_hwbase(dev);
if (!nv_optimized(np)) {
if (rxtx_flags & NV_SETUP_RX_RING)
writel(dma_low(np->ring_addr), base + NvRegRxRingPhysAddr);
if (rxtx_flags & NV_SETUP_TX_RING)
writel(dma_low(np->ring_addr + np->rx_ring_size*sizeof(struct ring_desc)), base + NvRegTxRingPhysAddr);
} else {
if (rxtx_flags & NV_SETUP_RX_RING) {
writel(dma_low(np->ring_addr), base + NvRegRxRingPhysAddr);
writel(dma_high(np->ring_addr), base + NvRegRxRingPhysAddrHigh);
}
if (rxtx_flags & NV_SETUP_TX_RING) {
writel(dma_low(np->ring_addr + np->rx_ring_size*sizeof(struct ring_desc_ex)), base + NvRegTxRingPhysAddr);
writel(dma_high(np->ring_addr + np->rx_ring_size*sizeof(struct ring_desc_ex)), base + NvRegTxRingPhysAddrHigh);
}
}
}
static void free_rings(struct net_device *dev)
{
struct fe_priv *np = get_nvpriv(dev);
if (!nv_optimized(np)) {
if (np->rx_ring.orig)
pci_free_consistent(np->pci_dev, sizeof(struct ring_desc) * (np->rx_ring_size + np->tx_ring_size),
np->rx_ring.orig, np->ring_addr);
} else {
if (np->rx_ring.ex)
pci_free_consistent(np->pci_dev, sizeof(struct ring_desc_ex) * (np->rx_ring_size + np->tx_ring_size),
np->rx_ring.ex, np->ring_addr);
}
kfree(np->rx_skb);
kfree(np->tx_skb);
}
static int using_multi_irqs(struct net_device *dev)
{
struct fe_priv *np = get_nvpriv(dev);
if (!(np->msi_flags & NV_MSI_X_ENABLED) ||
((np->msi_flags & NV_MSI_X_ENABLED) &&
((np->msi_flags & NV_MSI_X_VECTORS_MASK) == 0x1)))
return 0;
else
return 1;
}
static void nv_txrx_gate(struct net_device *dev, bool gate)
{
struct fe_priv *np = get_nvpriv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 powerstate;
if (!np->mac_in_use &&
(np->driver_data & DEV_HAS_POWER_CNTRL)) {
powerstate = readl(base + NvRegPowerState2);
if (gate)
powerstate |= NVREG_POWERSTATE2_GATE_CLOCKS;
else
powerstate &= ~NVREG_POWERSTATE2_GATE_CLOCKS;
writel(powerstate, base + NvRegPowerState2);
}
}
static void nv_enable_irq(struct net_device *dev)
{
struct fe_priv *np = get_nvpriv(dev);
if (!using_multi_irqs(dev)) {
if (np->msi_flags & NV_MSI_X_ENABLED)
enable_irq(np->msi_x_entry[NV_MSI_X_VECTOR_ALL].vector);
else
enable_irq(np->pci_dev->irq);
} else {
enable_irq(np->msi_x_entry[NV_MSI_X_VECTOR_RX].vector);
enable_irq(np->msi_x_entry[NV_MSI_X_VECTOR_TX].vector);
enable_irq(np->msi_x_entry[NV_MSI_X_VECTOR_OTHER].vector);
}
}
static void nv_disable_irq(struct net_device *dev)
{
struct fe_priv *np = get_nvpriv(dev);
if (!using_multi_irqs(dev)) {
if (np->msi_flags & NV_MSI_X_ENABLED)
disable_irq(np->msi_x_entry[NV_MSI_X_VECTOR_ALL].vector);
else
disable_irq(np->pci_dev->irq);
} else {
disable_irq(np->msi_x_entry[NV_MSI_X_VECTOR_RX].vector);
disable_irq(np->msi_x_entry[NV_MSI_X_VECTOR_TX].vector);
disable_irq(np->msi_x_entry[NV_MSI_X_VECTOR_OTHER].vector);
}
}
/* In MSIX mode, a write to irqmask behaves as XOR */
static void nv_enable_hw_interrupts(struct net_device *dev, u32 mask)
{
u8 __iomem *base = get_hwbase(dev);
writel(mask, base + NvRegIrqMask);
}
static void nv_disable_hw_interrupts(struct net_device *dev, u32 mask)
{
struct fe_priv *np = get_nvpriv(dev);
u8 __iomem *base = get_hwbase(dev);
if (np->msi_flags & NV_MSI_X_ENABLED) {
writel(mask, base + NvRegIrqMask);
} else {
if (np->msi_flags & NV_MSI_ENABLED)
writel(0, base + NvRegMSIIrqMask);
writel(0, base + NvRegIrqMask);
}
}
static void nv_napi_enable(struct net_device *dev)
{
struct fe_priv *np = get_nvpriv(dev);
napi_enable(&np->napi);
}
static void nv_napi_disable(struct net_device *dev)
{
struct fe_priv *np = get_nvpriv(dev);
napi_disable(&np->napi);
}
#define MII_READ (-1)
/* mii_rw: read/write a register on the PHY.
*
* Caller must guarantee serialization
*/
static int mii_rw(struct net_device *dev, int addr, int miireg, int value)
{
u8 __iomem *base = get_hwbase(dev);
u32 reg;
int retval;
writel(NVREG_MIISTAT_MASK_RW, base + NvRegMIIStatus);
reg = readl(base + NvRegMIIControl);
if (reg & NVREG_MIICTL_INUSE) {
writel(NVREG_MIICTL_INUSE, base + NvRegMIIControl);
udelay(NV_MIIBUSY_DELAY);
}
reg = (addr << NVREG_MIICTL_ADDRSHIFT) | miireg;
if (value != MII_READ) {
writel(value, base + NvRegMIIData);
reg |= NVREG_MIICTL_WRITE;
}
writel(reg, base + NvRegMIIControl);
if (reg_delay(dev, NvRegMIIControl, NVREG_MIICTL_INUSE, 0,
NV_MIIPHY_DELAY, NV_MIIPHY_DELAYMAX)) {
retval = -1;
} else if (value != MII_READ) {
/* it was a write operation - fewer failures are detectable */
retval = 0;
} else if (readl(base + NvRegMIIStatus) & NVREG_MIISTAT_ERROR) {
retval = -1;
} else {
retval = readl(base + NvRegMIIData);
}
return retval;
}
static int phy_reset(struct net_device *dev, u32 bmcr_setup)
{
struct fe_priv *np = netdev_priv(dev);
u32 miicontrol;
unsigned int tries = 0;
miicontrol = BMCR_RESET | bmcr_setup;
if (mii_rw(dev, np->phyaddr, MII_BMCR, miicontrol))
return -1;
/* wait for 500ms */
msleep(500);
/* must wait till reset is deasserted */
while (miicontrol & BMCR_RESET) {
usleep_range(10000, 20000);
miicontrol = mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ);
/* FIXME: 100 tries seem excessive */
if (tries++ > 100)
return -1;
}
return 0;
}
static int init_realtek_8211b(struct net_device *dev, struct fe_priv *np)
{
static const struct {
int reg;
int init;
} ri[] = {
{ PHY_REALTEK_INIT_REG1, PHY_REALTEK_INIT1 },
{ PHY_REALTEK_INIT_REG2, PHY_REALTEK_INIT2 },
{ PHY_REALTEK_INIT_REG1, PHY_REALTEK_INIT3 },
{ PHY_REALTEK_INIT_REG3, PHY_REALTEK_INIT4 },
{ PHY_REALTEK_INIT_REG4, PHY_REALTEK_INIT5 },
{ PHY_REALTEK_INIT_REG5, PHY_REALTEK_INIT6 },
{ PHY_REALTEK_INIT_REG1, PHY_REALTEK_INIT1 },
};
int i;
for (i = 0; i < ARRAY_SIZE(ri); i++) {
if (mii_rw(dev, np->phyaddr, ri[i].reg, ri[i].init))
return PHY_ERROR;
}
return 0;
}
static int init_realtek_8211c(struct net_device *dev, struct fe_priv *np)
{
u32 reg;
u8 __iomem *base = get_hwbase(dev);
u32 powerstate = readl(base + NvRegPowerState2);
/* need to perform hw phy reset */
powerstate |= NVREG_POWERSTATE2_PHY_RESET;
writel(powerstate, base + NvRegPowerState2);
msleep(25);
powerstate &= ~NVREG_POWERSTATE2_PHY_RESET;
writel(powerstate, base + NvRegPowerState2);
msleep(25);
reg = mii_rw(dev, np->phyaddr, PHY_REALTEK_INIT_REG6, MII_READ);
reg |= PHY_REALTEK_INIT9;
if (mii_rw(dev, np->phyaddr, PHY_REALTEK_INIT_REG6, reg))
return PHY_ERROR;
if (mii_rw(dev, np->phyaddr,
PHY_REALTEK_INIT_REG1, PHY_REALTEK_INIT10))
return PHY_ERROR;
reg = mii_rw(dev, np->phyaddr, PHY_REALTEK_INIT_REG7, MII_READ);
if (!(reg & PHY_REALTEK_INIT11)) {
reg |= PHY_REALTEK_INIT11;
if (mii_rw(dev, np->phyaddr, PHY_REALTEK_INIT_REG7, reg))
return PHY_ERROR;
}
if (mii_rw(dev, np->phyaddr,
PHY_REALTEK_INIT_REG1, PHY_REALTEK_INIT1))
return PHY_ERROR;
return 0;
}
static int init_realtek_8201(struct net_device *dev, struct fe_priv *np)
{
u32 phy_reserved;
if (np->driver_data & DEV_NEED_PHY_INIT_FIX) {
phy_reserved = mii_rw(dev, np->phyaddr,
PHY_REALTEK_INIT_REG6, MII_READ);
phy_reserved |= PHY_REALTEK_INIT7;
if (mii_rw(dev, np->phyaddr,
PHY_REALTEK_INIT_REG6, phy_reserved))
return PHY_ERROR;
}
return 0;
}
static int init_realtek_8201_cross(struct net_device *dev, struct fe_priv *np)
{
u32 phy_reserved;
if (phy_cross == NV_CROSSOVER_DETECTION_DISABLED) {
if (mii_rw(dev, np->phyaddr,
PHY_REALTEK_INIT_REG1, PHY_REALTEK_INIT3))
return PHY_ERROR;
phy_reserved = mii_rw(dev, np->phyaddr,
PHY_REALTEK_INIT_REG2, MII_READ);
phy_reserved &= ~PHY_REALTEK_INIT_MSK1;
phy_reserved |= PHY_REALTEK_INIT3;
if (mii_rw(dev, np->phyaddr,
PHY_REALTEK_INIT_REG2, phy_reserved))
return PHY_ERROR;
if (mii_rw(dev, np->phyaddr,
PHY_REALTEK_INIT_REG1, PHY_REALTEK_INIT1))
return PHY_ERROR;
}
return 0;
}
static int init_cicada(struct net_device *dev, struct fe_priv *np,
u32 phyinterface)
{
u32 phy_reserved;
if (phyinterface & PHY_RGMII) {
phy_reserved = mii_rw(dev, np->phyaddr, MII_RESV1, MII_READ);
phy_reserved &= ~(PHY_CICADA_INIT1 | PHY_CICADA_INIT2);
phy_reserved |= (PHY_CICADA_INIT3 | PHY_CICADA_INIT4);
if (mii_rw(dev, np->phyaddr, MII_RESV1, phy_reserved))
return PHY_ERROR;
phy_reserved = mii_rw(dev, np->phyaddr, MII_NCONFIG, MII_READ);
phy_reserved |= PHY_CICADA_INIT5;
if (mii_rw(dev, np->phyaddr, MII_NCONFIG, phy_reserved))
return PHY_ERROR;
}
phy_reserved = mii_rw(dev, np->phyaddr, MII_SREVISION, MII_READ);
phy_reserved |= PHY_CICADA_INIT6;
if (mii_rw(dev, np->phyaddr, MII_SREVISION, phy_reserved))
return PHY_ERROR;
return 0;
}
static int init_vitesse(struct net_device *dev, struct fe_priv *np)
{
u32 phy_reserved;
if (mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG1, PHY_VITESSE_INIT1))
return PHY_ERROR;
if (mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG2, PHY_VITESSE_INIT2))
return PHY_ERROR;
phy_reserved = mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG4, MII_READ);
if (mii_rw(dev, np->phyaddr, PHY_VITESSE_INIT_REG4, phy_reserved))
return PHY_ERROR;
phy_reserved = mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG3, MII_READ);
phy_reserved &= ~PHY_VITESSE_INIT_MSK1;
phy_reserved |= PHY_VITESSE_INIT3;
if (mii_rw(dev, np->phyaddr, PHY_VITESSE_INIT_REG3, phy_reserved))
return PHY_ERROR;
if (mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG2, PHY_VITESSE_INIT4))
return PHY_ERROR;
if (mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG2, PHY_VITESSE_INIT5))
return PHY_ERROR;
phy_reserved = mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG4, MII_READ);
phy_reserved &= ~PHY_VITESSE_INIT_MSK1;
phy_reserved |= PHY_VITESSE_INIT3;
if (mii_rw(dev, np->phyaddr, PHY_VITESSE_INIT_REG4, phy_reserved))
return PHY_ERROR;
phy_reserved = mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG3, MII_READ);
if (mii_rw(dev, np->phyaddr, PHY_VITESSE_INIT_REG3, phy_reserved))
return PHY_ERROR;
if (mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG2, PHY_VITESSE_INIT6))
return PHY_ERROR;
if (mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG2, PHY_VITESSE_INIT7))
return PHY_ERROR;
phy_reserved = mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG4, MII_READ);
if (mii_rw(dev, np->phyaddr, PHY_VITESSE_INIT_REG4, phy_reserved))
return PHY_ERROR;
phy_reserved = mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG3, MII_READ);
phy_reserved &= ~PHY_VITESSE_INIT_MSK2;
phy_reserved |= PHY_VITESSE_INIT8;
if (mii_rw(dev, np->phyaddr, PHY_VITESSE_INIT_REG3, phy_reserved))
return PHY_ERROR;
if (mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG2, PHY_VITESSE_INIT9))
return PHY_ERROR;
if (mii_rw(dev, np->phyaddr,
PHY_VITESSE_INIT_REG1, PHY_VITESSE_INIT10))
return PHY_ERROR;
return 0;
}
static int phy_init(struct net_device *dev)
{
struct fe_priv *np = get_nvpriv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 phyinterface;
u32 mii_status, mii_control, mii_control_1000, reg;
/* phy errata for E3016 phy */
if (np->phy_model == PHY_MODEL_MARVELL_E3016) {
reg = mii_rw(dev, np->phyaddr, MII_NCONFIG, MII_READ);
reg &= ~PHY_MARVELL_E3016_INITMASK;
if (mii_rw(dev, np->phyaddr, MII_NCONFIG, reg)) {
netdev_info(dev, "%s: phy write to errata reg failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
}
if (np->phy_oui == PHY_OUI_REALTEK) {
if (np->phy_model == PHY_MODEL_REALTEK_8211 &&
np->phy_rev == PHY_REV_REALTEK_8211B) {
if (init_realtek_8211b(dev, np)) {
netdev_info(dev, "%s: phy init failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
} else if (np->phy_model == PHY_MODEL_REALTEK_8211 &&
np->phy_rev == PHY_REV_REALTEK_8211C) {
if (init_realtek_8211c(dev, np)) {
netdev_info(dev, "%s: phy init failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
} else if (np->phy_model == PHY_MODEL_REALTEK_8201) {
if (init_realtek_8201(dev, np)) {
netdev_info(dev, "%s: phy init failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
}
}
/* set advertise register */
reg = mii_rw(dev, np->phyaddr, MII_ADVERTISE, MII_READ);
reg |= (ADVERTISE_10HALF | ADVERTISE_10FULL |
ADVERTISE_100HALF | ADVERTISE_100FULL |
ADVERTISE_PAUSE_ASYM | ADVERTISE_PAUSE_CAP);
if (mii_rw(dev, np->phyaddr, MII_ADVERTISE, reg)) {
netdev_info(dev, "%s: phy write to advertise failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
/* get phy interface type */
phyinterface = readl(base + NvRegPhyInterface);
/* see if gigabit phy */
mii_status = mii_rw(dev, np->phyaddr, MII_BMSR, MII_READ);
if (mii_status & PHY_GIGABIT) {
np->gigabit = PHY_GIGABIT;
mii_control_1000 = mii_rw(dev, np->phyaddr,
MII_CTRL1000, MII_READ);
mii_control_1000 &= ~ADVERTISE_1000HALF;
if (phyinterface & PHY_RGMII)
mii_control_1000 |= ADVERTISE_1000FULL;
else
mii_control_1000 &= ~ADVERTISE_1000FULL;
if (mii_rw(dev, np->phyaddr, MII_CTRL1000, mii_control_1000)) {
netdev_info(dev, "%s: phy init failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
} else
np->gigabit = 0;
mii_control = mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ);
mii_control |= BMCR_ANENABLE;
if (np->phy_oui == PHY_OUI_REALTEK &&
np->phy_model == PHY_MODEL_REALTEK_8211 &&
np->phy_rev == PHY_REV_REALTEK_8211C) {
/* start autoneg since we already performed hw reset above */
mii_control |= BMCR_ANRESTART;
if (mii_rw(dev, np->phyaddr, MII_BMCR, mii_control)) {
netdev_info(dev, "%s: phy init failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
} else {
/* reset the phy
* (certain phys need bmcr to be setup with reset)
*/
if (phy_reset(dev, mii_control)) {
netdev_info(dev, "%s: phy reset failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
}
/* phy vendor specific configuration */
if ((np->phy_oui == PHY_OUI_CICADA)) {
if (init_cicada(dev, np, phyinterface)) {
netdev_info(dev, "%s: phy init failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
} else if (np->phy_oui == PHY_OUI_VITESSE) {
if (init_vitesse(dev, np)) {
netdev_info(dev, "%s: phy init failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
} else if (np->phy_oui == PHY_OUI_REALTEK) {
if (np->phy_model == PHY_MODEL_REALTEK_8211 &&
np->phy_rev == PHY_REV_REALTEK_8211B) {
/* reset could have cleared these out, set them back */
if (init_realtek_8211b(dev, np)) {
netdev_info(dev, "%s: phy init failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
} else if (np->phy_model == PHY_MODEL_REALTEK_8201) {
if (init_realtek_8201(dev, np) ||
init_realtek_8201_cross(dev, np)) {
netdev_info(dev, "%s: phy init failed\n",
pci_name(np->pci_dev));
return PHY_ERROR;
}
}
}
/* some phys clear out pause advertisement on reset, set it back */
mii_rw(dev, np->phyaddr, MII_ADVERTISE, reg);
/* restart auto negotiation, power down phy */
mii_control = mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ);
mii_control |= (BMCR_ANRESTART | BMCR_ANENABLE);
if (phy_power_down)
mii_control |= BMCR_PDOWN;
if (mii_rw(dev, np->phyaddr, MII_BMCR, mii_control))
return PHY_ERROR;
return 0;
}
static void nv_start_rx(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 rx_ctrl = readl(base + NvRegReceiverControl);
/* Already running? Stop it. */
if ((readl(base + NvRegReceiverControl) & NVREG_RCVCTL_START) && !np->mac_in_use) {
rx_ctrl &= ~NVREG_RCVCTL_START;
writel(rx_ctrl, base + NvRegReceiverControl);
pci_push(base);
}
writel(np->linkspeed, base + NvRegLinkSpeed);
pci_push(base);
rx_ctrl |= NVREG_RCVCTL_START;
if (np->mac_in_use)
rx_ctrl &= ~NVREG_RCVCTL_RX_PATH_EN;
writel(rx_ctrl, base + NvRegReceiverControl);
pci_push(base);
}
static void nv_stop_rx(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 rx_ctrl = readl(base + NvRegReceiverControl);
if (!np->mac_in_use)
rx_ctrl &= ~NVREG_RCVCTL_START;
else
rx_ctrl |= NVREG_RCVCTL_RX_PATH_EN;
writel(rx_ctrl, base + NvRegReceiverControl);
if (reg_delay(dev, NvRegReceiverStatus, NVREG_RCVSTAT_BUSY, 0,
NV_RXSTOP_DELAY1, NV_RXSTOP_DELAY1MAX))
netdev_info(dev, "%s: ReceiverStatus remained busy\n",
__func__);
udelay(NV_RXSTOP_DELAY2);
if (!np->mac_in_use)
writel(0, base + NvRegLinkSpeed);
}
static void nv_start_tx(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 tx_ctrl = readl(base + NvRegTransmitterControl);
tx_ctrl |= NVREG_XMITCTL_START;
if (np->mac_in_use)
tx_ctrl &= ~NVREG_XMITCTL_TX_PATH_EN;
writel(tx_ctrl, base + NvRegTransmitterControl);
pci_push(base);
}
static void nv_stop_tx(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 tx_ctrl = readl(base + NvRegTransmitterControl);
if (!np->mac_in_use)
tx_ctrl &= ~NVREG_XMITCTL_START;
else
tx_ctrl |= NVREG_XMITCTL_TX_PATH_EN;
writel(tx_ctrl, base + NvRegTransmitterControl);
if (reg_delay(dev, NvRegTransmitterStatus, NVREG_XMITSTAT_BUSY, 0,
NV_TXSTOP_DELAY1, NV_TXSTOP_DELAY1MAX))
netdev_info(dev, "%s: TransmitterStatus remained busy\n",
__func__);
udelay(NV_TXSTOP_DELAY2);
if (!np->mac_in_use)
writel(readl(base + NvRegTransmitPoll) & NVREG_TRANSMITPOLL_MAC_ADDR_REV,
base + NvRegTransmitPoll);
}
static void nv_start_rxtx(struct net_device *dev)
{
nv_start_rx(dev);
nv_start_tx(dev);
}
static void nv_stop_rxtx(struct net_device *dev)
{
nv_stop_rx(dev);
nv_stop_tx(dev);
}
static void nv_txrx_reset(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
writel(NVREG_TXRXCTL_BIT2 | NVREG_TXRXCTL_RESET | np->txrxctl_bits, base + NvRegTxRxControl);
pci_push(base);
udelay(NV_TXRX_RESET_DELAY);
writel(NVREG_TXRXCTL_BIT2 | np->txrxctl_bits, base + NvRegTxRxControl);
pci_push(base);
}
static void nv_mac_reset(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 temp1, temp2, temp3;
writel(NVREG_TXRXCTL_BIT2 | NVREG_TXRXCTL_RESET | np->txrxctl_bits, base + NvRegTxRxControl);
pci_push(base);
/* save registers since they will be cleared on reset */
temp1 = readl(base + NvRegMacAddrA);
temp2 = readl(base + NvRegMacAddrB);
temp3 = readl(base + NvRegTransmitPoll);
writel(NVREG_MAC_RESET_ASSERT, base + NvRegMacReset);
pci_push(base);
udelay(NV_MAC_RESET_DELAY);
writel(0, base + NvRegMacReset);
pci_push(base);
udelay(NV_MAC_RESET_DELAY);
/* restore saved registers */
writel(temp1, base + NvRegMacAddrA);
writel(temp2, base + NvRegMacAddrB);
writel(temp3, base + NvRegTransmitPoll);
writel(NVREG_TXRXCTL_BIT2 | np->txrxctl_bits, base + NvRegTxRxControl);
pci_push(base);
}
static void nv_get_hw_stats(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
np->estats.tx_bytes += readl(base + NvRegTxCnt);
np->estats.tx_zero_rexmt += readl(base + NvRegTxZeroReXmt);
np->estats.tx_one_rexmt += readl(base + NvRegTxOneReXmt);
np->estats.tx_many_rexmt += readl(base + NvRegTxManyReXmt);
np->estats.tx_late_collision += readl(base + NvRegTxLateCol);
np->estats.tx_fifo_errors += readl(base + NvRegTxUnderflow);
np->estats.tx_carrier_errors += readl(base + NvRegTxLossCarrier);
np->estats.tx_excess_deferral += readl(base + NvRegTxExcessDef);
np->estats.tx_retry_error += readl(base + NvRegTxRetryErr);
np->estats.rx_frame_error += readl(base + NvRegRxFrameErr);
np->estats.rx_extra_byte += readl(base + NvRegRxExtraByte);
np->estats.rx_late_collision += readl(base + NvRegRxLateCol);
np->estats.rx_runt += readl(base + NvRegRxRunt);
np->estats.rx_frame_too_long += readl(base + NvRegRxFrameTooLong);
np->estats.rx_over_errors += readl(base + NvRegRxOverflow);
np->estats.rx_crc_errors += readl(base + NvRegRxFCSErr);
np->estats.rx_frame_align_error += readl(base + NvRegRxFrameAlignErr);
np->estats.rx_length_error += readl(base + NvRegRxLenErr);
np->estats.rx_unicast += readl(base + NvRegRxUnicast);
np->estats.rx_multicast += readl(base + NvRegRxMulticast);
np->estats.rx_broadcast += readl(base + NvRegRxBroadcast);
np->estats.rx_packets =
np->estats.rx_unicast +
np->estats.rx_multicast +
np->estats.rx_broadcast;
np->estats.rx_errors_total =
np->estats.rx_crc_errors +
np->estats.rx_over_errors +
np->estats.rx_frame_error +
(np->estats.rx_frame_align_error - np->estats.rx_extra_byte) +
np->estats.rx_late_collision +
np->estats.rx_runt +
np->estats.rx_frame_too_long;
np->estats.tx_errors_total =
np->estats.tx_late_collision +
np->estats.tx_fifo_errors +
np->estats.tx_carrier_errors +
np->estats.tx_excess_deferral +
np->estats.tx_retry_error;
if (np->driver_data & DEV_HAS_STATISTICS_V2) {
np->estats.tx_deferral += readl(base + NvRegTxDef);
np->estats.tx_packets += readl(base + NvRegTxFrame);
np->estats.rx_bytes += readl(base + NvRegRxCnt);
np->estats.tx_pause += readl(base + NvRegTxPause);
np->estats.rx_pause += readl(base + NvRegRxPause);
np->estats.rx_drop_frame += readl(base + NvRegRxDropFrame);
}
if (np->driver_data & DEV_HAS_STATISTICS_V3) {
np->estats.tx_unicast += readl(base + NvRegTxUnicast);
np->estats.tx_multicast += readl(base + NvRegTxMulticast);
np->estats.tx_broadcast += readl(base + NvRegTxBroadcast);
}
}
/*
* nv_get_stats: dev->get_stats function
* Get latest stats value from the nic.
* Called with read_lock(&dev_base_lock) held for read -
* only synchronized against unregister_netdevice.
*/
static struct net_device_stats *nv_get_stats(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
/* If the nic supports hw counters then retrieve latest values */
if (np->driver_data & (DEV_HAS_STATISTICS_V1|DEV_HAS_STATISTICS_V2|DEV_HAS_STATISTICS_V3)) {
nv_get_hw_stats(dev);
/* copy to net_device stats */
dev->stats.tx_bytes = np->estats.tx_bytes;
dev->stats.tx_fifo_errors = np->estats.tx_fifo_errors;
dev->stats.tx_carrier_errors = np->estats.tx_carrier_errors;
dev->stats.rx_crc_errors = np->estats.rx_crc_errors;
dev->stats.rx_over_errors = np->estats.rx_over_errors;
dev->stats.rx_errors = np->estats.rx_errors_total;
dev->stats.tx_errors = np->estats.tx_errors_total;
}
return &dev->stats;
}
/*
* nv_alloc_rx: fill rx ring entries.
* Return 1 if the allocations for the skbs failed and the
* rx engine is without Available descriptors
*/
static int nv_alloc_rx(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
struct ring_desc *less_rx;
less_rx = np->get_rx.orig;
if (less_rx-- == np->first_rx.orig)
less_rx = np->last_rx.orig;
while (np->put_rx.orig != less_rx) {
struct sk_buff *skb = dev_alloc_skb(np->rx_buf_sz + NV_RX_ALLOC_PAD);
if (skb) {
np->put_rx_ctx->skb = skb;
np->put_rx_ctx->dma = pci_map_single(np->pci_dev,
skb->data,
skb_tailroom(skb),
PCI_DMA_FROMDEVICE);
np->put_rx_ctx->dma_len = skb_tailroom(skb);
np->put_rx.orig->buf = cpu_to_le32(np->put_rx_ctx->dma);
wmb();
np->put_rx.orig->flaglen = cpu_to_le32(np->rx_buf_sz | NV_RX_AVAIL);
if (unlikely(np->put_rx.orig++ == np->last_rx.orig))
np->put_rx.orig = np->first_rx.orig;
if (unlikely(np->put_rx_ctx++ == np->last_rx_ctx))
np->put_rx_ctx = np->first_rx_ctx;
} else
return 1;
}
return 0;
}
static int nv_alloc_rx_optimized(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
struct ring_desc_ex *less_rx;
less_rx = np->get_rx.ex;
if (less_rx-- == np->first_rx.ex)
less_rx = np->last_rx.ex;
while (np->put_rx.ex != less_rx) {
struct sk_buff *skb = dev_alloc_skb(np->rx_buf_sz + NV_RX_ALLOC_PAD);
if (skb) {
np->put_rx_ctx->skb = skb;
np->put_rx_ctx->dma = pci_map_single(np->pci_dev,
skb->data,
skb_tailroom(skb),
PCI_DMA_FROMDEVICE);
np->put_rx_ctx->dma_len = skb_tailroom(skb);
np->put_rx.ex->bufhigh = cpu_to_le32(dma_high(np->put_rx_ctx->dma));
np->put_rx.ex->buflow = cpu_to_le32(dma_low(np->put_rx_ctx->dma));
wmb();
np->put_rx.ex->flaglen = cpu_to_le32(np->rx_buf_sz | NV_RX2_AVAIL);
if (unlikely(np->put_rx.ex++ == np->last_rx.ex))
np->put_rx.ex = np->first_rx.ex;
if (unlikely(np->put_rx_ctx++ == np->last_rx_ctx))
np->put_rx_ctx = np->first_rx_ctx;
} else
return 1;
}
return 0;
}
/* If rx bufs are exhausted called after 50ms to attempt to refresh */
static void nv_do_rx_refill(unsigned long data)
{
struct net_device *dev = (struct net_device *) data;
struct fe_priv *np = netdev_priv(dev);
/* Just reschedule NAPI rx processing */
napi_schedule(&np->napi);
}
static void nv_init_rx(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
int i;
np->get_rx = np->put_rx = np->first_rx = np->rx_ring;
if (!nv_optimized(np))
np->last_rx.orig = &np->rx_ring.orig[np->rx_ring_size-1];
else
np->last_rx.ex = &np->rx_ring.ex[np->rx_ring_size-1];
np->get_rx_ctx = np->put_rx_ctx = np->first_rx_ctx = np->rx_skb;
np->last_rx_ctx = &np->rx_skb[np->rx_ring_size-1];
for (i = 0; i < np->rx_ring_size; i++) {
if (!nv_optimized(np)) {
np->rx_ring.orig[i].flaglen = 0;
np->rx_ring.orig[i].buf = 0;
} else {
np->rx_ring.ex[i].flaglen = 0;
np->rx_ring.ex[i].txvlan = 0;
np->rx_ring.ex[i].bufhigh = 0;
np->rx_ring.ex[i].buflow = 0;
}
np->rx_skb[i].skb = NULL;
np->rx_skb[i].dma = 0;
}
}
static void nv_init_tx(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
int i;
np->get_tx = np->put_tx = np->first_tx = np->tx_ring;
if (!nv_optimized(np))
np->last_tx.orig = &np->tx_ring.orig[np->tx_ring_size-1];
else
np->last_tx.ex = &np->tx_ring.ex[np->tx_ring_size-1];
np->get_tx_ctx = np->put_tx_ctx = np->first_tx_ctx = np->tx_skb;
np->last_tx_ctx = &np->tx_skb[np->tx_ring_size-1];
np->tx_pkts_in_progress = 0;
np->tx_change_owner = NULL;
np->tx_end_flip = NULL;
np->tx_stop = 0;
for (i = 0; i < np->tx_ring_size; i++) {
if (!nv_optimized(np)) {
np->tx_ring.orig[i].flaglen = 0;
np->tx_ring.orig[i].buf = 0;
} else {
np->tx_ring.ex[i].flaglen = 0;
np->tx_ring.ex[i].txvlan = 0;
np->tx_ring.ex[i].bufhigh = 0;
np->tx_ring.ex[i].buflow = 0;
}
np->tx_skb[i].skb = NULL;
np->tx_skb[i].dma = 0;
np->tx_skb[i].dma_len = 0;
np->tx_skb[i].dma_single = 0;
np->tx_skb[i].first_tx_desc = NULL;
np->tx_skb[i].next_tx_ctx = NULL;
}
}
static int nv_init_ring(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
nv_init_tx(dev);
nv_init_rx(dev);
if (!nv_optimized(np))
return nv_alloc_rx(dev);
else
return nv_alloc_rx_optimized(dev);
}
static void nv_unmap_txskb(struct fe_priv *np, struct nv_skb_map *tx_skb)
{
if (tx_skb->dma) {
if (tx_skb->dma_single)
pci_unmap_single(np->pci_dev, tx_skb->dma,
tx_skb->dma_len,
PCI_DMA_TODEVICE);
else
pci_unmap_page(np->pci_dev, tx_skb->dma,
tx_skb->dma_len,
PCI_DMA_TODEVICE);
tx_skb->dma = 0;
}
}
static int nv_release_txskb(struct fe_priv *np, struct nv_skb_map *tx_skb)
{
nv_unmap_txskb(np, tx_skb);
if (tx_skb->skb) {
dev_kfree_skb_any(tx_skb->skb);
tx_skb->skb = NULL;
return 1;
}
return 0;
}
static void nv_drain_tx(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
unsigned int i;
for (i = 0; i < np->tx_ring_size; i++) {
if (!nv_optimized(np)) {
np->tx_ring.orig[i].flaglen = 0;
np->tx_ring.orig[i].buf = 0;
} else {
np->tx_ring.ex[i].flaglen = 0;
np->tx_ring.ex[i].txvlan = 0;
np->tx_ring.ex[i].bufhigh = 0;
np->tx_ring.ex[i].buflow = 0;
}
if (nv_release_txskb(np, &np->tx_skb[i]))
dev->stats.tx_dropped++;
np->tx_skb[i].dma = 0;
np->tx_skb[i].dma_len = 0;
np->tx_skb[i].dma_single = 0;
np->tx_skb[i].first_tx_desc = NULL;
np->tx_skb[i].next_tx_ctx = NULL;
}
np->tx_pkts_in_progress = 0;
np->tx_change_owner = NULL;
np->tx_end_flip = NULL;
}
static void nv_drain_rx(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
int i;
for (i = 0; i < np->rx_ring_size; i++) {
if (!nv_optimized(np)) {
np->rx_ring.orig[i].flaglen = 0;
np->rx_ring.orig[i].buf = 0;
} else {
np->rx_ring.ex[i].flaglen = 0;
np->rx_ring.ex[i].txvlan = 0;
np->rx_ring.ex[i].bufhigh = 0;
np->rx_ring.ex[i].buflow = 0;
}
wmb();
if (np->rx_skb[i].skb) {
pci_unmap_single(np->pci_dev, np->rx_skb[i].dma,
(skb_end_pointer(np->rx_skb[i].skb) -
np->rx_skb[i].skb->data),
PCI_DMA_FROMDEVICE);
dev_kfree_skb(np->rx_skb[i].skb);
np->rx_skb[i].skb = NULL;
}
}
}
static void nv_drain_rxtx(struct net_device *dev)
{
nv_drain_tx(dev);
nv_drain_rx(dev);
}
static inline u32 nv_get_empty_tx_slots(struct fe_priv *np)
{
return (u32)(np->tx_ring_size - ((np->tx_ring_size + (np->put_tx_ctx - np->get_tx_ctx)) % np->tx_ring_size));
}
static void nv_legacybackoff_reseed(struct net_device *dev)
{
u8 __iomem *base = get_hwbase(dev);
u32 reg;
u32 low;
int tx_status = 0;
reg = readl(base + NvRegSlotTime) & ~NVREG_SLOTTIME_MASK;
get_random_bytes(&low, sizeof(low));
reg |= low & NVREG_SLOTTIME_MASK;
/* Need to stop tx before change takes effect.
* Caller has already gained np->lock.
*/
tx_status = readl(base + NvRegTransmitterControl) & NVREG_XMITCTL_START;
if (tx_status)
nv_stop_tx(dev);
nv_stop_rx(dev);
writel(reg, base + NvRegSlotTime);
if (tx_status)
nv_start_tx(dev);
nv_start_rx(dev);
}
/* Gear Backoff Seeds */
#define BACKOFF_SEEDSET_ROWS 8
#define BACKOFF_SEEDSET_LFSRS 15
/* Known Good seed sets */
static const u32 main_seedset[BACKOFF_SEEDSET_ROWS][BACKOFF_SEEDSET_LFSRS] = {
{145, 155, 165, 175, 185, 196, 235, 245, 255, 265, 275, 285, 660, 690, 874},
{245, 255, 265, 575, 385, 298, 335, 345, 355, 366, 375, 385, 761, 790, 974},
{145, 155, 165, 175, 185, 196, 235, 245, 255, 265, 275, 285, 660, 690, 874},
{245, 255, 265, 575, 385, 298, 335, 345, 355, 366, 375, 386, 761, 790, 974},
{266, 265, 276, 585, 397, 208, 345, 355, 365, 376, 385, 396, 771, 700, 984},
{266, 265, 276, 586, 397, 208, 346, 355, 365, 376, 285, 396, 771, 700, 984},
{366, 365, 376, 686, 497, 308, 447, 455, 466, 476, 485, 496, 871, 800, 84},
{466, 465, 476, 786, 597, 408, 547, 555, 566, 576, 585, 597, 971, 900, 184} };
static const u32 gear_seedset[BACKOFF_SEEDSET_ROWS][BACKOFF_SEEDSET_LFSRS] = {
{251, 262, 273, 324, 319, 508, 375, 364, 341, 371, 398, 193, 375, 30, 295},
{351, 375, 373, 469, 551, 639, 477, 464, 441, 472, 498, 293, 476, 130, 395},
{351, 375, 373, 469, 551, 639, 477, 464, 441, 472, 498, 293, 476, 130, 397},
{251, 262, 273, 324, 319, 508, 375, 364, 341, 371, 398, 193, 375, 30, 295},
{251, 262, 273, 324, 319, 508, 375, 364, 341, 371, 398, 193, 375, 30, 295},
{351, 375, 373, 469, 551, 639, 477, 464, 441, 472, 498, 293, 476, 130, 395},
{351, 375, 373, 469, 551, 639, 477, 464, 441, 472, 498, 293, 476, 130, 395},
{351, 375, 373, 469, 551, 639, 477, 464, 441, 472, 498, 293, 476, 130, 395} };
static void nv_gear_backoff_reseed(struct net_device *dev)
{
u8 __iomem *base = get_hwbase(dev);
u32 miniseed1, miniseed2, miniseed2_reversed, miniseed3, miniseed3_reversed;
u32 temp, seedset, combinedSeed;
int i;
/* Setup seed for free running LFSR */
/* We are going to read the time stamp counter 3 times
and swizzle bits around to increase randomness */
get_random_bytes(&miniseed1, sizeof(miniseed1));
miniseed1 &= 0x0fff;
if (miniseed1 == 0)
miniseed1 = 0xabc;
get_random_bytes(&miniseed2, sizeof(miniseed2));
miniseed2 &= 0x0fff;
if (miniseed2 == 0)
miniseed2 = 0xabc;
miniseed2_reversed =
((miniseed2 & 0xF00) >> 8) |
(miniseed2 & 0x0F0) |
((miniseed2 & 0x00F) << 8);
get_random_bytes(&miniseed3, sizeof(miniseed3));
miniseed3 &= 0x0fff;
if (miniseed3 == 0)
miniseed3 = 0xabc;
miniseed3_reversed =
((miniseed3 & 0xF00) >> 8) |
(miniseed3 & 0x0F0) |
((miniseed3 & 0x00F) << 8);
combinedSeed = ((miniseed1 ^ miniseed2_reversed) << 12) |
(miniseed2 ^ miniseed3_reversed);
/* Seeds can not be zero */
if ((combinedSeed & NVREG_BKOFFCTRL_SEED_MASK) == 0)
combinedSeed |= 0x08;
if ((combinedSeed & (NVREG_BKOFFCTRL_SEED_MASK << NVREG_BKOFFCTRL_GEAR)) == 0)
combinedSeed |= 0x8000;
/* No need to disable tx here */
temp = NVREG_BKOFFCTRL_DEFAULT | (0 << NVREG_BKOFFCTRL_SELECT);
temp |= combinedSeed & NVREG_BKOFFCTRL_SEED_MASK;
temp |= combinedSeed >> NVREG_BKOFFCTRL_GEAR;
writel(temp, base + NvRegBackOffControl);
/* Setup seeds for all gear LFSRs. */
get_random_bytes(&seedset, sizeof(seedset));
seedset = seedset % BACKOFF_SEEDSET_ROWS;
for (i = 1; i <= BACKOFF_SEEDSET_LFSRS; i++) {
temp = NVREG_BKOFFCTRL_DEFAULT | (i << NVREG_BKOFFCTRL_SELECT);
temp |= main_seedset[seedset][i-1] & 0x3ff;
temp |= ((gear_seedset[seedset][i-1] & 0x3ff) << NVREG_BKOFFCTRL_GEAR);
writel(temp, base + NvRegBackOffControl);
}
}
/*
* nv_start_xmit: dev->hard_start_xmit function
* Called with netif_tx_lock held.
*/
static netdev_tx_t nv_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u32 tx_flags = 0;
u32 tx_flags_extra = (np->desc_ver == DESC_VER_1 ? NV_TX_LASTPACKET : NV_TX2_LASTPACKET);
unsigned int fragments = skb_shinfo(skb)->nr_frags;
unsigned int i;
u32 offset = 0;
u32 bcnt;
u32 size = skb_headlen(skb);
u32 entries = (size >> NV_TX2_TSO_MAX_SHIFT) + ((size & (NV_TX2_TSO_MAX_SIZE-1)) ? 1 : 0);
u32 empty_slots;
struct ring_desc *put_tx;
struct ring_desc *start_tx;
struct ring_desc *prev_tx;
struct nv_skb_map *prev_tx_ctx;
unsigned long flags;
/* add fragments to entries count */
for (i = 0; i < fragments; i++) {
entries += (skb_shinfo(skb)->frags[i].size >> NV_TX2_TSO_MAX_SHIFT) +
((skb_shinfo(skb)->frags[i].size & (NV_TX2_TSO_MAX_SIZE-1)) ? 1 : 0);
}
spin_lock_irqsave(&np->lock, flags);
empty_slots = nv_get_empty_tx_slots(np);
if (unlikely(empty_slots <= entries)) {
netif_stop_queue(dev);
np->tx_stop = 1;
spin_unlock_irqrestore(&np->lock, flags);
return NETDEV_TX_BUSY;
}
spin_unlock_irqrestore(&np->lock, flags);
start_tx = put_tx = np->put_tx.orig;
/* setup the header buffer */
do {
prev_tx = put_tx;
prev_tx_ctx = np->put_tx_ctx;
bcnt = (size > NV_TX2_TSO_MAX_SIZE) ? NV_TX2_TSO_MAX_SIZE : size;
np->put_tx_ctx->dma = pci_map_single(np->pci_dev, skb->data + offset, bcnt,
PCI_DMA_TODEVICE);
np->put_tx_ctx->dma_len = bcnt;
np->put_tx_ctx->dma_single = 1;
put_tx->buf = cpu_to_le32(np->put_tx_ctx->dma);
put_tx->flaglen = cpu_to_le32((bcnt-1) | tx_flags);
tx_flags = np->tx_flags;
offset += bcnt;
size -= bcnt;
if (unlikely(put_tx++ == np->last_tx.orig))
put_tx = np->first_tx.orig;
if (unlikely(np->put_tx_ctx++ == np->last_tx_ctx))
np->put_tx_ctx = np->first_tx_ctx;
} while (size);
/* setup the fragments */
for (i = 0; i < fragments; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
u32 size = frag->size;
offset = 0;
do {
prev_tx = put_tx;
prev_tx_ctx = np->put_tx_ctx;
bcnt = (size > NV_TX2_TSO_MAX_SIZE) ? NV_TX2_TSO_MAX_SIZE : size;
np->put_tx_ctx->dma = pci_map_page(np->pci_dev, frag->page, frag->page_offset+offset, bcnt,
PCI_DMA_TODEVICE);
np->put_tx_ctx->dma_len = bcnt;
np->put_tx_ctx->dma_single = 0;
put_tx->buf = cpu_to_le32(np->put_tx_ctx->dma);
put_tx->flaglen = cpu_to_le32((bcnt-1) | tx_flags);
offset += bcnt;
size -= bcnt;
if (unlikely(put_tx++ == np->last_tx.orig))
put_tx = np->first_tx.orig;
if (unlikely(np->put_tx_ctx++ == np->last_tx_ctx))
np->put_tx_ctx = np->first_tx_ctx;
} while (size);
}
/* set last fragment flag */
prev_tx->flaglen |= cpu_to_le32(tx_flags_extra);
/* save skb in this slot's context area */
prev_tx_ctx->skb = skb;
if (skb_is_gso(skb))
tx_flags_extra = NV_TX2_TSO | (skb_shinfo(skb)->gso_size << NV_TX2_TSO_SHIFT);
else
tx_flags_extra = skb->ip_summed == CHECKSUM_PARTIAL ?
NV_TX2_CHECKSUM_L3 | NV_TX2_CHECKSUM_L4 : 0;
spin_lock_irqsave(&np->lock, flags);
/* set tx flags */
start_tx->flaglen |= cpu_to_le32(tx_flags | tx_flags_extra);
np->put_tx.orig = put_tx;
spin_unlock_irqrestore(&np->lock, flags);
writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl);
return NETDEV_TX_OK;
}
static netdev_tx_t nv_start_xmit_optimized(struct sk_buff *skb,
struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u32 tx_flags = 0;
u32 tx_flags_extra;
unsigned int fragments = skb_shinfo(skb)->nr_frags;
unsigned int i;
u32 offset = 0;
u32 bcnt;
u32 size = skb_headlen(skb);
u32 entries = (size >> NV_TX2_TSO_MAX_SHIFT) + ((size & (NV_TX2_TSO_MAX_SIZE-1)) ? 1 : 0);
u32 empty_slots;
struct ring_desc_ex *put_tx;
struct ring_desc_ex *start_tx;
struct ring_desc_ex *prev_tx;
struct nv_skb_map *prev_tx_ctx;
struct nv_skb_map *start_tx_ctx;
unsigned long flags;
/* add fragments to entries count */
for (i = 0; i < fragments; i++) {
entries += (skb_shinfo(skb)->frags[i].size >> NV_TX2_TSO_MAX_SHIFT) +
((skb_shinfo(skb)->frags[i].size & (NV_TX2_TSO_MAX_SIZE-1)) ? 1 : 0);
}
spin_lock_irqsave(&np->lock, flags);
empty_slots = nv_get_empty_tx_slots(np);
if (unlikely(empty_slots <= entries)) {
netif_stop_queue(dev);
np->tx_stop = 1;
spin_unlock_irqrestore(&np->lock, flags);
return NETDEV_TX_BUSY;
}
spin_unlock_irqrestore(&np->lock, flags);
start_tx = put_tx = np->put_tx.ex;
start_tx_ctx = np->put_tx_ctx;
/* setup the header buffer */
do {
prev_tx = put_tx;
prev_tx_ctx = np->put_tx_ctx;
bcnt = (size > NV_TX2_TSO_MAX_SIZE) ? NV_TX2_TSO_MAX_SIZE : size;
np->put_tx_ctx->dma = pci_map_single(np->pci_dev, skb->data + offset, bcnt,
PCI_DMA_TODEVICE);
np->put_tx_ctx->dma_len = bcnt;
np->put_tx_ctx->dma_single = 1;
put_tx->bufhigh = cpu_to_le32(dma_high(np->put_tx_ctx->dma));
put_tx->buflow = cpu_to_le32(dma_low(np->put_tx_ctx->dma));
put_tx->flaglen = cpu_to_le32((bcnt-1) | tx_flags);
tx_flags = NV_TX2_VALID;
offset += bcnt;
size -= bcnt;
if (unlikely(put_tx++ == np->last_tx.ex))
put_tx = np->first_tx.ex;
if (unlikely(np->put_tx_ctx++ == np->last_tx_ctx))
np->put_tx_ctx = np->first_tx_ctx;
} while (size);
/* setup the fragments */
for (i = 0; i < fragments; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
u32 size = frag->size;
offset = 0;
do {
prev_tx = put_tx;
prev_tx_ctx = np->put_tx_ctx;
bcnt = (size > NV_TX2_TSO_MAX_SIZE) ? NV_TX2_TSO_MAX_SIZE : size;
np->put_tx_ctx->dma = pci_map_page(np->pci_dev, frag->page, frag->page_offset+offset, bcnt,
PCI_DMA_TODEVICE);
np->put_tx_ctx->dma_len = bcnt;
np->put_tx_ctx->dma_single = 0;
put_tx->bufhigh = cpu_to_le32(dma_high(np->put_tx_ctx->dma));
put_tx->buflow = cpu_to_le32(dma_low(np->put_tx_ctx->dma));
put_tx->flaglen = cpu_to_le32((bcnt-1) | tx_flags);
offset += bcnt;
size -= bcnt;
if (unlikely(put_tx++ == np->last_tx.ex))
put_tx = np->first_tx.ex;
if (unlikely(np->put_tx_ctx++ == np->last_tx_ctx))
np->put_tx_ctx = np->first_tx_ctx;
} while (size);
}
/* set last fragment flag */
prev_tx->flaglen |= cpu_to_le32(NV_TX2_LASTPACKET);
/* save skb in this slot's context area */
prev_tx_ctx->skb = skb;
if (skb_is_gso(skb))
tx_flags_extra = NV_TX2_TSO | (skb_shinfo(skb)->gso_size << NV_TX2_TSO_SHIFT);
else
tx_flags_extra = skb->ip_summed == CHECKSUM_PARTIAL ?
NV_TX2_CHECKSUM_L3 | NV_TX2_CHECKSUM_L4 : 0;
/* vlan tag */
if (vlan_tx_tag_present(skb))
start_tx->txvlan = cpu_to_le32(NV_TX3_VLAN_TAG_PRESENT |
vlan_tx_tag_get(skb));
else
start_tx->txvlan = 0;
spin_lock_irqsave(&np->lock, flags);
if (np->tx_limit) {
/* Limit the number of outstanding tx. Setup all fragments, but
* do not set the VALID bit on the first descriptor. Save a pointer
* to that descriptor and also for next skb_map element.
*/
if (np->tx_pkts_in_progress == NV_TX_LIMIT_COUNT) {
if (!np->tx_change_owner)
np->tx_change_owner = start_tx_ctx;
/* remove VALID bit */
tx_flags &= ~NV_TX2_VALID;
start_tx_ctx->first_tx_desc = start_tx;
start_tx_ctx->next_tx_ctx = np->put_tx_ctx;
np->tx_end_flip = np->put_tx_ctx;
} else {
np->tx_pkts_in_progress++;
}
}
/* set tx flags */
start_tx->flaglen |= cpu_to_le32(tx_flags | tx_flags_extra);
np->put_tx.ex = put_tx;
spin_unlock_irqrestore(&np->lock, flags);
writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl);
return NETDEV_TX_OK;
}
static inline void nv_tx_flip_ownership(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
np->tx_pkts_in_progress--;
if (np->tx_change_owner) {
np->tx_change_owner->first_tx_desc->flaglen |=
cpu_to_le32(NV_TX2_VALID);
np->tx_pkts_in_progress++;
np->tx_change_owner = np->tx_change_owner->next_tx_ctx;
if (np->tx_change_owner == np->tx_end_flip)
np->tx_change_owner = NULL;
writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl);
}
}
/*
* nv_tx_done: check for completed packets, release the skbs.
*
* Caller must own np->lock.
*/
static int nv_tx_done(struct net_device *dev, int limit)
{
struct fe_priv *np = netdev_priv(dev);
u32 flags;
int tx_work = 0;
struct ring_desc *orig_get_tx = np->get_tx.orig;
while ((np->get_tx.orig != np->put_tx.orig) &&
!((flags = le32_to_cpu(np->get_tx.orig->flaglen)) & NV_TX_VALID) &&
(tx_work < limit)) {
nv_unmap_txskb(np, np->get_tx_ctx);
if (np->desc_ver == DESC_VER_1) {
if (flags & NV_TX_LASTPACKET) {
if (flags & NV_TX_ERROR) {
if (flags & NV_TX_UNDERFLOW)
dev->stats.tx_fifo_errors++;
if (flags & NV_TX_CARRIERLOST)
dev->stats.tx_carrier_errors++;
if ((flags & NV_TX_RETRYERROR) && !(flags & NV_TX_RETRYCOUNT_MASK))
nv_legacybackoff_reseed(dev);
dev->stats.tx_errors++;
} else {
dev->stats.tx_packets++;
dev->stats.tx_bytes += np->get_tx_ctx->skb->len;
}
dev_kfree_skb_any(np->get_tx_ctx->skb);
np->get_tx_ctx->skb = NULL;
tx_work++;
}
} else {
if (flags & NV_TX2_LASTPACKET) {
if (flags & NV_TX2_ERROR) {
if (flags & NV_TX2_UNDERFLOW)
dev->stats.tx_fifo_errors++;
if (flags & NV_TX2_CARRIERLOST)
dev->stats.tx_carrier_errors++;
if ((flags & NV_TX2_RETRYERROR) && !(flags & NV_TX2_RETRYCOUNT_MASK))
nv_legacybackoff_reseed(dev);
dev->stats.tx_errors++;
} else {
dev->stats.tx_packets++;
dev->stats.tx_bytes += np->get_tx_ctx->skb->len;
}
dev_kfree_skb_any(np->get_tx_ctx->skb);
np->get_tx_ctx->skb = NULL;
tx_work++;
}
}
if (unlikely(np->get_tx.orig++ == np->last_tx.orig))
np->get_tx.orig = np->first_tx.orig;
if (unlikely(np->get_tx_ctx++ == np->last_tx_ctx))
np->get_tx_ctx = np->first_tx_ctx;
}
if (unlikely((np->tx_stop == 1) && (np->get_tx.orig != orig_get_tx))) {
np->tx_stop = 0;
netif_wake_queue(dev);
}
return tx_work;
}
static int nv_tx_done_optimized(struct net_device *dev, int limit)
{
struct fe_priv *np = netdev_priv(dev);
u32 flags;
int tx_work = 0;
struct ring_desc_ex *orig_get_tx = np->get_tx.ex;
while ((np->get_tx.ex != np->put_tx.ex) &&
!((flags = le32_to_cpu(np->get_tx.ex->flaglen)) & NV_TX2_VALID) &&
(tx_work < limit)) {
nv_unmap_txskb(np, np->get_tx_ctx);
if (flags & NV_TX2_LASTPACKET) {
if (!(flags & NV_TX2_ERROR))
dev->stats.tx_packets++;
else {
if ((flags & NV_TX2_RETRYERROR) && !(flags & NV_TX2_RETRYCOUNT_MASK)) {
if (np->driver_data & DEV_HAS_GEAR_MODE)
nv_gear_backoff_reseed(dev);
else
nv_legacybackoff_reseed(dev);
}
}
dev_kfree_skb_any(np->get_tx_ctx->skb);
np->get_tx_ctx->skb = NULL;
tx_work++;
if (np->tx_limit)
nv_tx_flip_ownership(dev);
}
if (unlikely(np->get_tx.ex++ == np->last_tx.ex))
np->get_tx.ex = np->first_tx.ex;
if (unlikely(np->get_tx_ctx++ == np->last_tx_ctx))
np->get_tx_ctx = np->first_tx_ctx;
}
if (unlikely((np->tx_stop == 1) && (np->get_tx.ex != orig_get_tx))) {
np->tx_stop = 0;
netif_wake_queue(dev);
}
return tx_work;
}
/*
* nv_tx_timeout: dev->tx_timeout function
* Called with netif_tx_lock held.
*/
static void nv_tx_timeout(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 status;
union ring_type put_tx;
int saved_tx_limit;
int i;
if (np->msi_flags & NV_MSI_X_ENABLED)
status = readl(base + NvRegMSIXIrqStatus) & NVREG_IRQSTAT_MASK;
else
status = readl(base + NvRegIrqStatus) & NVREG_IRQSTAT_MASK;
netdev_info(dev, "Got tx_timeout. irq: %08x\n", status);
netdev_info(dev, "Ring at %lx\n", (unsigned long)np->ring_addr);
netdev_info(dev, "Dumping tx registers\n");
for (i = 0; i <= np->register_size; i += 32) {
netdev_info(dev,
"%3x: %08x %08x %08x %08x %08x %08x %08x %08x\n",
i,
readl(base + i + 0), readl(base + i + 4),
readl(base + i + 8), readl(base + i + 12),
readl(base + i + 16), readl(base + i + 20),
readl(base + i + 24), readl(base + i + 28));
}
netdev_info(dev, "Dumping tx ring\n");
for (i = 0; i < np->tx_ring_size; i += 4) {
if (!nv_optimized(np)) {
netdev_info(dev,
"%03x: %08x %08x // %08x %08x // %08x %08x // %08x %08x\n",
i,
le32_to_cpu(np->tx_ring.orig[i].buf),
le32_to_cpu(np->tx_ring.orig[i].flaglen),
le32_to_cpu(np->tx_ring.orig[i+1].buf),
le32_to_cpu(np->tx_ring.orig[i+1].flaglen),
le32_to_cpu(np->tx_ring.orig[i+2].buf),
le32_to_cpu(np->tx_ring.orig[i+2].flaglen),
le32_to_cpu(np->tx_ring.orig[i+3].buf),
le32_to_cpu(np->tx_ring.orig[i+3].flaglen));
} else {
netdev_info(dev,
"%03x: %08x %08x %08x // %08x %08x %08x // %08x %08x %08x // %08x %08x %08x\n",
i,
le32_to_cpu(np->tx_ring.ex[i].bufhigh),
le32_to_cpu(np->tx_ring.ex[i].buflow),
le32_to_cpu(np->tx_ring.ex[i].flaglen),
le32_to_cpu(np->tx_ring.ex[i+1].bufhigh),
le32_to_cpu(np->tx_ring.ex[i+1].buflow),
le32_to_cpu(np->tx_ring.ex[i+1].flaglen),
le32_to_cpu(np->tx_ring.ex[i+2].bufhigh),
le32_to_cpu(np->tx_ring.ex[i+2].buflow),
le32_to_cpu(np->tx_ring.ex[i+2].flaglen),
le32_to_cpu(np->tx_ring.ex[i+3].bufhigh),
le32_to_cpu(np->tx_ring.ex[i+3].buflow),
le32_to_cpu(np->tx_ring.ex[i+3].flaglen));
}
}
spin_lock_irq(&np->lock);
/* 1) stop tx engine */
nv_stop_tx(dev);
/* 2) complete any outstanding tx and do not give HW any limited tx pkts */
saved_tx_limit = np->tx_limit;
np->tx_limit = 0; /* prevent giving HW any limited pkts */
np->tx_stop = 0; /* prevent waking tx queue */
if (!nv_optimized(np))
nv_tx_done(dev, np->tx_ring_size);
else
nv_tx_done_optimized(dev, np->tx_ring_size);
/* save current HW position */
if (np->tx_change_owner)
put_tx.ex = np->tx_change_owner->first_tx_desc;
else
put_tx = np->put_tx;
/* 3) clear all tx state */
nv_drain_tx(dev);
nv_init_tx(dev);
/* 4) restore state to current HW position */
np->get_tx = np->put_tx = put_tx;
np->tx_limit = saved_tx_limit;
/* 5) restart tx engine */
nv_start_tx(dev);
netif_wake_queue(dev);
spin_unlock_irq(&np->lock);
}
/*
* Called when the nic notices a mismatch between the actual data len on the
* wire and the len indicated in the 802 header
*/
static int nv_getlen(struct net_device *dev, void *packet, int datalen)
{
int hdrlen; /* length of the 802 header */
int protolen; /* length as stored in the proto field */
/* 1) calculate len according to header */
if (((struct vlan_ethhdr *)packet)->h_vlan_proto == htons(ETH_P_8021Q)) {
protolen = ntohs(((struct vlan_ethhdr *)packet)->h_vlan_encapsulated_proto);
hdrlen = VLAN_HLEN;
} else {
protolen = ntohs(((struct ethhdr *)packet)->h_proto);
hdrlen = ETH_HLEN;
}
if (protolen > ETH_DATA_LEN)
return datalen; /* Value in proto field not a len, no checks possible */
protolen += hdrlen;
/* consistency checks: */
if (datalen > ETH_ZLEN) {
if (datalen >= protolen) {
/* more data on wire than in 802 header, trim of
* additional data.
*/
return protolen;
} else {
/* less data on wire than mentioned in header.
* Discard the packet.
*/
return -1;
}
} else {
/* short packet. Accept only if 802 values are also short */
if (protolen > ETH_ZLEN) {
return -1;
}
return datalen;
}
}
static int nv_rx_process(struct net_device *dev, int limit)
{
struct fe_priv *np = netdev_priv(dev);
u32 flags;
int rx_work = 0;
struct sk_buff *skb;
int len;
while ((np->get_rx.orig != np->put_rx.orig) &&
!((flags = le32_to_cpu(np->get_rx.orig->flaglen)) & NV_RX_AVAIL) &&
(rx_work < limit)) {
/*
* the packet is for us - immediately tear down the pci mapping.
* TODO: check if a prefetch of the first cacheline improves
* the performance.
*/
pci_unmap_single(np->pci_dev, np->get_rx_ctx->dma,
np->get_rx_ctx->dma_len,
PCI_DMA_FROMDEVICE);
skb = np->get_rx_ctx->skb;
np->get_rx_ctx->skb = NULL;
/* look at what we actually got: */
if (np->desc_ver == DESC_VER_1) {
if (likely(flags & NV_RX_DESCRIPTORVALID)) {
len = flags & LEN_MASK_V1;
if (unlikely(flags & NV_RX_ERROR)) {
if ((flags & NV_RX_ERROR_MASK) == NV_RX_ERROR4) {
len = nv_getlen(dev, skb->data, len);
if (len < 0) {
dev->stats.rx_errors++;
dev_kfree_skb(skb);
goto next_pkt;
}
}
/* framing errors are soft errors */
else if ((flags & NV_RX_ERROR_MASK) == NV_RX_FRAMINGERR) {
if (flags & NV_RX_SUBSTRACT1)
len--;
}
/* the rest are hard errors */
else {
if (flags & NV_RX_MISSEDFRAME)
dev->stats.rx_missed_errors++;
if (flags & NV_RX_CRCERR)
dev->stats.rx_crc_errors++;
if (flags & NV_RX_OVERFLOW)
dev->stats.rx_over_errors++;
dev->stats.rx_errors++;
dev_kfree_skb(skb);
goto next_pkt;
}
}
} else {
dev_kfree_skb(skb);
goto next_pkt;
}
} else {
if (likely(flags & NV_RX2_DESCRIPTORVALID)) {
len = flags & LEN_MASK_V2;
if (unlikely(flags & NV_RX2_ERROR)) {
if ((flags & NV_RX2_ERROR_MASK) == NV_RX2_ERROR4) {
len = nv_getlen(dev, skb->data, len);
if (len < 0) {
dev->stats.rx_errors++;
dev_kfree_skb(skb);
goto next_pkt;
}
}
/* framing errors are soft errors */
else if ((flags & NV_RX2_ERROR_MASK) == NV_RX2_FRAMINGERR) {
if (flags & NV_RX2_SUBSTRACT1)
len--;
}
/* the rest are hard errors */
else {
if (flags & NV_RX2_CRCERR)
dev->stats.rx_crc_errors++;
if (flags & NV_RX2_OVERFLOW)
dev->stats.rx_over_errors++;
dev->stats.rx_errors++;
dev_kfree_skb(skb);
goto next_pkt;
}
}
if (((flags & NV_RX2_CHECKSUMMASK) == NV_RX2_CHECKSUM_IP_TCP) || /*ip and tcp */
((flags & NV_RX2_CHECKSUMMASK) == NV_RX2_CHECKSUM_IP_UDP)) /*ip and udp */
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else {
dev_kfree_skb(skb);
goto next_pkt;
}
}
/* got a valid packet - forward it to the network core */
skb_put(skb, len);
skb->protocol = eth_type_trans(skb, dev);
napi_gro_receive(&np->napi, skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += len;
next_pkt:
if (unlikely(np->get_rx.orig++ == np->last_rx.orig))
np->get_rx.orig = np->first_rx.orig;
if (unlikely(np->get_rx_ctx++ == np->last_rx_ctx))
np->get_rx_ctx = np->first_rx_ctx;
rx_work++;
}
return rx_work;
}
static int nv_rx_process_optimized(struct net_device *dev, int limit)
{
struct fe_priv *np = netdev_priv(dev);
u32 flags;
u32 vlanflags = 0;
int rx_work = 0;
struct sk_buff *skb;
int len;
while ((np->get_rx.ex != np->put_rx.ex) &&
!((flags = le32_to_cpu(np->get_rx.ex->flaglen)) & NV_RX2_AVAIL) &&
(rx_work < limit)) {
/*
* the packet is for us - immediately tear down the pci mapping.
* TODO: check if a prefetch of the first cacheline improves
* the performance.
*/
pci_unmap_single(np->pci_dev, np->get_rx_ctx->dma,
np->get_rx_ctx->dma_len,
PCI_DMA_FROMDEVICE);
skb = np->get_rx_ctx->skb;
np->get_rx_ctx->skb = NULL;
/* look at what we actually got: */
if (likely(flags & NV_RX2_DESCRIPTORVALID)) {
len = flags & LEN_MASK_V2;
if (unlikely(flags & NV_RX2_ERROR)) {
if ((flags & NV_RX2_ERROR_MASK) == NV_RX2_ERROR4) {
len = nv_getlen(dev, skb->data, len);
if (len < 0) {
dev_kfree_skb(skb);
goto next_pkt;
}
}
/* framing errors are soft errors */
else if ((flags & NV_RX2_ERROR_MASK) == NV_RX2_FRAMINGERR) {
if (flags & NV_RX2_SUBSTRACT1)
len--;
}
/* the rest are hard errors */
else {
dev_kfree_skb(skb);
goto next_pkt;
}
}
if (((flags & NV_RX2_CHECKSUMMASK) == NV_RX2_CHECKSUM_IP_TCP) || /*ip and tcp */
((flags & NV_RX2_CHECKSUMMASK) == NV_RX2_CHECKSUM_IP_UDP)) /*ip and udp */
skb->ip_summed = CHECKSUM_UNNECESSARY;
/* got a valid packet - forward it to the network core */
skb_put(skb, len);
skb->protocol = eth_type_trans(skb, dev);
prefetch(skb->data);
if (likely(!np->vlangrp)) {
napi_gro_receive(&np->napi, skb);
} else {
vlanflags = le32_to_cpu(np->get_rx.ex->buflow);
if (vlanflags & NV_RX3_VLAN_TAG_PRESENT) {
vlan_gro_receive(&np->napi, np->vlangrp,
vlanflags & NV_RX3_VLAN_TAG_MASK, skb);
} else {
napi_gro_receive(&np->napi, skb);
}
}
dev->stats.rx_packets++;
dev->stats.rx_bytes += len;
} else {
dev_kfree_skb(skb);
}
next_pkt:
if (unlikely(np->get_rx.ex++ == np->last_rx.ex))
np->get_rx.ex = np->first_rx.ex;
if (unlikely(np->get_rx_ctx++ == np->last_rx_ctx))
np->get_rx_ctx = np->first_rx_ctx;
rx_work++;
}
return rx_work;
}
static void set_bufsize(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
if (dev->mtu <= ETH_DATA_LEN)
np->rx_buf_sz = ETH_DATA_LEN + NV_RX_HEADERS;
else
np->rx_buf_sz = dev->mtu + NV_RX_HEADERS;
}
/*
* nv_change_mtu: dev->change_mtu function
* Called with dev_base_lock held for read.
*/
static int nv_change_mtu(struct net_device *dev, int new_mtu)
{
struct fe_priv *np = netdev_priv(dev);
int old_mtu;
if (new_mtu < 64 || new_mtu > np->pkt_limit)
return -EINVAL;
old_mtu = dev->mtu;
dev->mtu = new_mtu;
/* return early if the buffer sizes will not change */
if (old_mtu <= ETH_DATA_LEN && new_mtu <= ETH_DATA_LEN)
return 0;
if (old_mtu == new_mtu)
return 0;
/* synchronized against open : rtnl_lock() held by caller */
if (netif_running(dev)) {
u8 __iomem *base = get_hwbase(dev);
/*
* It seems that the nic preloads valid ring entries into an
* internal buffer. The procedure for flushing everything is
* guessed, there is probably a simpler approach.
* Changing the MTU is a rare event, it shouldn't matter.
*/
nv_disable_irq(dev);
nv_napi_disable(dev);
netif_tx_lock_bh(dev);
netif_addr_lock(dev);
spin_lock(&np->lock);
/* stop engines */
nv_stop_rxtx(dev);
nv_txrx_reset(dev);
/* drain rx queue */
nv_drain_rxtx(dev);
/* reinit driver view of the rx queue */
set_bufsize(dev);
if (nv_init_ring(dev)) {
if (!np->in_shutdown)
mod_timer(&np->oom_kick, jiffies + OOM_REFILL);
}
/* reinit nic view of the rx queue */
writel(np->rx_buf_sz, base + NvRegOffloadConfig);
setup_hw_rings(dev, NV_SETUP_RX_RING | NV_SETUP_TX_RING);
writel(((np->rx_ring_size-1) << NVREG_RINGSZ_RXSHIFT) + ((np->tx_ring_size-1) << NVREG_RINGSZ_TXSHIFT),
base + NvRegRingSizes);
pci_push(base);
writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl);
pci_push(base);
/* restart rx engine */
nv_start_rxtx(dev);
spin_unlock(&np->lock);
netif_addr_unlock(dev);
netif_tx_unlock_bh(dev);
nv_napi_enable(dev);
nv_enable_irq(dev);
}
return 0;
}
static void nv_copy_mac_to_hw(struct net_device *dev)
{
u8 __iomem *base = get_hwbase(dev);
u32 mac[2];
mac[0] = (dev->dev_addr[0] << 0) + (dev->dev_addr[1] << 8) +
(dev->dev_addr[2] << 16) + (dev->dev_addr[3] << 24);
mac[1] = (dev->dev_addr[4] << 0) + (dev->dev_addr[5] << 8);
writel(mac[0], base + NvRegMacAddrA);
writel(mac[1], base + NvRegMacAddrB);
}
/*
* nv_set_mac_address: dev->set_mac_address function
* Called with rtnl_lock() held.
*/
static int nv_set_mac_address(struct net_device *dev, void *addr)
{
struct fe_priv *np = netdev_priv(dev);
struct sockaddr *macaddr = (struct sockaddr *)addr;
if (!is_valid_ether_addr(macaddr->sa_data))
return -EADDRNOTAVAIL;
/* synchronized against open : rtnl_lock() held by caller */
memcpy(dev->dev_addr, macaddr->sa_data, ETH_ALEN);
if (netif_running(dev)) {
netif_tx_lock_bh(dev);
netif_addr_lock(dev);
spin_lock_irq(&np->lock);
/* stop rx engine */
nv_stop_rx(dev);
/* set mac address */
nv_copy_mac_to_hw(dev);
/* restart rx engine */
nv_start_rx(dev);
spin_unlock_irq(&np->lock);
netif_addr_unlock(dev);
netif_tx_unlock_bh(dev);
} else {
nv_copy_mac_to_hw(dev);
}
return 0;
}
/*
* nv_set_multicast: dev->set_multicast function
* Called with netif_tx_lock held.
*/
static void nv_set_multicast(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 addr[2];
u32 mask[2];
u32 pff = readl(base + NvRegPacketFilterFlags) & NVREG_PFF_PAUSE_RX;
memset(addr, 0, sizeof(addr));
memset(mask, 0, sizeof(mask));
if (dev->flags & IFF_PROMISC) {
pff |= NVREG_PFF_PROMISC;
} else {
pff |= NVREG_PFF_MYADDR;
if (dev->flags & IFF_ALLMULTI || !netdev_mc_empty(dev)) {
u32 alwaysOff[2];
u32 alwaysOn[2];
alwaysOn[0] = alwaysOn[1] = alwaysOff[0] = alwaysOff[1] = 0xffffffff;
if (dev->flags & IFF_ALLMULTI) {
alwaysOn[0] = alwaysOn[1] = alwaysOff[0] = alwaysOff[1] = 0;
} else {
struct netdev_hw_addr *ha;
netdev_for_each_mc_addr(ha, dev) {
unsigned char *addr = ha->addr;
u32 a, b;
a = le32_to_cpu(*(__le32 *) addr);
b = le16_to_cpu(*(__le16 *) (&addr[4]));
alwaysOn[0] &= a;
alwaysOff[0] &= ~a;
alwaysOn[1] &= b;
alwaysOff[1] &= ~b;
}
}
addr[0] = alwaysOn[0];
addr[1] = alwaysOn[1];
mask[0] = alwaysOn[0] | alwaysOff[0];
mask[1] = alwaysOn[1] | alwaysOff[1];
} else {
mask[0] = NVREG_MCASTMASKA_NONE;
mask[1] = NVREG_MCASTMASKB_NONE;
}
}
addr[0] |= NVREG_MCASTADDRA_FORCE;
pff |= NVREG_PFF_ALWAYS;
spin_lock_irq(&np->lock);
nv_stop_rx(dev);
writel(addr[0], base + NvRegMulticastAddrA);
writel(addr[1], base + NvRegMulticastAddrB);
writel(mask[0], base + NvRegMulticastMaskA);
writel(mask[1], base + NvRegMulticastMaskB);
writel(pff, base + NvRegPacketFilterFlags);
nv_start_rx(dev);
spin_unlock_irq(&np->lock);
}
static void nv_update_pause(struct net_device *dev, u32 pause_flags)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
np->pause_flags &= ~(NV_PAUSEFRAME_TX_ENABLE | NV_PAUSEFRAME_RX_ENABLE);
if (np->pause_flags & NV_PAUSEFRAME_RX_CAPABLE) {
u32 pff = readl(base + NvRegPacketFilterFlags) & ~NVREG_PFF_PAUSE_RX;
if (pause_flags & NV_PAUSEFRAME_RX_ENABLE) {
writel(pff|NVREG_PFF_PAUSE_RX, base + NvRegPacketFilterFlags);
np->pause_flags |= NV_PAUSEFRAME_RX_ENABLE;
} else {
writel(pff, base + NvRegPacketFilterFlags);
}
}
if (np->pause_flags & NV_PAUSEFRAME_TX_CAPABLE) {
u32 regmisc = readl(base + NvRegMisc1) & ~NVREG_MISC1_PAUSE_TX;
if (pause_flags & NV_PAUSEFRAME_TX_ENABLE) {
u32 pause_enable = NVREG_TX_PAUSEFRAME_ENABLE_V1;
if (np->driver_data & DEV_HAS_PAUSEFRAME_TX_V2)
pause_enable = NVREG_TX_PAUSEFRAME_ENABLE_V2;
if (np->driver_data & DEV_HAS_PAUSEFRAME_TX_V3) {
pause_enable = NVREG_TX_PAUSEFRAME_ENABLE_V3;
/* limit the number of tx pause frames to a default of 8 */
writel(readl(base + NvRegTxPauseFrameLimit)|NVREG_TX_PAUSEFRAMELIMIT_ENABLE, base + NvRegTxPauseFrameLimit);
}
writel(pause_enable, base + NvRegTxPauseFrame);
writel(regmisc|NVREG_MISC1_PAUSE_TX, base + NvRegMisc1);
np->pause_flags |= NV_PAUSEFRAME_TX_ENABLE;
} else {
writel(NVREG_TX_PAUSEFRAME_DISABLE, base + NvRegTxPauseFrame);
writel(regmisc, base + NvRegMisc1);
}
}
}
/**
* nv_update_linkspeed: Setup the MAC according to the link partner
* @dev: Network device to be configured
*
* The function queries the PHY and checks if there is a link partner.
* If yes, then it sets up the MAC accordingly. Otherwise, the MAC is
* set to 10 MBit HD.
*
* The function returns 0 if there is no link partner and 1 if there is
* a good link partner.
*/
static int nv_update_linkspeed(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
int adv = 0;
int lpa = 0;
int adv_lpa, adv_pause, lpa_pause;
int newls = np->linkspeed;
int newdup = np->duplex;
int mii_status;
int retval = 0;
u32 control_1000, status_1000, phyreg, pause_flags, txreg;
u32 txrxFlags = 0;
u32 phy_exp;
/* BMSR_LSTATUS is latched, read it twice:
* we want the current value.
*/
mii_rw(dev, np->phyaddr, MII_BMSR, MII_READ);
mii_status = mii_rw(dev, np->phyaddr, MII_BMSR, MII_READ);
if (!(mii_status & BMSR_LSTATUS)) {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_10;
newdup = 0;
retval = 0;
goto set_speed;
}
if (np->autoneg == 0) {
if (np->fixed_mode & LPA_100FULL) {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_100;
newdup = 1;
} else if (np->fixed_mode & LPA_100HALF) {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_100;
newdup = 0;
} else if (np->fixed_mode & LPA_10FULL) {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_10;
newdup = 1;
} else {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_10;
newdup = 0;
}
retval = 1;
goto set_speed;
}
/* check auto negotiation is complete */
if (!(mii_status & BMSR_ANEGCOMPLETE)) {
/* still in autonegotiation - configure nic for 10 MBit HD and wait. */
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_10;
newdup = 0;
retval = 0;
goto set_speed;
}
adv = mii_rw(dev, np->phyaddr, MII_ADVERTISE, MII_READ);
lpa = mii_rw(dev, np->phyaddr, MII_LPA, MII_READ);
retval = 1;
if (np->gigabit == PHY_GIGABIT) {
control_1000 = mii_rw(dev, np->phyaddr, MII_CTRL1000, MII_READ);
status_1000 = mii_rw(dev, np->phyaddr, MII_STAT1000, MII_READ);
if ((control_1000 & ADVERTISE_1000FULL) &&
(status_1000 & LPA_1000FULL)) {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_1000;
newdup = 1;
goto set_speed;
}
}
/* FIXME: handle parallel detection properly */
adv_lpa = lpa & adv;
if (adv_lpa & LPA_100FULL) {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_100;
newdup = 1;
} else if (adv_lpa & LPA_100HALF) {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_100;
newdup = 0;
} else if (adv_lpa & LPA_10FULL) {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_10;
newdup = 1;
} else if (adv_lpa & LPA_10HALF) {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_10;
newdup = 0;
} else {
newls = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_10;
newdup = 0;
}
set_speed:
if (np->duplex == newdup && np->linkspeed == newls)
return retval;
np->duplex = newdup;
np->linkspeed = newls;
/* The transmitter and receiver must be restarted for safe update */
if (readl(base + NvRegTransmitterControl) & NVREG_XMITCTL_START) {
txrxFlags |= NV_RESTART_TX;
nv_stop_tx(dev);
}
if (readl(base + NvRegReceiverControl) & NVREG_RCVCTL_START) {
txrxFlags |= NV_RESTART_RX;
nv_stop_rx(dev);
}
if (np->gigabit == PHY_GIGABIT) {
phyreg = readl(base + NvRegSlotTime);
phyreg &= ~(0x3FF00);
if (((np->linkspeed & 0xFFF) == NVREG_LINKSPEED_10) ||
((np->linkspeed & 0xFFF) == NVREG_LINKSPEED_100))
phyreg |= NVREG_SLOTTIME_10_100_FULL;
else if ((np->linkspeed & 0xFFF) == NVREG_LINKSPEED_1000)
phyreg |= NVREG_SLOTTIME_1000_FULL;
writel(phyreg, base + NvRegSlotTime);
}
phyreg = readl(base + NvRegPhyInterface);
phyreg &= ~(PHY_HALF|PHY_100|PHY_1000);
if (np->duplex == 0)
phyreg |= PHY_HALF;
if ((np->linkspeed & NVREG_LINKSPEED_MASK) == NVREG_LINKSPEED_100)
phyreg |= PHY_100;
else if ((np->linkspeed & NVREG_LINKSPEED_MASK) == NVREG_LINKSPEED_1000)
phyreg |= PHY_1000;
writel(phyreg, base + NvRegPhyInterface);
phy_exp = mii_rw(dev, np->phyaddr, MII_EXPANSION, MII_READ) & EXPANSION_NWAY; /* autoneg capable */
if (phyreg & PHY_RGMII) {
if ((np->linkspeed & NVREG_LINKSPEED_MASK) == NVREG_LINKSPEED_1000) {
txreg = NVREG_TX_DEFERRAL_RGMII_1000;
} else {
if (!phy_exp && !np->duplex && (np->driver_data & DEV_HAS_COLLISION_FIX)) {
if ((np->linkspeed & NVREG_LINKSPEED_MASK) == NVREG_LINKSPEED_10)
txreg = NVREG_TX_DEFERRAL_RGMII_STRETCH_10;
else
txreg = NVREG_TX_DEFERRAL_RGMII_STRETCH_100;
} else {
txreg = NVREG_TX_DEFERRAL_RGMII_10_100;
}
}
} else {
if (!phy_exp && !np->duplex && (np->driver_data & DEV_HAS_COLLISION_FIX))
txreg = NVREG_TX_DEFERRAL_MII_STRETCH;
else
txreg = NVREG_TX_DEFERRAL_DEFAULT;
}
writel(txreg, base + NvRegTxDeferral);
if (np->desc_ver == DESC_VER_1) {
txreg = NVREG_TX_WM_DESC1_DEFAULT;
} else {
if ((np->linkspeed & NVREG_LINKSPEED_MASK) == NVREG_LINKSPEED_1000)
txreg = NVREG_TX_WM_DESC2_3_1000;
else
txreg = NVREG_TX_WM_DESC2_3_DEFAULT;
}
writel(txreg, base + NvRegTxWatermark);
writel(NVREG_MISC1_FORCE | (np->duplex ? 0 : NVREG_MISC1_HD),
base + NvRegMisc1);
pci_push(base);
writel(np->linkspeed, base + NvRegLinkSpeed);
pci_push(base);
pause_flags = 0;
/* setup pause frame */
if (np->duplex != 0) {
if (np->autoneg && np->pause_flags & NV_PAUSEFRAME_AUTONEG) {
adv_pause = adv & (ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM);
lpa_pause = lpa & (LPA_PAUSE_CAP | LPA_PAUSE_ASYM);
switch (adv_pause) {
case ADVERTISE_PAUSE_CAP:
if (lpa_pause & LPA_PAUSE_CAP) {
pause_flags |= NV_PAUSEFRAME_RX_ENABLE;
if (np->pause_flags & NV_PAUSEFRAME_TX_REQ)
pause_flags |= NV_PAUSEFRAME_TX_ENABLE;
}
break;
case ADVERTISE_PAUSE_ASYM:
if (lpa_pause == (LPA_PAUSE_CAP | LPA_PAUSE_ASYM))
pause_flags |= NV_PAUSEFRAME_TX_ENABLE;
break;
case ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM:
if (lpa_pause & LPA_PAUSE_CAP) {
pause_flags |= NV_PAUSEFRAME_RX_ENABLE;
if (np->pause_flags & NV_PAUSEFRAME_TX_REQ)
pause_flags |= NV_PAUSEFRAME_TX_ENABLE;
}
if (lpa_pause == LPA_PAUSE_ASYM)
pause_flags |= NV_PAUSEFRAME_RX_ENABLE;
break;
}
} else {
pause_flags = np->pause_flags;
}
}
nv_update_pause(dev, pause_flags);
if (txrxFlags & NV_RESTART_TX)
nv_start_tx(dev);
if (txrxFlags & NV_RESTART_RX)
nv_start_rx(dev);
return retval;
}
static void nv_linkchange(struct net_device *dev)
{
if (nv_update_linkspeed(dev)) {
if (!netif_carrier_ok(dev)) {
netif_carrier_on(dev);
netdev_info(dev, "link up\n");
nv_txrx_gate(dev, false);
nv_start_rx(dev);
}
} else {
if (netif_carrier_ok(dev)) {
netif_carrier_off(dev);
netdev_info(dev, "link down\n");
nv_txrx_gate(dev, true);
nv_stop_rx(dev);
}
}
}
static void nv_link_irq(struct net_device *dev)
{
u8 __iomem *base = get_hwbase(dev);
u32 miistat;
miistat = readl(base + NvRegMIIStatus);
writel(NVREG_MIISTAT_LINKCHANGE, base + NvRegMIIStatus);
if (miistat & (NVREG_MIISTAT_LINKCHANGE))
nv_linkchange(dev);
}
static void nv_msi_workaround(struct fe_priv *np)
{
/* Need to toggle the msi irq mask within the ethernet device,
* otherwise, future interrupts will not be detected.
*/
if (np->msi_flags & NV_MSI_ENABLED) {
u8 __iomem *base = np->base;
writel(0, base + NvRegMSIIrqMask);
writel(NVREG_MSI_VECTOR_0_ENABLED, base + NvRegMSIIrqMask);
}
}
static inline int nv_change_interrupt_mode(struct net_device *dev, int total_work)
{
struct fe_priv *np = netdev_priv(dev);
if (optimization_mode == NV_OPTIMIZATION_MODE_DYNAMIC) {
if (total_work > NV_DYNAMIC_THRESHOLD) {
/* transition to poll based interrupts */
np->quiet_count = 0;
if (np->irqmask != NVREG_IRQMASK_CPU) {
np->irqmask = NVREG_IRQMASK_CPU;
return 1;
}
} else {
if (np->quiet_count < NV_DYNAMIC_MAX_QUIET_COUNT) {
np->quiet_count++;
} else {
/* reached a period of low activity, switch
to per tx/rx packet interrupts */
if (np->irqmask != NVREG_IRQMASK_THROUGHPUT) {
np->irqmask = NVREG_IRQMASK_THROUGHPUT;
return 1;
}
}
}
}
return 0;
}
static irqreturn_t nv_nic_irq(int foo, void *data)
{
struct net_device *dev = (struct net_device *) data;
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
if (!(np->msi_flags & NV_MSI_X_ENABLED)) {
np->events = readl(base + NvRegIrqStatus);
writel(np->events, base + NvRegIrqStatus);
} else {
np->events = readl(base + NvRegMSIXIrqStatus);
writel(np->events, base + NvRegMSIXIrqStatus);
}
if (!(np->events & np->irqmask))
return IRQ_NONE;
nv_msi_workaround(np);
if (napi_schedule_prep(&np->napi)) {
/*
* Disable further irq's (msix not enabled with napi)
*/
writel(0, base + NvRegIrqMask);
__napi_schedule(&np->napi);
}
return IRQ_HANDLED;
}
/**
* All _optimized functions are used to help increase performance
* (reduce CPU and increase throughput). They use descripter version 3,
* compiler directives, and reduce memory accesses.
*/
static irqreturn_t nv_nic_irq_optimized(int foo, void *data)
{
struct net_device *dev = (struct net_device *) data;
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
if (!(np->msi_flags & NV_MSI_X_ENABLED)) {
np->events = readl(base + NvRegIrqStatus);
writel(np->events, base + NvRegIrqStatus);
} else {
np->events = readl(base + NvRegMSIXIrqStatus);
writel(np->events, base + NvRegMSIXIrqStatus);
}
if (!(np->events & np->irqmask))
return IRQ_NONE;
nv_msi_workaround(np);
if (napi_schedule_prep(&np->napi)) {
/*
* Disable further irq's (msix not enabled with napi)
*/
writel(0, base + NvRegIrqMask);
__napi_schedule(&np->napi);
}
return IRQ_HANDLED;
}
static irqreturn_t nv_nic_irq_tx(int foo, void *data)
{
struct net_device *dev = (struct net_device *) data;
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 events;
int i;
unsigned long flags;
for (i = 0;; i++) {
events = readl(base + NvRegMSIXIrqStatus) & NVREG_IRQ_TX_ALL;
writel(NVREG_IRQ_TX_ALL, base + NvRegMSIXIrqStatus);
if (!(events & np->irqmask))
break;
spin_lock_irqsave(&np->lock, flags);
nv_tx_done_optimized(dev, TX_WORK_PER_LOOP);
spin_unlock_irqrestore(&np->lock, flags);
if (unlikely(i > max_interrupt_work)) {
spin_lock_irqsave(&np->lock, flags);
/* disable interrupts on the nic */
writel(NVREG_IRQ_TX_ALL, base + NvRegIrqMask);
pci_push(base);
if (!np->in_shutdown) {
np->nic_poll_irq |= NVREG_IRQ_TX_ALL;
mod_timer(&np->nic_poll, jiffies + POLL_WAIT);
}
spin_unlock_irqrestore(&np->lock, flags);
netdev_dbg(dev, "%s: too many iterations (%d)\n",
__func__, i);
break;
}
}
return IRQ_RETVAL(i);
}
static int nv_napi_poll(struct napi_struct *napi, int budget)
{
struct fe_priv *np = container_of(napi, struct fe_priv, napi);
struct net_device *dev = np->dev;
u8 __iomem *base = get_hwbase(dev);
unsigned long flags;
int retcode;
int rx_count, tx_work = 0, rx_work = 0;
do {
if (!nv_optimized(np)) {
spin_lock_irqsave(&np->lock, flags);
tx_work += nv_tx_done(dev, np->tx_ring_size);
spin_unlock_irqrestore(&np->lock, flags);
rx_count = nv_rx_process(dev, budget - rx_work);
retcode = nv_alloc_rx(dev);
} else {
spin_lock_irqsave(&np->lock, flags);
tx_work += nv_tx_done_optimized(dev, np->tx_ring_size);
spin_unlock_irqrestore(&np->lock, flags);
rx_count = nv_rx_process_optimized(dev,
budget - rx_work);
retcode = nv_alloc_rx_optimized(dev);
}
} while (retcode == 0 &&
rx_count > 0 && (rx_work += rx_count) < budget);
if (retcode) {
spin_lock_irqsave(&np->lock, flags);
if (!np->in_shutdown)
mod_timer(&np->oom_kick, jiffies + OOM_REFILL);
spin_unlock_irqrestore(&np->lock, flags);
}
nv_change_interrupt_mode(dev, tx_work + rx_work);
if (unlikely(np->events & NVREG_IRQ_LINK)) {
spin_lock_irqsave(&np->lock, flags);
nv_link_irq(dev);
spin_unlock_irqrestore(&np->lock, flags);
}
if (unlikely(np->need_linktimer && time_after(jiffies, np->link_timeout))) {
spin_lock_irqsave(&np->lock, flags);
nv_linkchange(dev);
spin_unlock_irqrestore(&np->lock, flags);
np->link_timeout = jiffies + LINK_TIMEOUT;
}
if (unlikely(np->events & NVREG_IRQ_RECOVER_ERROR)) {
spin_lock_irqsave(&np->lock, flags);
if (!np->in_shutdown) {
np->nic_poll_irq = np->irqmask;
np->recover_error = 1;
mod_timer(&np->nic_poll, jiffies + POLL_WAIT);
}
spin_unlock_irqrestore(&np->lock, flags);
napi_complete(napi);
return rx_work;
}
if (rx_work < budget) {
/* re-enable interrupts
(msix not enabled in napi) */
napi_complete(napi);
writel(np->irqmask, base + NvRegIrqMask);
}
return rx_work;
}
static irqreturn_t nv_nic_irq_rx(int foo, void *data)
{
struct net_device *dev = (struct net_device *) data;
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 events;
int i;
unsigned long flags;
for (i = 0;; i++) {
events = readl(base + NvRegMSIXIrqStatus) & NVREG_IRQ_RX_ALL;
writel(NVREG_IRQ_RX_ALL, base + NvRegMSIXIrqStatus);
if (!(events & np->irqmask))
break;
if (nv_rx_process_optimized(dev, RX_WORK_PER_LOOP)) {
if (unlikely(nv_alloc_rx_optimized(dev))) {
spin_lock_irqsave(&np->lock, flags);
if (!np->in_shutdown)
mod_timer(&np->oom_kick, jiffies + OOM_REFILL);
spin_unlock_irqrestore(&np->lock, flags);
}
}
if (unlikely(i > max_interrupt_work)) {
spin_lock_irqsave(&np->lock, flags);
/* disable interrupts on the nic */
writel(NVREG_IRQ_RX_ALL, base + NvRegIrqMask);
pci_push(base);
if (!np->in_shutdown) {
np->nic_poll_irq |= NVREG_IRQ_RX_ALL;
mod_timer(&np->nic_poll, jiffies + POLL_WAIT);
}
spin_unlock_irqrestore(&np->lock, flags);
netdev_dbg(dev, "%s: too many iterations (%d)\n",
__func__, i);
break;
}
}
return IRQ_RETVAL(i);
}
static irqreturn_t nv_nic_irq_other(int foo, void *data)
{
struct net_device *dev = (struct net_device *) data;
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 events;
int i;
unsigned long flags;
for (i = 0;; i++) {
events = readl(base + NvRegMSIXIrqStatus) & NVREG_IRQ_OTHER;
writel(NVREG_IRQ_OTHER, base + NvRegMSIXIrqStatus);
if (!(events & np->irqmask))
break;
/* check tx in case we reached max loop limit in tx isr */
spin_lock_irqsave(&np->lock, flags);
nv_tx_done_optimized(dev, TX_WORK_PER_LOOP);
spin_unlock_irqrestore(&np->lock, flags);
if (events & NVREG_IRQ_LINK) {
spin_lock_irqsave(&np->lock, flags);
nv_link_irq(dev);
spin_unlock_irqrestore(&np->lock, flags);
}
if (np->need_linktimer && time_after(jiffies, np->link_timeout)) {
spin_lock_irqsave(&np->lock, flags);
nv_linkchange(dev);
spin_unlock_irqrestore(&np->lock, flags);
np->link_timeout = jiffies + LINK_TIMEOUT;
}
if (events & NVREG_IRQ_RECOVER_ERROR) {
spin_lock_irq(&np->lock);
/* disable interrupts on the nic */
writel(NVREG_IRQ_OTHER, base + NvRegIrqMask);
pci_push(base);
if (!np->in_shutdown) {
np->nic_poll_irq |= NVREG_IRQ_OTHER;
np->recover_error = 1;
mod_timer(&np->nic_poll, jiffies + POLL_WAIT);
}
spin_unlock_irq(&np->lock);
break;
}
if (unlikely(i > max_interrupt_work)) {
spin_lock_irqsave(&np->lock, flags);
/* disable interrupts on the nic */
writel(NVREG_IRQ_OTHER, base + NvRegIrqMask);
pci_push(base);
if (!np->in_shutdown) {
np->nic_poll_irq |= NVREG_IRQ_OTHER;
mod_timer(&np->nic_poll, jiffies + POLL_WAIT);
}
spin_unlock_irqrestore(&np->lock, flags);
netdev_dbg(dev, "%s: too many iterations (%d)\n",
__func__, i);
break;
}
}
return IRQ_RETVAL(i);
}
static irqreturn_t nv_nic_irq_test(int foo, void *data)
{
struct net_device *dev = (struct net_device *) data;
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 events;
if (!(np->msi_flags & NV_MSI_X_ENABLED)) {
events = readl(base + NvRegIrqStatus) & NVREG_IRQSTAT_MASK;
writel(NVREG_IRQ_TIMER, base + NvRegIrqStatus);
} else {
events = readl(base + NvRegMSIXIrqStatus) & NVREG_IRQSTAT_MASK;
writel(NVREG_IRQ_TIMER, base + NvRegMSIXIrqStatus);
}
pci_push(base);
if (!(events & NVREG_IRQ_TIMER))
return IRQ_RETVAL(0);
nv_msi_workaround(np);
spin_lock(&np->lock);
np->intr_test = 1;
spin_unlock(&np->lock);
return IRQ_RETVAL(1);
}
static void set_msix_vector_map(struct net_device *dev, u32 vector, u32 irqmask)
{
u8 __iomem *base = get_hwbase(dev);
int i;
u32 msixmap = 0;
/* Each interrupt bit can be mapped to a MSIX vector (4 bits).
* MSIXMap0 represents the first 8 interrupts and MSIXMap1 represents
* the remaining 8 interrupts.
*/
for (i = 0; i < 8; i++) {
if ((irqmask >> i) & 0x1)
msixmap |= vector << (i << 2);
}
writel(readl(base + NvRegMSIXMap0) | msixmap, base + NvRegMSIXMap0);
msixmap = 0;
for (i = 0; i < 8; i++) {
if ((irqmask >> (i + 8)) & 0x1)
msixmap |= vector << (i << 2);
}
writel(readl(base + NvRegMSIXMap1) | msixmap, base + NvRegMSIXMap1);
}
static int nv_request_irq(struct net_device *dev, int intr_test)
{
struct fe_priv *np = get_nvpriv(dev);
u8 __iomem *base = get_hwbase(dev);
int ret = 1;
int i;
irqreturn_t (*handler)(int foo, void *data);
if (intr_test) {
handler = nv_nic_irq_test;
} else {
if (nv_optimized(np))
handler = nv_nic_irq_optimized;
else
handler = nv_nic_irq;
}
if (np->msi_flags & NV_MSI_X_CAPABLE) {
for (i = 0; i < (np->msi_flags & NV_MSI_X_VECTORS_MASK); i++)
np->msi_x_entry[i].entry = i;
ret = pci_enable_msix(np->pci_dev, np->msi_x_entry, (np->msi_flags & NV_MSI_X_VECTORS_MASK));
if (ret == 0) {
np->msi_flags |= NV_MSI_X_ENABLED;
if (optimization_mode == NV_OPTIMIZATION_MODE_THROUGHPUT && !intr_test) {
/* Request irq for rx handling */
sprintf(np->name_rx, "%s-rx", dev->name);
if (request_irq(np->msi_x_entry[NV_MSI_X_VECTOR_RX].vector,
nv_nic_irq_rx, IRQF_SHARED, np->name_rx, dev) != 0) {
netdev_info(dev,
"request_irq failed for rx %d\n",
ret);
pci_disable_msix(np->pci_dev);
np->msi_flags &= ~NV_MSI_X_ENABLED;
goto out_err;
}
/* Request irq for tx handling */
sprintf(np->name_tx, "%s-tx", dev->name);
if (request_irq(np->msi_x_entry[NV_MSI_X_VECTOR_TX].vector,
nv_nic_irq_tx, IRQF_SHARED, np->name_tx, dev) != 0) {
netdev_info(dev,
"request_irq failed for tx %d\n",
ret);
pci_disable_msix(np->pci_dev);
np->msi_flags &= ~NV_MSI_X_ENABLED;
goto out_free_rx;
}
/* Request irq for link and timer handling */
sprintf(np->name_other, "%s-other", dev->name);
if (request_irq(np->msi_x_entry[NV_MSI_X_VECTOR_OTHER].vector,
nv_nic_irq_other, IRQF_SHARED, np->name_other, dev) != 0) {
netdev_info(dev,
"request_irq failed for link %d\n",
ret);
pci_disable_msix(np->pci_dev);
np->msi_flags &= ~NV_MSI_X_ENABLED;
goto out_free_tx;
}
/* map interrupts to their respective vector */
writel(0, base + NvRegMSIXMap0);
writel(0, base + NvRegMSIXMap1);
set_msix_vector_map(dev, NV_MSI_X_VECTOR_RX, NVREG_IRQ_RX_ALL);
set_msix_vector_map(dev, NV_MSI_X_VECTOR_TX, NVREG_IRQ_TX_ALL);
set_msix_vector_map(dev, NV_MSI_X_VECTOR_OTHER, NVREG_IRQ_OTHER);
} else {
/* Request irq for all interrupts */
if (request_irq(np->msi_x_entry[NV_MSI_X_VECTOR_ALL].vector, handler, IRQF_SHARED, dev->name, dev) != 0) {
netdev_info(dev,
"request_irq failed %d\n",
ret);
pci_disable_msix(np->pci_dev);
np->msi_flags &= ~NV_MSI_X_ENABLED;
goto out_err;
}
/* map interrupts to vector 0 */
writel(0, base + NvRegMSIXMap0);
writel(0, base + NvRegMSIXMap1);
}
}
}
if (ret != 0 && np->msi_flags & NV_MSI_CAPABLE) {
ret = pci_enable_msi(np->pci_dev);
if (ret == 0) {
np->msi_flags |= NV_MSI_ENABLED;
dev->irq = np->pci_dev->irq;
if (request_irq(np->pci_dev->irq, handler, IRQF_SHARED, dev->name, dev) != 0) {
netdev_info(dev, "request_irq failed %d\n",
ret);
pci_disable_msi(np->pci_dev);
np->msi_flags &= ~NV_MSI_ENABLED;
dev->irq = np->pci_dev->irq;
goto out_err;
}
/* map interrupts to vector 0 */
writel(0, base + NvRegMSIMap0);
writel(0, base + NvRegMSIMap1);
/* enable msi vector 0 */
writel(NVREG_MSI_VECTOR_0_ENABLED, base + NvRegMSIIrqMask);
}
}
if (ret != 0) {
if (request_irq(np->pci_dev->irq, handler, IRQF_SHARED, dev->name, dev) != 0)
goto out_err;
}
return 0;
out_free_tx:
free_irq(np->msi_x_entry[NV_MSI_X_VECTOR_TX].vector, dev);
out_free_rx:
free_irq(np->msi_x_entry[NV_MSI_X_VECTOR_RX].vector, dev);
out_err:
return 1;
}
static void nv_free_irq(struct net_device *dev)
{
struct fe_priv *np = get_nvpriv(dev);
int i;
if (np->msi_flags & NV_MSI_X_ENABLED) {
for (i = 0; i < (np->msi_flags & NV_MSI_X_VECTORS_MASK); i++)
free_irq(np->msi_x_entry[i].vector, dev);
pci_disable_msix(np->pci_dev);
np->msi_flags &= ~NV_MSI_X_ENABLED;
} else {
free_irq(np->pci_dev->irq, dev);
if (np->msi_flags & NV_MSI_ENABLED) {
pci_disable_msi(np->pci_dev);
np->msi_flags &= ~NV_MSI_ENABLED;
}
}
}
static void nv_do_nic_poll(unsigned long data)
{
struct net_device *dev = (struct net_device *) data;
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 mask = 0;
/*
* First disable irq(s) and then
* reenable interrupts on the nic, we have to do this before calling
* nv_nic_irq because that may decide to do otherwise
*/
if (!using_multi_irqs(dev)) {
if (np->msi_flags & NV_MSI_X_ENABLED)
disable_irq_lockdep(np->msi_x_entry[NV_MSI_X_VECTOR_ALL].vector);
else
disable_irq_lockdep(np->pci_dev->irq);
mask = np->irqmask;
} else {
if (np->nic_poll_irq & NVREG_IRQ_RX_ALL) {
disable_irq_lockdep(np->msi_x_entry[NV_MSI_X_VECTOR_RX].vector);
mask |= NVREG_IRQ_RX_ALL;
}
if (np->nic_poll_irq & NVREG_IRQ_TX_ALL) {
disable_irq_lockdep(np->msi_x_entry[NV_MSI_X_VECTOR_TX].vector);
mask |= NVREG_IRQ_TX_ALL;
}
if (np->nic_poll_irq & NVREG_IRQ_OTHER) {
disable_irq_lockdep(np->msi_x_entry[NV_MSI_X_VECTOR_OTHER].vector);
mask |= NVREG_IRQ_OTHER;
}
}
/* disable_irq() contains synchronize_irq, thus no irq handler can run now */
if (np->recover_error) {
np->recover_error = 0;
netdev_info(dev, "MAC in recoverable error state\n");
if (netif_running(dev)) {
netif_tx_lock_bh(dev);
netif_addr_lock(dev);
spin_lock(&np->lock);
/* stop engines */
nv_stop_rxtx(dev);
if (np->driver_data & DEV_HAS_POWER_CNTRL)
nv_mac_reset(dev);
nv_txrx_reset(dev);
/* drain rx queue */
nv_drain_rxtx(dev);
/* reinit driver view of the rx queue */
set_bufsize(dev);
if (nv_init_ring(dev)) {
if (!np->in_shutdown)
mod_timer(&np->oom_kick, jiffies + OOM_REFILL);
}
/* reinit nic view of the rx queue */
writel(np->rx_buf_sz, base + NvRegOffloadConfig);
setup_hw_rings(dev, NV_SETUP_RX_RING | NV_SETUP_TX_RING);
writel(((np->rx_ring_size-1) << NVREG_RINGSZ_RXSHIFT) + ((np->tx_ring_size-1) << NVREG_RINGSZ_TXSHIFT),
base + NvRegRingSizes);
pci_push(base);
writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl);
pci_push(base);
/* clear interrupts */
if (!(np->msi_flags & NV_MSI_X_ENABLED))
writel(NVREG_IRQSTAT_MASK, base + NvRegIrqStatus);
else
writel(NVREG_IRQSTAT_MASK, base + NvRegMSIXIrqStatus);
/* restart rx engine */
nv_start_rxtx(dev);
spin_unlock(&np->lock);
netif_addr_unlock(dev);
netif_tx_unlock_bh(dev);
}
}
writel(mask, base + NvRegIrqMask);
pci_push(base);
if (!using_multi_irqs(dev)) {
np->nic_poll_irq = 0;
if (nv_optimized(np))
nv_nic_irq_optimized(0, dev);
else
nv_nic_irq(0, dev);
if (np->msi_flags & NV_MSI_X_ENABLED)
enable_irq_lockdep(np->msi_x_entry[NV_MSI_X_VECTOR_ALL].vector);
else
enable_irq_lockdep(np->pci_dev->irq);
} else {
if (np->nic_poll_irq & NVREG_IRQ_RX_ALL) {
np->nic_poll_irq &= ~NVREG_IRQ_RX_ALL;
nv_nic_irq_rx(0, dev);
enable_irq_lockdep(np->msi_x_entry[NV_MSI_X_VECTOR_RX].vector);
}
if (np->nic_poll_irq & NVREG_IRQ_TX_ALL) {
np->nic_poll_irq &= ~NVREG_IRQ_TX_ALL;
nv_nic_irq_tx(0, dev);
enable_irq_lockdep(np->msi_x_entry[NV_MSI_X_VECTOR_TX].vector);
}
if (np->nic_poll_irq & NVREG_IRQ_OTHER) {
np->nic_poll_irq &= ~NVREG_IRQ_OTHER;
nv_nic_irq_other(0, dev);
enable_irq_lockdep(np->msi_x_entry[NV_MSI_X_VECTOR_OTHER].vector);
}
}
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void nv_poll_controller(struct net_device *dev)
{
nv_do_nic_poll((unsigned long) dev);
}
#endif
static void nv_do_stats_poll(unsigned long data)
{
struct net_device *dev = (struct net_device *) data;
struct fe_priv *np = netdev_priv(dev);
nv_get_hw_stats(dev);
if (!np->in_shutdown)
mod_timer(&np->stats_poll,
round_jiffies(jiffies + STATS_INTERVAL));
}
static void nv_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct fe_priv *np = netdev_priv(dev);
strcpy(info->driver, DRV_NAME);
strcpy(info->version, FORCEDETH_VERSION);
strcpy(info->bus_info, pci_name(np->pci_dev));
}
static void nv_get_wol(struct net_device *dev, struct ethtool_wolinfo *wolinfo)
{
struct fe_priv *np = netdev_priv(dev);
wolinfo->supported = WAKE_MAGIC;
spin_lock_irq(&np->lock);
if (np->wolenabled)
wolinfo->wolopts = WAKE_MAGIC;
spin_unlock_irq(&np->lock);
}
static int nv_set_wol(struct net_device *dev, struct ethtool_wolinfo *wolinfo)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 flags = 0;
if (wolinfo->wolopts == 0) {
np->wolenabled = 0;
} else if (wolinfo->wolopts & WAKE_MAGIC) {
np->wolenabled = 1;
flags = NVREG_WAKEUPFLAGS_ENABLE;
}
if (netif_running(dev)) {
spin_lock_irq(&np->lock);
writel(flags, base + NvRegWakeUpFlags);
spin_unlock_irq(&np->lock);
}
device_set_wakeup_enable(&np->pci_dev->dev, np->wolenabled);
return 0;
}
static int nv_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct fe_priv *np = netdev_priv(dev);
u32 speed;
int adv;
spin_lock_irq(&np->lock);
ecmd->port = PORT_MII;
if (!netif_running(dev)) {
/* We do not track link speed / duplex setting if the
* interface is disabled. Force a link check */
if (nv_update_linkspeed(dev)) {
if (!netif_carrier_ok(dev))
netif_carrier_on(dev);
} else {
if (netif_carrier_ok(dev))
netif_carrier_off(dev);
}
}
if (netif_carrier_ok(dev)) {
switch (np->linkspeed & (NVREG_LINKSPEED_MASK)) {
case NVREG_LINKSPEED_10:
speed = SPEED_10;
break;
case NVREG_LINKSPEED_100:
speed = SPEED_100;
break;
case NVREG_LINKSPEED_1000:
speed = SPEED_1000;
break;
default:
speed = -1;
break;
}
ecmd->duplex = DUPLEX_HALF;
if (np->duplex)
ecmd->duplex = DUPLEX_FULL;
} else {
speed = -1;
ecmd->duplex = -1;
}
ethtool_cmd_speed_set(ecmd, speed);
ecmd->autoneg = np->autoneg;
ecmd->advertising = ADVERTISED_MII;
if (np->autoneg) {
ecmd->advertising |= ADVERTISED_Autoneg;
adv = mii_rw(dev, np->phyaddr, MII_ADVERTISE, MII_READ);
if (adv & ADVERTISE_10HALF)
ecmd->advertising |= ADVERTISED_10baseT_Half;
if (adv & ADVERTISE_10FULL)
ecmd->advertising |= ADVERTISED_10baseT_Full;
if (adv & ADVERTISE_100HALF)
ecmd->advertising |= ADVERTISED_100baseT_Half;
if (adv & ADVERTISE_100FULL)
ecmd->advertising |= ADVERTISED_100baseT_Full;
if (np->gigabit == PHY_GIGABIT) {
adv = mii_rw(dev, np->phyaddr, MII_CTRL1000, MII_READ);
if (adv & ADVERTISE_1000FULL)
ecmd->advertising |= ADVERTISED_1000baseT_Full;
}
}
ecmd->supported = (SUPPORTED_Autoneg |
SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full |
SUPPORTED_MII);
if (np->gigabit == PHY_GIGABIT)
ecmd->supported |= SUPPORTED_1000baseT_Full;
ecmd->phy_address = np->phyaddr;
ecmd->transceiver = XCVR_EXTERNAL;
/* ignore maxtxpkt, maxrxpkt for now */
spin_unlock_irq(&np->lock);
return 0;
}
static int nv_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct fe_priv *np = netdev_priv(dev);
u32 speed = ethtool_cmd_speed(ecmd);
if (ecmd->port != PORT_MII)
return -EINVAL;
if (ecmd->transceiver != XCVR_EXTERNAL)
return -EINVAL;
if (ecmd->phy_address != np->phyaddr) {
/* TODO: support switching between multiple phys. Should be
* trivial, but not enabled due to lack of test hardware. */
return -EINVAL;
}
if (ecmd->autoneg == AUTONEG_ENABLE) {
u32 mask;
mask = ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full |
ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full;
if (np->gigabit == PHY_GIGABIT)
mask |= ADVERTISED_1000baseT_Full;
if ((ecmd->advertising & mask) == 0)
return -EINVAL;
} else if (ecmd->autoneg == AUTONEG_DISABLE) {
/* Note: autonegotiation disable, speed 1000 intentionally
* forbidden - no one should need that. */
if (speed != SPEED_10 && speed != SPEED_100)
return -EINVAL;
if (ecmd->duplex != DUPLEX_HALF && ecmd->duplex != DUPLEX_FULL)
return -EINVAL;
} else {
return -EINVAL;
}
netif_carrier_off(dev);
if (netif_running(dev)) {
unsigned long flags;
nv_disable_irq(dev);
netif_tx_lock_bh(dev);
netif_addr_lock(dev);
/* with plain spinlock lockdep complains */
spin_lock_irqsave(&np->lock, flags);
/* stop engines */
/* FIXME:
* this can take some time, and interrupts are disabled
* due to spin_lock_irqsave, but let's hope no daemon
* is going to change the settings very often...
* Worst case:
* NV_RXSTOP_DELAY1MAX + NV_TXSTOP_DELAY1MAX
* + some minor delays, which is up to a second approximately
*/
nv_stop_rxtx(dev);
spin_unlock_irqrestore(&np->lock, flags);
netif_addr_unlock(dev);
netif_tx_unlock_bh(dev);
}
if (ecmd->autoneg == AUTONEG_ENABLE) {
int adv, bmcr;
np->autoneg = 1;
/* advertise only what has been requested */
adv = mii_rw(dev, np->phyaddr, MII_ADVERTISE, MII_READ);
adv &= ~(ADVERTISE_ALL | ADVERTISE_100BASE4 | ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM);
if (ecmd->advertising & ADVERTISED_10baseT_Half)
adv |= ADVERTISE_10HALF;
if (ecmd->advertising & ADVERTISED_10baseT_Full)
adv |= ADVERTISE_10FULL;
if (ecmd->advertising & ADVERTISED_100baseT_Half)
adv |= ADVERTISE_100HALF;
if (ecmd->advertising & ADVERTISED_100baseT_Full)
adv |= ADVERTISE_100FULL;
if (np->pause_flags & NV_PAUSEFRAME_RX_REQ) /* for rx we set both advertisements but disable tx pause */
adv |= ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM;
if (np->pause_flags & NV_PAUSEFRAME_TX_REQ)
adv |= ADVERTISE_PAUSE_ASYM;
mii_rw(dev, np->phyaddr, MII_ADVERTISE, adv);
if (np->gigabit == PHY_GIGABIT) {
adv = mii_rw(dev, np->phyaddr, MII_CTRL1000, MII_READ);
adv &= ~ADVERTISE_1000FULL;
if (ecmd->advertising & ADVERTISED_1000baseT_Full)
adv |= ADVERTISE_1000FULL;
mii_rw(dev, np->phyaddr, MII_CTRL1000, adv);
}
if (netif_running(dev))
netdev_info(dev, "link down\n");
bmcr = mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ);
if (np->phy_model == PHY_MODEL_MARVELL_E3016) {
bmcr |= BMCR_ANENABLE;
/* reset the phy in order for settings to stick,
* and cause autoneg to start */
if (phy_reset(dev, bmcr)) {
netdev_info(dev, "phy reset failed\n");
return -EINVAL;
}
} else {
bmcr |= (BMCR_ANENABLE | BMCR_ANRESTART);
mii_rw(dev, np->phyaddr, MII_BMCR, bmcr);
}
} else {
int adv, bmcr;
np->autoneg = 0;
adv = mii_rw(dev, np->phyaddr, MII_ADVERTISE, MII_READ);
adv &= ~(ADVERTISE_ALL | ADVERTISE_100BASE4 | ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM);
if (speed == SPEED_10 && ecmd->duplex == DUPLEX_HALF)
adv |= ADVERTISE_10HALF;
if (speed == SPEED_10 && ecmd->duplex == DUPLEX_FULL)
adv |= ADVERTISE_10FULL;
if (speed == SPEED_100 && ecmd->duplex == DUPLEX_HALF)
adv |= ADVERTISE_100HALF;
if (speed == SPEED_100 && ecmd->duplex == DUPLEX_FULL)
adv |= ADVERTISE_100FULL;
np->pause_flags &= ~(NV_PAUSEFRAME_AUTONEG|NV_PAUSEFRAME_RX_ENABLE|NV_PAUSEFRAME_TX_ENABLE);
if (np->pause_flags & NV_PAUSEFRAME_RX_REQ) {/* for rx we set both advertisements but disable tx pause */
adv |= ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM;
np->pause_flags |= NV_PAUSEFRAME_RX_ENABLE;
}
if (np->pause_flags & NV_PAUSEFRAME_TX_REQ) {
adv |= ADVERTISE_PAUSE_ASYM;
np->pause_flags |= NV_PAUSEFRAME_TX_ENABLE;
}
mii_rw(dev, np->phyaddr, MII_ADVERTISE, adv);
np->fixed_mode = adv;
if (np->gigabit == PHY_GIGABIT) {
adv = mii_rw(dev, np->phyaddr, MII_CTRL1000, MII_READ);
adv &= ~ADVERTISE_1000FULL;
mii_rw(dev, np->phyaddr, MII_CTRL1000, adv);
}
bmcr = mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ);
bmcr &= ~(BMCR_ANENABLE|BMCR_SPEED100|BMCR_SPEED1000|BMCR_FULLDPLX);
if (np->fixed_mode & (ADVERTISE_10FULL|ADVERTISE_100FULL))
bmcr |= BMCR_FULLDPLX;
if (np->fixed_mode & (ADVERTISE_100HALF|ADVERTISE_100FULL))
bmcr |= BMCR_SPEED100;
if (np->phy_oui == PHY_OUI_MARVELL) {
/* reset the phy in order for forced mode settings to stick */
if (phy_reset(dev, bmcr)) {
netdev_info(dev, "phy reset failed\n");
return -EINVAL;
}
} else {
mii_rw(dev, np->phyaddr, MII_BMCR, bmcr);
if (netif_running(dev)) {
/* Wait a bit and then reconfigure the nic. */
udelay(10);
nv_linkchange(dev);
}
}
}
if (netif_running(dev)) {
nv_start_rxtx(dev);
nv_enable_irq(dev);
}
return 0;
}
#define FORCEDETH_REGS_VER 1
static int nv_get_regs_len(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
return np->register_size;
}
static void nv_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *buf)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 *rbuf = buf;
int i;
regs->version = FORCEDETH_REGS_VER;
spin_lock_irq(&np->lock);
for (i = 0; i <= np->register_size/sizeof(u32); i++)
rbuf[i] = readl(base + i*sizeof(u32));
spin_unlock_irq(&np->lock);
}
static int nv_nway_reset(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
int ret;
if (np->autoneg) {
int bmcr;
netif_carrier_off(dev);
if (netif_running(dev)) {
nv_disable_irq(dev);
netif_tx_lock_bh(dev);
netif_addr_lock(dev);
spin_lock(&np->lock);
/* stop engines */
nv_stop_rxtx(dev);
spin_unlock(&np->lock);
netif_addr_unlock(dev);
netif_tx_unlock_bh(dev);
netdev_info(dev, "link down\n");
}
bmcr = mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ);
if (np->phy_model == PHY_MODEL_MARVELL_E3016) {
bmcr |= BMCR_ANENABLE;
/* reset the phy in order for settings to stick*/
if (phy_reset(dev, bmcr)) {
netdev_info(dev, "phy reset failed\n");
return -EINVAL;
}
} else {
bmcr |= (BMCR_ANENABLE | BMCR_ANRESTART);
mii_rw(dev, np->phyaddr, MII_BMCR, bmcr);
}
if (netif_running(dev)) {
nv_start_rxtx(dev);
nv_enable_irq(dev);
}
ret = 0;
} else {
ret = -EINVAL;
}
return ret;
}
static void nv_get_ringparam(struct net_device *dev, struct ethtool_ringparam* ring)
{
struct fe_priv *np = netdev_priv(dev);
ring->rx_max_pending = (np->desc_ver == DESC_VER_1) ? RING_MAX_DESC_VER_1 : RING_MAX_DESC_VER_2_3;
ring->rx_mini_max_pending = 0;
ring->rx_jumbo_max_pending = 0;
ring->tx_max_pending = (np->desc_ver == DESC_VER_1) ? RING_MAX_DESC_VER_1 : RING_MAX_DESC_VER_2_3;
ring->rx_pending = np->rx_ring_size;
ring->rx_mini_pending = 0;
ring->rx_jumbo_pending = 0;
ring->tx_pending = np->tx_ring_size;
}
static int nv_set_ringparam(struct net_device *dev, struct ethtool_ringparam* ring)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u8 *rxtx_ring, *rx_skbuff, *tx_skbuff;
dma_addr_t ring_addr;
if (ring->rx_pending < RX_RING_MIN ||
ring->tx_pending < TX_RING_MIN ||
ring->rx_mini_pending != 0 ||
ring->rx_jumbo_pending != 0 ||
(np->desc_ver == DESC_VER_1 &&
(ring->rx_pending > RING_MAX_DESC_VER_1 ||
ring->tx_pending > RING_MAX_DESC_VER_1)) ||
(np->desc_ver != DESC_VER_1 &&
(ring->rx_pending > RING_MAX_DESC_VER_2_3 ||
ring->tx_pending > RING_MAX_DESC_VER_2_3))) {
return -EINVAL;
}
/* allocate new rings */
if (!nv_optimized(np)) {
rxtx_ring = pci_alloc_consistent(np->pci_dev,
sizeof(struct ring_desc) * (ring->rx_pending + ring->tx_pending),
&ring_addr);
} else {
rxtx_ring = pci_alloc_consistent(np->pci_dev,
sizeof(struct ring_desc_ex) * (ring->rx_pending + ring->tx_pending),
&ring_addr);
}
rx_skbuff = kmalloc(sizeof(struct nv_skb_map) * ring->rx_pending, GFP_KERNEL);
tx_skbuff = kmalloc(sizeof(struct nv_skb_map) * ring->tx_pending, GFP_KERNEL);
if (!rxtx_ring || !rx_skbuff || !tx_skbuff) {
/* fall back to old rings */
if (!nv_optimized(np)) {
if (rxtx_ring)
pci_free_consistent(np->pci_dev, sizeof(struct ring_desc) * (ring->rx_pending + ring->tx_pending),
rxtx_ring, ring_addr);
} else {
if (rxtx_ring)
pci_free_consistent(np->pci_dev, sizeof(struct ring_desc_ex) * (ring->rx_pending + ring->tx_pending),
rxtx_ring, ring_addr);
}
kfree(rx_skbuff);
kfree(tx_skbuff);
goto exit;
}
if (netif_running(dev)) {
nv_disable_irq(dev);
nv_napi_disable(dev);
netif_tx_lock_bh(dev);
netif_addr_lock(dev);
spin_lock(&np->lock);
/* stop engines */
nv_stop_rxtx(dev);
nv_txrx_reset(dev);
/* drain queues */
nv_drain_rxtx(dev);
/* delete queues */
free_rings(dev);
}
/* set new values */
np->rx_ring_size = ring->rx_pending;
np->tx_ring_size = ring->tx_pending;
if (!nv_optimized(np)) {
np->rx_ring.orig = (struct ring_desc *)rxtx_ring;
np->tx_ring.orig = &np->rx_ring.orig[np->rx_ring_size];
} else {
np->rx_ring.ex = (struct ring_desc_ex *)rxtx_ring;
np->tx_ring.ex = &np->rx_ring.ex[np->rx_ring_size];
}
np->rx_skb = (struct nv_skb_map *)rx_skbuff;
np->tx_skb = (struct nv_skb_map *)tx_skbuff;
np->ring_addr = ring_addr;
memset(np->rx_skb, 0, sizeof(struct nv_skb_map) * np->rx_ring_size);
memset(np->tx_skb, 0, sizeof(struct nv_skb_map) * np->tx_ring_size);
if (netif_running(dev)) {
/* reinit driver view of the queues */
set_bufsize(dev);
if (nv_init_ring(dev)) {
if (!np->in_shutdown)
mod_timer(&np->oom_kick, jiffies + OOM_REFILL);
}
/* reinit nic view of the queues */
writel(np->rx_buf_sz, base + NvRegOffloadConfig);
setup_hw_rings(dev, NV_SETUP_RX_RING | NV_SETUP_TX_RING);
writel(((np->rx_ring_size-1) << NVREG_RINGSZ_RXSHIFT) + ((np->tx_ring_size-1) << NVREG_RINGSZ_TXSHIFT),
base + NvRegRingSizes);
pci_push(base);
writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl);
pci_push(base);
/* restart engines */
nv_start_rxtx(dev);
spin_unlock(&np->lock);
netif_addr_unlock(dev);
netif_tx_unlock_bh(dev);
nv_napi_enable(dev);
nv_enable_irq(dev);
}
return 0;
exit:
return -ENOMEM;
}
static void nv_get_pauseparam(struct net_device *dev, struct ethtool_pauseparam* pause)
{
struct fe_priv *np = netdev_priv(dev);
pause->autoneg = (np->pause_flags & NV_PAUSEFRAME_AUTONEG) != 0;
pause->rx_pause = (np->pause_flags & NV_PAUSEFRAME_RX_ENABLE) != 0;
pause->tx_pause = (np->pause_flags & NV_PAUSEFRAME_TX_ENABLE) != 0;
}
static int nv_set_pauseparam(struct net_device *dev, struct ethtool_pauseparam* pause)
{
struct fe_priv *np = netdev_priv(dev);
int adv, bmcr;
if ((!np->autoneg && np->duplex == 0) ||
(np->autoneg && !pause->autoneg && np->duplex == 0)) {
netdev_info(dev, "can not set pause settings when forced link is in half duplex\n");
return -EINVAL;
}
if (pause->tx_pause && !(np->pause_flags & NV_PAUSEFRAME_TX_CAPABLE)) {
netdev_info(dev, "hardware does not support tx pause frames\n");
return -EINVAL;
}
netif_carrier_off(dev);
if (netif_running(dev)) {
nv_disable_irq(dev);
netif_tx_lock_bh(dev);
netif_addr_lock(dev);
spin_lock(&np->lock);
/* stop engines */
nv_stop_rxtx(dev);
spin_unlock(&np->lock);
netif_addr_unlock(dev);
netif_tx_unlock_bh(dev);
}
np->pause_flags &= ~(NV_PAUSEFRAME_RX_REQ|NV_PAUSEFRAME_TX_REQ);
if (pause->rx_pause)
np->pause_flags |= NV_PAUSEFRAME_RX_REQ;
if (pause->tx_pause)
np->pause_flags |= NV_PAUSEFRAME_TX_REQ;
if (np->autoneg && pause->autoneg) {
np->pause_flags |= NV_PAUSEFRAME_AUTONEG;
adv = mii_rw(dev, np->phyaddr, MII_ADVERTISE, MII_READ);
adv &= ~(ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM);
if (np->pause_flags & NV_PAUSEFRAME_RX_REQ) /* for rx we set both advertisements but disable tx pause */
adv |= ADVERTISE_PAUSE_CAP | ADVERTISE_PAUSE_ASYM;
if (np->pause_flags & NV_PAUSEFRAME_TX_REQ)
adv |= ADVERTISE_PAUSE_ASYM;
mii_rw(dev, np->phyaddr, MII_ADVERTISE, adv);
if (netif_running(dev))
netdev_info(dev, "link down\n");
bmcr = mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ);
bmcr |= (BMCR_ANENABLE | BMCR_ANRESTART);
mii_rw(dev, np->phyaddr, MII_BMCR, bmcr);
} else {
np->pause_flags &= ~(NV_PAUSEFRAME_AUTONEG|NV_PAUSEFRAME_RX_ENABLE|NV_PAUSEFRAME_TX_ENABLE);
if (pause->rx_pause)
np->pause_flags |= NV_PAUSEFRAME_RX_ENABLE;
if (pause->tx_pause)
np->pause_flags |= NV_PAUSEFRAME_TX_ENABLE;
if (!netif_running(dev))
nv_update_linkspeed(dev);
else
nv_update_pause(dev, np->pause_flags);
}
if (netif_running(dev)) {
nv_start_rxtx(dev);
nv_enable_irq(dev);
}
return 0;
}
static u32 nv_fix_features(struct net_device *dev, u32 features)
{
/* vlan is dependent on rx checksum offload */
if (features & (NETIF_F_HW_VLAN_TX|NETIF_F_HW_VLAN_RX))
features |= NETIF_F_RXCSUM;
return features;
}
static int nv_set_features(struct net_device *dev, u32 features)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 changed = dev->features ^ features;
if (changed & NETIF_F_RXCSUM) {
spin_lock_irq(&np->lock);
if (features & NETIF_F_RXCSUM)
np->txrxctl_bits |= NVREG_TXRXCTL_RXCHECK;
else
np->txrxctl_bits &= ~NVREG_TXRXCTL_RXCHECK;
if (netif_running(dev))
writel(np->txrxctl_bits, base + NvRegTxRxControl);
spin_unlock_irq(&np->lock);
}
return 0;
}
static int nv_get_sset_count(struct net_device *dev, int sset)
{
struct fe_priv *np = netdev_priv(dev);
switch (sset) {
case ETH_SS_TEST:
if (np->driver_data & DEV_HAS_TEST_EXTENDED)
return NV_TEST_COUNT_EXTENDED;
else
return NV_TEST_COUNT_BASE;
case ETH_SS_STATS:
if (np->driver_data & DEV_HAS_STATISTICS_V3)
return NV_DEV_STATISTICS_V3_COUNT;
else if (np->driver_data & DEV_HAS_STATISTICS_V2)
return NV_DEV_STATISTICS_V2_COUNT;
else if (np->driver_data & DEV_HAS_STATISTICS_V1)
return NV_DEV_STATISTICS_V1_COUNT;
else
return 0;
default:
return -EOPNOTSUPP;
}
}
static void nv_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *estats, u64 *buffer)
{
struct fe_priv *np = netdev_priv(dev);
/* update stats */
nv_do_stats_poll((unsigned long)dev);
memcpy(buffer, &np->estats, nv_get_sset_count(dev, ETH_SS_STATS)*sizeof(u64));
}
static int nv_link_test(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
int mii_status;
mii_rw(dev, np->phyaddr, MII_BMSR, MII_READ);
mii_status = mii_rw(dev, np->phyaddr, MII_BMSR, MII_READ);
/* check phy link status */
if (!(mii_status & BMSR_LSTATUS))
return 0;
else
return 1;
}
static int nv_register_test(struct net_device *dev)
{
u8 __iomem *base = get_hwbase(dev);
int i = 0;
u32 orig_read, new_read;
do {
orig_read = readl(base + nv_registers_test[i].reg);
/* xor with mask to toggle bits */
orig_read ^= nv_registers_test[i].mask;
writel(orig_read, base + nv_registers_test[i].reg);
new_read = readl(base + nv_registers_test[i].reg);
if ((new_read & nv_registers_test[i].mask) != (orig_read & nv_registers_test[i].mask))
return 0;
/* restore original value */
orig_read ^= nv_registers_test[i].mask;
writel(orig_read, base + nv_registers_test[i].reg);
} while (nv_registers_test[++i].reg != 0);
return 1;
}
static int nv_interrupt_test(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
int ret = 1;
int testcnt;
u32 save_msi_flags, save_poll_interval = 0;
if (netif_running(dev)) {
/* free current irq */
nv_free_irq(dev);
save_poll_interval = readl(base+NvRegPollingInterval);
}
/* flag to test interrupt handler */
np->intr_test = 0;
/* setup test irq */
save_msi_flags = np->msi_flags;
np->msi_flags &= ~NV_MSI_X_VECTORS_MASK;
np->msi_flags |= 0x001; /* setup 1 vector */
if (nv_request_irq(dev, 1))
return 0;
/* setup timer interrupt */
writel(NVREG_POLL_DEFAULT_CPU, base + NvRegPollingInterval);
writel(NVREG_UNKSETUP6_VAL, base + NvRegUnknownSetupReg6);
nv_enable_hw_interrupts(dev, NVREG_IRQ_TIMER);
/* wait for at least one interrupt */
msleep(100);
spin_lock_irq(&np->lock);
/* flag should be set within ISR */
testcnt = np->intr_test;
if (!testcnt)
ret = 2;
nv_disable_hw_interrupts(dev, NVREG_IRQ_TIMER);
if (!(np->msi_flags & NV_MSI_X_ENABLED))
writel(NVREG_IRQSTAT_MASK, base + NvRegIrqStatus);
else
writel(NVREG_IRQSTAT_MASK, base + NvRegMSIXIrqStatus);
spin_unlock_irq(&np->lock);
nv_free_irq(dev);
np->msi_flags = save_msi_flags;
if (netif_running(dev)) {
writel(save_poll_interval, base + NvRegPollingInterval);
writel(NVREG_UNKSETUP6_VAL, base + NvRegUnknownSetupReg6);
/* restore original irq */
if (nv_request_irq(dev, 0))
return 0;
}
return ret;
}
static int nv_loopback_test(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
struct sk_buff *tx_skb, *rx_skb;
dma_addr_t test_dma_addr;
u32 tx_flags_extra = (np->desc_ver == DESC_VER_1 ? NV_TX_LASTPACKET : NV_TX2_LASTPACKET);
u32 flags;
int len, i, pkt_len;
u8 *pkt_data;
u32 filter_flags = 0;
u32 misc1_flags = 0;
int ret = 1;
if (netif_running(dev)) {
nv_disable_irq(dev);
filter_flags = readl(base + NvRegPacketFilterFlags);
misc1_flags = readl(base + NvRegMisc1);
} else {
nv_txrx_reset(dev);
}
/* reinit driver view of the rx queue */
set_bufsize(dev);
nv_init_ring(dev);
/* setup hardware for loopback */
writel(NVREG_MISC1_FORCE, base + NvRegMisc1);
writel(NVREG_PFF_ALWAYS | NVREG_PFF_LOOPBACK, base + NvRegPacketFilterFlags);
/* reinit nic view of the rx queue */
writel(np->rx_buf_sz, base + NvRegOffloadConfig);
setup_hw_rings(dev, NV_SETUP_RX_RING | NV_SETUP_TX_RING);
writel(((np->rx_ring_size-1) << NVREG_RINGSZ_RXSHIFT) + ((np->tx_ring_size-1) << NVREG_RINGSZ_TXSHIFT),
base + NvRegRingSizes);
pci_push(base);
/* restart rx engine */
nv_start_rxtx(dev);
/* setup packet for tx */
pkt_len = ETH_DATA_LEN;
tx_skb = dev_alloc_skb(pkt_len);
if (!tx_skb) {
netdev_err(dev, "dev_alloc_skb() failed during loopback test\n");
ret = 0;
goto out;
}
test_dma_addr = pci_map_single(np->pci_dev, tx_skb->data,
skb_tailroom(tx_skb),
PCI_DMA_FROMDEVICE);
pkt_data = skb_put(tx_skb, pkt_len);
for (i = 0; i < pkt_len; i++)
pkt_data[i] = (u8)(i & 0xff);
if (!nv_optimized(np)) {
np->tx_ring.orig[0].buf = cpu_to_le32(test_dma_addr);
np->tx_ring.orig[0].flaglen = cpu_to_le32((pkt_len-1) | np->tx_flags | tx_flags_extra);
} else {
np->tx_ring.ex[0].bufhigh = cpu_to_le32(dma_high(test_dma_addr));
np->tx_ring.ex[0].buflow = cpu_to_le32(dma_low(test_dma_addr));
np->tx_ring.ex[0].flaglen = cpu_to_le32((pkt_len-1) | np->tx_flags | tx_flags_extra);
}
writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl);
pci_push(get_hwbase(dev));
msleep(500);
/* check for rx of the packet */
if (!nv_optimized(np)) {
flags = le32_to_cpu(np->rx_ring.orig[0].flaglen);
len = nv_descr_getlength(&np->rx_ring.orig[0], np->desc_ver);
} else {
flags = le32_to_cpu(np->rx_ring.ex[0].flaglen);
len = nv_descr_getlength_ex(&np->rx_ring.ex[0], np->desc_ver);
}
if (flags & NV_RX_AVAIL) {
ret = 0;
} else if (np->desc_ver == DESC_VER_1) {
if (flags & NV_RX_ERROR)
ret = 0;
} else {
if (flags & NV_RX2_ERROR)
ret = 0;
}
if (ret) {
if (len != pkt_len) {
ret = 0;
} else {
rx_skb = np->rx_skb[0].skb;
for (i = 0; i < pkt_len; i++) {
if (rx_skb->data[i] != (u8)(i & 0xff)) {
ret = 0;
break;
}
}
}
}
pci_unmap_single(np->pci_dev, test_dma_addr,
(skb_end_pointer(tx_skb) - tx_skb->data),
PCI_DMA_TODEVICE);
dev_kfree_skb_any(tx_skb);
out:
/* stop engines */
nv_stop_rxtx(dev);
nv_txrx_reset(dev);
/* drain rx queue */
nv_drain_rxtx(dev);
if (netif_running(dev)) {
writel(misc1_flags, base + NvRegMisc1);
writel(filter_flags, base + NvRegPacketFilterFlags);
nv_enable_irq(dev);
}
return ret;
}
static void nv_self_test(struct net_device *dev, struct ethtool_test *test, u64 *buffer)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
int result;
memset(buffer, 0, nv_get_sset_count(dev, ETH_SS_TEST)*sizeof(u64));
if (!nv_link_test(dev)) {
test->flags |= ETH_TEST_FL_FAILED;
buffer[0] = 1;
}
if (test->flags & ETH_TEST_FL_OFFLINE) {
if (netif_running(dev)) {
netif_stop_queue(dev);
nv_napi_disable(dev);
netif_tx_lock_bh(dev);
netif_addr_lock(dev);
spin_lock_irq(&np->lock);
nv_disable_hw_interrupts(dev, np->irqmask);
if (!(np->msi_flags & NV_MSI_X_ENABLED))
writel(NVREG_IRQSTAT_MASK, base + NvRegIrqStatus);
else
writel(NVREG_IRQSTAT_MASK, base + NvRegMSIXIrqStatus);
/* stop engines */
nv_stop_rxtx(dev);
nv_txrx_reset(dev);
/* drain rx queue */
nv_drain_rxtx(dev);
spin_unlock_irq(&np->lock);
netif_addr_unlock(dev);
netif_tx_unlock_bh(dev);
}
if (!nv_register_test(dev)) {
test->flags |= ETH_TEST_FL_FAILED;
buffer[1] = 1;
}
result = nv_interrupt_test(dev);
if (result != 1) {
test->flags |= ETH_TEST_FL_FAILED;
buffer[2] = 1;
}
if (result == 0) {
/* bail out */
return;
}
if (!nv_loopback_test(dev)) {
test->flags |= ETH_TEST_FL_FAILED;
buffer[3] = 1;
}
if (netif_running(dev)) {
/* reinit driver view of the rx queue */
set_bufsize(dev);
if (nv_init_ring(dev)) {
if (!np->in_shutdown)
mod_timer(&np->oom_kick, jiffies + OOM_REFILL);
}
/* reinit nic view of the rx queue */
writel(np->rx_buf_sz, base + NvRegOffloadConfig);
setup_hw_rings(dev, NV_SETUP_RX_RING | NV_SETUP_TX_RING);
writel(((np->rx_ring_size-1) << NVREG_RINGSZ_RXSHIFT) + ((np->tx_ring_size-1) << NVREG_RINGSZ_TXSHIFT),
base + NvRegRingSizes);
pci_push(base);
writel(NVREG_TXRXCTL_KICK|np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl);
pci_push(base);
/* restart rx engine */
nv_start_rxtx(dev);
netif_start_queue(dev);
nv_napi_enable(dev);
nv_enable_hw_interrupts(dev, np->irqmask);
}
}
}
static void nv_get_strings(struct net_device *dev, u32 stringset, u8 *buffer)
{
switch (stringset) {
case ETH_SS_STATS:
memcpy(buffer, &nv_estats_str, nv_get_sset_count(dev, ETH_SS_STATS)*sizeof(struct nv_ethtool_str));
break;
case ETH_SS_TEST:
memcpy(buffer, &nv_etests_str, nv_get_sset_count(dev, ETH_SS_TEST)*sizeof(struct nv_ethtool_str));
break;
}
}
static const struct ethtool_ops ops = {
.get_drvinfo = nv_get_drvinfo,
.get_link = ethtool_op_get_link,
.get_wol = nv_get_wol,
.set_wol = nv_set_wol,
.get_settings = nv_get_settings,
.set_settings = nv_set_settings,
.get_regs_len = nv_get_regs_len,
.get_regs = nv_get_regs,
.nway_reset = nv_nway_reset,
.get_ringparam = nv_get_ringparam,
.set_ringparam = nv_set_ringparam,
.get_pauseparam = nv_get_pauseparam,
.set_pauseparam = nv_set_pauseparam,
.get_strings = nv_get_strings,
.get_ethtool_stats = nv_get_ethtool_stats,
.get_sset_count = nv_get_sset_count,
.self_test = nv_self_test,
};
static void nv_vlan_rx_register(struct net_device *dev, struct vlan_group *grp)
{
struct fe_priv *np = get_nvpriv(dev);
spin_lock_irq(&np->lock);
/* save vlan group */
np->vlangrp = grp;
if (grp) {
/* enable vlan on MAC */
np->txrxctl_bits |= NVREG_TXRXCTL_VLANSTRIP | NVREG_TXRXCTL_VLANINS;
} else {
/* disable vlan on MAC */
np->txrxctl_bits &= ~NVREG_TXRXCTL_VLANSTRIP;
np->txrxctl_bits &= ~NVREG_TXRXCTL_VLANINS;
}
writel(np->txrxctl_bits, get_hwbase(dev) + NvRegTxRxControl);
spin_unlock_irq(&np->lock);
}
/* The mgmt unit and driver use a semaphore to access the phy during init */
static int nv_mgmt_acquire_sema(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
int i;
u32 tx_ctrl, mgmt_sema;
for (i = 0; i < 10; i++) {
mgmt_sema = readl(base + NvRegTransmitterControl) & NVREG_XMITCTL_MGMT_SEMA_MASK;
if (mgmt_sema == NVREG_XMITCTL_MGMT_SEMA_FREE)
break;
msleep(500);
}
if (mgmt_sema != NVREG_XMITCTL_MGMT_SEMA_FREE)
return 0;
for (i = 0; i < 2; i++) {
tx_ctrl = readl(base + NvRegTransmitterControl);
tx_ctrl |= NVREG_XMITCTL_HOST_SEMA_ACQ;
writel(tx_ctrl, base + NvRegTransmitterControl);
/* verify that semaphore was acquired */
tx_ctrl = readl(base + NvRegTransmitterControl);
if (((tx_ctrl & NVREG_XMITCTL_HOST_SEMA_MASK) == NVREG_XMITCTL_HOST_SEMA_ACQ) &&
((tx_ctrl & NVREG_XMITCTL_MGMT_SEMA_MASK) == NVREG_XMITCTL_MGMT_SEMA_FREE)) {
np->mgmt_sema = 1;
return 1;
} else
udelay(50);
}
return 0;
}
static void nv_mgmt_release_sema(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 tx_ctrl;
if (np->driver_data & DEV_HAS_MGMT_UNIT) {
if (np->mgmt_sema) {
tx_ctrl = readl(base + NvRegTransmitterControl);
tx_ctrl &= ~NVREG_XMITCTL_HOST_SEMA_ACQ;
writel(tx_ctrl, base + NvRegTransmitterControl);
}
}
}
static int nv_mgmt_get_version(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
u32 data_ready = readl(base + NvRegTransmitterControl);
u32 data_ready2 = 0;
unsigned long start;
int ready = 0;
writel(NVREG_MGMTUNITGETVERSION, base + NvRegMgmtUnitGetVersion);
writel(data_ready ^ NVREG_XMITCTL_DATA_START, base + NvRegTransmitterControl);
start = jiffies;
while (time_before(jiffies, start + 5*HZ)) {
data_ready2 = readl(base + NvRegTransmitterControl);
if ((data_ready & NVREG_XMITCTL_DATA_READY) != (data_ready2 & NVREG_XMITCTL_DATA_READY)) {
ready = 1;
break;
}
schedule_timeout_uninterruptible(1);
}
if (!ready || (data_ready2 & NVREG_XMITCTL_DATA_ERROR))
return 0;
np->mgmt_version = readl(base + NvRegMgmtUnitVersion) & NVREG_MGMTUNITVERSION;
return 1;
}
static int nv_open(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
int ret = 1;
int oom, i;
u32 low;
/* power up phy */
mii_rw(dev, np->phyaddr, MII_BMCR,
mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ) & ~BMCR_PDOWN);
nv_txrx_gate(dev, false);
/* erase previous misconfiguration */
if (np->driver_data & DEV_HAS_POWER_CNTRL)
nv_mac_reset(dev);
writel(NVREG_MCASTADDRA_FORCE, base + NvRegMulticastAddrA);
writel(0, base + NvRegMulticastAddrB);
writel(NVREG_MCASTMASKA_NONE, base + NvRegMulticastMaskA);
writel(NVREG_MCASTMASKB_NONE, base + NvRegMulticastMaskB);
writel(0, base + NvRegPacketFilterFlags);
writel(0, base + NvRegTransmitterControl);
writel(0, base + NvRegReceiverControl);
writel(0, base + NvRegAdapterControl);
if (np->pause_flags & NV_PAUSEFRAME_TX_CAPABLE)
writel(NVREG_TX_PAUSEFRAME_DISABLE, base + NvRegTxPauseFrame);
/* initialize descriptor rings */
set_bufsize(dev);
oom = nv_init_ring(dev);
writel(0, base + NvRegLinkSpeed);
writel(readl(base + NvRegTransmitPoll) & NVREG_TRANSMITPOLL_MAC_ADDR_REV, base + NvRegTransmitPoll);
nv_txrx_reset(dev);
writel(0, base + NvRegUnknownSetupReg6);
np->in_shutdown = 0;
/* give hw rings */
setup_hw_rings(dev, NV_SETUP_RX_RING | NV_SETUP_TX_RING);
writel(((np->rx_ring_size-1) << NVREG_RINGSZ_RXSHIFT) + ((np->tx_ring_size-1) << NVREG_RINGSZ_TXSHIFT),
base + NvRegRingSizes);
writel(np->linkspeed, base + NvRegLinkSpeed);
if (np->desc_ver == DESC_VER_1)
writel(NVREG_TX_WM_DESC1_DEFAULT, base + NvRegTxWatermark);
else
writel(NVREG_TX_WM_DESC2_3_DEFAULT, base + NvRegTxWatermark);
writel(np->txrxctl_bits, base + NvRegTxRxControl);
writel(np->vlanctl_bits, base + NvRegVlanControl);
pci_push(base);
writel(NVREG_TXRXCTL_BIT1|np->txrxctl_bits, base + NvRegTxRxControl);
if (reg_delay(dev, NvRegUnknownSetupReg5,
NVREG_UNKSETUP5_BIT31, NVREG_UNKSETUP5_BIT31,
NV_SETUP5_DELAY, NV_SETUP5_DELAYMAX))
netdev_info(dev,
"%s: SetupReg5, Bit 31 remained off\n", __func__);
writel(0, base + NvRegMIIMask);
writel(NVREG_IRQSTAT_MASK, base + NvRegIrqStatus);
writel(NVREG_MIISTAT_MASK_ALL, base + NvRegMIIStatus);
writel(NVREG_MISC1_FORCE | NVREG_MISC1_HD, base + NvRegMisc1);
writel(readl(base + NvRegTransmitterStatus), base + NvRegTransmitterStatus);
writel(NVREG_PFF_ALWAYS, base + NvRegPacketFilterFlags);
writel(np->rx_buf_sz, base + NvRegOffloadConfig);
writel(readl(base + NvRegReceiverStatus), base + NvRegReceiverStatus);
get_random_bytes(&low, sizeof(low));
low &= NVREG_SLOTTIME_MASK;
if (np->desc_ver == DESC_VER_1) {
writel(low|NVREG_SLOTTIME_DEFAULT, base + NvRegSlotTime);
} else {
if (!(np->driver_data & DEV_HAS_GEAR_MODE)) {
/* setup legacy backoff */
writel(NVREG_SLOTTIME_LEGBF_ENABLED|NVREG_SLOTTIME_10_100_FULL|low, base + NvRegSlotTime);
} else {
writel(NVREG_SLOTTIME_10_100_FULL, base + NvRegSlotTime);
nv_gear_backoff_reseed(dev);
}
}
writel(NVREG_TX_DEFERRAL_DEFAULT, base + NvRegTxDeferral);
writel(NVREG_RX_DEFERRAL_DEFAULT, base + NvRegRxDeferral);
if (poll_interval == -1) {
if (optimization_mode == NV_OPTIMIZATION_MODE_THROUGHPUT)
writel(NVREG_POLL_DEFAULT_THROUGHPUT, base + NvRegPollingInterval);
else
writel(NVREG_POLL_DEFAULT_CPU, base + NvRegPollingInterval);
} else
writel(poll_interval & 0xFFFF, base + NvRegPollingInterval);
writel(NVREG_UNKSETUP6_VAL, base + NvRegUnknownSetupReg6);
writel((np->phyaddr << NVREG_ADAPTCTL_PHYSHIFT)|NVREG_ADAPTCTL_PHYVALID|NVREG_ADAPTCTL_RUNNING,
base + NvRegAdapterControl);
writel(NVREG_MIISPEED_BIT8|NVREG_MIIDELAY, base + NvRegMIISpeed);
writel(NVREG_MII_LINKCHANGE, base + NvRegMIIMask);
if (np->wolenabled)
writel(NVREG_WAKEUPFLAGS_ENABLE , base + NvRegWakeUpFlags);
i = readl(base + NvRegPowerState);
if ((i & NVREG_POWERSTATE_POWEREDUP) == 0)
writel(NVREG_POWERSTATE_POWEREDUP|i, base + NvRegPowerState);
pci_push(base);
udelay(10);
writel(readl(base + NvRegPowerState) | NVREG_POWERSTATE_VALID, base + NvRegPowerState);
nv_disable_hw_interrupts(dev, np->irqmask);
pci_push(base);
writel(NVREG_MIISTAT_MASK_ALL, base + NvRegMIIStatus);
writel(NVREG_IRQSTAT_MASK, base + NvRegIrqStatus);
pci_push(base);
if (nv_request_irq(dev, 0))
goto out_drain;
/* ask for interrupts */
nv_enable_hw_interrupts(dev, np->irqmask);
spin_lock_irq(&np->lock);
writel(NVREG_MCASTADDRA_FORCE, base + NvRegMulticastAddrA);
writel(0, base + NvRegMulticastAddrB);
writel(NVREG_MCASTMASKA_NONE, base + NvRegMulticastMaskA);
writel(NVREG_MCASTMASKB_NONE, base + NvRegMulticastMaskB);
writel(NVREG_PFF_ALWAYS|NVREG_PFF_MYADDR, base + NvRegPacketFilterFlags);
/* One manual link speed update: Interrupts are enabled, future link
* speed changes cause interrupts and are handled by nv_link_irq().
*/
{
u32 miistat;
miistat = readl(base + NvRegMIIStatus);
writel(NVREG_MIISTAT_MASK_ALL, base + NvRegMIIStatus);
}
/* set linkspeed to invalid value, thus force nv_update_linkspeed
* to init hw */
np->linkspeed = 0;
ret = nv_update_linkspeed(dev);
nv_start_rxtx(dev);
netif_start_queue(dev);
nv_napi_enable(dev);
if (ret) {
netif_carrier_on(dev);
} else {
netdev_info(dev, "no link during initialization\n");
netif_carrier_off(dev);
}
if (oom)
mod_timer(&np->oom_kick, jiffies + OOM_REFILL);
/* start statistics timer */
if (np->driver_data & (DEV_HAS_STATISTICS_V1|DEV_HAS_STATISTICS_V2|DEV_HAS_STATISTICS_V3))
mod_timer(&np->stats_poll,
round_jiffies(jiffies + STATS_INTERVAL));
spin_unlock_irq(&np->lock);
return 0;
out_drain:
nv_drain_rxtx(dev);
return ret;
}
static int nv_close(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base;
spin_lock_irq(&np->lock);
np->in_shutdown = 1;
spin_unlock_irq(&np->lock);
nv_napi_disable(dev);
synchronize_irq(np->pci_dev->irq);
del_timer_sync(&np->oom_kick);
del_timer_sync(&np->nic_poll);
del_timer_sync(&np->stats_poll);
netif_stop_queue(dev);
spin_lock_irq(&np->lock);
nv_stop_rxtx(dev);
nv_txrx_reset(dev);
/* disable interrupts on the nic or we will lock up */
base = get_hwbase(dev);
nv_disable_hw_interrupts(dev, np->irqmask);
pci_push(base);
spin_unlock_irq(&np->lock);
nv_free_irq(dev);
nv_drain_rxtx(dev);
if (np->wolenabled || !phy_power_down) {
nv_txrx_gate(dev, false);
writel(NVREG_PFF_ALWAYS|NVREG_PFF_MYADDR, base + NvRegPacketFilterFlags);
nv_start_rx(dev);
} else {
/* power down phy */
mii_rw(dev, np->phyaddr, MII_BMCR,
mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ)|BMCR_PDOWN);
nv_txrx_gate(dev, true);
}
/* FIXME: power down nic */
return 0;
}
static const struct net_device_ops nv_netdev_ops = {
.ndo_open = nv_open,
.ndo_stop = nv_close,
.ndo_get_stats = nv_get_stats,
.ndo_start_xmit = nv_start_xmit,
.ndo_tx_timeout = nv_tx_timeout,
.ndo_change_mtu = nv_change_mtu,
.ndo_fix_features = nv_fix_features,
.ndo_set_features = nv_set_features,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = nv_set_mac_address,
.ndo_set_multicast_list = nv_set_multicast,
.ndo_vlan_rx_register = nv_vlan_rx_register,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = nv_poll_controller,
#endif
};
static const struct net_device_ops nv_netdev_ops_optimized = {
.ndo_open = nv_open,
.ndo_stop = nv_close,
.ndo_get_stats = nv_get_stats,
.ndo_start_xmit = nv_start_xmit_optimized,
.ndo_tx_timeout = nv_tx_timeout,
.ndo_change_mtu = nv_change_mtu,
.ndo_fix_features = nv_fix_features,
.ndo_set_features = nv_set_features,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = nv_set_mac_address,
.ndo_set_multicast_list = nv_set_multicast,
.ndo_vlan_rx_register = nv_vlan_rx_register,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = nv_poll_controller,
#endif
};
static int __devinit nv_probe(struct pci_dev *pci_dev, const struct pci_device_id *id)
{
struct net_device *dev;
struct fe_priv *np;
unsigned long addr;
u8 __iomem *base;
int err, i;
u32 powerstate, txreg;
u32 phystate_orig = 0, phystate;
int phyinitialized = 0;
static int printed_version;
if (!printed_version++)
pr_info("Reverse Engineered nForce ethernet driver. Version %s.\n",
FORCEDETH_VERSION);
dev = alloc_etherdev(sizeof(struct fe_priv));
err = -ENOMEM;
if (!dev)
goto out;
np = netdev_priv(dev);
np->dev = dev;
np->pci_dev = pci_dev;
spin_lock_init(&np->lock);
SET_NETDEV_DEV(dev, &pci_dev->dev);
init_timer(&np->oom_kick);
np->oom_kick.data = (unsigned long) dev;
np->oom_kick.function = nv_do_rx_refill; /* timer handler */
init_timer(&np->nic_poll);
np->nic_poll.data = (unsigned long) dev;
np->nic_poll.function = nv_do_nic_poll; /* timer handler */
init_timer(&np->stats_poll);
np->stats_poll.data = (unsigned long) dev;
np->stats_poll.function = nv_do_stats_poll; /* timer handler */
err = pci_enable_device(pci_dev);
if (err)
goto out_free;
pci_set_master(pci_dev);
err = pci_request_regions(pci_dev, DRV_NAME);
if (err < 0)
goto out_disable;
if (id->driver_data & (DEV_HAS_VLAN|DEV_HAS_MSI_X|DEV_HAS_POWER_CNTRL|DEV_HAS_STATISTICS_V2|DEV_HAS_STATISTICS_V3))
np->register_size = NV_PCI_REGSZ_VER3;
else if (id->driver_data & DEV_HAS_STATISTICS_V1)
np->register_size = NV_PCI_REGSZ_VER2;
else
np->register_size = NV_PCI_REGSZ_VER1;
err = -EINVAL;
addr = 0;
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
if (pci_resource_flags(pci_dev, i) & IORESOURCE_MEM &&
pci_resource_len(pci_dev, i) >= np->register_size) {
addr = pci_resource_start(pci_dev, i);
break;
}
}
if (i == DEVICE_COUNT_RESOURCE) {
dev_info(&pci_dev->dev, "Couldn't find register window\n");
goto out_relreg;
}
/* copy of driver data */
np->driver_data = id->driver_data;
/* copy of device id */
np->device_id = id->device;
/* handle different descriptor versions */
if (id->driver_data & DEV_HAS_HIGH_DMA) {
/* packet format 3: supports 40-bit addressing */
np->desc_ver = DESC_VER_3;
np->txrxctl_bits = NVREG_TXRXCTL_DESC_3;
if (dma_64bit) {
if (pci_set_dma_mask(pci_dev, DMA_BIT_MASK(39)))
dev_info(&pci_dev->dev,
"64-bit DMA failed, using 32-bit addressing\n");
else
dev->features |= NETIF_F_HIGHDMA;
if (pci_set_consistent_dma_mask(pci_dev, DMA_BIT_MASK(39))) {
dev_info(&pci_dev->dev,
"64-bit DMA (consistent) failed, using 32-bit ring buffers\n");
}
}
} else if (id->driver_data & DEV_HAS_LARGEDESC) {
/* packet format 2: supports jumbo frames */
np->desc_ver = DESC_VER_2;
np->txrxctl_bits = NVREG_TXRXCTL_DESC_2;
} else {
/* original packet format */
np->desc_ver = DESC_VER_1;
np->txrxctl_bits = NVREG_TXRXCTL_DESC_1;
}
np->pkt_limit = NV_PKTLIMIT_1;
if (id->driver_data & DEV_HAS_LARGEDESC)
np->pkt_limit = NV_PKTLIMIT_2;
if (id->driver_data & DEV_HAS_CHECKSUM) {
np->txrxctl_bits |= NVREG_TXRXCTL_RXCHECK;
dev->hw_features |= NETIF_F_IP_CSUM | NETIF_F_SG |
NETIF_F_TSO | NETIF_F_RXCSUM;
dev->features |= dev->hw_features;
}
np->vlanctl_bits = 0;
if (id->driver_data & DEV_HAS_VLAN) {
np->vlanctl_bits = NVREG_VLANCONTROL_ENABLE;
dev->features |= NETIF_F_HW_VLAN_RX | NETIF_F_HW_VLAN_TX;
}
np->pause_flags = NV_PAUSEFRAME_RX_CAPABLE | NV_PAUSEFRAME_RX_REQ | NV_PAUSEFRAME_AUTONEG;
if ((id->driver_data & DEV_HAS_PAUSEFRAME_TX_V1) ||
(id->driver_data & DEV_HAS_PAUSEFRAME_TX_V2) ||
(id->driver_data & DEV_HAS_PAUSEFRAME_TX_V3)) {
np->pause_flags |= NV_PAUSEFRAME_TX_CAPABLE | NV_PAUSEFRAME_TX_REQ;
}
err = -ENOMEM;
np->base = ioremap(addr, np->register_size);
if (!np->base)
goto out_relreg;
dev->base_addr = (unsigned long)np->base;
dev->irq = pci_dev->irq;
np->rx_ring_size = RX_RING_DEFAULT;
np->tx_ring_size = TX_RING_DEFAULT;
if (!nv_optimized(np)) {
np->rx_ring.orig = pci_alloc_consistent(pci_dev,
sizeof(struct ring_desc) * (np->rx_ring_size + np->tx_ring_size),
&np->ring_addr);
if (!np->rx_ring.orig)
goto out_unmap;
np->tx_ring.orig = &np->rx_ring.orig[np->rx_ring_size];
} else {
np->rx_ring.ex = pci_alloc_consistent(pci_dev,
sizeof(struct ring_desc_ex) * (np->rx_ring_size + np->tx_ring_size),
&np->ring_addr);
if (!np->rx_ring.ex)
goto out_unmap;
np->tx_ring.ex = &np->rx_ring.ex[np->rx_ring_size];
}
np->rx_skb = kcalloc(np->rx_ring_size, sizeof(struct nv_skb_map), GFP_KERNEL);
np->tx_skb = kcalloc(np->tx_ring_size, sizeof(struct nv_skb_map), GFP_KERNEL);
if (!np->rx_skb || !np->tx_skb)
goto out_freering;
if (!nv_optimized(np))
dev->netdev_ops = &nv_netdev_ops;
else
dev->netdev_ops = &nv_netdev_ops_optimized;
netif_napi_add(dev, &np->napi, nv_napi_poll, RX_WORK_PER_LOOP);
SET_ETHTOOL_OPS(dev, &ops);
dev->watchdog_timeo = NV_WATCHDOG_TIMEO;
pci_set_drvdata(pci_dev, dev);
/* read the mac address */
base = get_hwbase(dev);
np->orig_mac[0] = readl(base + NvRegMacAddrA);
np->orig_mac[1] = readl(base + NvRegMacAddrB);
/* check the workaround bit for correct mac address order */
txreg = readl(base + NvRegTransmitPoll);
if (id->driver_data & DEV_HAS_CORRECT_MACADDR) {
/* mac address is already in correct order */
dev->dev_addr[0] = (np->orig_mac[0] >> 0) & 0xff;
dev->dev_addr[1] = (np->orig_mac[0] >> 8) & 0xff;
dev->dev_addr[2] = (np->orig_mac[0] >> 16) & 0xff;
dev->dev_addr[3] = (np->orig_mac[0] >> 24) & 0xff;
dev->dev_addr[4] = (np->orig_mac[1] >> 0) & 0xff;
dev->dev_addr[5] = (np->orig_mac[1] >> 8) & 0xff;
} else if (txreg & NVREG_TRANSMITPOLL_MAC_ADDR_REV) {
/* mac address is already in correct order */
dev->dev_addr[0] = (np->orig_mac[0] >> 0) & 0xff;
dev->dev_addr[1] = (np->orig_mac[0] >> 8) & 0xff;
dev->dev_addr[2] = (np->orig_mac[0] >> 16) & 0xff;
dev->dev_addr[3] = (np->orig_mac[0] >> 24) & 0xff;
dev->dev_addr[4] = (np->orig_mac[1] >> 0) & 0xff;
dev->dev_addr[5] = (np->orig_mac[1] >> 8) & 0xff;
/*
* Set orig mac address back to the reversed version.
* This flag will be cleared during low power transition.
* Therefore, we should always put back the reversed address.
*/
np->orig_mac[0] = (dev->dev_addr[5] << 0) + (dev->dev_addr[4] << 8) +
(dev->dev_addr[3] << 16) + (dev->dev_addr[2] << 24);
np->orig_mac[1] = (dev->dev_addr[1] << 0) + (dev->dev_addr[0] << 8);
} else {
/* need to reverse mac address to correct order */
dev->dev_addr[0] = (np->orig_mac[1] >> 8) & 0xff;
dev->dev_addr[1] = (np->orig_mac[1] >> 0) & 0xff;
dev->dev_addr[2] = (np->orig_mac[0] >> 24) & 0xff;
dev->dev_addr[3] = (np->orig_mac[0] >> 16) & 0xff;
dev->dev_addr[4] = (np->orig_mac[0] >> 8) & 0xff;
dev->dev_addr[5] = (np->orig_mac[0] >> 0) & 0xff;
writel(txreg|NVREG_TRANSMITPOLL_MAC_ADDR_REV, base + NvRegTransmitPoll);
dev_dbg(&pci_dev->dev,
"%s: set workaround bit for reversed mac addr\n",
__func__);
}
memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
if (!is_valid_ether_addr(dev->perm_addr)) {
/*
* Bad mac address. At least one bios sets the mac address
* to 01:23:45:67:89:ab
*/
dev_err(&pci_dev->dev,
"Invalid MAC address detected: %pM - Please complain to your hardware vendor.\n",
dev->dev_addr);
random_ether_addr(dev->dev_addr);
dev_err(&pci_dev->dev,
"Using random MAC address: %pM\n", dev->dev_addr);
}
/* set mac address */
nv_copy_mac_to_hw(dev);
/* disable WOL */
writel(0, base + NvRegWakeUpFlags);
np->wolenabled = 0;
device_set_wakeup_enable(&pci_dev->dev, false);
if (id->driver_data & DEV_HAS_POWER_CNTRL) {
/* take phy and nic out of low power mode */
powerstate = readl(base + NvRegPowerState2);
powerstate &= ~NVREG_POWERSTATE2_POWERUP_MASK;
if ((id->driver_data & DEV_NEED_LOW_POWER_FIX) &&
pci_dev->revision >= 0xA3)
powerstate |= NVREG_POWERSTATE2_POWERUP_REV_A3;
writel(powerstate, base + NvRegPowerState2);
}
if (np->desc_ver == DESC_VER_1)
np->tx_flags = NV_TX_VALID;
else
np->tx_flags = NV_TX2_VALID;
np->msi_flags = 0;
if ((id->driver_data & DEV_HAS_MSI) && msi)
np->msi_flags |= NV_MSI_CAPABLE;
if ((id->driver_data & DEV_HAS_MSI_X) && msix) {
/* msix has had reported issues when modifying irqmask
as in the case of napi, therefore, disable for now
*/
#if 0
np->msi_flags |= NV_MSI_X_CAPABLE;
#endif
}
if (optimization_mode == NV_OPTIMIZATION_MODE_CPU) {
np->irqmask = NVREG_IRQMASK_CPU;
if (np->msi_flags & NV_MSI_X_CAPABLE) /* set number of vectors */
np->msi_flags |= 0x0001;
} else if (optimization_mode == NV_OPTIMIZATION_MODE_DYNAMIC &&
!(id->driver_data & DEV_NEED_TIMERIRQ)) {
/* start off in throughput mode */
np->irqmask = NVREG_IRQMASK_THROUGHPUT;
/* remove support for msix mode */
np->msi_flags &= ~NV_MSI_X_CAPABLE;
} else {
optimization_mode = NV_OPTIMIZATION_MODE_THROUGHPUT;
np->irqmask = NVREG_IRQMASK_THROUGHPUT;
if (np->msi_flags & NV_MSI_X_CAPABLE) /* set number of vectors */
np->msi_flags |= 0x0003;
}
if (id->driver_data & DEV_NEED_TIMERIRQ)
np->irqmask |= NVREG_IRQ_TIMER;
if (id->driver_data & DEV_NEED_LINKTIMER) {
np->need_linktimer = 1;
np->link_timeout = jiffies + LINK_TIMEOUT;
} else {
np->need_linktimer = 0;
}
/* Limit the number of tx's outstanding for hw bug */
if (id->driver_data & DEV_NEED_TX_LIMIT) {
np->tx_limit = 1;
if (((id->driver_data & DEV_NEED_TX_LIMIT2) == DEV_NEED_TX_LIMIT2) &&
pci_dev->revision >= 0xA2)
np->tx_limit = 0;
}
/* clear phy state and temporarily halt phy interrupts */
writel(0, base + NvRegMIIMask);
phystate = readl(base + NvRegAdapterControl);
if (phystate & NVREG_ADAPTCTL_RUNNING) {
phystate_orig = 1;
phystate &= ~NVREG_ADAPTCTL_RUNNING;
writel(phystate, base + NvRegAdapterControl);
}
writel(NVREG_MIISTAT_MASK_ALL, base + NvRegMIIStatus);
if (id->driver_data & DEV_HAS_MGMT_UNIT) {
/* management unit running on the mac? */
if ((readl(base + NvRegTransmitterControl) & NVREG_XMITCTL_MGMT_ST) &&
(readl(base + NvRegTransmitterControl) & NVREG_XMITCTL_SYNC_PHY_INIT) &&
nv_mgmt_acquire_sema(dev) &&
nv_mgmt_get_version(dev)) {
np->mac_in_use = 1;
if (np->mgmt_version > 0)
np->mac_in_use = readl(base + NvRegMgmtUnitControl) & NVREG_MGMTUNITCONTROL_INUSE;
/* management unit setup the phy already? */
if (np->mac_in_use &&
((readl(base + NvRegTransmitterControl) & NVREG_XMITCTL_SYNC_MASK) ==
NVREG_XMITCTL_SYNC_PHY_INIT)) {
/* phy is inited by mgmt unit */
phyinitialized = 1;
} else {
/* we need to init the phy */
}
}
}
/* find a suitable phy */
for (i = 1; i <= 32; i++) {
int id1, id2;
int phyaddr = i & 0x1F;
spin_lock_irq(&np->lock);
id1 = mii_rw(dev, phyaddr, MII_PHYSID1, MII_READ);
spin_unlock_irq(&np->lock);
if (id1 < 0 || id1 == 0xffff)
continue;
spin_lock_irq(&np->lock);
id2 = mii_rw(dev, phyaddr, MII_PHYSID2, MII_READ);
spin_unlock_irq(&np->lock);
if (id2 < 0 || id2 == 0xffff)
continue;
np->phy_model = id2 & PHYID2_MODEL_MASK;
id1 = (id1 & PHYID1_OUI_MASK) << PHYID1_OUI_SHFT;
id2 = (id2 & PHYID2_OUI_MASK) >> PHYID2_OUI_SHFT;
np->phyaddr = phyaddr;
np->phy_oui = id1 | id2;
/* Realtek hardcoded phy id1 to all zero's on certain phys */
if (np->phy_oui == PHY_OUI_REALTEK2)
np->phy_oui = PHY_OUI_REALTEK;
/* Setup phy revision for Realtek */
if (np->phy_oui == PHY_OUI_REALTEK && np->phy_model == PHY_MODEL_REALTEK_8211)
np->phy_rev = mii_rw(dev, phyaddr, MII_RESV1, MII_READ) & PHY_REV_MASK;
break;
}
if (i == 33) {
dev_info(&pci_dev->dev, "open: Could not find a valid PHY\n");
goto out_error;
}
if (!phyinitialized) {
/* reset it */
phy_init(dev);
} else {
/* see if it is a gigabit phy */
u32 mii_status = mii_rw(dev, np->phyaddr, MII_BMSR, MII_READ);
if (mii_status & PHY_GIGABIT)
np->gigabit = PHY_GIGABIT;
}
/* set default link speed settings */
np->linkspeed = NVREG_LINKSPEED_FORCE|NVREG_LINKSPEED_10;
np->duplex = 0;
np->autoneg = 1;
err = register_netdev(dev);
if (err) {
dev_info(&pci_dev->dev, "unable to register netdev: %d\n", err);
goto out_error;
}
netif_carrier_off(dev);
dev_info(&pci_dev->dev, "ifname %s, PHY OUI 0x%x @ %d, addr %pM\n",
dev->name, np->phy_oui, np->phyaddr, dev->dev_addr);
dev_info(&pci_dev->dev, "%s%s%s%s%s%s%s%s%s%sdesc-v%u\n",
dev->features & NETIF_F_HIGHDMA ? "highdma " : "",
dev->features & (NETIF_F_IP_CSUM | NETIF_F_SG) ?
"csum " : "",
dev->features & (NETIF_F_HW_VLAN_RX | NETIF_F_HW_VLAN_TX) ?
"vlan " : "",
id->driver_data & DEV_HAS_POWER_CNTRL ? "pwrctl " : "",
id->driver_data & DEV_HAS_MGMT_UNIT ? "mgmt " : "",
id->driver_data & DEV_NEED_TIMERIRQ ? "timirq " : "",
np->gigabit == PHY_GIGABIT ? "gbit " : "",
np->need_linktimer ? "lnktim " : "",
np->msi_flags & NV_MSI_CAPABLE ? "msi " : "",
np->msi_flags & NV_MSI_X_CAPABLE ? "msi-x " : "",
np->desc_ver);
return 0;
out_error:
if (phystate_orig)
writel(phystate|NVREG_ADAPTCTL_RUNNING, base + NvRegAdapterControl);
pci_set_drvdata(pci_dev, NULL);
out_freering:
free_rings(dev);
out_unmap:
iounmap(get_hwbase(dev));
out_relreg:
pci_release_regions(pci_dev);
out_disable:
pci_disable_device(pci_dev);
out_free:
free_netdev(dev);
out:
return err;
}
static void nv_restore_phy(struct net_device *dev)
{
struct fe_priv *np = netdev_priv(dev);
u16 phy_reserved, mii_control;
if (np->phy_oui == PHY_OUI_REALTEK &&
np->phy_model == PHY_MODEL_REALTEK_8201 &&
phy_cross == NV_CROSSOVER_DETECTION_DISABLED) {
mii_rw(dev, np->phyaddr, PHY_REALTEK_INIT_REG1, PHY_REALTEK_INIT3);
phy_reserved = mii_rw(dev, np->phyaddr, PHY_REALTEK_INIT_REG2, MII_READ);
phy_reserved &= ~PHY_REALTEK_INIT_MSK1;
phy_reserved |= PHY_REALTEK_INIT8;
mii_rw(dev, np->phyaddr, PHY_REALTEK_INIT_REG2, phy_reserved);
mii_rw(dev, np->phyaddr, PHY_REALTEK_INIT_REG1, PHY_REALTEK_INIT1);
/* restart auto negotiation */
mii_control = mii_rw(dev, np->phyaddr, MII_BMCR, MII_READ);
mii_control |= (BMCR_ANRESTART | BMCR_ANENABLE);
mii_rw(dev, np->phyaddr, MII_BMCR, mii_control);
}
}
static void nv_restore_mac_addr(struct pci_dev *pci_dev)
{
struct net_device *dev = pci_get_drvdata(pci_dev);
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
/* special op: write back the misordered MAC address - otherwise
* the next nv_probe would see a wrong address.
*/
writel(np->orig_mac[0], base + NvRegMacAddrA);
writel(np->orig_mac[1], base + NvRegMacAddrB);
writel(readl(base + NvRegTransmitPoll) & ~NVREG_TRANSMITPOLL_MAC_ADDR_REV,
base + NvRegTransmitPoll);
}
static void __devexit nv_remove(struct pci_dev *pci_dev)
{
struct net_device *dev = pci_get_drvdata(pci_dev);
unregister_netdev(dev);
nv_restore_mac_addr(pci_dev);
/* restore any phy related changes */
nv_restore_phy(dev);
nv_mgmt_release_sema(dev);
/* free all structures */
free_rings(dev);
iounmap(get_hwbase(dev));
pci_release_regions(pci_dev);
pci_disable_device(pci_dev);
free_netdev(dev);
pci_set_drvdata(pci_dev, NULL);
}
#ifdef CONFIG_PM_SLEEP
static int nv_suspend(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct net_device *dev = pci_get_drvdata(pdev);
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
int i;
if (netif_running(dev)) {
/* Gross. */
nv_close(dev);
}
netif_device_detach(dev);
/* save non-pci configuration space */
for (i = 0; i <= np->register_size/sizeof(u32); i++)
np->saved_config_space[i] = readl(base + i*sizeof(u32));
return 0;
}
static int nv_resume(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct net_device *dev = pci_get_drvdata(pdev);
struct fe_priv *np = netdev_priv(dev);
u8 __iomem *base = get_hwbase(dev);
int i, rc = 0;
/* restore non-pci configuration space */
for (i = 0; i <= np->register_size/sizeof(u32); i++)
writel(np->saved_config_space[i], base+i*sizeof(u32));
if (np->driver_data & DEV_NEED_MSI_FIX)
pci_write_config_dword(pdev, NV_MSI_PRIV_OFFSET, NV_MSI_PRIV_VALUE);
/* restore phy state, including autoneg */
phy_init(dev);
netif_device_attach(dev);
if (netif_running(dev)) {
rc = nv_open(dev);
nv_set_multicast(dev);
}
return rc;
}
static SIMPLE_DEV_PM_OPS(nv_pm_ops, nv_suspend, nv_resume);
#define NV_PM_OPS (&nv_pm_ops)
#else
#define NV_PM_OPS NULL
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM
static void nv_shutdown(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct fe_priv *np = netdev_priv(dev);
if (netif_running(dev))
nv_close(dev);
/*
* Restore the MAC so a kernel started by kexec won't get confused.
* If we really go for poweroff, we must not restore the MAC,
* otherwise the MAC for WOL will be reversed at least on some boards.
*/
if (system_state != SYSTEM_POWER_OFF)
nv_restore_mac_addr(pdev);
pci_disable_device(pdev);
/*
* Apparently it is not possible to reinitialise from D3 hot,
* only put the device into D3 if we really go for poweroff.
*/
if (system_state == SYSTEM_POWER_OFF) {
pci_wake_from_d3(pdev, np->wolenabled);
pci_set_power_state(pdev, PCI_D3hot);
}
}
#else
#define nv_shutdown NULL
#endif /* CONFIG_PM */
static DEFINE_PCI_DEVICE_TABLE(pci_tbl) = {
{ /* nForce Ethernet Controller */
PCI_DEVICE(0x10DE, 0x01C3),
.driver_data = DEV_NEED_TIMERIRQ|DEV_NEED_LINKTIMER,
},
{ /* nForce2 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0066),
.driver_data = DEV_NEED_TIMERIRQ|DEV_NEED_LINKTIMER,
},
{ /* nForce3 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x00D6),
.driver_data = DEV_NEED_TIMERIRQ|DEV_NEED_LINKTIMER,
},
{ /* nForce3 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0086),
.driver_data = DEV_NEED_TIMERIRQ|DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM,
},
{ /* nForce3 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x008C),
.driver_data = DEV_NEED_TIMERIRQ|DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM,
},
{ /* nForce3 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x00E6),
.driver_data = DEV_NEED_TIMERIRQ|DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM,
},
{ /* nForce3 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x00DF),
.driver_data = DEV_NEED_TIMERIRQ|DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM,
},
{ /* CK804 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0056),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_STATISTICS_V1|DEV_NEED_TX_LIMIT,
},
{ /* CK804 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0057),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_STATISTICS_V1|DEV_NEED_TX_LIMIT,
},
{ /* MCP04 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0037),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_STATISTICS_V1|DEV_NEED_TX_LIMIT,
},
{ /* MCP04 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0038),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_STATISTICS_V1|DEV_NEED_TX_LIMIT,
},
{ /* MCP51 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0268),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_STATISTICS_V1|DEV_NEED_LOW_POWER_FIX,
},
{ /* MCP51 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0269),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_STATISTICS_V1|DEV_NEED_LOW_POWER_FIX,
},
{ /* MCP55 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0372),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_VLAN|DEV_HAS_MSI|DEV_HAS_MSI_X|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_NEED_TX_LIMIT|DEV_NEED_MSI_FIX,
},
{ /* MCP55 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0373),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_VLAN|DEV_HAS_MSI|DEV_HAS_MSI_X|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_NEED_TX_LIMIT|DEV_NEED_MSI_FIX,
},
{ /* MCP61 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x03E5),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_NEED_MSI_FIX,
},
{ /* MCP61 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x03E6),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_NEED_MSI_FIX,
},
{ /* MCP61 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x03EE),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_NEED_MSI_FIX,
},
{ /* MCP61 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x03EF),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_NEED_MSI_FIX,
},
{ /* MCP65 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0450),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_NEED_TX_LIMIT|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP65 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0451),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_NEED_TX_LIMIT|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP65 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0452),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_NEED_TX_LIMIT|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP65 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0453),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_NEED_TX_LIMIT|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP67 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x054C),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP67 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x054D),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP67 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x054E),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP67 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x054F),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP73 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x07DC),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP73 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x07DD),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP73 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x07DE),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP73 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x07DF),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_HIGH_DMA|DEV_HAS_POWER_CNTRL|DEV_HAS_MSI|DEV_HAS_PAUSEFRAME_TX_V1|DEV_HAS_STATISTICS_V12|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_HAS_GEAR_MODE|DEV_NEED_MSI_FIX,
},
{ /* MCP77 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0760),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_MSI|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V2|DEV_HAS_STATISTICS_V123|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_NEED_TX_LIMIT2|DEV_HAS_GEAR_MODE|DEV_NEED_PHY_INIT_FIX|DEV_NEED_MSI_FIX,
},
{ /* MCP77 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0761),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_MSI|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V2|DEV_HAS_STATISTICS_V123|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_NEED_TX_LIMIT2|DEV_HAS_GEAR_MODE|DEV_NEED_PHY_INIT_FIX|DEV_NEED_MSI_FIX,
},
{ /* MCP77 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0762),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_MSI|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V2|DEV_HAS_STATISTICS_V123|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_NEED_TX_LIMIT2|DEV_HAS_GEAR_MODE|DEV_NEED_PHY_INIT_FIX|DEV_NEED_MSI_FIX,
},
{ /* MCP77 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0763),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_MSI|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V2|DEV_HAS_STATISTICS_V123|DEV_HAS_TEST_EXTENDED|DEV_HAS_MGMT_UNIT|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_NEED_TX_LIMIT2|DEV_HAS_GEAR_MODE|DEV_NEED_PHY_INIT_FIX|DEV_NEED_MSI_FIX,
},
{ /* MCP79 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0AB0),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_MSI|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V3|DEV_HAS_STATISTICS_V123|DEV_HAS_TEST_EXTENDED|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_NEED_TX_LIMIT2|DEV_HAS_GEAR_MODE|DEV_NEED_PHY_INIT_FIX|DEV_NEED_MSI_FIX,
},
{ /* MCP79 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0AB1),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_MSI|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V3|DEV_HAS_STATISTICS_V123|DEV_HAS_TEST_EXTENDED|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_NEED_TX_LIMIT2|DEV_HAS_GEAR_MODE|DEV_NEED_PHY_INIT_FIX|DEV_NEED_MSI_FIX,
},
{ /* MCP79 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0AB2),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_MSI|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V3|DEV_HAS_STATISTICS_V123|DEV_HAS_TEST_EXTENDED|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_NEED_TX_LIMIT2|DEV_HAS_GEAR_MODE|DEV_NEED_PHY_INIT_FIX|DEV_NEED_MSI_FIX,
},
{ /* MCP79 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0AB3),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_MSI|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V3|DEV_HAS_STATISTICS_V123|DEV_HAS_TEST_EXTENDED|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_NEED_TX_LIMIT2|DEV_HAS_GEAR_MODE|DEV_NEED_PHY_INIT_FIX|DEV_NEED_MSI_FIX,
},
{ /* MCP89 Ethernet Controller */
PCI_DEVICE(0x10DE, 0x0D7D),
.driver_data = DEV_NEED_LINKTIMER|DEV_HAS_LARGEDESC|DEV_HAS_CHECKSUM|DEV_HAS_HIGH_DMA|DEV_HAS_MSI|DEV_HAS_POWER_CNTRL|DEV_HAS_PAUSEFRAME_TX_V3|DEV_HAS_STATISTICS_V123|DEV_HAS_TEST_EXTENDED|DEV_HAS_CORRECT_MACADDR|DEV_HAS_COLLISION_FIX|DEV_HAS_GEAR_MODE|DEV_NEED_PHY_INIT_FIX,
},
{0,},
};
static struct pci_driver driver = {
.name = DRV_NAME,
.id_table = pci_tbl,
.probe = nv_probe,
.remove = __devexit_p(nv_remove),
.shutdown = nv_shutdown,
.driver.pm = NV_PM_OPS,
};
static int __init init_nic(void)
{
return pci_register_driver(&driver);
}
static void __exit exit_nic(void)
{
pci_unregister_driver(&driver);
}
module_param(max_interrupt_work, int, 0);
MODULE_PARM_DESC(max_interrupt_work, "forcedeth maximum events handled per interrupt");
module_param(optimization_mode, int, 0);
MODULE_PARM_DESC(optimization_mode, "In throughput mode (0), every tx & rx packet will generate an interrupt. In CPU mode (1), interrupts are controlled by a timer. In dynamic mode (2), the mode toggles between throughput and CPU mode based on network load.");
module_param(poll_interval, int, 0);
MODULE_PARM_DESC(poll_interval, "Interval determines how frequent timer interrupt is generated by [(time_in_micro_secs * 100) / (2^10)]. Min is 0 and Max is 65535.");
module_param(msi, int, 0);
MODULE_PARM_DESC(msi, "MSI interrupts are enabled by setting to 1 and disabled by setting to 0.");
module_param(msix, int, 0);
MODULE_PARM_DESC(msix, "MSIX interrupts are enabled by setting to 1 and disabled by setting to 0.");
module_param(dma_64bit, int, 0);
MODULE_PARM_DESC(dma_64bit, "High DMA is enabled by setting to 1 and disabled by setting to 0.");
module_param(phy_cross, int, 0);
MODULE_PARM_DESC(phy_cross, "Phy crossover detection for Realtek 8201 phy is enabled by setting to 1 and disabled by setting to 0.");
module_param(phy_power_down, int, 0);
MODULE_PARM_DESC(phy_power_down, "Power down phy and disable link when interface is down (1), or leave phy powered up (0).");
MODULE_AUTHOR("Manfred Spraul <manfred@colorfullife.com>");
MODULE_DESCRIPTION("Reverse Engineered nForce ethernet driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, pci_tbl);
module_init(init_nic);
module_exit(exit_nic);
| gpl-2.0 |
hwmt1-u06/android_kernel_huawei_hwmt1-u06 | drivers/crypto/omap-sham.c | 2378 | 31437 | /*
* Cryptographic API.
*
* Support for OMAP SHA1/MD5 HW acceleration.
*
* Copyright (c) 2010 Nokia Corporation
* Author: Dmitry Kasatkin <dmitry.kasatkin@nokia.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.
*
* Some ideas are from old omap-sha1-md5.c driver.
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/err.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/scatterlist.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <linux/crypto.h>
#include <linux/cryptohash.h>
#include <crypto/scatterwalk.h>
#include <crypto/algapi.h>
#include <crypto/sha.h>
#include <crypto/hash.h>
#include <crypto/internal/hash.h>
#include <plat/cpu.h>
#include <plat/dma.h>
#include <mach/irqs.h>
#define SHA_REG_DIGEST(x) (0x00 + ((x) * 0x04))
#define SHA_REG_DIN(x) (0x1C + ((x) * 0x04))
#define SHA1_MD5_BLOCK_SIZE SHA1_BLOCK_SIZE
#define MD5_DIGEST_SIZE 16
#define SHA_REG_DIGCNT 0x14
#define SHA_REG_CTRL 0x18
#define SHA_REG_CTRL_LENGTH (0xFFFFFFFF << 5)
#define SHA_REG_CTRL_CLOSE_HASH (1 << 4)
#define SHA_REG_CTRL_ALGO_CONST (1 << 3)
#define SHA_REG_CTRL_ALGO (1 << 2)
#define SHA_REG_CTRL_INPUT_READY (1 << 1)
#define SHA_REG_CTRL_OUTPUT_READY (1 << 0)
#define SHA_REG_REV 0x5C
#define SHA_REG_REV_MAJOR 0xF0
#define SHA_REG_REV_MINOR 0x0F
#define SHA_REG_MASK 0x60
#define SHA_REG_MASK_DMA_EN (1 << 3)
#define SHA_REG_MASK_IT_EN (1 << 2)
#define SHA_REG_MASK_SOFTRESET (1 << 1)
#define SHA_REG_AUTOIDLE (1 << 0)
#define SHA_REG_SYSSTATUS 0x64
#define SHA_REG_SYSSTATUS_RESETDONE (1 << 0)
#define DEFAULT_TIMEOUT_INTERVAL HZ
#define FLAGS_FINUP 0x0002
#define FLAGS_FINAL 0x0004
#define FLAGS_SG 0x0008
#define FLAGS_SHA1 0x0010
#define FLAGS_DMA_ACTIVE 0x0020
#define FLAGS_OUTPUT_READY 0x0040
#define FLAGS_INIT 0x0100
#define FLAGS_CPU 0x0200
#define FLAGS_HMAC 0x0400
#define FLAGS_ERROR 0x0800
#define FLAGS_BUSY 0x1000
#define OP_UPDATE 1
#define OP_FINAL 2
#define OMAP_ALIGN_MASK (sizeof(u32)-1)
#define OMAP_ALIGNED __attribute__((aligned(sizeof(u32))))
#define BUFLEN PAGE_SIZE
struct omap_sham_dev;
struct omap_sham_reqctx {
struct omap_sham_dev *dd;
unsigned long flags;
unsigned long op;
u8 digest[SHA1_DIGEST_SIZE] OMAP_ALIGNED;
size_t digcnt;
size_t bufcnt;
size_t buflen;
dma_addr_t dma_addr;
/* walk state */
struct scatterlist *sg;
unsigned int offset; /* offset in current sg */
unsigned int total; /* total request */
u8 buffer[0] OMAP_ALIGNED;
};
struct omap_sham_hmac_ctx {
struct crypto_shash *shash;
u8 ipad[SHA1_MD5_BLOCK_SIZE];
u8 opad[SHA1_MD5_BLOCK_SIZE];
};
struct omap_sham_ctx {
struct omap_sham_dev *dd;
unsigned long flags;
/* fallback stuff */
struct crypto_shash *fallback;
struct omap_sham_hmac_ctx base[0];
};
#define OMAP_SHAM_QUEUE_LENGTH 1
struct omap_sham_dev {
struct list_head list;
unsigned long phys_base;
struct device *dev;
void __iomem *io_base;
int irq;
struct clk *iclk;
spinlock_t lock;
int err;
int dma;
int dma_lch;
struct tasklet_struct done_task;
struct tasklet_struct queue_task;
unsigned long flags;
struct crypto_queue queue;
struct ahash_request *req;
};
struct omap_sham_drv {
struct list_head dev_list;
spinlock_t lock;
unsigned long flags;
};
static struct omap_sham_drv sham = {
.dev_list = LIST_HEAD_INIT(sham.dev_list),
.lock = __SPIN_LOCK_UNLOCKED(sham.lock),
};
static inline u32 omap_sham_read(struct omap_sham_dev *dd, u32 offset)
{
return __raw_readl(dd->io_base + offset);
}
static inline void omap_sham_write(struct omap_sham_dev *dd,
u32 offset, u32 value)
{
__raw_writel(value, dd->io_base + offset);
}
static inline void omap_sham_write_mask(struct omap_sham_dev *dd, u32 address,
u32 value, u32 mask)
{
u32 val;
val = omap_sham_read(dd, address);
val &= ~mask;
val |= value;
omap_sham_write(dd, address, val);
}
static inline int omap_sham_wait(struct omap_sham_dev *dd, u32 offset, u32 bit)
{
unsigned long timeout = jiffies + DEFAULT_TIMEOUT_INTERVAL;
while (!(omap_sham_read(dd, offset) & bit)) {
if (time_is_before_jiffies(timeout))
return -ETIMEDOUT;
}
return 0;
}
static void omap_sham_copy_hash(struct ahash_request *req, int out)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
u32 *hash = (u32 *)ctx->digest;
int i;
/* MD5 is almost unused. So copy sha1 size to reduce code */
for (i = 0; i < SHA1_DIGEST_SIZE / sizeof(u32); i++) {
if (out)
hash[i] = omap_sham_read(ctx->dd,
SHA_REG_DIGEST(i));
else
omap_sham_write(ctx->dd,
SHA_REG_DIGEST(i), hash[i]);
}
}
static void omap_sham_copy_ready_hash(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
u32 *in = (u32 *)ctx->digest;
u32 *hash = (u32 *)req->result;
int i;
if (!hash)
return;
if (likely(ctx->flags & FLAGS_SHA1)) {
/* SHA1 results are in big endian */
for (i = 0; i < SHA1_DIGEST_SIZE / sizeof(u32); i++)
hash[i] = be32_to_cpu(in[i]);
} else {
/* MD5 results are in little endian */
for (i = 0; i < MD5_DIGEST_SIZE / sizeof(u32); i++)
hash[i] = le32_to_cpu(in[i]);
}
}
static int omap_sham_hw_init(struct omap_sham_dev *dd)
{
clk_enable(dd->iclk);
if (!(dd->flags & FLAGS_INIT)) {
omap_sham_write_mask(dd, SHA_REG_MASK,
SHA_REG_MASK_SOFTRESET, SHA_REG_MASK_SOFTRESET);
if (omap_sham_wait(dd, SHA_REG_SYSSTATUS,
SHA_REG_SYSSTATUS_RESETDONE))
return -ETIMEDOUT;
dd->flags |= FLAGS_INIT;
dd->err = 0;
}
return 0;
}
static void omap_sham_write_ctrl(struct omap_sham_dev *dd, size_t length,
int final, int dma)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
u32 val = length << 5, mask;
if (likely(ctx->digcnt))
omap_sham_write(dd, SHA_REG_DIGCNT, ctx->digcnt);
omap_sham_write_mask(dd, SHA_REG_MASK,
SHA_REG_MASK_IT_EN | (dma ? SHA_REG_MASK_DMA_EN : 0),
SHA_REG_MASK_IT_EN | SHA_REG_MASK_DMA_EN);
/*
* Setting ALGO_CONST only for the first iteration
* and CLOSE_HASH only for the last one.
*/
if (ctx->flags & FLAGS_SHA1)
val |= SHA_REG_CTRL_ALGO;
if (!ctx->digcnt)
val |= SHA_REG_CTRL_ALGO_CONST;
if (final)
val |= SHA_REG_CTRL_CLOSE_HASH;
mask = SHA_REG_CTRL_ALGO_CONST | SHA_REG_CTRL_CLOSE_HASH |
SHA_REG_CTRL_ALGO | SHA_REG_CTRL_LENGTH;
omap_sham_write_mask(dd, SHA_REG_CTRL, val, mask);
}
static int omap_sham_xmit_cpu(struct omap_sham_dev *dd, const u8 *buf,
size_t length, int final)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
int count, len32;
const u32 *buffer = (const u32 *)buf;
dev_dbg(dd->dev, "xmit_cpu: digcnt: %d, length: %d, final: %d\n",
ctx->digcnt, length, final);
omap_sham_write_ctrl(dd, length, final, 0);
/* should be non-zero before next lines to disable clocks later */
ctx->digcnt += length;
if (omap_sham_wait(dd, SHA_REG_CTRL, SHA_REG_CTRL_INPUT_READY))
return -ETIMEDOUT;
if (final)
ctx->flags |= FLAGS_FINAL; /* catch last interrupt */
len32 = DIV_ROUND_UP(length, sizeof(u32));
for (count = 0; count < len32; count++)
omap_sham_write(dd, SHA_REG_DIN(count), buffer[count]);
return -EINPROGRESS;
}
static int omap_sham_xmit_dma(struct omap_sham_dev *dd, dma_addr_t dma_addr,
size_t length, int final)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
int len32;
dev_dbg(dd->dev, "xmit_dma: digcnt: %d, length: %d, final: %d\n",
ctx->digcnt, length, final);
len32 = DIV_ROUND_UP(length, sizeof(u32));
omap_set_dma_transfer_params(dd->dma_lch, OMAP_DMA_DATA_TYPE_S32, len32,
1, OMAP_DMA_SYNC_PACKET, dd->dma,
OMAP_DMA_DST_SYNC_PREFETCH);
omap_set_dma_src_params(dd->dma_lch, 0, OMAP_DMA_AMODE_POST_INC,
dma_addr, 0, 0);
omap_sham_write_ctrl(dd, length, final, 1);
ctx->digcnt += length;
if (final)
ctx->flags |= FLAGS_FINAL; /* catch last interrupt */
dd->flags |= FLAGS_DMA_ACTIVE;
omap_start_dma(dd->dma_lch);
return -EINPROGRESS;
}
static size_t omap_sham_append_buffer(struct omap_sham_reqctx *ctx,
const u8 *data, size_t length)
{
size_t count = min(length, ctx->buflen - ctx->bufcnt);
count = min(count, ctx->total);
if (count <= 0)
return 0;
memcpy(ctx->buffer + ctx->bufcnt, data, count);
ctx->bufcnt += count;
return count;
}
static size_t omap_sham_append_sg(struct omap_sham_reqctx *ctx)
{
size_t count;
while (ctx->sg) {
count = omap_sham_append_buffer(ctx,
sg_virt(ctx->sg) + ctx->offset,
ctx->sg->length - ctx->offset);
if (!count)
break;
ctx->offset += count;
ctx->total -= count;
if (ctx->offset == ctx->sg->length) {
ctx->sg = sg_next(ctx->sg);
if (ctx->sg)
ctx->offset = 0;
else
ctx->total = 0;
}
}
return 0;
}
static int omap_sham_xmit_dma_map(struct omap_sham_dev *dd,
struct omap_sham_reqctx *ctx,
size_t length, int final)
{
ctx->dma_addr = dma_map_single(dd->dev, ctx->buffer, ctx->buflen,
DMA_TO_DEVICE);
if (dma_mapping_error(dd->dev, ctx->dma_addr)) {
dev_err(dd->dev, "dma %u bytes error\n", ctx->buflen);
return -EINVAL;
}
ctx->flags &= ~FLAGS_SG;
/* next call does not fail... so no unmap in the case of error */
return omap_sham_xmit_dma(dd, ctx->dma_addr, length, final);
}
static int omap_sham_update_dma_slow(struct omap_sham_dev *dd)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
unsigned int final;
size_t count;
omap_sham_append_sg(ctx);
final = (ctx->flags & FLAGS_FINUP) && !ctx->total;
dev_dbg(dd->dev, "slow: bufcnt: %u, digcnt: %d, final: %d\n",
ctx->bufcnt, ctx->digcnt, final);
if (final || (ctx->bufcnt == ctx->buflen && ctx->total)) {
count = ctx->bufcnt;
ctx->bufcnt = 0;
return omap_sham_xmit_dma_map(dd, ctx, count, final);
}
return 0;
}
/* Start address alignment */
#define SG_AA(sg) (IS_ALIGNED(sg->offset, sizeof(u32)))
/* SHA1 block size alignment */
#define SG_SA(sg) (IS_ALIGNED(sg->length, SHA1_MD5_BLOCK_SIZE))
static int omap_sham_update_dma_start(struct omap_sham_dev *dd)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
unsigned int length, final, tail;
struct scatterlist *sg;
if (!ctx->total)
return 0;
if (ctx->bufcnt || ctx->offset)
return omap_sham_update_dma_slow(dd);
dev_dbg(dd->dev, "fast: digcnt: %d, bufcnt: %u, total: %u\n",
ctx->digcnt, ctx->bufcnt, ctx->total);
sg = ctx->sg;
if (!SG_AA(sg))
return omap_sham_update_dma_slow(dd);
if (!sg_is_last(sg) && !SG_SA(sg))
/* size is not SHA1_BLOCK_SIZE aligned */
return omap_sham_update_dma_slow(dd);
length = min(ctx->total, sg->length);
if (sg_is_last(sg)) {
if (!(ctx->flags & FLAGS_FINUP)) {
/* not last sg must be SHA1_MD5_BLOCK_SIZE aligned */
tail = length & (SHA1_MD5_BLOCK_SIZE - 1);
/* without finup() we need one block to close hash */
if (!tail)
tail = SHA1_MD5_BLOCK_SIZE;
length -= tail;
}
}
if (!dma_map_sg(dd->dev, ctx->sg, 1, DMA_TO_DEVICE)) {
dev_err(dd->dev, "dma_map_sg error\n");
return -EINVAL;
}
ctx->flags |= FLAGS_SG;
ctx->total -= length;
ctx->offset = length; /* offset where to start slow */
final = (ctx->flags & FLAGS_FINUP) && !ctx->total;
/* next call does not fail... so no unmap in the case of error */
return omap_sham_xmit_dma(dd, sg_dma_address(ctx->sg), length, final);
}
static int omap_sham_update_cpu(struct omap_sham_dev *dd)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
int bufcnt;
omap_sham_append_sg(ctx);
bufcnt = ctx->bufcnt;
ctx->bufcnt = 0;
return omap_sham_xmit_cpu(dd, ctx->buffer, bufcnt, 1);
}
static int omap_sham_update_dma_stop(struct omap_sham_dev *dd)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
omap_stop_dma(dd->dma_lch);
if (ctx->flags & FLAGS_SG) {
dma_unmap_sg(dd->dev, ctx->sg, 1, DMA_TO_DEVICE);
if (ctx->sg->length == ctx->offset) {
ctx->sg = sg_next(ctx->sg);
if (ctx->sg)
ctx->offset = 0;
}
} else {
dma_unmap_single(dd->dev, ctx->dma_addr, ctx->buflen,
DMA_TO_DEVICE);
}
return 0;
}
static int omap_sham_init(struct ahash_request *req)
{
struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
struct omap_sham_ctx *tctx = crypto_ahash_ctx(tfm);
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = NULL, *tmp;
spin_lock_bh(&sham.lock);
if (!tctx->dd) {
list_for_each_entry(tmp, &sham.dev_list, list) {
dd = tmp;
break;
}
tctx->dd = dd;
} else {
dd = tctx->dd;
}
spin_unlock_bh(&sham.lock);
ctx->dd = dd;
ctx->flags = 0;
dev_dbg(dd->dev, "init: digest size: %d\n",
crypto_ahash_digestsize(tfm));
if (crypto_ahash_digestsize(tfm) == SHA1_DIGEST_SIZE)
ctx->flags |= FLAGS_SHA1;
ctx->bufcnt = 0;
ctx->digcnt = 0;
ctx->buflen = BUFLEN;
if (tctx->flags & FLAGS_HMAC) {
struct omap_sham_hmac_ctx *bctx = tctx->base;
memcpy(ctx->buffer, bctx->ipad, SHA1_MD5_BLOCK_SIZE);
ctx->bufcnt = SHA1_MD5_BLOCK_SIZE;
ctx->flags |= FLAGS_HMAC;
}
return 0;
}
static int omap_sham_update_req(struct omap_sham_dev *dd)
{
struct ahash_request *req = dd->req;
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
int err;
dev_dbg(dd->dev, "update_req: total: %u, digcnt: %d, finup: %d\n",
ctx->total, ctx->digcnt, (ctx->flags & FLAGS_FINUP) != 0);
if (ctx->flags & FLAGS_CPU)
err = omap_sham_update_cpu(dd);
else
err = omap_sham_update_dma_start(dd);
/* wait for dma completion before can take more data */
dev_dbg(dd->dev, "update: err: %d, digcnt: %d\n", err, ctx->digcnt);
return err;
}
static int omap_sham_final_req(struct omap_sham_dev *dd)
{
struct ahash_request *req = dd->req;
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
int err = 0, use_dma = 1;
if (ctx->bufcnt <= 64)
/* faster to handle last block with cpu */
use_dma = 0;
if (use_dma)
err = omap_sham_xmit_dma_map(dd, ctx, ctx->bufcnt, 1);
else
err = omap_sham_xmit_cpu(dd, ctx->buffer, ctx->bufcnt, 1);
ctx->bufcnt = 0;
dev_dbg(dd->dev, "final_req: err: %d\n", err);
return err;
}
static int omap_sham_finish_hmac(struct ahash_request *req)
{
struct omap_sham_ctx *tctx = crypto_tfm_ctx(req->base.tfm);
struct omap_sham_hmac_ctx *bctx = tctx->base;
int bs = crypto_shash_blocksize(bctx->shash);
int ds = crypto_shash_digestsize(bctx->shash);
struct {
struct shash_desc shash;
char ctx[crypto_shash_descsize(bctx->shash)];
} desc;
desc.shash.tfm = bctx->shash;
desc.shash.flags = 0; /* not CRYPTO_TFM_REQ_MAY_SLEEP */
return crypto_shash_init(&desc.shash) ?:
crypto_shash_update(&desc.shash, bctx->opad, bs) ?:
crypto_shash_finup(&desc.shash, req->result, ds, req->result);
}
static int omap_sham_finish(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = ctx->dd;
int err = 0;
if (ctx->digcnt) {
omap_sham_copy_ready_hash(req);
if (ctx->flags & FLAGS_HMAC)
err = omap_sham_finish_hmac(req);
}
dev_dbg(dd->dev, "digcnt: %d, bufcnt: %d\n", ctx->digcnt, ctx->bufcnt);
return err;
}
static void omap_sham_finish_req(struct ahash_request *req, int err)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_dev *dd = ctx->dd;
if (!err) {
omap_sham_copy_hash(ctx->dd->req, 1);
if (ctx->flags & FLAGS_FINAL)
err = omap_sham_finish(req);
} else {
ctx->flags |= FLAGS_ERROR;
}
clk_disable(dd->iclk);
dd->flags &= ~FLAGS_BUSY;
if (req->base.complete)
req->base.complete(&req->base, err);
}
static int omap_sham_handle_queue(struct omap_sham_dev *dd,
struct ahash_request *req)
{
struct crypto_async_request *async_req, *backlog;
struct omap_sham_reqctx *ctx;
struct ahash_request *prev_req;
unsigned long flags;
int err = 0, ret = 0;
spin_lock_irqsave(&dd->lock, flags);
if (req)
ret = ahash_enqueue_request(&dd->queue, req);
if (dd->flags & FLAGS_BUSY) {
spin_unlock_irqrestore(&dd->lock, flags);
return ret;
}
backlog = crypto_get_backlog(&dd->queue);
async_req = crypto_dequeue_request(&dd->queue);
if (async_req)
dd->flags |= FLAGS_BUSY;
spin_unlock_irqrestore(&dd->lock, flags);
if (!async_req)
return ret;
if (backlog)
backlog->complete(backlog, -EINPROGRESS);
req = ahash_request_cast(async_req);
prev_req = dd->req;
dd->req = req;
ctx = ahash_request_ctx(req);
dev_dbg(dd->dev, "handling new req, op: %lu, nbytes: %d\n",
ctx->op, req->nbytes);
err = omap_sham_hw_init(dd);
if (err)
goto err1;
omap_set_dma_dest_params(dd->dma_lch, 0,
OMAP_DMA_AMODE_CONSTANT,
dd->phys_base + SHA_REG_DIN(0), 0, 16);
omap_set_dma_dest_burst_mode(dd->dma_lch,
OMAP_DMA_DATA_BURST_16);
omap_set_dma_src_burst_mode(dd->dma_lch,
OMAP_DMA_DATA_BURST_4);
if (ctx->digcnt)
/* request has changed - restore hash */
omap_sham_copy_hash(req, 0);
if (ctx->op == OP_UPDATE) {
err = omap_sham_update_req(dd);
if (err != -EINPROGRESS && (ctx->flags & FLAGS_FINUP))
/* no final() after finup() */
err = omap_sham_final_req(dd);
} else if (ctx->op == OP_FINAL) {
err = omap_sham_final_req(dd);
}
err1:
if (err != -EINPROGRESS) {
/* done_task will not finish it, so do it here */
omap_sham_finish_req(req, err);
tasklet_schedule(&dd->queue_task);
}
dev_dbg(dd->dev, "exit, err: %d\n", err);
return ret;
}
static int omap_sham_enqueue(struct ahash_request *req, unsigned int op)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
struct omap_sham_ctx *tctx = crypto_tfm_ctx(req->base.tfm);
struct omap_sham_dev *dd = tctx->dd;
ctx->op = op;
return omap_sham_handle_queue(dd, req);
}
static int omap_sham_update(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
if (!req->nbytes)
return 0;
ctx->total = req->nbytes;
ctx->sg = req->src;
ctx->offset = 0;
if (ctx->flags & FLAGS_FINUP) {
if ((ctx->digcnt + ctx->bufcnt + ctx->total) < 9) {
/*
* OMAP HW accel works only with buffers >= 9
* will switch to bypass in final()
* final has the same request and data
*/
omap_sham_append_sg(ctx);
return 0;
} else if (ctx->bufcnt + ctx->total <= SHA1_MD5_BLOCK_SIZE) {
/*
* faster to use CPU for short transfers
*/
ctx->flags |= FLAGS_CPU;
}
} else if (ctx->bufcnt + ctx->total < ctx->buflen) {
omap_sham_append_sg(ctx);
return 0;
}
return omap_sham_enqueue(req, OP_UPDATE);
}
static int omap_sham_shash_digest(struct crypto_shash *shash, u32 flags,
const u8 *data, unsigned int len, u8 *out)
{
struct {
struct shash_desc shash;
char ctx[crypto_shash_descsize(shash)];
} desc;
desc.shash.tfm = shash;
desc.shash.flags = flags & CRYPTO_TFM_REQ_MAY_SLEEP;
return crypto_shash_digest(&desc.shash, data, len, out);
}
static int omap_sham_final_shash(struct ahash_request *req)
{
struct omap_sham_ctx *tctx = crypto_tfm_ctx(req->base.tfm);
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
return omap_sham_shash_digest(tctx->fallback, req->base.flags,
ctx->buffer, ctx->bufcnt, req->result);
}
static int omap_sham_final(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
ctx->flags |= FLAGS_FINUP;
if (ctx->flags & FLAGS_ERROR)
return 0; /* uncompleted hash is not needed */
/* OMAP HW accel works only with buffers >= 9 */
/* HMAC is always >= 9 because ipad == block size */
if ((ctx->digcnt + ctx->bufcnt) < 9)
return omap_sham_final_shash(req);
else if (ctx->bufcnt)
return omap_sham_enqueue(req, OP_FINAL);
/* copy ready hash (+ finalize hmac) */
return omap_sham_finish(req);
}
static int omap_sham_finup(struct ahash_request *req)
{
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
int err1, err2;
ctx->flags |= FLAGS_FINUP;
err1 = omap_sham_update(req);
if (err1 == -EINPROGRESS || err1 == -EBUSY)
return err1;
/*
* final() has to be always called to cleanup resources
* even if udpate() failed, except EINPROGRESS
*/
err2 = omap_sham_final(req);
return err1 ?: err2;
}
static int omap_sham_digest(struct ahash_request *req)
{
return omap_sham_init(req) ?: omap_sham_finup(req);
}
static int omap_sham_setkey(struct crypto_ahash *tfm, const u8 *key,
unsigned int keylen)
{
struct omap_sham_ctx *tctx = crypto_ahash_ctx(tfm);
struct omap_sham_hmac_ctx *bctx = tctx->base;
int bs = crypto_shash_blocksize(bctx->shash);
int ds = crypto_shash_digestsize(bctx->shash);
int err, i;
err = crypto_shash_setkey(tctx->fallback, key, keylen);
if (err)
return err;
if (keylen > bs) {
err = omap_sham_shash_digest(bctx->shash,
crypto_shash_get_flags(bctx->shash),
key, keylen, bctx->ipad);
if (err)
return err;
keylen = ds;
} else {
memcpy(bctx->ipad, key, keylen);
}
memset(bctx->ipad + keylen, 0, bs - keylen);
memcpy(bctx->opad, bctx->ipad, bs);
for (i = 0; i < bs; i++) {
bctx->ipad[i] ^= 0x36;
bctx->opad[i] ^= 0x5c;
}
return err;
}
static int omap_sham_cra_init_alg(struct crypto_tfm *tfm, const char *alg_base)
{
struct omap_sham_ctx *tctx = crypto_tfm_ctx(tfm);
const char *alg_name = crypto_tfm_alg_name(tfm);
/* Allocate a fallback and abort if it failed. */
tctx->fallback = crypto_alloc_shash(alg_name, 0,
CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(tctx->fallback)) {
pr_err("omap-sham: fallback driver '%s' "
"could not be loaded.\n", alg_name);
return PTR_ERR(tctx->fallback);
}
crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),
sizeof(struct omap_sham_reqctx) + BUFLEN);
if (alg_base) {
struct omap_sham_hmac_ctx *bctx = tctx->base;
tctx->flags |= FLAGS_HMAC;
bctx->shash = crypto_alloc_shash(alg_base, 0,
CRYPTO_ALG_NEED_FALLBACK);
if (IS_ERR(bctx->shash)) {
pr_err("omap-sham: base driver '%s' "
"could not be loaded.\n", alg_base);
crypto_free_shash(tctx->fallback);
return PTR_ERR(bctx->shash);
}
}
return 0;
}
static int omap_sham_cra_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, NULL);
}
static int omap_sham_cra_sha1_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, "sha1");
}
static int omap_sham_cra_md5_init(struct crypto_tfm *tfm)
{
return omap_sham_cra_init_alg(tfm, "md5");
}
static void omap_sham_cra_exit(struct crypto_tfm *tfm)
{
struct omap_sham_ctx *tctx = crypto_tfm_ctx(tfm);
crypto_free_shash(tctx->fallback);
tctx->fallback = NULL;
if (tctx->flags & FLAGS_HMAC) {
struct omap_sham_hmac_ctx *bctx = tctx->base;
crypto_free_shash(bctx->shash);
}
}
static struct ahash_alg algs[] = {
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.halg.digestsize = SHA1_DIGEST_SIZE,
.halg.base = {
.cra_name = "sha1",
.cra_driver_name = "omap-sha1",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_AHASH |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx),
.cra_alignmask = 0,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.halg.digestsize = MD5_DIGEST_SIZE,
.halg.base = {
.cra_name = "md5",
.cra_driver_name = "omap-md5",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_AHASH |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.setkey = omap_sham_setkey,
.halg.digestsize = SHA1_DIGEST_SIZE,
.halg.base = {
.cra_name = "hmac(sha1)",
.cra_driver_name = "omap-hmac-sha1",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_AHASH |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx) +
sizeof(struct omap_sham_hmac_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_sha1_init,
.cra_exit = omap_sham_cra_exit,
}
},
{
.init = omap_sham_init,
.update = omap_sham_update,
.final = omap_sham_final,
.finup = omap_sham_finup,
.digest = omap_sham_digest,
.setkey = omap_sham_setkey,
.halg.digestsize = MD5_DIGEST_SIZE,
.halg.base = {
.cra_name = "hmac(md5)",
.cra_driver_name = "omap-hmac-md5",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_AHASH |
CRYPTO_ALG_ASYNC |
CRYPTO_ALG_NEED_FALLBACK,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct omap_sham_ctx) +
sizeof(struct omap_sham_hmac_ctx),
.cra_alignmask = OMAP_ALIGN_MASK,
.cra_module = THIS_MODULE,
.cra_init = omap_sham_cra_md5_init,
.cra_exit = omap_sham_cra_exit,
}
}
};
static void omap_sham_done_task(unsigned long data)
{
struct omap_sham_dev *dd = (struct omap_sham_dev *)data;
struct ahash_request *req = dd->req;
struct omap_sham_reqctx *ctx = ahash_request_ctx(req);
int ready = 0, err = 0;
if (ctx->flags & FLAGS_OUTPUT_READY) {
ctx->flags &= ~FLAGS_OUTPUT_READY;
ready = 1;
}
if (dd->flags & FLAGS_DMA_ACTIVE) {
dd->flags &= ~FLAGS_DMA_ACTIVE;
omap_sham_update_dma_stop(dd);
if (!dd->err)
err = omap_sham_update_dma_start(dd);
}
err = dd->err ? : err;
if (err != -EINPROGRESS && (ready || err)) {
dev_dbg(dd->dev, "update done: err: %d\n", err);
/* finish curent request */
omap_sham_finish_req(req, err);
/* start new request */
omap_sham_handle_queue(dd, NULL);
}
}
static void omap_sham_queue_task(unsigned long data)
{
struct omap_sham_dev *dd = (struct omap_sham_dev *)data;
omap_sham_handle_queue(dd, NULL);
}
static irqreturn_t omap_sham_irq(int irq, void *dev_id)
{
struct omap_sham_dev *dd = dev_id;
struct omap_sham_reqctx *ctx = ahash_request_ctx(dd->req);
if (!ctx) {
dev_err(dd->dev, "unknown interrupt.\n");
return IRQ_HANDLED;
}
if (unlikely(ctx->flags & FLAGS_FINAL))
/* final -> allow device to go to power-saving mode */
omap_sham_write_mask(dd, SHA_REG_CTRL, 0, SHA_REG_CTRL_LENGTH);
omap_sham_write_mask(dd, SHA_REG_CTRL, SHA_REG_CTRL_OUTPUT_READY,
SHA_REG_CTRL_OUTPUT_READY);
omap_sham_read(dd, SHA_REG_CTRL);
ctx->flags |= FLAGS_OUTPUT_READY;
dd->err = 0;
tasklet_schedule(&dd->done_task);
return IRQ_HANDLED;
}
static void omap_sham_dma_callback(int lch, u16 ch_status, void *data)
{
struct omap_sham_dev *dd = data;
if (ch_status != OMAP_DMA_BLOCK_IRQ) {
pr_err("omap-sham DMA error status: 0x%hx\n", ch_status);
dd->err = -EIO;
dd->flags &= ~FLAGS_INIT; /* request to re-initialize */
}
tasklet_schedule(&dd->done_task);
}
static int omap_sham_dma_init(struct omap_sham_dev *dd)
{
int err;
dd->dma_lch = -1;
err = omap_request_dma(dd->dma, dev_name(dd->dev),
omap_sham_dma_callback, dd, &dd->dma_lch);
if (err) {
dev_err(dd->dev, "Unable to request DMA channel\n");
return err;
}
return 0;
}
static void omap_sham_dma_cleanup(struct omap_sham_dev *dd)
{
if (dd->dma_lch >= 0) {
omap_free_dma(dd->dma_lch);
dd->dma_lch = -1;
}
}
static int __devinit omap_sham_probe(struct platform_device *pdev)
{
struct omap_sham_dev *dd;
struct device *dev = &pdev->dev;
struct resource *res;
int err, i, j;
dd = kzalloc(sizeof(struct omap_sham_dev), GFP_KERNEL);
if (dd == NULL) {
dev_err(dev, "unable to alloc data struct.\n");
err = -ENOMEM;
goto data_err;
}
dd->dev = dev;
platform_set_drvdata(pdev, dd);
INIT_LIST_HEAD(&dd->list);
spin_lock_init(&dd->lock);
tasklet_init(&dd->done_task, omap_sham_done_task, (unsigned long)dd);
tasklet_init(&dd->queue_task, omap_sham_queue_task, (unsigned long)dd);
crypto_init_queue(&dd->queue, OMAP_SHAM_QUEUE_LENGTH);
dd->irq = -1;
/* Get the base address */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(dev, "no MEM resource info\n");
err = -ENODEV;
goto res_err;
}
dd->phys_base = res->start;
/* Get the DMA */
res = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!res) {
dev_err(dev, "no DMA resource info\n");
err = -ENODEV;
goto res_err;
}
dd->dma = res->start;
/* Get the IRQ */
dd->irq = platform_get_irq(pdev, 0);
if (dd->irq < 0) {
dev_err(dev, "no IRQ resource info\n");
err = dd->irq;
goto res_err;
}
err = request_irq(dd->irq, omap_sham_irq,
IRQF_TRIGGER_LOW, dev_name(dev), dd);
if (err) {
dev_err(dev, "unable to request irq.\n");
goto res_err;
}
err = omap_sham_dma_init(dd);
if (err)
goto dma_err;
/* Initializing the clock */
dd->iclk = clk_get(dev, "ick");
if (IS_ERR(dd->iclk)) {
dev_err(dev, "clock intialization failed.\n");
err = PTR_ERR(dd->iclk);
goto clk_err;
}
dd->io_base = ioremap(dd->phys_base, SZ_4K);
if (!dd->io_base) {
dev_err(dev, "can't ioremap\n");
err = -ENOMEM;
goto io_err;
}
clk_enable(dd->iclk);
dev_info(dev, "hw accel on OMAP rev %u.%u\n",
(omap_sham_read(dd, SHA_REG_REV) & SHA_REG_REV_MAJOR) >> 4,
omap_sham_read(dd, SHA_REG_REV) & SHA_REG_REV_MINOR);
clk_disable(dd->iclk);
spin_lock(&sham.lock);
list_add_tail(&dd->list, &sham.dev_list);
spin_unlock(&sham.lock);
for (i = 0; i < ARRAY_SIZE(algs); i++) {
err = crypto_register_ahash(&algs[i]);
if (err)
goto err_algs;
}
return 0;
err_algs:
for (j = 0; j < i; j++)
crypto_unregister_ahash(&algs[j]);
iounmap(dd->io_base);
io_err:
clk_put(dd->iclk);
clk_err:
omap_sham_dma_cleanup(dd);
dma_err:
if (dd->irq >= 0)
free_irq(dd->irq, dd);
res_err:
kfree(dd);
dd = NULL;
data_err:
dev_err(dev, "initialization failed.\n");
return err;
}
static int __devexit omap_sham_remove(struct platform_device *pdev)
{
static struct omap_sham_dev *dd;
int i;
dd = platform_get_drvdata(pdev);
if (!dd)
return -ENODEV;
spin_lock(&sham.lock);
list_del(&dd->list);
spin_unlock(&sham.lock);
for (i = 0; i < ARRAY_SIZE(algs); i++)
crypto_unregister_ahash(&algs[i]);
tasklet_kill(&dd->done_task);
tasklet_kill(&dd->queue_task);
iounmap(dd->io_base);
clk_put(dd->iclk);
omap_sham_dma_cleanup(dd);
if (dd->irq >= 0)
free_irq(dd->irq, dd);
kfree(dd);
dd = NULL;
return 0;
}
static struct platform_driver omap_sham_driver = {
.probe = omap_sham_probe,
.remove = omap_sham_remove,
.driver = {
.name = "omap-sham",
.owner = THIS_MODULE,
},
};
static int __init omap_sham_mod_init(void)
{
pr_info("loading %s driver\n", "omap-sham");
if (!cpu_class_is_omap2() ||
(omap_type() != OMAP2_DEVICE_TYPE_SEC &&
omap_type() != OMAP2_DEVICE_TYPE_EMU)) {
pr_err("Unsupported cpu\n");
return -ENODEV;
}
return platform_driver_register(&omap_sham_driver);
}
static void __exit omap_sham_mod_exit(void)
{
platform_driver_unregister(&omap_sham_driver);
}
module_init(omap_sham_mod_init);
module_exit(omap_sham_mod_exit);
MODULE_DESCRIPTION("OMAP SHA1/MD5 hw acceleration support.");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Dmitry Kasatkin");
| gpl-2.0 |
TRKP/android_kernel_samsung_i9300 | net/sctp/sm_statefuns.c | 2378 | 197062 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001-2002 Intel Corp.
* Copyright (c) 2002 Nokia Corp.
*
* This is part of the SCTP Linux Kernel Implementation.
*
* These are the state functions for the state machine.
*
* This SCTP implementation 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 SCTP implementation 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 GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Karl Knutson <karl@athena.chicago.il.us>
* Mathew Kotowsky <kotowsky@sctp.org>
* Sridhar Samudrala <samudrala@us.ibm.com>
* Jon Grimm <jgrimm@us.ibm.com>
* Hui Huang <hui.huang@nokia.com>
* Dajiang Zhang <dajiang.zhang@nokia.com>
* Daisy Chang <daisyc@us.ibm.com>
* Ardelle Fan <ardelle.fan@intel.com>
* Ryan Layer <rmlayer@us.ibm.com>
* Kevin Gao <kevin.gao@intel.com>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/inet_ecn.h>
#include <linux/skbuff.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <net/sctp/structs.h>
static struct sctp_packet *sctp_abort_pkt_new(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload,
size_t paylen);
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands);
static struct sctp_packet *sctp_ootb_pkt_new(const struct sctp_association *asoc,
const struct sctp_chunk *chunk);
static void sctp_send_stale_cookie_err(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_chunk *err_chunk);
static sctp_disposition_t sctp_sf_do_5_2_6_stale(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_shut_8_4_5(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_tabort_8_4_8(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk);
static sctp_disposition_t sctp_stop_t1_and_abort(sctp_cmd_seq_t *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport);
static sctp_disposition_t sctp_sf_abort_violation(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
sctp_cmd_seq_t *commands,
const __u8 *payload,
const size_t paylen);
static sctp_disposition_t sctp_sf_violation_chunklen(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_violation_paramlen(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, void *ext,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_violation_ctsn(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_disposition_t sctp_sf_violation_chunk(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
static sctp_ierror_t sctp_sf_authenticate(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
struct sctp_chunk *chunk);
static sctp_disposition_t __sctp_sf_do_9_1_abort(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands);
/* Small helper function that checks if the chunk length
* is of the appropriate length. The 'required_length' argument
* is set to be the size of a specific chunk we are testing.
* Return Values: 1 = Valid length
* 0 = Invalid length
*
*/
static inline int
sctp_chunk_length_valid(struct sctp_chunk *chunk,
__u16 required_length)
{
__u16 chunk_length = ntohs(chunk->chunk_hdr->length);
if (unlikely(chunk_length < required_length))
return 0;
return 1;
}
/**********************************************************
* These are the state functions for handling chunk events.
**********************************************************/
/*
* Process the final SHUTDOWN COMPLETE.
*
* Section: 4 (C) (diagram), 9.2
* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint will verify
* that it is in SHUTDOWN-ACK-SENT state, if it is not the chunk should be
* discarded. If the endpoint is in the SHUTDOWN-ACK-SENT state the endpoint
* should stop the T2-shutdown timer and remove all knowledge of the
* association (and thus the association enters the CLOSED state).
*
* Verification Tag: 8.5.1(C), sctpimpguide 2.41.
* C) Rules for packet carrying SHUTDOWN COMPLETE:
* ...
* - The receiver of a SHUTDOWN COMPLETE shall accept the packet
* if the Verification Tag field of the packet matches its own tag and
* the T bit is not set
* OR
* it is set to its peer's tag and the T bit is set in the Chunk
* Flags.
* Otherwise, the receiver MUST silently discard the packet
* and take no further action. An endpoint MUST ignore the
* SHUTDOWN COMPLETE if it is not in the SHUTDOWN-ACK-SENT state.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_4_C(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* RFC 2960 6.10 Bundling
*
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return sctp_sf_violation_chunk(ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_COMPLETE chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* RFC 2960 10.2 SCTP-to-ULP
*
* H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
/* Upon reception of the SHUTDOWN COMPLETE chunk the endpoint
* will verify that it is in SHUTDOWN-ACK-SENT state, if it is
* not the chunk should be discarded. If the endpoint is in
* the SHUTDOWN-ACK-SENT state the endpoint should stop the
* T2-shutdown timer and remove all knowledge of the
* association (and thus the association enters the CLOSED
* state).
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
}
/*
* Respond to a normal INIT chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, B
* B) "Z" shall respond immediately with an INIT ACK chunk. The
* destination IP address of the INIT ACK MUST be set to the source
* IP address of the INIT to which this INIT ACK is responding. In
* the response, besides filling in other parameters, "Z" must set the
* Verification Tag field to Tag_A, and also provide its own
* Verification Tag (Tag_Z) in the Initiate Tag field.
*
* Verification Tag: Must be 0.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1B_init(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *repl;
struct sctp_association *new_asoc;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
sctp_unrecognized_param_t *unk_param;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk((sctp_get_ctl_sock()))->ep) {
SCTP_INC_STATS(SCTP_MIB_OUTOFBLUES);
return sctp_sf_tabort_8_4_8(ep, asoc, type, arg, commands);
}
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return sctp_sf_tabort_8_4_8(ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length.
* Normally, this would cause an ABORT with a Protocol Violation
* error, but since we don't have an association, we'll
* just discard the packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t)))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* If the INIT is coming toward a closing socket, we'll send back
* and ABORT. Essentially, this catches the race of INIT being
* backloged to the socket at the same time as the user isses close().
* Since the socket and all its associations are going away, we
* can treat this OOTB
*/
if (sctp_sstate(ep->base.sk, CLOSING))
return sctp_sf_tabort_8_4_8(ep, asoc, type, arg, commands);
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
return SCTP_DISPOSITION_CONSUME;
} else {
return SCTP_DISPOSITION_NOMEM;
}
} else {
return sctp_sf_tabort_8_4_8(ep, asoc, type, arg,
commands);
}
}
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *)chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
if (sctp_assoc_set_bind_addr_from_ep(new_asoc,
sctp_scope(sctp_source(chunk)),
GFP_ATOMIC) < 0)
goto nomem_init;
/* The call, sctp_process_init(), can fail on memory allocation. */
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(sctp_init_chunk_t *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem_init;
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk)
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem_init;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (sctp_unrecognized_param_t *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
sctp_chunk_free(err_chunk);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources, nor keep any states for the
* new association. Otherwise, "Z" will be vulnerable to resource
* attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
nomem_init:
sctp_association_free(new_asoc);
nomem:
if (err_chunk)
sctp_chunk_free(err_chunk);
return SCTP_DISPOSITION_NOMEM;
}
/*
* Respond to a normal INIT ACK chunk.
* We are the side that is initiating the association.
*
* Section: 5.1 Normal Establishment of an Association, C
* C) Upon reception of the INIT ACK from "Z", "A" shall stop the T1-init
* timer and leave COOKIE-WAIT state. "A" shall then send the State
* Cookie received in the INIT ACK chunk in a COOKIE ECHO chunk, start
* the T1-cookie timer, and enter the COOKIE-ECHOED state.
*
* Note: The COOKIE ECHO chunk can be bundled with any pending outbound
* DATA chunks, but it MUST be the first chunk in the packet and
* until the COOKIE ACK is returned the sender MUST NOT send any
* other packets to the peer.
*
* Verification Tag: 3.3.3
* If the value of the Initiate Tag in a received INIT ACK chunk is
* found to be 0, the receiver MUST treat it as an error and close the
* association by transmitting an ABORT.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1C_ack(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_init_chunk_t *initchunk;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*/
if (!chunk->singleton)
return sctp_sf_violation_chunk(ep, asoc, type, arg, commands);
/* Make sure that the INIT-ACK chunk has a valid length */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_initack_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data;
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
sctp_error_t error = SCTP_ERROR_NO_RESOURCE;
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes. If there are no causes,
* then there wasn't enough memory. Just terminate
* the association.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
sctp_chunk_free(err_chunk);
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
error = SCTP_ERROR_INV_PARAM;
}
}
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
return sctp_stop_t1_and_abort(commands, error, ECONNREFUSED,
asoc, chunk->transport);
}
/* Tag the variable length parameters. Note that we never
* convert the parameters in an INIT chunk.
*/
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
initchunk = (sctp_init_chunk_t *) chunk->chunk_hdr;
sctp_add_cmd_sf(commands, SCTP_CMD_PEER_INIT,
SCTP_PEER_INIT(initchunk));
/* Reset init error count upon receipt of INIT-ACK. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL());
/* 5.1 C) "A" shall stop the T1-init timer and leave
* COOKIE-WAIT state. "A" shall then ... start the T1-cookie
* timer, and enter the COOKIE-ECHOED state.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_ECHOED));
/* SCTP-AUTH: genereate the assocition shared keys so that
* we can potentially signe the COOKIE-ECHO.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_SHKEY, SCTP_NULL());
/* 5.1 C) "A" shall then send the State Cookie received in the
* INIT ACK chunk in a COOKIE ECHO chunk, ...
*/
/* If there is any errors to report, send the ERROR chunk generated
* for unknown parameters as well.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_COOKIE_ECHO,
SCTP_CHUNK(err_chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Respond to a normal COOKIE ECHO chunk.
* We are the side that is being asked for an association.
*
* Section: 5.1 Normal Establishment of an Association, D
* D) Upon reception of the COOKIE ECHO chunk, Endpoint "Z" will reply
* with a COOKIE ACK chunk after building a TCB and moving to
* the ESTABLISHED state. A COOKIE ACK chunk may be bundled with
* any pending DATA chunks (and/or SACK chunks), but the COOKIE ACK
* chunk MUST be the first chunk in the packet.
*
* IMPLEMENTATION NOTE: An implementation may choose to send the
* Communication Up notification to the SCTP user upon reception
* of a valid COOKIE ECHO chunk.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* D) Rules for packet carrying a COOKIE ECHO
*
* - When sending a COOKIE ECHO, the endpoint MUST use the value of the
* Initial Tag received in the INIT ACK.
*
* - The receiver of a COOKIE ECHO follows the procedures in Section 5.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1D_ce(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
sctp_init_chunk_t *peer_init;
struct sctp_chunk *repl;
struct sctp_ulpevent *ev, *ai_ev = NULL;
int error = 0;
struct sctp_chunk *err_chk_p;
struct sock *sk;
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk((sctp_get_ctl_sock()))->ep) {
SCTP_INC_STATS(SCTP_MIB_OUTOFBLUES);
return sctp_sf_tabort_8_4_8(ep, asoc, type, arg, commands);
}
/* Make sure that the COOKIE_ECHO chunk has a valid length.
* In this case, we check that we have enough for at least a
* chunk header. More detailed verification is done
* in sctp_unpack_cookie().
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* If the endpoint is not listening or if the number of associations
* on the TCP-style socket exceed the max backlog, respond with an
* ABORT.
*/
sk = ep->base.sk;
if (!sctp_sstate(sk, LISTENING) ||
(sctp_style(sk, TCP) && sk_acceptq_is_full(sk)))
return sctp_sf_tabort_8_4_8(ep, asoc, type, arg, commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr =
(struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* 5.1 D) Upon reception of the COOKIE ECHO chunk, Endpoint
* "Z" will reply with a COOKIE ACK chunk after building a TCB
* and moving to the ESTABLISHED state.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
}
/* Delay state machine commands until later.
*
* Re-build the bind address for the association is done in
* the sctp_unpack_cookie() already.
*/
/* This is a brand-new association, so these are not yet side
* effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk,
&chunk->subh.cookie_hdr->c.peer_addr,
peer_init, GFP_ATOMIC))
goto nomem_init;
/* SCTP-AUTH: Now that we've populate required fields in
* sctp_process_init, set up the assocaition shared keys as
* necessary so that we can potentially authenticate the ACK
*/
error = sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC);
if (error)
goto nomem_init;
/* SCTP-AUTH: auth_chunk pointer is only set when the cookie-echo
* is supposed to be authenticated and we have to do delayed
* authentication. We've just recreated the association using
* the information in the cookie and now it's much easier to
* do the authentication.
*/
if (chunk->auth_chunk) {
struct sctp_chunk auth;
sctp_ierror_t ret;
/* set-up our fake chunk so that we can process it */
auth.skb = chunk->auth_chunk;
auth.asoc = chunk->asoc;
auth.sctp_hdr = chunk->sctp_hdr;
auth.chunk_hdr = (sctp_chunkhdr_t *)skb_push(chunk->auth_chunk,
sizeof(sctp_chunkhdr_t));
skb_pull(chunk->auth_chunk, sizeof(sctp_chunkhdr_t));
auth.transport = chunk->transport;
ret = sctp_sf_authenticate(ep, new_asoc, type, &auth);
/* We can now safely free the auth_chunk clone */
kfree_skb(chunk->auth_chunk);
if (ret != SCTP_IERROR_NO_ERROR) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
}
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem_init;
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*/
ev = sctp_ulpevent_make_assoc_change(new_asoc, 0, SCTP_COMM_UP, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (new_asoc->peer.adaptation_ind) {
ai_ev = sctp_ulpevent_make_adaptation_indication(new_asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem_aiev;
}
/* Add all the state machine commands now since we've created
* everything. This way we don't introduce memory corruptions
* during side-effect processing and correclty count established
* associations.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(SCTP_MIB_PASSIVEESTABS);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
if (new_asoc->autoclose)
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* This will send the COOKIE ACK */
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* Queue the ASSOC_CHANGE event */
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Send up the Adaptation Layer Indication event */
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
return SCTP_DISPOSITION_CONSUME;
nomem_aiev:
sctp_ulpevent_free(ev);
nomem_ev:
sctp_chunk_free(repl);
nomem_init:
sctp_association_free(new_asoc);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Respond to a normal COOKIE ACK chunk.
* We are the side that is being asked for an association.
*
* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move from the
* COOKIE-ECHOED state to the ESTABLISHED state, stopping the T1-cookie
* timer. It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*
* Verification Tag:
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_1E_ca(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Verify that the chunk length for the COOKIE-ACK is OK.
* If we don't do this, any bundled chunks may be junked.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* Reset init error count upon receipt of COOKIE-ACK,
* to avoid problems with the managemement of this
* counter in stale cookie situations when a transition back
* from the COOKIE-ECHOED state to the COOKIE-WAIT
* state is performed.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_RESET, SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* E) Upon reception of the COOKIE ACK, endpoint "A" will move
* from the COOKIE-ECHOED state to the ESTABLISHED state,
* stopping the T1-cookie timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(SCTP_MIB_ACTIVEESTABS);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
if (asoc->autoclose)
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* It may also notify its ULP about the successful
* establishment of the association with a Communication Up
* notification (see Section 10).
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_COMM_UP,
0, asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ev = sctp_ulpevent_make_adaptation_indication(asoc, GFP_ATOMIC);
if (!ev)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Generate and sendout a heartbeat packet. */
static sctp_disposition_t sctp_sf_heartbeat(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
struct sctp_chunk *reply;
/* Send a heartbeat to our peer. */
reply = sctp_make_heartbeat(asoc, transport);
if (!reply)
return SCTP_DISPOSITION_NOMEM;
/* Set rto_pending indicating that an RTT measurement
* is started with this heartbeat chunk.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_RTO_PENDING,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
}
/* Generate a HEARTBEAT packet on the given transport. */
sctp_disposition_t sctp_sf_sendbeat_8_3(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = (struct sctp_transport *) arg;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
/* Section 3.3.5.
* The Sender-specific Heartbeat Info field should normally include
* information about the sender's current time when this HEARTBEAT
* chunk is sent and the destination transport address to which this
* HEARTBEAT is sent (see Section 8.3).
*/
if (transport->param_flags & SPP_HB_ENABLE) {
if (SCTP_DISPOSITION_NOMEM ==
sctp_sf_heartbeat(ep, asoc, type, arg,
commands))
return SCTP_DISPOSITION_NOMEM;
/* Set transport error counter and association error counter
* when sending heartbeat.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT,
SCTP_TRANSPORT(transport));
}
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_IDLE,
SCTP_TRANSPORT(transport));
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMER_UPDATE,
SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an heartbeat request.
*
* Section: 8.3 Path Heartbeat
* The receiver of the HEARTBEAT should immediately respond with a
* HEARTBEAT ACK that contains the Heartbeat Information field copied
* from the received HEARTBEAT chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* When receiving an SCTP packet, the endpoint MUST ensure that the
* value in the Verification Tag field of the received SCTP packet
* matches its own Tag. If the received Verification Tag value does not
* match the receiver's own tag value, the receiver shall silently
* discard the packet and shall not process it any further except for
* those cases listed in Section 8.5.1 below.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_beat_8_3(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
size_t paylen = 0;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_heartbeat_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* 8.3 The receiver of the HEARTBEAT should immediately
* respond with a HEARTBEAT ACK that contains the Heartbeat
* Information field copied from the received HEARTBEAT chunk.
*/
chunk->subh.hb_hdr = (sctp_heartbeathdr_t *) chunk->skb->data;
paylen = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_chunkhdr_t);
if (!pskb_pull(chunk->skb, paylen))
goto nomem;
reply = sctp_make_heartbeat_ack(asoc, chunk,
chunk->subh.hb_hdr, paylen);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process the returning HEARTBEAT ACK.
*
* Section: 8.3 Path Heartbeat
* Upon the receipt of the HEARTBEAT ACK, the sender of the HEARTBEAT
* should clear the error counter of the destination transport
* address to which the HEARTBEAT was sent, and mark the destination
* transport address as active if it is not so marked. The endpoint may
* optionally report to the upper layer when an inactive destination
* address is marked as active due to the reception of the latest
* HEARTBEAT ACK. The receiver of the HEARTBEAT ACK must also
* clear the association overall error count as well (as defined
* in section 8.1).
*
* The receiver of the HEARTBEAT ACK should also perform an RTT
* measurement for that destination transport address using the time
* value carried in the HEARTBEAT ACK chunk.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_backbeat_8_3(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
union sctp_addr from_addr;
struct sctp_transport *link;
sctp_sender_hb_info_t *hbinfo;
unsigned long max_interval;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the HEARTBEAT-ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t) +
sizeof(sctp_sender_hb_info_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
hbinfo = (sctp_sender_hb_info_t *) chunk->skb->data;
/* Make sure that the length of the parameter is what we expect */
if (ntohs(hbinfo->param_hdr.length) !=
sizeof(sctp_sender_hb_info_t)) {
return SCTP_DISPOSITION_DISCARD;
}
from_addr = hbinfo->daddr;
link = sctp_assoc_lookup_paddr(asoc, &from_addr);
/* This should never happen, but lets log it if so. */
if (unlikely(!link)) {
if (from_addr.sa.sa_family == AF_INET6) {
if (net_ratelimit())
pr_warn("%s association %p could not find address %pI6\n",
__func__,
asoc,
&from_addr.v6.sin6_addr);
} else {
if (net_ratelimit())
pr_warn("%s association %p could not find address %pI4\n",
__func__,
asoc,
&from_addr.v4.sin_addr.s_addr);
}
return SCTP_DISPOSITION_DISCARD;
}
/* Validate the 64-bit random nonce. */
if (hbinfo->hb_nonce != link->hb_nonce)
return SCTP_DISPOSITION_DISCARD;
max_interval = link->hbinterval + link->rto;
/* Check if the timestamp looks valid. */
if (time_after(hbinfo->sent_at, jiffies) ||
time_after(jiffies, hbinfo->sent_at + max_interval)) {
SCTP_DEBUG_PRINTK("%s: HEARTBEAT ACK with invalid timestamp "
"received for transport: %p\n",
__func__, link);
return SCTP_DISPOSITION_DISCARD;
}
/* 8.3 Upon the receipt of the HEARTBEAT ACK, the sender of
* the HEARTBEAT should clear the error counter of the
* destination transport address to which the HEARTBEAT was
* sent and mark the destination transport address as active if
* it is not so marked.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_ON, SCTP_TRANSPORT(link));
return SCTP_DISPOSITION_CONSUME;
}
/* Helper function to send out an abort for the restart
* condition.
*/
static int sctp_sf_send_restart_abort(union sctp_addr *ssa,
struct sctp_chunk *init,
sctp_cmd_seq_t *commands)
{
int len;
struct sctp_packet *pkt;
union sctp_addr_param *addrparm;
struct sctp_errhdr *errhdr;
struct sctp_endpoint *ep;
char buffer[sizeof(struct sctp_errhdr)+sizeof(union sctp_addr_param)];
struct sctp_af *af = sctp_get_af_specific(ssa->v4.sin_family);
/* Build the error on the stack. We are way to malloc crazy
* throughout the code today.
*/
errhdr = (struct sctp_errhdr *)buffer;
addrparm = (union sctp_addr_param *)errhdr->variable;
/* Copy into a parm format. */
len = af->to_addr_param(ssa, addrparm);
len += sizeof(sctp_errhdr_t);
errhdr->cause = SCTP_ERROR_RESTART;
errhdr->length = htons(len);
/* Assign to the control socket. */
ep = sctp_sk((sctp_get_ctl_sock()))->ep;
/* Association is NULL since this may be a restart attack and we
* want to send back the attacker's vtag.
*/
pkt = sctp_abort_pkt_new(ep, NULL, init, errhdr, len);
if (!pkt)
goto out;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, SCTP_PACKET(pkt));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
/* Discard the rest of the inbound packet. */
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
out:
/* Even if there is no memory, treat as a failure so
* the packet will get dropped.
*/
return 0;
}
static bool list_has_sctp_addr(const struct list_head *list,
union sctp_addr *ipaddr)
{
struct sctp_transport *addr;
list_for_each_entry(addr, list, transports) {
if (sctp_cmp_addr_exact(ipaddr, &addr->ipaddr))
return true;
}
return false;
}
/* A restart is occurring, check to make sure no new addresses
* are being added as we may be under a takeover attack.
*/
static int sctp_sf_check_restart_addrs(const struct sctp_association *new_asoc,
const struct sctp_association *asoc,
struct sctp_chunk *init,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *new_addr;
int ret = 1;
/* Implementor's Guide - Section 5.2.2
* ...
* Before responding the endpoint MUST check to see if the
* unexpected INIT adds new addresses to the association. If new
* addresses are added to the association, the endpoint MUST respond
* with an ABORT..
*/
/* Search through all current addresses and make sure
* we aren't adding any new ones.
*/
list_for_each_entry(new_addr, &new_asoc->peer.transport_addr_list,
transports) {
if (!list_has_sctp_addr(&asoc->peer.transport_addr_list,
&new_addr->ipaddr)) {
sctp_sf_send_restart_abort(&new_addr->ipaddr, init,
commands);
ret = 0;
break;
}
}
/* Return success if all addresses were found. */
return ret;
}
/* Populate the verification/tie tags based on overlapping INIT
* scenario.
*
* Note: Do not use in CLOSED or SHUTDOWN-ACK-SENT state.
*/
static void sctp_tietags_populate(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
switch (asoc->state) {
/* 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State */
case SCTP_STATE_COOKIE_WAIT:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = 0;
break;
case SCTP_STATE_COOKIE_ECHOED:
new_asoc->c.my_vtag = asoc->c.my_vtag;
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
/* 5.2.2 Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED,
* COOKIE-WAIT and SHUTDOWN-ACK-SENT
*/
default:
new_asoc->c.my_ttag = asoc->c.my_vtag;
new_asoc->c.peer_ttag = asoc->c.peer_vtag;
break;
}
/* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
*/
new_asoc->rwnd = asoc->rwnd;
new_asoc->c.sinit_num_ostreams = asoc->c.sinit_num_ostreams;
new_asoc->c.sinit_max_instreams = asoc->c.sinit_max_instreams;
new_asoc->c.initial_tsn = asoc->c.initial_tsn;
}
/*
* Compare vtag/tietag values to determine unexpected COOKIE-ECHO
* handling action.
*
* RFC 2960 5.2.4 Handle a COOKIE ECHO when a TCB exists.
*
* Returns value representing action to be taken. These action values
* correspond to Action/Description values in RFC 2960, Table 2.
*/
static char sctp_tietags_compare(struct sctp_association *new_asoc,
const struct sctp_association *asoc)
{
/* In this case, the peer may have restarted. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag != new_asoc->c.peer_vtag) &&
(asoc->c.my_vtag == new_asoc->c.my_ttag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_ttag))
return 'A';
/* Collision case B. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
((asoc->c.peer_vtag != new_asoc->c.peer_vtag) ||
(0 == asoc->c.peer_vtag))) {
return 'B';
}
/* Collision case D. */
if ((asoc->c.my_vtag == new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag))
return 'D';
/* Collision case C. */
if ((asoc->c.my_vtag != new_asoc->c.my_vtag) &&
(asoc->c.peer_vtag == new_asoc->c.peer_vtag) &&
(0 == new_asoc->c.my_ttag) &&
(0 == new_asoc->c.peer_ttag))
return 'C';
/* No match to any of the special cases; discard this packet. */
return 'E';
}
/* Common helper routine for both duplicate and simulataneous INIT
* chunk handling.
*/
static sctp_disposition_t sctp_sf_do_unexpected_init(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
sctp_disposition_t retval;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *repl;
struct sctp_association *new_asoc;
struct sctp_chunk *err_chunk;
struct sctp_packet *packet;
sctp_unrecognized_param_t *unk_param;
int len;
/* 6.10 Bundling
* An endpoint MUST NOT bundle INIT, INIT ACK or
* SHUTDOWN COMPLETE with any other chunks.
*
* IG Section 2.11.2
* Furthermore, we require that the receiver of an INIT chunk MUST
* enforce these rules by silently discarding an arriving packet
* with an INIT chunk that is bundled with other chunks.
*/
if (!chunk->singleton)
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* 3.1 A packet containing an INIT chunk MUST have a zero Verification
* Tag.
*/
if (chunk->sctp_hdr->vtag != 0)
return sctp_sf_tabort_8_4_8(ep, asoc, type, arg, commands);
/* Make sure that the INIT chunk has a valid length.
* In this case, we generate a protocol violation since we have
* an association established.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* Grab the INIT header. */
chunk->subh.init_hdr = (sctp_inithdr_t *) chunk->skb->data;
/* Tag the variable length parameters. */
chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t));
/* Verify the INIT chunk before processing it. */
err_chunk = NULL;
if (!sctp_verify_init(asoc, chunk->chunk_hdr->type,
(sctp_init_chunk_t *)chunk->chunk_hdr, chunk,
&err_chunk)) {
/* This chunk contains fatal error. It is to be discarded.
* Send an ABORT, with causes if there is any.
*/
if (err_chunk) {
packet = sctp_abort_pkt_new(ep, asoc, arg,
(__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t),
ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t));
if (packet) {
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
retval = SCTP_DISPOSITION_CONSUME;
} else {
retval = SCTP_DISPOSITION_NOMEM;
}
goto cleanup;
} else {
return sctp_sf_tabort_8_4_8(ep, asoc, type, arg,
commands);
}
}
/*
* Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of
* outbound streams) into the INIT ACK and cookie.
* FIXME: We are copying parameters from the endpoint not the
* association.
*/
new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC);
if (!new_asoc)
goto nomem;
if (sctp_assoc_set_bind_addr_from_ep(new_asoc,
sctp_scope(sctp_source(chunk)), GFP_ATOMIC) < 0)
goto nomem;
/* In the outbound INIT ACK the endpoint MUST copy its current
* Verification Tag and Peers Verification tag into a reserved
* place (local tie-tag and per tie-tag) within the state cookie.
*/
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk),
(sctp_init_chunk_t *)chunk->chunk_hdr,
GFP_ATOMIC))
goto nomem;
/* Make sure no new addresses are being added during the
* restart. Do not do this check for COOKIE-WAIT state,
* since there are no peer addresses to check against.
* Upon return an ABORT will have been sent if needed.
*/
if (!sctp_state(asoc, COOKIE_WAIT)) {
if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk,
commands)) {
retval = SCTP_DISPOSITION_CONSUME;
goto nomem_retval;
}
}
sctp_tietags_populate(new_asoc, asoc);
/* B) "Z" shall respond immediately with an INIT ACK chunk. */
/* If there are errors need to be reported for unknown parameters,
* make sure to reserve enough room in the INIT ACK for them.
*/
len = 0;
if (err_chunk) {
len = ntohs(err_chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t);
}
repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len);
if (!repl)
goto nomem;
/* If there are errors need to be reported for unknown parameters,
* include them in the outgoing INIT ACK as "Unrecognized parameter"
* parameter.
*/
if (err_chunk) {
/* Get the "Unrecognized parameter" parameter(s) out of the
* ERROR chunk generated by sctp_verify_init(). Since the
* error cause code for "unknown parameter" and the
* "Unrecognized parameter" type is the same, we can
* construct the parameters in INIT ACK by copying the
* ERROR causes over.
*/
unk_param = (sctp_unrecognized_param_t *)
((__u8 *)(err_chunk->chunk_hdr) +
sizeof(sctp_chunkhdr_t));
/* Replace the cause code with the "Unrecognized parameter"
* parameter type.
*/
sctp_addto_chunk(repl, len, unk_param);
}
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/*
* Note: After sending out INIT ACK with the State Cookie parameter,
* "Z" MUST NOT allocate any resources for this new association.
* Otherwise, "Z" will be vulnerable to resource attacks.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
retval = SCTP_DISPOSITION_CONSUME;
return retval;
nomem:
retval = SCTP_DISPOSITION_NOMEM;
nomem_retval:
if (new_asoc)
sctp_association_free(new_asoc);
cleanup:
if (err_chunk)
sctp_chunk_free(err_chunk);
return retval;
}
/*
* Handle simultaneous INIT.
* This means we started an INIT and then we got an INIT request from
* our peer.
*
* Section: 5.2.1 INIT received in COOKIE-WAIT or COOKIE-ECHOED State (Item B)
* This usually indicates an initialization collision, i.e., each
* endpoint is attempting, at about the same time, to establish an
* association with the other endpoint.
*
* Upon receipt of an INIT in the COOKIE-WAIT or COOKIE-ECHOED state, an
* endpoint MUST respond with an INIT ACK using the same parameters it
* sent in its original INIT chunk (including its Verification Tag,
* unchanged). These original parameters are combined with those from the
* newly received INIT chunk. The endpoint shall also generate a State
* Cookie with the INIT ACK. The endpoint uses the parameters sent in its
* INIT to calculate the State Cookie.
*
* After that, the endpoint MUST NOT change its state, the T1-init
* timer shall be left running and the corresponding TCB MUST NOT be
* destroyed. The normal procedures for handling State Cookies when
* a TCB exists will resolve the duplicate INITs to a single association.
*
* For an endpoint that is in the COOKIE-ECHOED state it MUST populate
* its Tie-Tags with the Tag information of itself and its peer (see
* section 5.2.2 for a description of the Tie-Tags).
*
* Verification Tag: Not explicit, but an INIT can not have a valid
* verification tag, so we skip the check.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_1_siminit(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Call helper to do the real work for both simulataneous and
* duplicate INIT chunk handling.
*/
return sctp_sf_do_unexpected_init(ep, asoc, type, arg, commands);
}
/*
* Handle duplicated INIT messages. These are usually delayed
* restransmissions.
*
* Section: 5.2.2 Unexpected INIT in States Other than CLOSED,
* COOKIE-ECHOED and COOKIE-WAIT
*
* Unless otherwise stated, upon reception of an unexpected INIT for
* this association, the endpoint shall generate an INIT ACK with a
* State Cookie. In the outbound INIT ACK the endpoint MUST copy its
* current Verification Tag and peer's Verification Tag into a reserved
* place within the state cookie. We shall refer to these locations as
* the Peer's-Tie-Tag and the Local-Tie-Tag. The outbound SCTP packet
* containing this INIT ACK MUST carry a Verification Tag value equal to
* the Initiation Tag found in the unexpected INIT. And the INIT ACK
* MUST contain a new Initiation Tag (randomly generated see Section
* 5.3.1). Other parameters for the endpoint SHOULD be copied from the
* existing parameters of the association (e.g. number of outbound
* streams) into the INIT ACK and cookie.
*
* After sending out the INIT ACK, the endpoint shall take no further
* actions, i.e., the existing association, including its current state,
* and the corresponding TCB MUST NOT be changed.
*
* Note: Only when a TCB exists and the association is not in a COOKIE-
* WAIT state are the Tie-Tags populated. For a normal association INIT
* (i.e. the endpoint is in a COOKIE-WAIT state), the Tie-Tags MUST be
* set to 0 (indicating that no previous TCB existed). The INIT ACK and
* State Cookie are populated as specified in section 5.2.1.
*
* Verification Tag: Not specified, but an INIT has no way of knowing
* what the verification tag could be, so we ignore it.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_2_dupinit(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Call helper to do the real work for both simulataneous and
* duplicate INIT chunk handling.
*/
return sctp_sf_do_unexpected_init(ep, asoc, type, arg, commands);
}
/*
* Unexpected INIT-ACK handler.
*
* Section 5.2.3
* If an INIT ACK received by an endpoint in any state other than the
* COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk.
* An unexpected INIT ACK usually indicates the processing of an old or
* duplicated INIT chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_3_initack(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
/* Per the above section, we'll discard the chunk if we have an
* endpoint. If this is an OOTB INIT-ACK, treat it as such.
*/
if (ep == sctp_sk((sctp_get_ctl_sock()))->ep)
return sctp_sf_ootb(ep, asoc, type, arg, commands);
else
return sctp_sf_discard_chunk(ep, asoc, type, arg, commands);
}
/* Unexpected COOKIE-ECHO handler for peer restart (Table 2, action 'A')
*
* Section 5.2.4
* A) In this case, the peer may have restarted.
*/
static sctp_disposition_t sctp_sf_do_dupcook_a(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
sctp_init_chunk_t *peer_init;
struct sctp_ulpevent *ev;
struct sctp_chunk *repl;
struct sctp_chunk *err;
sctp_disposition_t disposition;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
/* Make sure no new addresses are being added during the
* restart. Though this is a pretty complicated attack
* since you'd have to get inside the cookie.
*/
if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands)) {
return SCTP_DISPOSITION_CONSUME;
}
/* If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes
* the peer has restarted (Action A), it MUST NOT setup a new
* association but instead resend the SHUTDOWN ACK and send an ERROR
* chunk with a "Cookie Received while Shutting Down" error cause to
* its peer.
*/
if (sctp_state(asoc, SHUTDOWN_ACK_SENT)) {
disposition = sctp_sf_do_9_2_reshutack(ep, asoc,
SCTP_ST_CHUNK(chunk->chunk_hdr->type),
chunk, commands);
if (SCTP_DISPOSITION_NOMEM == disposition)
goto nomem;
err = sctp_make_op_error(asoc, chunk,
SCTP_ERROR_COOKIE_IN_SHUTDOWN,
NULL, 0, 0);
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return SCTP_DISPOSITION_CONSUME;
}
/* For now, stop pending T3-rtx and SACK timers, fail any unsent/unacked
* data. Consider the optional choice of resending of this data.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_SACK));
sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_OUTQUEUE, SCTP_NULL());
/* Stop pending T4-rto timer, teardown ASCONF queue, ASCONF-ACK queue
* and ASCONF-ACK cache.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_ASCONF_QUEUE, SCTP_NULL());
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem;
/* Report association restart to upper layer. */
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_RESTART, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Update the content of current association. */
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
return SCTP_DISPOSITION_CONSUME;
nomem_ev:
sctp_chunk_free(repl);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'B')
*
* Section 5.2.4
* B) In this case, both sides may be attempting to start an association
* at about the same time but the peer endpoint started its INIT
* after responding to the local endpoint's INIT
*/
/* This case represents an initialization collision. */
static sctp_disposition_t sctp_sf_do_dupcook_b(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
sctp_init_chunk_t *peer_init;
struct sctp_chunk *repl;
/* new_asoc is a brand-new association, so these are not yet
* side effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init,
GFP_ATOMIC))
goto nomem;
/* Update the content of current association. */
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*
* Sadly, this needs to be implemented as a side-effect, because
* we are not guaranteed to have set the association id of the real
* association and so these notifications need to be delayed until
* the association id is allocated.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_CHANGE, SCTP_U8(SCTP_COMM_UP));
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*
* This also needs to be done as a side effect for the same reason as
* above.
*/
if (asoc->peer.adaptation_ind)
sctp_add_cmd_sf(commands, SCTP_CMD_ADAPTATION_IND, SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Unexpected COOKIE-ECHO handler for setup collision (Table 2, action 'C')
*
* Section 5.2.4
* C) In this case, the local endpoint's cookie has arrived late.
* Before it arrived, the local endpoint sent an INIT and received an
* INIT-ACK and finally sent a COOKIE ECHO with the peer's same tag
* but a new tag of its own.
*/
/* This case represents an initialization collision. */
static sctp_disposition_t sctp_sf_do_dupcook_c(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
/* The cookie should be silently discarded.
* The endpoint SHOULD NOT change states and should leave
* any timers running.
*/
return SCTP_DISPOSITION_DISCARD;
}
/* Unexpected COOKIE-ECHO handler lost chunk (Table 2, action 'D')
*
* Section 5.2.4
*
* D) When both local and remote tags match the endpoint should always
* enter the ESTABLISHED state, if it has not already done so.
*/
/* This case represents an initialization collision. */
static sctp_disposition_t sctp_sf_do_dupcook_d(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_association *new_asoc)
{
struct sctp_ulpevent *ev = NULL, *ai_ev = NULL;
struct sctp_chunk *repl;
/* Clarification from Implementor's Guide:
* D) When both local and remote tags match the endpoint should
* enter the ESTABLISHED state, if it is in the COOKIE-ECHOED state.
* It should stop any cookie timer that may be running and send
* a COOKIE ACK.
*/
/* Don't accidentally move back into established state. */
if (asoc->state < SCTP_STATE_ESTABLISHED) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START,
SCTP_NULL());
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose
* to send the Communication Up notification to the
* SCTP user upon reception of a valid COOKIE
* ECHO chunk.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0,
SCTP_COMM_UP, 0,
asoc->c.sinit_num_ostreams,
asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter,
* SCTP delivers this notification to inform the application
* that of the peers requested adaptation layer.
*/
if (asoc->peer.adaptation_ind) {
ai_ev = sctp_ulpevent_make_adaptation_indication(asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem;
}
}
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
if (ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
return SCTP_DISPOSITION_CONSUME;
nomem:
if (ai_ev)
sctp_ulpevent_free(ai_ev);
if (ev)
sctp_ulpevent_free(ev);
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle a duplicate COOKIE-ECHO. This usually means a cookie-carrying
* chunk was retransmitted and then delayed in the network.
*
* Section: 5.2.4 Handle a COOKIE ECHO when a TCB exists
*
* Verification Tag: None. Do cookie validation.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_5_2_4_dupcook(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_disposition_t retval;
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
int error = 0;
char action;
struct sctp_chunk *err_chk_p;
/* Make sure that the chunk has a valid length from the protocol
* perspective. In this case check to make sure we have at least
* enough for the chunk header. Cookie length verification is
* done later.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr = (struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* In RFC 2960 5.2.4 3, if both Verification Tags in the State Cookie
* of a duplicate COOKIE ECHO match the Verification Tags of the
* current association, consider the State Cookie valid even if
* the lifespan is exceeded.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
}
/* Compare the tie_tag in cookie with the verification tag of
* current association.
*/
action = sctp_tietags_compare(new_asoc, asoc);
switch (action) {
case 'A': /* Association restart. */
retval = sctp_sf_do_dupcook_a(ep, asoc, chunk, commands,
new_asoc);
break;
case 'B': /* Collision case B. */
retval = sctp_sf_do_dupcook_b(ep, asoc, chunk, commands,
new_asoc);
break;
case 'C': /* Collision case C. */
retval = sctp_sf_do_dupcook_c(ep, asoc, chunk, commands,
new_asoc);
break;
case 'D': /* Collision case D. */
retval = sctp_sf_do_dupcook_d(ep, asoc, chunk, commands,
new_asoc);
break;
default: /* Discard packet for all others. */
retval = sctp_sf_pdiscard(ep, asoc, type, arg, commands);
break;
}
/* Delete the tempory new association. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return retval;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process an ABORT. (SHUTDOWN-PENDING state)
*
* See sctp_sf_do_9_1_abort().
*/
sctp_disposition_t sctp_sf_shutdown_pending_abort(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_discard_chunk(ep, asoc, type, arg, commands);
return __sctp_sf_do_9_1_abort(ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-SENT state)
*
* See sctp_sf_do_9_1_abort().
*/
sctp_disposition_t sctp_sf_shutdown_sent_abort(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_discard_chunk(ep, asoc, type, arg, commands);
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return __sctp_sf_do_9_1_abort(ep, asoc, type, arg, commands);
}
/*
* Process an ABORT. (SHUTDOWN-ACK-SENT state)
*
* See sctp_sf_do_9_1_abort().
*/
sctp_disposition_t sctp_sf_shutdown_ack_sent_abort(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return sctp_sf_shutdown_sent_abort(ep, asoc, type, arg, commands);
}
/*
* Handle an Error received in COOKIE_ECHOED state.
*
* Only handle the error type of stale COOKIE Error, the other errors will
* be ignored.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_cookie_echoed_err(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_errhdr_t *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length.
* The parameter walking depends on this as well.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_operr_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* Process the error here */
/* FUTURE FIXME: When PR-SCTP related and other optional
* parms are emitted, this will have to change to handle multiple
* errors.
*/
sctp_walk_errors(err, chunk->chunk_hdr) {
if (SCTP_ERROR_STALE_COOKIE == err->cause)
return sctp_sf_do_5_2_6_stale(ep, asoc, type,
arg, commands);
}
/* It is possible to have malformed error causes, and that
* will cause us to end the walk early. However, since
* we are discarding the packet, there should be no adverse
* affects.
*/
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
/*
* Handle a Stale COOKIE Error
*
* Section: 5.2.6 Handle Stale COOKIE Error
* If the association is in the COOKIE-ECHOED state, the endpoint may elect
* one of the following three alternatives.
* ...
* 3) Send a new INIT chunk to the endpoint, adding a Cookie
* Preservative parameter requesting an extension to the lifetime of
* the State Cookie. When calculating the time extension, an
* implementation SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no more
* than 1 second beyond the measured RTT, due to long State Cookie
* lifetimes making the endpoint more subject to a replay attack.
*
* Verification Tag: Not explicit, but safe to ignore.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_do_5_2_6_stale(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
time_t stale;
sctp_cookie_preserve_param_t bht;
sctp_errhdr_t *err;
struct sctp_chunk *reply;
struct sctp_bind_addr *bp;
int attempts = asoc->init_err_counter + 1;
if (attempts > asoc->max_init_attempts) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_STALE_COOKIE));
return SCTP_DISPOSITION_DELETE_TCB;
}
err = (sctp_errhdr_t *)(chunk->skb->data);
/* When calculating the time extension, an implementation
* SHOULD use the RTT information measured based on the
* previous COOKIE ECHO / ERROR exchange, and should add no
* more than 1 second beyond the measured RTT, due to long
* State Cookie lifetimes making the endpoint more subject to
* a replay attack.
* Measure of Staleness's unit is usec. (1/1000000 sec)
* Suggested Cookie Life-span Increment's unit is msec.
* (1/1000 sec)
* In general, if you use the suggested cookie life, the value
* found in the field of measure of staleness should be doubled
* to give ample time to retransmit the new cookie and thus
* yield a higher probability of success on the reattempt.
*/
stale = ntohl(*(__be32 *)((u8 *)err + sizeof(sctp_errhdr_t)));
stale = (stale * 2) / 1000;
bht.param_hdr.type = SCTP_PARAM_COOKIE_PRESERVATIVE;
bht.param_hdr.length = htons(sizeof(bht));
bht.lifespan_increment = htonl(stale);
/* Build that new INIT chunk. */
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
reply = sctp_make_init(asoc, bp, GFP_ATOMIC, sizeof(bht));
if (!reply)
goto nomem;
sctp_addto_chunk(reply, sizeof(bht), &bht);
/* Clear peer's init_tag cached in assoc as we are sending a new INIT */
sctp_add_cmd_sf(commands, SCTP_CMD_CLEAR_INIT_TAG, SCTP_NULL());
/* Stop pending T3-rtx and heartbeat timers */
sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
/* Delete non-primary peer ip addresses since we are transitioning
* back to the COOKIE-WAIT state
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DEL_NON_PRIMARY, SCTP_NULL());
/* If we've sent any data bundled with COOKIE-ECHO we will need to
* resend
*/
sctp_add_cmd_sf(commands, SCTP_CMD_T1_RETRAN,
SCTP_TRANSPORT(asoc->peer.primary_path));
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_COUNTER_INC, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_WAIT));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process an ABORT.
*
* Section: 9.1
* After checking the Verification Tag, the receiving endpoint shall
* remove the association from its record, and shall report the
* termination to its upper layer.
*
* Verification Tag: 8.5.1 Exceptions in Verification Tag Rules
* B) Rules for packet carrying ABORT:
*
* - The endpoint shall always fill in the Verification Tag field of the
* outbound packet with the destination endpoint's tag value if it
* is known.
*
* - If the ABORT is sent in response to an OOTB packet, the endpoint
* MUST follow the procedure described in Section 8.4.
*
* - The receiver MUST accept the packet if the Verification Tag
* matches either its own tag, OR the tag of its peer. Otherwise, the
* receiver MUST silently discard the packet and take no further
* action.
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_9_1_abort(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* ADD-IP: Special case for ABORT chunks
* F4) One special consideration is that ABORT Chunks arriving
* destined to the IP address being deleted MUST be
* ignored (see Section 5.3.1 for further details).
*/
if (SCTP_ADDR_DEL ==
sctp_bind_addr_state(&asoc->base.bind_addr, &chunk->dest))
return sctp_sf_discard_chunk(ep, asoc, type, arg, commands);
return __sctp_sf_do_9_1_abort(ep, asoc, type, arg, commands);
}
static sctp_disposition_t __sctp_sf_do_9_1_abort(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
unsigned len;
__be16 error = SCTP_ERROR_NO_ERROR;
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr)) {
sctp_errhdr_t *err;
sctp_walk_errors(err, chunk->chunk_hdr);
if ((void *)err != (void *)chunk->chunk_end)
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
error = ((sctp_errhdr_t *)chunk->skb->data)->cause;
}
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNRESET));
/* ASSOC_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(error));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/*
* Process an ABORT. (COOKIE-WAIT state)
*
* See sctp_sf_do_9_1_abort() above.
*/
sctp_disposition_t sctp_sf_cookie_wait_abort(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
unsigned len;
__be16 error = SCTP_ERROR_NO_ERROR;
if (!sctp_vtag_verify_either(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the ABORT chunk has a valid length.
* Since this is an ABORT chunk, we have to discard it
* because of the following text:
* RFC 2960, Section 3.3.7
* If an endpoint receives an ABORT with a format error or for an
* association that doesn't exist, it MUST silently discard it.
* Because the length is "invalid", we can't really discard just
* as we do not know its true length. So, to be safe, discard the
* packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_abort_chunk_t)))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* See if we have an error cause code in the chunk. */
len = ntohs(chunk->chunk_hdr->length);
if (len >= sizeof(struct sctp_chunkhdr) + sizeof(struct sctp_errhdr))
error = ((sctp_errhdr_t *)chunk->skb->data)->cause;
return sctp_stop_t1_and_abort(commands, error, ECONNREFUSED, asoc,
chunk->transport);
}
/*
* Process an incoming ICMP as an ABORT. (COOKIE-WAIT state)
*/
sctp_disposition_t sctp_sf_cookie_wait_icmp_abort(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return sctp_stop_t1_and_abort(commands, SCTP_ERROR_NO_ERROR,
ENOPROTOOPT, asoc,
(struct sctp_transport *)arg);
}
/*
* Process an ABORT. (COOKIE-ECHOED state)
*/
sctp_disposition_t sctp_sf_cookie_echoed_abort(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_abort(ep, asoc, type, arg, commands);
}
/*
* Stop T1 timer and abort association with "INIT failed".
*
* This is common code called by several sctp_sf_*_abort() functions above.
*/
static sctp_disposition_t sctp_stop_t1_and_abort(sctp_cmd_seq_t *commands,
__be16 error, int sk_err,
const struct sctp_association *asoc,
struct sctp_transport *transport)
{
SCTP_DEBUG_PRINTK("ABORT received (INIT).\n");
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(sk_err));
/* CMD_INIT_FAILED will DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(error));
return SCTP_DISPOSITION_ABORT;
}
/*
* sctp_sf_do_9_2_shut
*
* Section: 9.2
* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
*
* - stop accepting new data from its SCTP user
*
* - verify, by checking the Cumulative TSN Ack field of the chunk,
* that all its outstanding DATA chunks have been received by the
* SHUTDOWN sender.
*
* Once an endpoint as reached the SHUTDOWN-RECEIVED state it MUST NOT
* send a SHUTDOWN in response to a ULP request. And should discard
* subsequent SHUTDOWN chunks.
*
* If there are still outstanding DATA chunks left, the SHUTDOWN
* receiver shall continue to follow normal data transmission
* procedures defined in Section 6 until all outstanding DATA chunks
* are acknowledged; however, the SHUTDOWN receiver MUST NOT accept
* new data from its SCTP user.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_9_2_shutdown(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_shutdownhdr_t *sdh;
sctp_disposition_t disposition;
struct sctp_ulpevent *ev;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk,
sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* Convert the elaborate header. */
sdh = (sctp_shutdownhdr_t *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_shutdownhdr_t));
chunk->subh.shutdown_hdr = sdh;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
SCTP_DEBUG_PRINTK("ctsn %x\n", ctsn);
SCTP_DEBUG_PRINTK("ctsn_ack_point %x\n", asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(ep, asoc, type, arg, commands);
/* API 5.3.1.5 SCTP_SHUTDOWN_EVENT
* When a peer sends a SHUTDOWN, SCTP delivers this notification to
* inform the application that it should cease sending data.
*/
ev = sctp_ulpevent_make_shutdown_event(asoc, 0, GFP_ATOMIC);
if (!ev) {
disposition = SCTP_DISPOSITION_NOMEM;
goto out;
}
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the reception of the SHUTDOWN, the peer endpoint shall
* - enter the SHUTDOWN-RECEIVED state,
* - stop accepting new data from its SCTP user
*
* [This is implicit in the new state.]
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_RECEIVED));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_shutdown_ack(ep, asoc, type,
arg, commands);
}
if (SCTP_DISPOSITION_NOMEM == disposition)
goto out;
/* - verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN,
SCTP_BE32(chunk->subh.shutdown_hdr->cum_tsn_ack));
out:
return disposition;
}
/*
* sctp_sf_do_9_2_shut_ctsn
*
* Once an endpoint has reached the SHUTDOWN-RECEIVED state,
* it MUST NOT send a SHUTDOWN in response to a ULP request.
* The Cumulative TSN Ack of the received SHUTDOWN chunk
* MUST be processed.
*/
sctp_disposition_t sctp_sf_do_9_2_shut_ctsn(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_shutdownhdr_t *sdh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk,
sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
sdh = (sctp_shutdownhdr_t *)chunk->skb->data;
ctsn = ntohl(sdh->cum_tsn_ack);
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
SCTP_DEBUG_PRINTK("ctsn %x\n", ctsn);
SCTP_DEBUG_PRINTK("ctsn_ack_point %x\n", asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(ep, asoc, type, arg, commands);
/* verify, by checking the Cumulative TSN Ack field of the
* chunk, that all its outstanding DATA chunks have been
* received by the SHUTDOWN sender.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_CTSN,
SCTP_BE32(sdh->cum_tsn_ack));
return SCTP_DISPOSITION_CONSUME;
}
/* RFC 2960 9.2
* If an endpoint is in SHUTDOWN-ACK-SENT state and receives an INIT chunk
* (e.g., if the SHUTDOWN COMPLETE was lost) with source and destination
* transport addresses (either in the IP addresses or in the INIT chunk)
* that belong to this association, it should discard the INIT chunk and
* retransmit the SHUTDOWN ACK chunk.
*/
sctp_disposition_t sctp_sf_do_9_2_reshutack(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = (struct sctp_chunk *) arg;
struct sctp_chunk *reply;
/* Make sure that the chunk has a valid length */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* Since we are not going to really process this INIT, there
* is no point in verifying chunk boundries. Just generate
* the SHUTDOWN ACK.
*/
reply = sctp_make_shutdown_ack(asoc, chunk);
if (NULL == reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-SHUTDOWN timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* sctp_sf_do_ecn_cwr
*
* Section: Appendix A: Explicit Congestion Notification
*
* CWR:
*
* RFC 2481 details a specific bit for a sender to send in the header of
* its next outbound TCP segment to indicate to its peer that it has
* reduced its congestion window. This is termed the CWR bit. For
* SCTP the same indication is made by including the CWR chunk.
* This chunk contains one data element, i.e. the TSN number that
* was sent in the ECNE chunk. This element represents the lowest
* TSN number in the datagram that was originally marked with the
* CE bit.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_ecn_cwr(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_cwrhdr_t *cwr;
struct sctp_chunk *chunk = arg;
u32 lowest_tsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_ecne_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
cwr = (sctp_cwrhdr_t *) chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_cwrhdr_t));
lowest_tsn = ntohl(cwr->lowest_tsn);
/* Does this CWR ack the last sent congestion notification? */
if (TSN_lte(asoc->last_ecne_tsn, lowest_tsn)) {
/* Stop sending ECNE. */
sctp_add_cmd_sf(commands,
SCTP_CMD_ECN_CWR,
SCTP_U32(lowest_tsn));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_do_ecne
*
* Section: Appendix A: Explicit Congestion Notification
*
* ECN-Echo
*
* RFC 2481 details a specific bit for a receiver to send back in its
* TCP acknowledgements to notify the sender of the Congestion
* Experienced (CE) bit having arrived from the network. For SCTP this
* same indication is made by including the ECNE chunk. This chunk
* contains one data element, i.e. the lowest TSN associated with the IP
* datagram marked with the CE bit.....
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_ecne(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_ecnehdr_t *ecne;
struct sctp_chunk *chunk = arg;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_ecne_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
ecne = (sctp_ecnehdr_t *) chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_ecnehdr_t));
/* If this is a newer ECNE than the last CWR packet we sent out */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_ECNE,
SCTP_U32(ntohl(ecne->lowest_tsn)));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of each valid
* DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated within
* 200 ms of the arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to be more
* conservative than the algorithms detailed in this document allow.
* However, an SCTP transmitter MUST NOT be more aggressive than the
* following algorithms allow.
*
* A SCTP receiver MUST NOT generate more than one SACK for every
* incoming packet, other than to update the offered window as the
* receiving application consumes new data.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_data_6_2(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_arg_t force = SCTP_NOFORCE();
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_data_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands );
switch (error) {
case SCTP_IERROR_NO_ERROR:
break;
case SCTP_IERROR_HIGH_TSN:
case SCTP_IERROR_BAD_STREAM:
SCTP_INC_STATS(SCTP_MIB_IN_DATA_CHUNK_DISCARDS);
goto discard_noforce;
case SCTP_IERROR_DUP_TSN:
case SCTP_IERROR_IGNORE_TSN:
SCTP_INC_STATS(SCTP_MIB_IN_DATA_CHUNK_DISCARDS);
goto discard_force;
case SCTP_IERROR_NO_DATA:
goto consume;
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_abort_violation(ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t));
default:
BUG();
}
if (chunk->chunk_hdr->flags & SCTP_DATA_SACK_IMM)
force = SCTP_FORCE();
if (asoc->autoclose) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
}
/* If this is the last chunk in a packet, we need to count it
* toward sack generation. Note that we need to SACK every
* OTHER packet containing data chunks, EVEN IF WE DISCARD
* THEM. We elect to NOT generate SACK's if the chunk fails
* the verification tag test.
*
* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* The SCTP endpoint MUST always acknowledge the reception of
* each valid DATA chunk.
*
* The guidelines on delayed acknowledgement algorithm
* specified in Section 4.2 of [RFC2581] SHOULD be followed.
* Specifically, an acknowledgement SHOULD be generated for at
* least every second packet (not every second DATA chunk)
* received, and SHOULD be generated within 200 ms of the
* arrival of any unacknowledged DATA chunk. In some
* situations it may be beneficial for an SCTP transmitter to
* be more conservative than the algorithms detailed in this
* document allow. However, an SCTP transmitter MUST NOT be
* more aggressive than the following algorithms allow.
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return SCTP_DISPOSITION_CONSUME;
discard_force:
/* RFC 2960 6.2 Acknowledgement on Reception of DATA Chunks
*
* When a packet arrives with duplicate DATA chunk(s) and with
* no new DATA chunk(s), the endpoint MUST immediately send a
* SACK with no delay. If a packet arrives with duplicate
* DATA chunk(s) bundled with new DATA chunks, the endpoint
* MAY immediately send a SACK. Normally receipt of duplicate
* DATA chunks will occur when the original SACK chunk was lost
* and the peer's RTO has expired. The duplicate TSN number(s)
* SHOULD be reported in the SACK as duplicate.
*/
/* In our case, we split the MAY SACK advice up whether or not
* the last chunk is a duplicate.'
*/
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return SCTP_DISPOSITION_DISCARD;
discard_noforce:
if (chunk->end_of_packet)
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, force);
return SCTP_DISPOSITION_DISCARD;
consume:
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_eat_data_fast_4_4
*
* Section: 4 (4)
* (4) In SHUTDOWN-SENT state the endpoint MUST acknowledge any received
* DATA chunks without delay.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_data_fast_4_4(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
int error;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_data_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
error = sctp_eat_data(asoc, chunk, commands );
switch (error) {
case SCTP_IERROR_NO_ERROR:
case SCTP_IERROR_HIGH_TSN:
case SCTP_IERROR_DUP_TSN:
case SCTP_IERROR_IGNORE_TSN:
case SCTP_IERROR_BAD_STREAM:
break;
case SCTP_IERROR_NO_DATA:
goto consume;
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_abort_violation(ep, asoc, chunk, commands,
(u8 *)chunk->subh.data_hdr, sizeof(sctp_datahdr_t));
default:
BUG();
}
/* Go a head and force a SACK, since we are shutting down. */
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
if (chunk->end_of_packet) {
/* We must delay the chunk creation since the cumulative
* TSN has not been updated yet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
}
consume:
return SCTP_DISPOSITION_CONSUME;
}
/*
* Section: 6.2 Processing a Received SACK
* D) Any time a SACK arrives, the endpoint performs the following:
*
* i) If Cumulative TSN Ack is less than the Cumulative TSN Ack Point,
* then drop the SACK. Since Cumulative TSN Ack is monotonically
* increasing, a SACK whose Cumulative TSN Ack is less than the
* Cumulative TSN Ack Point indicates an out-of-order SACK.
*
* ii) Set rwnd equal to the newly received a_rwnd minus the number
* of bytes still outstanding after processing the Cumulative TSN Ack
* and the Gap Ack Blocks.
*
* iii) If the SACK is missing a TSN that was previously
* acknowledged via a Gap Ack Block (e.g., the data receiver
* reneged on the data), then mark the corresponding DATA chunk
* as available for retransmit: Mark it as missing for fast
* retransmit as described in Section 7.2.4 and if no retransmit
* timer is running for the destination address to which the DATA
* chunk was originally transmitted, then T3-rtx is started for
* that destination address.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_sack_6_2(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_sackhdr_t *sackh;
__u32 ctsn;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the SACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_sack_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* Pull the SACK chunk from the data buffer */
sackh = sctp_sm_pull_sack(chunk);
/* Was this a bogus SACK? */
if (!sackh)
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
chunk->subh.sack_hdr = sackh;
ctsn = ntohl(sackh->cum_tsn_ack);
/* i) If Cumulative TSN Ack is less than the Cumulative TSN
* Ack Point, then drop the SACK. Since Cumulative TSN
* Ack is monotonically increasing, a SACK whose
* Cumulative TSN Ack is less than the Cumulative TSN Ack
* Point indicates an out-of-order SACK.
*/
if (TSN_lt(ctsn, asoc->ctsn_ack_point)) {
SCTP_DEBUG_PRINTK("ctsn %x\n", ctsn);
SCTP_DEBUG_PRINTK("ctsn_ack_point %x\n", asoc->ctsn_ack_point);
return SCTP_DISPOSITION_DISCARD;
}
/* If Cumulative TSN Ack beyond the max tsn currently
* send, terminating the association and respond to the
* sender with an ABORT.
*/
if (!TSN_lt(ctsn, asoc->next_tsn))
return sctp_sf_violation_ctsn(ep, asoc, type, arg, commands);
/* Return this SACK for further processing. */
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_SACK, SCTP_SACKH(sackh));
/* Note: We do the rest of the work on the PROCESS_SACK
* sideeffect.
*/
return SCTP_DISPOSITION_CONSUME;
}
/*
* Generate an ABORT in response to a packet.
*
* Section: 8.4 Handle "Out of the blue" Packets, sctpimpguide 2.41
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*
* Verification Tag:
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_tabort_8_4_8(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(asoc, chunk);
if (packet) {
/* Make an ABORT. The T bit will be set if the asoc
* is NULL.
*/
abort = sctp_make_abort(asoc, chunk, 0);
if (!abort) {
sctp_ootb_pkt_free(packet);
return SCTP_DISPOSITION_NOMEM;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
sctp_sf_pdiscard(ep, asoc, type, arg, commands);
return SCTP_DISPOSITION_CONSUME;
}
return SCTP_DISPOSITION_NOMEM;
}
/*
* Received an ERROR chunk from peer. Generate SCTP_REMOTE_ERROR
* event as ULP notification for each cause included in the chunk.
*
* API 5.3.1.3 - SCTP_REMOTE_ERROR
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_operr_notify(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_errhdr_t *err;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the ERROR chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_operr_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
sctp_walk_errors(err, chunk->chunk_hdr);
if ((void *)err != (void *)chunk->chunk_end)
return sctp_sf_violation_paramlen(ep, asoc, type, arg,
(void *)err, commands);
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_OPERR,
SCTP_CHUNK(chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an inbound SHUTDOWN ACK.
*
* From Section 9.2:
* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its
* peer, and remove all record of the association.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_final(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *reply;
struct sctp_ulpevent *ev;
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* 10.2 H) SHUTDOWN COMPLETE notification
*
* When SCTP completes the shutdown procedures (section 9.2) this
* notification is passed to the upper layer.
*/
ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_SHUTDOWN_COMP,
0, 0, 0, NULL, GFP_ATOMIC);
if (!ev)
goto nomem;
/* ...send a SHUTDOWN COMPLETE chunk to its peer, */
reply = sctp_make_shutdown_complete(asoc, chunk);
if (!reply)
goto nomem_chunk;
/* Do all the commands now (after allocation), so that we
* have consistent state if memory allocation failes
*/
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall
* stop the T2-shutdown timer,
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(SCTP_MIB_SHUTDOWNS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
/* ...and remove all record of the association. */
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
nomem_chunk:
sctp_ulpevent_free(ev);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* RFC 2960, 8.4 - Handle "Out of the blue" Packets, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* 8) The receiver should respond to the sender of the OOTB packet with
* an ABORT. When sending the ABORT, the receiver of the OOTB packet
* MUST fill in the Verification Tag field of the outbound packet
* with the value found in the Verification Tag field of the OOTB
* packet and set the T-bit in the Chunk Flags to indicate that the
* Verification Tag is reflected. After sending this ABORT, the
* receiver of the OOTB packet shall discard the OOTB packet and take
* no further action.
*/
sctp_disposition_t sctp_sf_ootb(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sk_buff *skb = chunk->skb;
sctp_chunkhdr_t *ch;
sctp_errhdr_t *err;
__u8 *ch_end;
int ootb_shut_ack = 0;
int ootb_cookie_ack = 0;
SCTP_INC_STATS(SCTP_MIB_OUTOFBLUES);
ch = (sctp_chunkhdr_t *) chunk->chunk_hdr;
do {
/* Report violation if the chunk is less then minimal */
if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* Now that we know we at least have a chunk header,
* do things that are type appropriate.
*/
if (SCTP_CID_SHUTDOWN_ACK == ch->type)
ootb_shut_ack = 1;
/* RFC 2960, Section 3.3.7
* Moreover, under any circumstances, an endpoint that
* receives an ABORT MUST NOT respond to that ABORT by
* sending an ABORT of its own.
*/
if (SCTP_CID_ABORT == ch->type)
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR
* or a COOKIE ACK the SCTP Packet should be silently
* discarded.
*/
if (SCTP_CID_COOKIE_ACK == ch->type)
ootb_cookie_ack = 1;
if (SCTP_CID_ERROR == ch->type) {
sctp_walk_errors(err, ch) {
if (SCTP_ERROR_STALE_COOKIE == err->cause) {
ootb_cookie_ack = 1;
break;
}
}
}
/* Report violation if chunk len overflows */
ch_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length));
if (ch_end > skb_tail_pointer(skb))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
ch = (sctp_chunkhdr_t *) ch_end;
} while (ch_end < skb_tail_pointer(skb));
if (ootb_shut_ack)
return sctp_sf_shut_8_4_5(ep, asoc, type, arg, commands);
else if (ootb_cookie_ack)
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
else
return sctp_sf_tabort_8_4_8(ep, asoc, type, arg, commands);
}
/*
* Handle an "Out of the blue" SHUTDOWN ACK.
*
* Section: 8.4 5, sctpimpguide 2.41.
*
* 5) If the packet contains a SHUTDOWN ACK chunk, the receiver should
* respond to the sender of the OOTB packet with a SHUTDOWN COMPLETE.
* When sending the SHUTDOWN COMPLETE, the receiver of the OOTB
* packet must fill in the Verification Tag field of the outbound
* packet with the Verification Tag received in the SHUTDOWN ACK and
* set the T-bit in the Chunk Flags to indicate that the Verification
* Tag is reflected.
*
* Inputs
* (endpoint, asoc, type, arg, commands)
*
* Outputs
* (sctp_disposition_t)
*
* The return value is the disposition of the chunk.
*/
static sctp_disposition_t sctp_sf_shut_8_4_5(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *shut;
packet = sctp_ootb_pkt_new(asoc, chunk);
if (packet) {
/* Make an SHUTDOWN_COMPLETE.
* The T bit will be set if the asoc is NULL.
*/
shut = sctp_make_shutdown_complete(asoc, chunk);
if (!shut) {
sctp_ootb_pkt_free(packet);
return SCTP_DISPOSITION_NOMEM;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(shut))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Set the skb to the belonging sock for accounting. */
shut->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, shut);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
/* If the chunk length is invalid, we don't want to process
* the reset of the packet.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* We need to discard the rest of the packet to prevent
* potential bomming attacks from additional bundled chunks.
* This is documented in SCTP Threats ID.
*/
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle SHUTDOWN ACK in COOKIE_ECHOED or COOKIE_WAIT state.
*
* Verification Tag: 8.5.1 E) Rules for packet carrying a SHUTDOWN ACK
* If the receiver is in COOKIE-ECHOED or COOKIE-WAIT state the
* procedures in section 8.4 SHOULD be followed, in other words it
* should be treated as an Out Of The Blue packet.
* [This means that we do NOT check the Verification Tag on these
* chunks. --piggy ]
*
*/
sctp_disposition_t sctp_sf_do_8_5_1_E_sa(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the SHUTDOWN_ACK chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
/* Although we do have an association in this case, it corresponds
* to a restarted association. So the packet is treated as an OOTB
* packet and the state function that handles OOTB SHUTDOWN_ACK is
* called with a NULL association.
*/
SCTP_INC_STATS(SCTP_MIB_OUTOFBLUES);
return sctp_sf_shut_8_4_5(ep, NULL, type, arg, commands);
}
/* ADDIP Section 4.2 Upon reception of an ASCONF Chunk. */
sctp_disposition_t sctp_sf_do_asconf(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_chunk *asconf_ack = NULL;
struct sctp_paramhdr *err_param = NULL;
sctp_addiphdr_t *hdr;
union sctp_addr_param *addr_param;
__u32 serial;
int length;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
/* ADD-IP: Section 4.1.1
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.ietf-tsvwg-sctp-auth].
*/
if (!sctp_addip_noauth && !chunk->auth)
return sctp_sf_discard_chunk(ep, asoc, type, arg, commands);
/* Make sure that the ASCONF ADDIP chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_addip_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
hdr = (sctp_addiphdr_t *)chunk->skb->data;
serial = ntohl(hdr->serial);
addr_param = (union sctp_addr_param *)hdr->params;
length = ntohs(addr_param->p.length);
if (length < sizeof(sctp_paramhdr_t))
return sctp_sf_violation_paramlen(ep, asoc, type, arg,
(void *)addr_param, commands);
/* Verify the ASCONF chunk before processing it. */
if (!sctp_verify_asconf(asoc,
(sctp_paramhdr_t *)((void *)addr_param + length),
(void *)chunk->chunk_end,
&err_param))
return sctp_sf_violation_paramlen(ep, asoc, type, arg,
(void *)err_param, commands);
/* ADDIP 5.2 E1) Compare the value of the serial number to the value
* the endpoint stored in a new association variable
* 'Peer-Serial-Number'.
*/
if (serial == asoc->peer.addip_serial + 1) {
/* If this is the first instance of ASCONF in the packet,
* we can clean our old ASCONF-ACKs.
*/
if (!chunk->has_asconf)
sctp_assoc_clean_asconf_ack_cache(asoc);
/* ADDIP 5.2 E4) When the Sequence Number matches the next one
* expected, process the ASCONF as described below and after
* processing the ASCONF Chunk, append an ASCONF-ACK Chunk to
* the response packet and cache a copy of it (in the event it
* later needs to be retransmitted).
*
* Essentially, do V1-V5.
*/
asconf_ack = sctp_process_asconf((struct sctp_association *)
asoc, chunk);
if (!asconf_ack)
return SCTP_DISPOSITION_NOMEM;
} else if (serial < asoc->peer.addip_serial + 1) {
/* ADDIP 5.2 E2)
* If the value found in the Sequence Number is less than the
* ('Peer- Sequence-Number' + 1), simply skip to the next
* ASCONF, and include in the outbound response packet
* any previously cached ASCONF-ACK response that was
* sent and saved that matches the Sequence Number of the
* ASCONF. Note: It is possible that no cached ASCONF-ACK
* Chunk exists. This will occur when an older ASCONF
* arrives out of order. In such a case, the receiver
* should skip the ASCONF Chunk and not include ASCONF-ACK
* Chunk for that chunk.
*/
asconf_ack = sctp_assoc_lookup_asconf_ack(asoc, hdr->serial);
if (!asconf_ack)
return SCTP_DISPOSITION_DISCARD;
/* Reset the transport so that we select the correct one
* this time around. This is to make sure that we don't
* accidentally use a stale transport that's been removed.
*/
asconf_ack->transport = NULL;
} else {
/* ADDIP 5.2 E5) Otherwise, the ASCONF Chunk is discarded since
* it must be either a stale packet or from an attacker.
*/
return SCTP_DISPOSITION_DISCARD;
}
/* ADDIP 5.2 E6) The destination address of the SCTP packet
* containing the ASCONF-ACK Chunks MUST be the source address of
* the SCTP packet that held the ASCONF Chunks.
*
* To do this properly, we'll set the destination address of the chunk
* and at the transmit time, will try look up the transport to use.
* Since ASCONFs may be bundled, the correct transport may not be
* created until we process the entire packet, thus this workaround.
*/
asconf_ack->dest = chunk->source;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(asconf_ack));
return SCTP_DISPOSITION_CONSUME;
}
/*
* ADDIP Section 4.3 General rules for address manipulation
* When building TLV parameters for the ASCONF Chunk that will add or
* delete IP addresses the D0 to D13 rules should be applied:
*/
sctp_disposition_t sctp_sf_do_asconf_ack(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *asconf_ack = arg;
struct sctp_chunk *last_asconf = asoc->addip_last_asconf;
struct sctp_chunk *abort;
struct sctp_paramhdr *err_param = NULL;
sctp_addiphdr_t *addip_hdr;
__u32 sent_serial, rcvd_serial;
if (!sctp_vtag_verify(asconf_ack, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
/* ADD-IP, Section 4.1.2:
* This chunk MUST be sent in an authenticated way by using
* the mechanism defined in [I-D.ietf-tsvwg-sctp-auth]. If this chunk
* is received unauthenticated it MUST be silently discarded as
* described in [I-D.ietf-tsvwg-sctp-auth].
*/
if (!sctp_addip_noauth && !asconf_ack->auth)
return sctp_sf_discard_chunk(ep, asoc, type, arg, commands);
/* Make sure that the ADDIP chunk has a valid length. */
if (!sctp_chunk_length_valid(asconf_ack, sizeof(sctp_addip_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
addip_hdr = (sctp_addiphdr_t *)asconf_ack->skb->data;
rcvd_serial = ntohl(addip_hdr->serial);
/* Verify the ASCONF-ACK chunk before processing it. */
if (!sctp_verify_asconf(asoc,
(sctp_paramhdr_t *)addip_hdr->params,
(void *)asconf_ack->chunk_end,
&err_param))
return sctp_sf_violation_paramlen(ep, asoc, type, arg,
(void *)err_param, commands);
if (last_asconf) {
addip_hdr = (sctp_addiphdr_t *)last_asconf->subh.addip_hdr;
sent_serial = ntohl(addip_hdr->serial);
} else {
sent_serial = asoc->addip_serial - 1;
}
/* D0) If an endpoint receives an ASCONF-ACK that is greater than or
* equal to the next serial number to be used but no ASCONF chunk is
* outstanding the endpoint MUST ABORT the association. Note that a
* sequence number is greater than if it is no more than 2^^31-1
* larger than the current sequence number (using serial arithmetic).
*/
if (ADDIP_SERIAL_gte(rcvd_serial, sent_serial + 1) &&
!(asoc->addip_last_asconf)) {
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_ASCONF_ACK, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET,SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
if ((rcvd_serial == sent_serial) && asoc->addip_last_asconf) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
if (!sctp_process_asconf_ack((struct sctp_association *)asoc,
asconf_ack)) {
/* Successfully processed ASCONF_ACK. We can
* release the next asconf if we have one.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_NEXT_ASCONF,
SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
}
abort = sctp_make_abort(asoc, asconf_ack,
sizeof(sctp_errhdr_t));
if (abort) {
sctp_init_cause(abort, SCTP_ERROR_RSRC_LOW, 0);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(abort));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET,SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_ASCONF_ACK));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
return SCTP_DISPOSITION_DISCARD;
}
/*
* PR-SCTP Section 3.6 Receiver Side Implementation of PR-SCTP
*
* When a FORWARD TSN chunk arrives, the data receiver MUST first update
* its cumulative TSN point to the value carried in the FORWARD TSN
* chunk, and then MUST further advance its cumulative TSN point locally
* if possible.
* After the above processing, the data receiver MUST stop reporting any
* missing TSNs earlier than or equal to the new cumulative TSN point.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_eat_fwd_tsn(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_fwdtsn_skip *skip;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
/* Make sure that the FORWARD_TSN chunk has valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
SCTP_DEBUG_PRINTK("%s: TSN 0x%x.\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto discard_noforce;
/* Silently discard the chunk if stream-id is not valid */
sctp_walk_fwdtsn(skip, chunk) {
if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams)
goto discard_noforce;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn));
if (len > sizeof(struct sctp_fwdtsn_hdr))
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN,
SCTP_CHUNK(chunk));
/* Count this as receiving DATA. */
if (asoc->autoclose) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
}
/* FIXME: For now send a SACK, but DATA processing may
* send another.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_NOFORCE());
return SCTP_DISPOSITION_CONSUME;
discard_noforce:
return SCTP_DISPOSITION_DISCARD;
}
sctp_disposition_t sctp_sf_eat_fwd_tsn_fast(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_fwdtsn_hdr *fwdtsn_hdr;
struct sctp_fwdtsn_skip *skip;
__u16 len;
__u32 tsn;
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
/* Make sure that the FORWARD_TSN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data;
chunk->subh.fwdtsn_hdr = fwdtsn_hdr;
len = ntohs(chunk->chunk_hdr->length);
len -= sizeof(struct sctp_chunkhdr);
skb_pull(chunk->skb, len);
tsn = ntohl(fwdtsn_hdr->new_cum_tsn);
SCTP_DEBUG_PRINTK("%s: TSN 0x%x.\n", __func__, tsn);
/* The TSN is too high--silently discard the chunk and count on it
* getting retransmitted later.
*/
if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0)
goto gen_shutdown;
/* Silently discard the chunk if stream-id is not valid */
sctp_walk_fwdtsn(skip, chunk) {
if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams)
goto gen_shutdown;
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn));
if (len > sizeof(struct sctp_fwdtsn_hdr))
sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN,
SCTP_CHUNK(chunk));
/* Go a head and force a SACK, since we are shutting down. */
gen_shutdown:
/* Implementor's Guide.
*
* While in SHUTDOWN-SENT state, the SHUTDOWN sender MUST immediately
* respond to each received packet containing one or more DATA chunk(s)
* with a SACK, a SHUTDOWN chunk, and restart the T2-shutdown timer
*/
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SHUTDOWN, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
return SCTP_DISPOSITION_CONSUME;
}
/*
* SCTP-AUTH Section 6.3 Receiving authenticated chukns
*
* The receiver MUST use the HMAC algorithm indicated in the HMAC
* Identifier field. If this algorithm was not specified by the
* receiver in the HMAC-ALGO parameter in the INIT or INIT-ACK chunk
* during association setup, the AUTH chunk and all chunks after it MUST
* be discarded and an ERROR chunk SHOULD be sent with the error cause
* defined in Section 4.1.
*
* If an endpoint with no shared key receives a Shared Key Identifier
* other than 0, it MUST silently discard all authenticated chunks. If
* the endpoint has at least one endpoint pair shared key for the peer,
* it MUST use the key specified by the Shared Key Identifier if a
* key has been configured for that Shared Key Identifier. If no
* endpoint pair shared key has been configured for that Shared Key
* Identifier, all authenticated chunks MUST be silently discarded.
*
* Verification Tag: 8.5 Verification Tag [Normal verification]
*
* The return value is the disposition of the chunk.
*/
static sctp_ierror_t sctp_sf_authenticate(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
struct sctp_chunk *chunk)
{
struct sctp_authhdr *auth_hdr;
struct sctp_hmac *hmac;
unsigned int sig_len;
__u16 key_id;
__u8 *save_digest;
__u8 *digest;
/* Pull in the auth header, so we can do some more verification */
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
chunk->subh.auth_hdr = auth_hdr;
skb_pull(chunk->skb, sizeof(struct sctp_authhdr));
/* Make sure that we suport the HMAC algorithm from the auth
* chunk.
*/
if (!sctp_auth_asoc_verify_hmac_id(asoc, auth_hdr->hmac_id))
return SCTP_IERROR_AUTH_BAD_HMAC;
/* Make sure that the provided shared key identifier has been
* configured
*/
key_id = ntohs(auth_hdr->shkey_id);
if (key_id != asoc->active_key_id && !sctp_auth_get_shkey(asoc, key_id))
return SCTP_IERROR_AUTH_BAD_KEYID;
/* Make sure that the length of the signature matches what
* we expect.
*/
sig_len = ntohs(chunk->chunk_hdr->length) - sizeof(sctp_auth_chunk_t);
hmac = sctp_auth_get_hmac(ntohs(auth_hdr->hmac_id));
if (sig_len != hmac->hmac_len)
return SCTP_IERROR_PROTO_VIOLATION;
/* Now that we've done validation checks, we can compute and
* verify the hmac. The steps involved are:
* 1. Save the digest from the chunk.
* 2. Zero out the digest in the chunk.
* 3. Compute the new digest
* 4. Compare saved and new digests.
*/
digest = auth_hdr->hmac;
skb_pull(chunk->skb, sig_len);
save_digest = kmemdup(digest, sig_len, GFP_ATOMIC);
if (!save_digest)
goto nomem;
memset(digest, 0, sig_len);
sctp_auth_calculate_hmac(asoc, chunk->skb,
(struct sctp_auth_chunk *)chunk->chunk_hdr,
GFP_ATOMIC);
/* Discard the packet if the digests do not match */
if (memcmp(save_digest, digest, sig_len)) {
kfree(save_digest);
return SCTP_IERROR_BAD_SIG;
}
kfree(save_digest);
chunk->auth = 1;
return SCTP_IERROR_NO_ERROR;
nomem:
return SCTP_IERROR_NOMEM;
}
sctp_disposition_t sctp_sf_eat_auth(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_authhdr *auth_hdr;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *err_chunk;
sctp_ierror_t error;
/* Make sure that the peer has AUTH capable */
if (!asoc->peer.auth_capable)
return sctp_sf_unk_chunk(ep, asoc, type, arg, commands);
if (!sctp_vtag_verify(chunk, asoc)) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG,
SCTP_NULL());
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
}
/* Make sure that the AUTH chunk has valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_auth_chunk)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
auth_hdr = (struct sctp_authhdr *)chunk->skb->data;
error = sctp_sf_authenticate(ep, asoc, type, chunk);
switch (error) {
case SCTP_IERROR_AUTH_BAD_HMAC:
/* Generate the ERROR chunk and discard the rest
* of the packet
*/
err_chunk = sctp_make_op_error(asoc, chunk,
SCTP_ERROR_UNSUP_HMAC,
&auth_hdr->hmac_id,
sizeof(__u16), 0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Fall Through */
case SCTP_IERROR_AUTH_BAD_KEYID:
case SCTP_IERROR_BAD_SIG:
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
break;
case SCTP_IERROR_PROTO_VIOLATION:
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
break;
case SCTP_IERROR_NOMEM:
return SCTP_DISPOSITION_NOMEM;
default:
break;
}
if (asoc->active_key_id != ntohs(auth_hdr->shkey_id)) {
struct sctp_ulpevent *ev;
ev = sctp_ulpevent_make_authkey(asoc, ntohs(auth_hdr->shkey_id),
SCTP_AUTH_NEWKEY, GFP_ATOMIC);
if (!ev)
return -ENOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ev));
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process an unknown chunk.
*
* Section: 3.2. Also, 2.1 in the implementor's guide.
*
* Chunk Types are encoded such that the highest-order two bits specify
* the action that must be taken if the processing endpoint does not
* recognize the Chunk Type.
*
* 00 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it.
*
* 01 - Stop processing this SCTP packet and discard it, do not process
* any further chunks within it, and report the unrecognized
* chunk in an 'Unrecognized Chunk Type'.
*
* 10 - Skip this chunk and continue processing.
*
* 11 - Skip this chunk and continue processing, but report in an ERROR
* Chunk using the 'Unrecognized Chunk Type' cause of error.
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_unk_chunk(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *unk_chunk = arg;
struct sctp_chunk *err_chunk;
sctp_chunkhdr_t *hdr;
SCTP_DEBUG_PRINTK("Processing the unknown chunk id %d.\n", type.chunk);
if (!sctp_vtag_verify(unk_chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!sctp_chunk_length_valid(unk_chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
switch (type.chunk & SCTP_CID_ACTION_MASK) {
case SCTP_CID_ACTION_DISCARD:
/* Discard the packet. */
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
break;
case SCTP_CID_ACTION_DISCARD_ERR:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
SCTP_ERROR_UNKNOWN_CHUNK, hdr,
WORD_ROUND(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Discard the packet. */
sctp_sf_pdiscard(ep, asoc, type, arg, commands);
return SCTP_DISPOSITION_CONSUME;
break;
case SCTP_CID_ACTION_SKIP:
/* Skip the chunk. */
return SCTP_DISPOSITION_DISCARD;
break;
case SCTP_CID_ACTION_SKIP_ERR:
/* Generate an ERROR chunk as response. */
hdr = unk_chunk->chunk_hdr;
err_chunk = sctp_make_op_error(asoc, unk_chunk,
SCTP_ERROR_UNKNOWN_CHUNK, hdr,
WORD_ROUND(ntohs(hdr->length)),
0);
if (err_chunk) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err_chunk));
}
/* Skip the chunk. */
return SCTP_DISPOSITION_CONSUME;
break;
default:
break;
}
return SCTP_DISPOSITION_DISCARD;
}
/*
* Discard the chunk.
*
* Section: 0.2, 5.2.3, 5.2.5, 5.2.6, 6.0, 8.4.6, 8.5.1c, 9.2
* [Too numerous to mention...]
* Verification Tag: No verification needed.
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_discard_chunk(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the chunk has a valid length.
* Since we don't know the chunk type, we use a general
* chunkhdr structure to make a comparison.
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
SCTP_DEBUG_PRINTK("Chunk %d is discarded\n", type.chunk);
return SCTP_DISPOSITION_DISCARD;
}
/*
* Discard the whole packet.
*
* Section: 8.4 2)
*
* 2) If the OOTB packet contains an ABORT chunk, the receiver MUST
* silently discard the OOTB packet and take no further action.
*
* Verification Tag: No verification necessary
*
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_pdiscard(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_INC_STATS(SCTP_MIB_IN_PKT_DISCARDS);
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET, SCTP_NULL());
return SCTP_DISPOSITION_CONSUME;
}
/*
* The other end is violating protocol.
*
* Section: Not specified
* Verification Tag: Not specified
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (asoc, reply_msg, msg_up, timers, counters)
*
* We simply tag the chunk as a violation. The state machine will log
* the violation and continue.
*/
sctp_disposition_t sctp_sf_violation(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
/* Make sure that the chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
return SCTP_DISPOSITION_VIOLATION;
}
/*
* Common function to handle a protocol violation.
*/
static sctp_disposition_t sctp_sf_abort_violation(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
void *arg,
sctp_cmd_seq_t *commands,
const __u8 *payload,
const size_t paylen)
{
struct sctp_packet *packet = NULL;
struct sctp_chunk *chunk = arg;
struct sctp_chunk *abort = NULL;
/* SCTP-AUTH, Section 6.3:
* It should be noted that if the receiver wants to tear
* down an association in an authenticated way only, the
* handling of malformed packets should not result in
* tearing down the association.
*
* This means that if we only want to abort associations
* in an authenticated way (i.e AUTH+ABORT), then we
* can't destroy this association just because the packet
* was malformed.
*/
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = sctp_make_abort_violation(asoc, chunk, payload, paylen);
if (!abort)
goto nomem;
if (asoc) {
/* Treat INIT-ACK as a special case during COOKIE-WAIT. */
if (chunk->chunk_hdr->type == SCTP_CID_INIT_ACK &&
!asoc->peer.i.init_tag) {
sctp_initack_chunk_t *initack;
initack = (sctp_initack_chunk_t *)chunk->chunk_hdr;
if (!sctp_chunk_length_valid(chunk,
sizeof(sctp_initack_chunk_t)))
abort->chunk_hdr->flags |= SCTP_CHUNK_FLAG_T;
else {
unsigned int inittag;
inittag = ntohl(initack->init_hdr.init_tag);
sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_INITTAG,
SCTP_U32(inittag));
}
}
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
if (asoc->state <= SCTP_STATE_COOKIE_ECHOED) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
}
} else {
packet = sctp_ootb_pkt_new(asoc, chunk);
if (!packet)
goto nomem_pkt;
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
}
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return SCTP_DISPOSITION_ABORT;
nomem_pkt:
sctp_chunk_free(abort);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Handle a protocol violation when the chunk length is invalid.
* "Invalid" length is identified as smaller than the minimal length a
* given chunk can be. For example, a SACK chunk has invalid length
* if its length is set to be smaller than the size of sctp_sack_chunk_t.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*
* Section: Not specified
* Verification Tag: Nothing to do
* Inputs
* (endpoint, asoc, chunk)
*
* Outputs
* (reply_msg, msg_up, counters)
*
* Generate an ABORT chunk and terminate the association.
*/
static sctp_disposition_t sctp_sf_violation_chunklen(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[]="The following chunk had invalid length:";
return sctp_sf_abort_violation(ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/*
* Handle a protocol violation when the parameter length is invalid.
* If the length is smaller than the minimum length of a given parameter,
* or accumulated length in multi parameters exceeds the end of the chunk,
* the length is considered as invalid.
*/
static sctp_disposition_t sctp_sf_violation_paramlen(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, void *ext,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_paramhdr *param = ext;
struct sctp_chunk *abort = NULL;
if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc))
goto discard;
/* Make the abort chunk. */
abort = sctp_make_violation_paramlen(asoc, chunk, param);
if (!abort)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION));
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
discard:
sctp_sf_pdiscard(ep, asoc, SCTP_ST_CHUNK(0), arg, commands);
return SCTP_DISPOSITION_ABORT;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Handle a protocol violation when the peer trying to advance the
* cumulative tsn ack to a point beyond the max tsn currently sent.
*
* We inform the other end by sending an ABORT with a Protocol Violation
* error code.
*/
static sctp_disposition_t sctp_sf_violation_ctsn(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[]="The cumulative tsn ack beyond the max tsn currently sent:";
return sctp_sf_abort_violation(ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/* Handle protocol violation of an invalid chunk bundling. For example,
* when we have an association and we receive bundled INIT-ACK, or
* SHUDOWN-COMPLETE, our peer is clearly violationg the "MUST NOT bundle"
* statement from the specs. Additionally, there might be an attacker
* on the path and we may not want to continue this communication.
*/
static sctp_disposition_t sctp_sf_violation_chunk(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
static const char err_str[]="The following chunk violates protocol:";
if (!asoc)
return sctp_sf_violation(ep, asoc, type, arg, commands);
return sctp_sf_abort_violation(ep, asoc, arg, commands, err_str,
sizeof(err_str));
}
/***************************************************************************
* These are the state functions for handling primitive (Section 10) events.
***************************************************************************/
/*
* sctp_sf_do_prm_asoc
*
* Section: 10.1 ULP-to-SCTP
* B) Associate
*
* Format: ASSOCIATE(local SCTP instance name, destination transport addr,
* outbound stream count)
* -> association id [,destination transport addr list] [,outbound stream
* count]
*
* This primitive allows the upper layer to initiate an association to a
* specific peer endpoint.
*
* The peer endpoint shall be specified by one of the transport addresses
* which defines the endpoint (see Section 1.4). If the local SCTP
* instance has not been initialized, the ASSOCIATE is considered an
* error.
* [This is not relevant for the kernel implementation since we do all
* initialization at boot time. It we hadn't initialized we wouldn't
* get anywhere near this code.]
*
* An association id, which is a local handle to the SCTP association,
* will be returned on successful establishment of the association. If
* SCTP is not able to open an SCTP association with the peer endpoint,
* an error is returned.
* [In the kernel implementation, the struct sctp_association needs to
* be created BEFORE causing this primitive to run.]
*
* Other association parameters may be returned, including the
* complete destination transport addresses of the peer as well as the
* outbound stream count of the local endpoint. One of the transport
* address from the returned destination addresses will be selected by
* the local endpoint as default primary path for sending SCTP packets
* to this peer. The returned "destination transport addr list" can
* be used by the ULP to change the default primary path or to force
* sending a packet to a specific transport address. [All of this
* stuff happens when the INIT ACK arrives. This is a NON-BLOCKING
* function.]
*
* Mandatory attributes:
*
* o local SCTP instance name - obtained from the INITIALIZE operation.
* [This is the argument asoc.]
* o destination transport addr - specified as one of the transport
* addresses of the peer endpoint with which the association is to be
* established.
* [This is asoc->peer.active_path.]
* o outbound stream count - the number of outbound streams the ULP
* would like to open towards this peer endpoint.
* [BUG: This is not currently implemented.]
* Optional attributes:
*
* None.
*
* The return value is a disposition.
*/
sctp_disposition_t sctp_sf_do_prm_asoc(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl;
struct sctp_association* my_asoc;
/* The comment below says that we enter COOKIE-WAIT AFTER
* sending the INIT, but that doesn't actually work in our
* implementation...
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_COOKIE_WAIT));
/* RFC 2960 5.1 Normal Establishment of an Association
*
* A) "A" first sends an INIT chunk to "Z". In the INIT, "A"
* must provide its Verification Tag (Tag_A) in the Initiate
* Tag field. Tag_A SHOULD be a random number in the range of
* 1 to 4294967295 (see 5.3.1 for Tag value selection). ...
*/
repl = sctp_make_init(asoc, &asoc->base.bind_addr, GFP_ATOMIC, 0);
if (!repl)
goto nomem;
/* Cast away the const modifier, as we want to just
* rerun it through as a sideffect.
*/
my_asoc = (struct sctp_association *)asoc;
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(my_asoc));
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* After sending the INIT, "A" starts the T1-init timer and
* enters the COOKIE-WAIT state.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Process the SEND primitive.
*
* Section: 10.1 ULP-to-SCTP
* E) Send
*
* Format: SEND(association id, buffer address, byte count [,context]
* [,stream id] [,life time] [,destination transport address]
* [,unorder flag] [,no-bundle flag] [,payload protocol-id] )
* -> result
*
* This is the main method to send user data via SCTP.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o buffer address - the location where the user message to be
* transmitted is stored;
*
* o byte count - The size of the user data in number of bytes;
*
* Optional attributes:
*
* o context - an optional 32 bit integer that will be carried in the
* sending failure notification to the ULP if the transportation of
* this User Message fails.
*
* o stream id - to indicate which stream to send the data on. If not
* specified, stream 0 will be used.
*
* o life time - specifies the life time of the user data. The user data
* will not be sent by SCTP after the life time expires. This
* parameter can be used to avoid efforts to transmit stale
* user messages. SCTP notifies the ULP if the data cannot be
* initiated to transport (i.e. sent to the destination via SCTP's
* send primitive) within the life time variable. However, the
* user data will be transmitted if SCTP has attempted to transmit a
* chunk before the life time expired.
*
* o destination transport address - specified as one of the destination
* transport addresses of the peer endpoint to which this packet
* should be sent. Whenever possible, SCTP should use this destination
* transport address for sending the packets, instead of the current
* primary path.
*
* o unorder flag - this flag, if present, indicates that the user
* would like the data delivered in an unordered fashion to the peer
* (i.e., the U flag is set to 1 on all DATA chunks carrying this
* message).
*
* o no-bundle flag - instructs SCTP not to bundle this user data with
* other outbound DATA chunks. SCTP MAY still bundle even when
* this flag is present, when faced with network congestion.
*
* o payload protocol-id - A 32 bit unsigned integer that is to be
* passed to the peer indicating the type of payload protocol data
* being transmitted. This value is passed as opaque data by SCTP.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_prm_send(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_datamsg *msg = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_MSG, SCTP_DATAMSG(msg));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Process the SHUTDOWN primitive.
*
* Section: 10.1:
* C) Shutdown
*
* Format: SHUTDOWN(association id)
* -> result
*
* Gracefully closes an association. Any locally queued user data
* will be delivered to the peer. The association will be terminated only
* after the peer acknowledges all the SCTP packets sent. A success code
* will be returned on successful termination of the association. If
* attempting to terminate the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* None.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_prm_shutdown(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
int disposition;
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_start_shutdown(ep, asoc, type,
arg, commands);
}
return disposition;
}
/*
* Process the ABORT primitive.
*
* Section: 10.1:
* C) Abort
*
* Format: Abort(association id [, cause code])
* -> result
*
* Ungracefully closes an association. Any locally queued user data
* will be discarded and an ABORT chunk is sent to the peer. A success code
* will be returned on successful abortion of the association. If
* attempting to abort the association results in a failure, an error
* code shall be returned.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* Optional attributes:
*
* o cause code - reason of the abort to be passed to the peer
*
* None.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_1_prm_abort(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* From 9.1 Abort of an Association
* Upon receipt of the ABORT primitive from its upper
* layer, the endpoint enters CLOSED state and
* discard all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
struct sctp_chunk *abort = arg;
sctp_disposition_t retval;
retval = SCTP_DISPOSITION_CONSUME;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_USER_ABORT));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return retval;
}
/* We tried an illegal operation on an association which is closed. */
sctp_disposition_t sctp_sf_error_closed(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR, SCTP_ERROR(-EINVAL));
return SCTP_DISPOSITION_CONSUME;
}
/* We tried an illegal operation on an association which is shutting
* down.
*/
sctp_disposition_t sctp_sf_error_shutdown(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_ERROR,
SCTP_ERROR(-ESHUTDOWN));
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_cookie_wait_prm_shutdown
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_wait_prm_shutdown(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(SCTP_MIB_SHUTDOWNS);
sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL());
return SCTP_DISPOSITION_DELETE_TCB;
}
/*
* sctp_cookie_echoed_prm_shutdown
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues a shutdown while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_echoed_prm_shutdown(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg, sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_prm_shutdown(ep, asoc, type, arg, commands);
}
/*
* sctp_sf_cookie_wait_prm_abort
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_WAIT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_wait_prm_abort(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *abort = arg;
sctp_disposition_t retval;
/* Stop T1-init timer */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
retval = SCTP_DISPOSITION_CONSUME;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_CLOSED));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
/* Even if we can't send the ABORT due to low memory delete the
* TCB. This is a departure from our typical NOMEM handling.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNREFUSED));
/* Delete the established association. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_USER_ABORT));
return retval;
}
/*
* sctp_sf_cookie_echoed_prm_abort
*
* Section: 4 Note: 3
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_cookie_echoed_prm_abort(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* There is a single T1 timer, so we should be able to use
* common function with the COOKIE-WAIT state.
*/
return sctp_sf_cookie_wait_prm_abort(ep, asoc, type, arg, commands);
}
/*
* sctp_sf_shutdown_pending_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-PENDING state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_shutdown_pending_prm_abort(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return sctp_sf_do_9_1_prm_abort(ep, asoc, type, arg, commands);
}
/*
* sctp_sf_shutdown_sent_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explicitly address this issue, but is the route through the
* state table when someone issues an abort while in SHUTDOWN-SENT state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_shutdown_sent_prm_abort(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* Stop the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* Stop the T5-shutdown guard timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
return sctp_sf_do_9_1_prm_abort(ep, asoc, type, arg, commands);
}
/*
* sctp_sf_cookie_echoed_prm_abort
*
* Inputs
* (endpoint, asoc)
*
* The RFC does not explcitly address this issue, but is the route through the
* state table when someone issues an abort while in COOKIE_ECHOED state.
*
* Outputs
* (timers)
*/
sctp_disposition_t sctp_sf_shutdown_ack_sent_prm_abort(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
/* The same T2 timer, so we should be able to use
* common function with the SHUTDOWN-SENT state.
*/
return sctp_sf_shutdown_sent_prm_abort(ep, asoc, type, arg, commands);
}
/*
* Process the REQUESTHEARTBEAT primitive
*
* 10.1 ULP-to-SCTP
* J) Request Heartbeat
*
* Format: REQUESTHEARTBEAT(association id, destination transport address)
*
* -> result
*
* Instructs the local endpoint to perform a HeartBeat on the specified
* destination transport address of the given association. The returned
* result should indicate whether the transmission of the HEARTBEAT
* chunk to the destination address is successful.
*
* Mandatory attributes:
*
* o association id - local handle to the SCTP association
*
* o destination transport address - the transport address of the
* association on which a heartbeat should be issued.
*/
sctp_disposition_t sctp_sf_do_prm_requestheartbeat(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
if (SCTP_DISPOSITION_NOMEM == sctp_sf_heartbeat(ep, asoc, type,
(struct sctp_transport *)arg, commands))
return SCTP_DISPOSITION_NOMEM;
/*
* RFC 2960 (bis), section 8.3
*
* D) Request an on-demand HEARTBEAT on a specific destination
* transport address of a given association.
*
* The endpoint should increment the respective error counter of
* the destination transport address each time a HEARTBEAT is sent
* to that address and not acknowledged within one RTO.
*
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TRANSPORT_HB_SENT,
SCTP_TRANSPORT(arg));
return SCTP_DISPOSITION_CONSUME;
}
/*
* ADDIP Section 4.1 ASCONF Chunk Procedures
* When an endpoint has an ASCONF signaled change to be sent to the
* remote endpoint it should do A1 to A9
*/
sctp_disposition_t sctp_sf_do_prm_asconf(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(chunk));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Ignore the primitive event
*
* The return value is the disposition of the primitive.
*/
sctp_disposition_t sctp_sf_ignore_primitive(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_DEBUG_PRINTK("Primitive type %d is ignored.\n", type.primitive);
return SCTP_DISPOSITION_DISCARD;
}
/***************************************************************************
* These are the state functions for the OTHER events.
***************************************************************************/
/*
* When the SCTP stack has no more user data to send or retransmit, this
* notification is given to the user. Also, at the time when a user app
* subscribes to this event, if there is no data to be sent or
* retransmit, the stack will immediately send up this notification.
*/
sctp_disposition_t sctp_sf_do_no_pending_tsn(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_ulpevent *event;
event = sctp_ulpevent_make_sender_dry_event(asoc, GFP_ATOMIC);
if (!event)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(event));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Start the shutdown negotiation.
*
* From Section 9.2:
* Once all its outstanding data has been acknowledged, the endpoint
* shall send a SHUTDOWN chunk to its peer including in the Cumulative
* TSN Ack field the last sequential TSN it has received from the peer.
* It shall then start the T2-shutdown timer and enter the SHUTDOWN-SENT
* state. If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_start_shutdown(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply;
/* Once all its outstanding data has been acknowledged, the
* endpoint shall send a SHUTDOWN chunk to its peer including
* in the Cumulative TSN Ack field the last sequential TSN it
* has received from the peer.
*/
reply = sctp_make_shutdown(asoc, NULL);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN chunk and the timeout for the
* T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* It shall then start the T2-shutdown timer */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
/* RFC 4960 Section 9.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
if (asoc->autoclose)
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* and enter the SHUTDOWN-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_SENT));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Generate a SHUTDOWN ACK now that everything is SACK'd.
*
* From Section 9.2:
*
* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK and start a T2-shutdown timer of its own,
* entering the SHUTDOWN-ACK-SENT state. If the timer expires, the
* endpoint must re-send the SHUTDOWN ACK.
*
* The return value is the disposition.
*/
sctp_disposition_t sctp_sf_do_9_2_shutdown_ack(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = (struct sctp_chunk *) arg;
struct sctp_chunk *reply;
/* There are 2 ways of getting here:
* 1) called in response to a SHUTDOWN chunk
* 2) called when SCTP_EVENT_NO_PENDING_TSN event is issued.
*
* For the case (2), the arg parameter is set to NULL. We need
* to check that we have a chunk before accessing it's fields.
*/
if (chunk) {
if (!sctp_vtag_verify(chunk, asoc))
return sctp_sf_pdiscard(ep, asoc, type, arg, commands);
/* Make sure that the SHUTDOWN chunk has a valid length. */
if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_shutdown_chunk_t)))
return sctp_sf_violation_chunklen(ep, asoc, type, arg,
commands);
}
/* If it has no more outstanding DATA chunks, the SHUTDOWN receiver
* shall send a SHUTDOWN ACK ...
*/
reply = sctp_make_shutdown_ack(asoc, chunk);
if (!reply)
goto nomem;
/* Set the transport for the SHUTDOWN ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* and start/restart a T2-shutdown timer of its own, */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
if (asoc->autoclose)
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* Enter the SHUTDOWN-ACK-SENT state. */
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_ACK_SENT));
/* sctp-implguide 2.10 Issues with Heartbeating and failover
*
* HEARTBEAT ... is discontinued after sending either SHUTDOWN
* or SHUTDOWN-ACK.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_STOP, SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* Ignore the event defined as other
*
* The return value is the disposition of the event.
*/
sctp_disposition_t sctp_sf_ignore_other(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_DEBUG_PRINTK("The event other type %d is ignored\n", type.other);
return SCTP_DISPOSITION_DISCARD;
}
/************************************************************
* These are the state functions for handling timeout events.
************************************************************/
/*
* RTX Timeout
*
* Section: 6.3.3 Handle T3-rtx Expiration
*
* Whenever the retransmission timer T3-rtx expires for a destination
* address, do the following:
* [See below]
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_do_6_3_3_rtx(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_transport *transport = arg;
SCTP_INC_STATS(SCTP_MIB_T3_RTX_EXPIREDS);
if (asoc->overall_error_count >= asoc->max_retrans) {
if (asoc->state == SCTP_STATE_SHUTDOWN_PENDING) {
/*
* We are here likely because the receiver had its rwnd
* closed for a while and we have not been able to
* transmit the locally queued data within the maximum
* retransmission attempts limit. Start the T5
* shutdown guard timer to give the receiver one last
* chance and some additional time to recover before
* aborting.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START_ONCE,
SCTP_TO(SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
}
/* E1) For the destination address for which the timer
* expires, adjust its ssthresh with rules defined in Section
* 7.2.3 and set the cwnd <- MTU.
*/
/* E2) For the destination address for which the timer
* expires, set RTO <- RTO * 2 ("back off the timer"). The
* maximum value discussed in rule C7 above (RTO.max) may be
* used to provide an upper bound to this doubling operation.
*/
/* E3) Determine how many of the earliest (i.e., lowest TSN)
* outstanding DATA chunks for the address for which the
* T3-rtx has expired will fit into a single packet, subject
* to the MTU constraint for the path corresponding to the
* destination transport address to which the retransmission
* is being sent (this may be different from the address for
* which the timer expires [see Section 6.4]). Call this
* value K. Bundle and retransmit those K DATA chunks in a
* single packet to the destination endpoint.
*
* Note: Any DATA chunks that were sent to the address for
* which the T3-rtx timer expired but did not fit in one MTU
* (rule E3 above), should be marked for retransmission and
* sent as soon as cwnd allows (normally when a SACK arrives).
*/
/* Do some failure management (Section 8.2). */
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport));
/* NB: Rules E4 and F1 are implicit in R1. */
sctp_add_cmd_sf(commands, SCTP_CMD_RETRAN, SCTP_TRANSPORT(transport));
return SCTP_DISPOSITION_CONSUME;
}
/*
* Generate delayed SACK on timeout
*
* Section: 6.2 Acknowledgement on Reception of DATA Chunks
*
* The guidelines on delayed acknowledgement algorithm specified in
* Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
* acknowledgement SHOULD be generated for at least every second packet
* (not every second DATA chunk) received, and SHOULD be generated
* within 200 ms of the arrival of any unacknowledged DATA chunk. In
* some situations it may be beneficial for an SCTP transmitter to be
* more conservative than the algorithms detailed in this document
* allow. However, an SCTP transmitter MUST NOT be more aggressive than
* the following algorithms allow.
*/
sctp_disposition_t sctp_sf_do_6_2_sack(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_INC_STATS(SCTP_MIB_DELAY_SACK_EXPIREDS);
sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_FORCE());
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_t1_init_timer_expire
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 2) If the T1-init timer expires, the endpoint MUST retransmit INIT
* and re-start the T1-init timer without changing state. This MUST
* be repeated up to 'Max.Init.Retransmits' times. After that, the
* endpoint MUST abort the initialization process and report the
* error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
sctp_disposition_t sctp_sf_t1_init_timer_expire(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl = NULL;
struct sctp_bind_addr *bp;
int attempts = asoc->init_err_counter + 1;
SCTP_DEBUG_PRINTK("Timer T1 expired (INIT).\n");
SCTP_INC_STATS(SCTP_MIB_T1_INIT_EXPIREDS);
if (attempts <= asoc->max_init_attempts) {
bp = (struct sctp_bind_addr *) &asoc->base.bind_addr;
repl = sctp_make_init(asoc, bp, GFP_ATOMIC, 0);
if (!repl)
return SCTP_DISPOSITION_NOMEM;
/* Choose transport for INIT. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_INIT));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
SCTP_DEBUG_PRINTK("Giving up on INIT, attempts: %d"
" max_init_attempts: %d\n",
attempts, asoc->max_init_attempts);
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return SCTP_DISPOSITION_DELETE_TCB;
}
return SCTP_DISPOSITION_CONSUME;
}
/*
* sctp_sf_t1_cookie_timer_expire
*
* Section: 4 Note: 2
* Verification Tag:
* Inputs
* (endpoint, asoc)
*
* RFC 2960 Section 4 Notes
* 3) If the T1-cookie timer expires, the endpoint MUST retransmit
* COOKIE ECHO and re-start the T1-cookie timer without changing
* state. This MUST be repeated up to 'Max.Init.Retransmits' times.
* After that, the endpoint MUST abort the initialization process and
* report the error to SCTP user.
*
* Outputs
* (timers, events)
*
*/
sctp_disposition_t sctp_sf_t1_cookie_timer_expire(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *repl = NULL;
int attempts = asoc->init_err_counter + 1;
SCTP_DEBUG_PRINTK("Timer T1 expired (COOKIE-ECHO).\n");
SCTP_INC_STATS(SCTP_MIB_T1_COOKIE_EXPIREDS);
if (attempts <= asoc->max_init_attempts) {
repl = sctp_make_cookie_echo(asoc, NULL);
if (!repl)
return SCTP_DISPOSITION_NOMEM;
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_CHOOSE_TRANSPORT,
SCTP_CHUNK(repl));
/* Issue a sideeffect to do the needed accounting. */
sctp_add_cmd_sf(commands, SCTP_CMD_COOKIEECHO_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T1_COOKIE));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
} else {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_INIT_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
return SCTP_DISPOSITION_DELETE_TCB;
}
return SCTP_DISPOSITION_CONSUME;
}
/* RFC2960 9.2 If the timer expires, the endpoint must re-send the SHUTDOWN
* with the updated last sequential TSN received from its peer.
*
* An endpoint should limit the number of retransmissions of the
* SHUTDOWN chunk to the protocol parameter 'Association.Max.Retrans'.
* If this threshold is exceeded the endpoint should destroy the TCB and
* MUST report the peer endpoint unreachable to the upper layer (and
* thus the association enters the CLOSED state). The reception of any
* packet from its peer (i.e. as the peer sends all of its queued DATA
* chunks) should clear the endpoint's retransmission count and restart
* the T2-Shutdown timer, giving its peer ample opportunity to transmit
* all of its queued DATA chunks that have not yet been sent.
*/
sctp_disposition_t sctp_sf_t2_timer_expire(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply = NULL;
SCTP_DEBUG_PRINTK("Timer T2 expired.\n");
SCTP_INC_STATS(SCTP_MIB_T2_SHUTDOWN_EXPIREDS);
((struct sctp_association *)asoc)->shutdown_retries++;
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
/* Note: CMD_ASSOC_FAILED calls CMD_DELETE_TCB. */
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
}
switch (asoc->state) {
case SCTP_STATE_SHUTDOWN_SENT:
reply = sctp_make_shutdown(asoc, NULL);
break;
case SCTP_STATE_SHUTDOWN_ACK_SENT:
reply = sctp_make_shutdown_ack(asoc, NULL);
break;
default:
BUG();
break;
}
if (!reply)
goto nomem;
/* Do some failure management (Section 8.2).
* If we remove the transport an SHUTDOWN was last sent to, don't
* do failure management.
*/
if (asoc->shutdown_last_sent_to)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(asoc->shutdown_last_sent_to));
/* Set the transport for the SHUTDOWN/ACK chunk and the timeout for
* the T2-shutdown timer.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T2, SCTP_CHUNK(reply));
/* Restart the T2-shutdown timer. */
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T2_SHUTDOWN));
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
return SCTP_DISPOSITION_CONSUME;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/*
* ADDIP Section 4.1 ASCONF CHunk Procedures
* If the T4 RTO timer expires the endpoint should do B1 to B5
*/
sctp_disposition_t sctp_sf_t4_timer_expire(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = asoc->addip_last_asconf;
struct sctp_transport *transport = chunk->transport;
SCTP_INC_STATS(SCTP_MIB_T4_RTO_EXPIREDS);
/* ADDIP 4.1 B1) Increment the error counters and perform path failure
* detection on the appropriate destination address as defined in
* RFC2960 [5] section 8.1 and 8.2.
*/
if (transport)
sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE,
SCTP_TRANSPORT(transport));
/* Reconfig T4 timer and transport. */
sctp_add_cmd_sf(commands, SCTP_CMD_SETUP_T4, SCTP_CHUNK(chunk));
/* ADDIP 4.1 B2) Increment the association error counters and perform
* endpoint failure detection on the association as defined in
* RFC2960 [5] section 8.1 and 8.2.
* association error counter is incremented in SCTP_CMD_STRIKE.
*/
if (asoc->overall_error_count >= asoc->max_retrans) {
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_ABORT;
}
/* ADDIP 4.1 B3) Back-off the destination address RTO value to which
* the ASCONF chunk was sent by doubling the RTO timer value.
* This is done in SCTP_CMD_STRIKE.
*/
/* ADDIP 4.1 B4) Re-transmit the ASCONF Chunk last sent and if possible
* choose an alternate destination address (please refer to RFC2960
* [5] section 6.4.1). An endpoint MUST NOT add new parameters to this
* chunk, it MUST be the same (including its serial number) as the last
* ASCONF sent.
*/
sctp_chunk_hold(asoc->addip_last_asconf);
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(asoc->addip_last_asconf));
/* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different
* destination is selected, then the RTO used will be that of the new
* destination address.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART,
SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO));
return SCTP_DISPOSITION_CONSUME;
}
/* sctpimpguide-05 Section 2.12.2
* The sender of the SHUTDOWN MAY also start an overall guard timer
* 'T5-shutdown-guard' to bound the overall time for shutdown sequence.
* At the expiration of this timer the sender SHOULD abort the association
* by sending an ABORT chunk.
*/
sctp_disposition_t sctp_sf_t5_timer_expire(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *reply = NULL;
SCTP_DEBUG_PRINTK("Timer T5 expired.\n");
SCTP_INC_STATS(SCTP_MIB_T5_SHUTDOWN_GUARD_EXPIREDS);
reply = sctp_make_abort(asoc, NULL, 0);
if (!reply)
goto nomem;
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(reply));
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ETIMEDOUT));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_ERROR));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_DISPOSITION_DELETE_TCB;
nomem:
return SCTP_DISPOSITION_NOMEM;
}
/* Handle expiration of AUTOCLOSE timer. When the autoclose timer expires,
* the association is automatically closed by starting the shutdown process.
* The work that needs to be done is same as when SHUTDOWN is initiated by
* the user. So this routine looks same as sctp_sf_do_9_2_prm_shutdown().
*/
sctp_disposition_t sctp_sf_autoclose_timer_expire(
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
int disposition;
SCTP_INC_STATS(SCTP_MIB_AUTOCLOSE_EXPIREDS);
/* From 9.2 Shutdown of an Association
* Upon receipt of the SHUTDOWN primitive from its upper
* layer, the endpoint enters SHUTDOWN-PENDING state and
* remains there until all outstanding data has been
* acknowledged by its peer. The endpoint accepts no new data
* from its upper layer, but retransmits data to the far end
* if necessary to fill gaps.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_SHUTDOWN_PENDING));
disposition = SCTP_DISPOSITION_CONSUME;
if (sctp_outq_is_empty(&asoc->outqueue)) {
disposition = sctp_sf_do_9_2_start_shutdown(ep, asoc, type,
arg, commands);
}
return disposition;
}
/*****************************************************************************
* These are sa state functions which could apply to all types of events.
****************************************************************************/
/*
* This table entry is not implemented.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_not_impl(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return SCTP_DISPOSITION_NOT_IMPL;
}
/*
* This table entry represents a bug.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_bug(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
return SCTP_DISPOSITION_BUG;
}
/*
* This table entry represents the firing of a timer in the wrong state.
* Since timer deletion cannot be guaranteed a timer 'may' end up firing
* when the association is in the wrong state. This event should
* be ignored, so as to prevent any rearming of the timer.
*
* Inputs
* (endpoint, asoc, chunk)
*
* The return value is the disposition of the chunk.
*/
sctp_disposition_t sctp_sf_timer_ignore(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type,
void *arg,
sctp_cmd_seq_t *commands)
{
SCTP_DEBUG_PRINTK("Timer %d ignored.\n", type.chunk);
return SCTP_DISPOSITION_CONSUME;
}
/********************************************************************
* 2nd Level Abstractions
********************************************************************/
/* Pull the SACK chunk based on the SACK header. */
static struct sctp_sackhdr *sctp_sm_pull_sack(struct sctp_chunk *chunk)
{
struct sctp_sackhdr *sack;
unsigned int len;
__u16 num_blocks;
__u16 num_dup_tsns;
/* Protect ourselves from reading too far into
* the skb from a bogus sender.
*/
sack = (struct sctp_sackhdr *) chunk->skb->data;
num_blocks = ntohs(sack->num_gap_ack_blocks);
num_dup_tsns = ntohs(sack->num_dup_tsns);
len = sizeof(struct sctp_sackhdr);
len += (num_blocks + num_dup_tsns) * sizeof(__u32);
if (len > chunk->skb->len)
return NULL;
skb_pull(chunk->skb, len);
return sack;
}
/* Create an ABORT packet to be sent as a response, with the specified
* error causes.
*/
static struct sctp_packet *sctp_abort_pkt_new(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
struct sctp_chunk *chunk,
const void *payload,
size_t paylen)
{
struct sctp_packet *packet;
struct sctp_chunk *abort;
packet = sctp_ootb_pkt_new(asoc, chunk);
if (packet) {
/* Make an ABORT.
* The T bit will be set if the asoc is NULL.
*/
abort = sctp_make_abort(asoc, chunk, paylen);
if (!abort) {
sctp_ootb_pkt_free(packet);
return NULL;
}
/* Reflect vtag if T-Bit is set */
if (sctp_test_T_bit(abort))
packet->vtag = ntohl(chunk->sctp_hdr->vtag);
/* Add specified error causes, i.e., payload, to the
* end of the chunk.
*/
sctp_addto_chunk(abort, paylen, payload);
/* Set the skb to the belonging sock for accounting. */
abort->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, abort);
}
return packet;
}
/* Allocate a packet for responding in the OOTB conditions. */
static struct sctp_packet *sctp_ootb_pkt_new(const struct sctp_association *asoc,
const struct sctp_chunk *chunk)
{
struct sctp_packet *packet;
struct sctp_transport *transport;
__u16 sport;
__u16 dport;
__u32 vtag;
/* Get the source and destination port from the inbound packet. */
sport = ntohs(chunk->sctp_hdr->dest);
dport = ntohs(chunk->sctp_hdr->source);
/* The V-tag is going to be the same as the inbound packet if no
* association exists, otherwise, use the peer's vtag.
*/
if (asoc) {
/* Special case the INIT-ACK as there is no peer's vtag
* yet.
*/
switch(chunk->chunk_hdr->type) {
case SCTP_CID_INIT_ACK:
{
sctp_initack_chunk_t *initack;
initack = (sctp_initack_chunk_t *)chunk->chunk_hdr;
vtag = ntohl(initack->init_hdr.init_tag);
break;
}
default:
vtag = asoc->peer.i.init_tag;
break;
}
} else {
/* Special case the INIT and stale COOKIE_ECHO as there is no
* vtag yet.
*/
switch(chunk->chunk_hdr->type) {
case SCTP_CID_INIT:
{
sctp_init_chunk_t *init;
init = (sctp_init_chunk_t *)chunk->chunk_hdr;
vtag = ntohl(init->init_hdr.init_tag);
break;
}
default:
vtag = ntohl(chunk->sctp_hdr->vtag);
break;
}
}
/* Make a transport for the bucket, Eliza... */
transport = sctp_transport_new(sctp_source(chunk), GFP_ATOMIC);
if (!transport)
goto nomem;
/* Cache a route for the transport with the chunk's destination as
* the source address.
*/
sctp_transport_route(transport, (union sctp_addr *)&chunk->dest,
sctp_sk(sctp_get_ctl_sock()));
packet = sctp_packet_init(&transport->packet, transport, sport, dport);
packet = sctp_packet_config(packet, vtag, 0);
return packet;
nomem:
return NULL;
}
/* Free the packet allocated earlier for responding in the OOTB condition. */
void sctp_ootb_pkt_free(struct sctp_packet *packet)
{
sctp_transport_free(packet->transport);
}
/* Send a stale cookie error when a invalid COOKIE ECHO chunk is found */
static void sctp_send_stale_cookie_err(const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands,
struct sctp_chunk *err_chunk)
{
struct sctp_packet *packet;
if (err_chunk) {
packet = sctp_ootb_pkt_new(asoc, chunk);
if (packet) {
struct sctp_signed_cookie *cookie;
/* Override the OOTB vtag from the cookie. */
cookie = chunk->subh.cookie_hdr;
packet->vtag = cookie->c.peer_vtag;
/* Set the skb to the belonging sock for accounting. */
err_chunk->skb->sk = ep->base.sk;
sctp_packet_append_chunk(packet, err_chunk);
sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT,
SCTP_PACKET(packet));
SCTP_INC_STATS(SCTP_MIB_OUTCTRLCHUNKS);
} else
sctp_chunk_free (err_chunk);
}
}
/* Process a data chunk */
static int sctp_eat_data(const struct sctp_association *asoc,
struct sctp_chunk *chunk,
sctp_cmd_seq_t *commands)
{
sctp_datahdr_t *data_hdr;
struct sctp_chunk *err;
size_t datalen;
sctp_verb_t deliver;
int tmp;
__u32 tsn;
struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map;
struct sock *sk = asoc->base.sk;
u16 ssn;
u16 sid;
u8 ordered = 0;
data_hdr = chunk->subh.data_hdr = (sctp_datahdr_t *)chunk->skb->data;
skb_pull(chunk->skb, sizeof(sctp_datahdr_t));
tsn = ntohl(data_hdr->tsn);
SCTP_DEBUG_PRINTK("eat_data: TSN 0x%x.\n", tsn);
/* ASSERT: Now skb->data is really the user data. */
/* Process ECN based congestion.
*
* Since the chunk structure is reused for all chunks within
* a packet, we use ecn_ce_done to track if we've already
* done CE processing for this packet.
*
* We need to do ECN processing even if we plan to discard the
* chunk later.
*/
if (!chunk->ecn_ce_done) {
struct sctp_af *af;
chunk->ecn_ce_done = 1;
af = sctp_get_af_specific(
ipver2af(ip_hdr(chunk->skb)->version));
if (af && af->is_ce(chunk->skb) && asoc->peer.ecn_capable) {
/* Do real work as sideffect. */
sctp_add_cmd_sf(commands, SCTP_CMD_ECN_CE,
SCTP_U32(tsn));
}
}
tmp = sctp_tsnmap_check(&asoc->peer.tsn_map, tsn);
if (tmp < 0) {
/* The TSN is too high--silently discard the chunk and
* count on it getting retransmitted later.
*/
return SCTP_IERROR_HIGH_TSN;
} else if (tmp > 0) {
/* This is a duplicate. Record it. */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_DUP, SCTP_U32(tsn));
return SCTP_IERROR_DUP_TSN;
}
/* This is a new TSN. */
/* Discard if there is no room in the receive window.
* Actually, allow a little bit of overflow (up to a MTU).
*/
datalen = ntohs(chunk->chunk_hdr->length);
datalen -= sizeof(sctp_data_chunk_t);
deliver = SCTP_CMD_CHUNK_ULP;
/* Think about partial delivery. */
if ((datalen >= asoc->rwnd) && (!asoc->ulpq.pd_mode)) {
/* Even if we don't accept this chunk there is
* memory pressure.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_PART_DELIVER, SCTP_NULL());
}
/* Spill over rwnd a little bit. Note: While allowed, this spill over
* seems a bit troublesome in that frag_point varies based on
* PMTU. In cases, such as loopback, this might be a rather
* large spill over.
*/
if ((!chunk->data_accepted) && (!asoc->rwnd || asoc->rwnd_over ||
(datalen > asoc->rwnd + asoc->frag_point))) {
/* If this is the next TSN, consider reneging to make
* room. Note: Playing nice with a confused sender. A
* malicious sender can still eat up all our buffer
* space and in the future we may want to detect and
* do more drastic reneging.
*/
if (sctp_tsnmap_has_gap(map) &&
(sctp_tsnmap_get_ctsn(map) + 1) == tsn) {
SCTP_DEBUG_PRINTK("Reneging for tsn:%u\n", tsn);
deliver = SCTP_CMD_RENEGE;
} else {
SCTP_DEBUG_PRINTK("Discard tsn: %u len: %Zd, "
"rwnd: %d\n", tsn, datalen,
asoc->rwnd);
return SCTP_IERROR_IGNORE_TSN;
}
}
/*
* Also try to renege to limit our memory usage in the event that
* we are under memory pressure
* If we can't renege, don't worry about it, the sk_rmem_schedule
* in sctp_ulpevent_make_rcvmsg will drop the frame if we grow our
* memory usage too much
*/
if (*sk->sk_prot_creator->memory_pressure) {
if (sctp_tsnmap_has_gap(map) &&
(sctp_tsnmap_get_ctsn(map) + 1) == tsn) {
SCTP_DEBUG_PRINTK("Under Pressure! Reneging for tsn:%u\n", tsn);
deliver = SCTP_CMD_RENEGE;
}
}
/*
* Section 3.3.10.9 No User Data (9)
*
* Cause of error
* ---------------
* No User Data: This error cause is returned to the originator of a
* DATA chunk if a received DATA chunk has no user data.
*/
if (unlikely(0 == datalen)) {
err = sctp_make_abort_no_data(asoc, chunk, tsn);
if (err) {
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
}
/* We are going to ABORT, so we might as well stop
* processing the rest of the chunks in the packet.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_DISCARD_PACKET,SCTP_NULL());
sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR,
SCTP_ERROR(ECONNABORTED));
sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED,
SCTP_PERR(SCTP_ERROR_NO_DATA));
SCTP_INC_STATS(SCTP_MIB_ABORTEDS);
SCTP_DEC_STATS(SCTP_MIB_CURRESTAB);
return SCTP_IERROR_NO_DATA;
}
chunk->data_accepted = 1;
/* Note: Some chunks may get overcounted (if we drop) or overcounted
* if we renege and the chunk arrives again.
*/
if (chunk->chunk_hdr->flags & SCTP_DATA_UNORDERED)
SCTP_INC_STATS(SCTP_MIB_INUNORDERCHUNKS);
else {
SCTP_INC_STATS(SCTP_MIB_INORDERCHUNKS);
ordered = 1;
}
/* RFC 2960 6.5 Stream Identifier and Stream Sequence Number
*
* If an endpoint receive a DATA chunk with an invalid stream
* identifier, it shall acknowledge the reception of the DATA chunk
* following the normal procedure, immediately send an ERROR chunk
* with cause set to "Invalid Stream Identifier" (See Section 3.3.10)
* and discard the DATA chunk.
*/
sid = ntohs(data_hdr->stream);
if (sid >= asoc->c.sinit_max_instreams) {
/* Mark tsn as received even though we drop it */
sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_TSN, SCTP_U32(tsn));
err = sctp_make_op_error(asoc, chunk, SCTP_ERROR_INV_STRM,
&data_hdr->stream,
sizeof(data_hdr->stream),
sizeof(u16));
if (err)
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY,
SCTP_CHUNK(err));
return SCTP_IERROR_BAD_STREAM;
}
/* Check to see if the SSN is possible for this TSN.
* The biggest gap we can record is 4K wide. Since SSNs wrap
* at an unsigned short, there is no way that an SSN can
* wrap and for a valid TSN. We can simply check if the current
* SSN is smaller then the next expected one. If it is, it wrapped
* and is invalid.
*/
ssn = ntohs(data_hdr->ssn);
if (ordered && SSN_lt(ssn, sctp_ssn_peek(&asoc->ssnmap->in, sid))) {
return SCTP_IERROR_PROTO_VIOLATION;
}
/* Send the data up to the user. Note: Schedule the
* SCTP_CMD_CHUNK_ULP cmd before the SCTP_CMD_GEN_SACK, as the SACK
* chunk needs the updated rwnd.
*/
sctp_add_cmd_sf(commands, deliver, SCTP_CHUNK(chunk));
return SCTP_IERROR_NO_ERROR;
}
| gpl-2.0 |
Falklore/shamu | arch/arm/mach-s3c24xx/clock-dclk.c | 2634 | 4339 | /*
* Copyright (c) 2004-2008 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
* http://armlinux.simtec.co.uk/
*
* 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.
*
* S3C24XX - definitions for DCLK and CLKOUT registers
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <mach/regs-clock.h>
#include <mach/regs-gpio.h>
#include <plat/clock.h>
#include <plat/cpu.h>
/* clocks that could be registered by external code */
static int s3c24xx_dclk_enable(struct clk *clk, int enable)
{
unsigned long dclkcon = __raw_readl(S3C24XX_DCLKCON);
if (enable)
dclkcon |= clk->ctrlbit;
else
dclkcon &= ~clk->ctrlbit;
__raw_writel(dclkcon, S3C24XX_DCLKCON);
return 0;
}
static int s3c24xx_dclk_setparent(struct clk *clk, struct clk *parent)
{
unsigned long dclkcon;
unsigned int uclk;
if (parent == &clk_upll)
uclk = 1;
else if (parent == &clk_p)
uclk = 0;
else
return -EINVAL;
clk->parent = parent;
dclkcon = __raw_readl(S3C24XX_DCLKCON);
if (clk->ctrlbit == S3C2410_DCLKCON_DCLK0EN) {
if (uclk)
dclkcon |= S3C2410_DCLKCON_DCLK0_UCLK;
else
dclkcon &= ~S3C2410_DCLKCON_DCLK0_UCLK;
} else {
if (uclk)
dclkcon |= S3C2410_DCLKCON_DCLK1_UCLK;
else
dclkcon &= ~S3C2410_DCLKCON_DCLK1_UCLK;
}
__raw_writel(dclkcon, S3C24XX_DCLKCON);
return 0;
}
static unsigned long s3c24xx_calc_div(struct clk *clk, unsigned long rate)
{
unsigned long div;
if ((rate == 0) || !clk->parent)
return 0;
div = clk_get_rate(clk->parent) / rate;
if (div < 2)
div = 2;
else if (div > 16)
div = 16;
return div;
}
static unsigned long s3c24xx_round_dclk_rate(struct clk *clk,
unsigned long rate)
{
unsigned long div = s3c24xx_calc_div(clk, rate);
if (div == 0)
return 0;
return clk_get_rate(clk->parent) / div;
}
static int s3c24xx_set_dclk_rate(struct clk *clk, unsigned long rate)
{
unsigned long mask, data, div = s3c24xx_calc_div(clk, rate);
if (div == 0)
return -EINVAL;
if (clk == &s3c24xx_dclk0) {
mask = S3C2410_DCLKCON_DCLK0_DIV_MASK |
S3C2410_DCLKCON_DCLK0_CMP_MASK;
data = S3C2410_DCLKCON_DCLK0_DIV(div) |
S3C2410_DCLKCON_DCLK0_CMP((div + 1) / 2);
} else if (clk == &s3c24xx_dclk1) {
mask = S3C2410_DCLKCON_DCLK1_DIV_MASK |
S3C2410_DCLKCON_DCLK1_CMP_MASK;
data = S3C2410_DCLKCON_DCLK1_DIV(div) |
S3C2410_DCLKCON_DCLK1_CMP((div + 1) / 2);
} else
return -EINVAL;
clk->rate = clk_get_rate(clk->parent) / div;
__raw_writel(((__raw_readl(S3C24XX_DCLKCON) & ~mask) | data),
S3C24XX_DCLKCON);
return clk->rate;
}
static int s3c24xx_clkout_setparent(struct clk *clk, struct clk *parent)
{
unsigned long mask;
unsigned long source;
/* calculate the MISCCR setting for the clock */
if (parent == &clk_mpll)
source = S3C2410_MISCCR_CLK0_MPLL;
else if (parent == &clk_upll)
source = S3C2410_MISCCR_CLK0_UPLL;
else if (parent == &clk_f)
source = S3C2410_MISCCR_CLK0_FCLK;
else if (parent == &clk_h)
source = S3C2410_MISCCR_CLK0_HCLK;
else if (parent == &clk_p)
source = S3C2410_MISCCR_CLK0_PCLK;
else if (clk == &s3c24xx_clkout0 && parent == &s3c24xx_dclk0)
source = S3C2410_MISCCR_CLK0_DCLK0;
else if (clk == &s3c24xx_clkout1 && parent == &s3c24xx_dclk1)
source = S3C2410_MISCCR_CLK0_DCLK0;
else
return -EINVAL;
clk->parent = parent;
if (clk == &s3c24xx_clkout0)
mask = S3C2410_MISCCR_CLK0_MASK;
else {
source <<= 4;
mask = S3C2410_MISCCR_CLK1_MASK;
}
s3c2410_modify_misccr(mask, source);
return 0;
}
/* external clock definitions */
static struct clk_ops dclk_ops = {
.set_parent = s3c24xx_dclk_setparent,
.set_rate = s3c24xx_set_dclk_rate,
.round_rate = s3c24xx_round_dclk_rate,
};
struct clk s3c24xx_dclk0 = {
.name = "dclk0",
.ctrlbit = S3C2410_DCLKCON_DCLK0EN,
.enable = s3c24xx_dclk_enable,
.ops = &dclk_ops,
};
struct clk s3c24xx_dclk1 = {
.name = "dclk1",
.ctrlbit = S3C2410_DCLKCON_DCLK1EN,
.enable = s3c24xx_dclk_enable,
.ops = &dclk_ops,
};
static struct clk_ops clkout_ops = {
.set_parent = s3c24xx_clkout_setparent,
};
struct clk s3c24xx_clkout0 = {
.name = "clkout0",
.ops = &clkout_ops,
};
struct clk s3c24xx_clkout1 = {
.name = "clkout1",
.ops = &clkout_ops,
};
| gpl-2.0 |
sev3n85/samsung_s3ve3g_EUR | fs/btrfs/async-thread.c | 2890 | 18234 | /*
* Copyright (C) 2007 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.
*/
#include <linux/kthread.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/freezer.h>
#include "async-thread.h"
#define WORK_QUEUED_BIT 0
#define WORK_DONE_BIT 1
#define WORK_ORDER_DONE_BIT 2
#define WORK_HIGH_PRIO_BIT 3
/*
* container for the kthread task pointer and the list of pending work
* One of these is allocated per thread.
*/
struct btrfs_worker_thread {
/* pool we belong to */
struct btrfs_workers *workers;
/* list of struct btrfs_work that are waiting for service */
struct list_head pending;
struct list_head prio_pending;
/* list of worker threads from struct btrfs_workers */
struct list_head worker_list;
/* kthread */
struct task_struct *task;
/* number of things on the pending list */
atomic_t num_pending;
/* reference counter for this struct */
atomic_t refs;
unsigned long sequence;
/* protects the pending list. */
spinlock_t lock;
/* set to non-zero when this thread is already awake and kicking */
int working;
/* are we currently idle */
int idle;
};
static int __btrfs_start_workers(struct btrfs_workers *workers);
/*
* btrfs_start_workers uses kthread_run, which can block waiting for memory
* for a very long time. It will actually throttle on page writeback,
* and so it may not make progress until after our btrfs worker threads
* process all of the pending work structs in their queue
*
* This means we can't use btrfs_start_workers from inside a btrfs worker
* thread that is used as part of cleaning dirty memory, which pretty much
* involves all of the worker threads.
*
* Instead we have a helper queue who never has more than one thread
* where we scheduler thread start operations. This worker_start struct
* is used to contain the work and hold a pointer to the queue that needs
* another worker.
*/
struct worker_start {
struct btrfs_work work;
struct btrfs_workers *queue;
};
static void start_new_worker_func(struct btrfs_work *work)
{
struct worker_start *start;
start = container_of(work, struct worker_start, work);
__btrfs_start_workers(start->queue);
kfree(start);
}
/*
* helper function to move a thread onto the idle list after it
* has finished some requests.
*/
static void check_idle_worker(struct btrfs_worker_thread *worker)
{
if (!worker->idle && atomic_read(&worker->num_pending) <
worker->workers->idle_thresh / 2) {
unsigned long flags;
spin_lock_irqsave(&worker->workers->lock, flags);
worker->idle = 1;
/* the list may be empty if the worker is just starting */
if (!list_empty(&worker->worker_list)) {
list_move(&worker->worker_list,
&worker->workers->idle_list);
}
spin_unlock_irqrestore(&worker->workers->lock, flags);
}
}
/*
* helper function to move a thread off the idle list after new
* pending work is added.
*/
static void check_busy_worker(struct btrfs_worker_thread *worker)
{
if (worker->idle && atomic_read(&worker->num_pending) >=
worker->workers->idle_thresh) {
unsigned long flags;
spin_lock_irqsave(&worker->workers->lock, flags);
worker->idle = 0;
if (!list_empty(&worker->worker_list)) {
list_move_tail(&worker->worker_list,
&worker->workers->worker_list);
}
spin_unlock_irqrestore(&worker->workers->lock, flags);
}
}
static void check_pending_worker_creates(struct btrfs_worker_thread *worker)
{
struct btrfs_workers *workers = worker->workers;
struct worker_start *start;
unsigned long flags;
rmb();
if (!workers->atomic_start_pending)
return;
start = kzalloc(sizeof(*start), GFP_NOFS);
if (!start)
return;
start->work.func = start_new_worker_func;
start->queue = workers;
spin_lock_irqsave(&workers->lock, flags);
if (!workers->atomic_start_pending)
goto out;
workers->atomic_start_pending = 0;
if (workers->num_workers + workers->num_workers_starting >=
workers->max_workers)
goto out;
workers->num_workers_starting += 1;
spin_unlock_irqrestore(&workers->lock, flags);
btrfs_queue_worker(workers->atomic_worker_start, &start->work);
return;
out:
kfree(start);
spin_unlock_irqrestore(&workers->lock, flags);
}
static noinline void run_ordered_completions(struct btrfs_workers *workers,
struct btrfs_work *work)
{
if (!workers->ordered)
return;
set_bit(WORK_DONE_BIT, &work->flags);
spin_lock(&workers->order_lock);
while (1) {
if (!list_empty(&workers->prio_order_list)) {
work = list_entry(workers->prio_order_list.next,
struct btrfs_work, order_list);
} else if (!list_empty(&workers->order_list)) {
work = list_entry(workers->order_list.next,
struct btrfs_work, order_list);
} else {
break;
}
if (!test_bit(WORK_DONE_BIT, &work->flags))
break;
/* we are going to call the ordered done function, but
* we leave the work item on the list as a barrier so
* that later work items that are done don't have their
* functions called before this one returns
*/
if (test_and_set_bit(WORK_ORDER_DONE_BIT, &work->flags))
break;
spin_unlock(&workers->order_lock);
work->ordered_func(work);
/* now take the lock again and call the freeing code */
spin_lock(&workers->order_lock);
list_del(&work->order_list);
work->ordered_free(work);
}
spin_unlock(&workers->order_lock);
}
static void put_worker(struct btrfs_worker_thread *worker)
{
if (atomic_dec_and_test(&worker->refs))
kfree(worker);
}
static int try_worker_shutdown(struct btrfs_worker_thread *worker)
{
int freeit = 0;
spin_lock_irq(&worker->lock);
spin_lock(&worker->workers->lock);
if (worker->workers->num_workers > 1 &&
worker->idle &&
!worker->working &&
!list_empty(&worker->worker_list) &&
list_empty(&worker->prio_pending) &&
list_empty(&worker->pending) &&
atomic_read(&worker->num_pending) == 0) {
freeit = 1;
list_del_init(&worker->worker_list);
worker->workers->num_workers--;
}
spin_unlock(&worker->workers->lock);
spin_unlock_irq(&worker->lock);
if (freeit)
put_worker(worker);
return freeit;
}
static struct btrfs_work *get_next_work(struct btrfs_worker_thread *worker,
struct list_head *prio_head,
struct list_head *head)
{
struct btrfs_work *work = NULL;
struct list_head *cur = NULL;
if(!list_empty(prio_head))
cur = prio_head->next;
smp_mb();
if (!list_empty(&worker->prio_pending))
goto refill;
if (!list_empty(head))
cur = head->next;
if (cur)
goto out;
refill:
spin_lock_irq(&worker->lock);
list_splice_tail_init(&worker->prio_pending, prio_head);
list_splice_tail_init(&worker->pending, head);
if (!list_empty(prio_head))
cur = prio_head->next;
else if (!list_empty(head))
cur = head->next;
spin_unlock_irq(&worker->lock);
if (!cur)
goto out_fail;
out:
work = list_entry(cur, struct btrfs_work, list);
out_fail:
return work;
}
/*
* main loop for servicing work items
*/
static int worker_loop(void *arg)
{
struct btrfs_worker_thread *worker = arg;
struct list_head head;
struct list_head prio_head;
struct btrfs_work *work;
INIT_LIST_HEAD(&head);
INIT_LIST_HEAD(&prio_head);
do {
again:
while (1) {
work = get_next_work(worker, &prio_head, &head);
if (!work)
break;
list_del(&work->list);
clear_bit(WORK_QUEUED_BIT, &work->flags);
work->worker = worker;
work->func(work);
atomic_dec(&worker->num_pending);
/*
* unless this is an ordered work queue,
* 'work' was probably freed by func above.
*/
run_ordered_completions(worker->workers, work);
check_pending_worker_creates(worker);
cond_resched();
}
spin_lock_irq(&worker->lock);
check_idle_worker(worker);
if (freezing(current)) {
worker->working = 0;
spin_unlock_irq(&worker->lock);
try_to_freeze();
} else {
spin_unlock_irq(&worker->lock);
if (!kthread_should_stop()) {
cpu_relax();
/*
* we've dropped the lock, did someone else
* jump_in?
*/
smp_mb();
if (!list_empty(&worker->pending) ||
!list_empty(&worker->prio_pending))
continue;
/*
* this short schedule allows more work to
* come in without the queue functions
* needing to go through wake_up_process()
*
* worker->working is still 1, so nobody
* is going to try and wake us up
*/
schedule_timeout(1);
smp_mb();
if (!list_empty(&worker->pending) ||
!list_empty(&worker->prio_pending))
continue;
if (kthread_should_stop())
break;
/* still no more work?, sleep for real */
spin_lock_irq(&worker->lock);
set_current_state(TASK_INTERRUPTIBLE);
if (!list_empty(&worker->pending) ||
!list_empty(&worker->prio_pending)) {
spin_unlock_irq(&worker->lock);
set_current_state(TASK_RUNNING);
goto again;
}
/*
* this makes sure we get a wakeup when someone
* adds something new to the queue
*/
worker->working = 0;
spin_unlock_irq(&worker->lock);
if (!kthread_should_stop()) {
schedule_timeout(HZ * 120);
if (!worker->working &&
try_worker_shutdown(worker)) {
return 0;
}
}
}
__set_current_state(TASK_RUNNING);
}
} while (!kthread_should_stop());
return 0;
}
/*
* this will wait for all the worker threads to shutdown
*/
void btrfs_stop_workers(struct btrfs_workers *workers)
{
struct list_head *cur;
struct btrfs_worker_thread *worker;
int can_stop;
spin_lock_irq(&workers->lock);
list_splice_init(&workers->idle_list, &workers->worker_list);
while (!list_empty(&workers->worker_list)) {
cur = workers->worker_list.next;
worker = list_entry(cur, struct btrfs_worker_thread,
worker_list);
atomic_inc(&worker->refs);
workers->num_workers -= 1;
if (!list_empty(&worker->worker_list)) {
list_del_init(&worker->worker_list);
put_worker(worker);
can_stop = 1;
} else
can_stop = 0;
spin_unlock_irq(&workers->lock);
if (can_stop)
kthread_stop(worker->task);
spin_lock_irq(&workers->lock);
put_worker(worker);
}
spin_unlock_irq(&workers->lock);
}
/*
* simple init on struct btrfs_workers
*/
void btrfs_init_workers(struct btrfs_workers *workers, char *name, int max,
struct btrfs_workers *async_helper)
{
workers->num_workers = 0;
workers->num_workers_starting = 0;
INIT_LIST_HEAD(&workers->worker_list);
INIT_LIST_HEAD(&workers->idle_list);
INIT_LIST_HEAD(&workers->order_list);
INIT_LIST_HEAD(&workers->prio_order_list);
spin_lock_init(&workers->lock);
spin_lock_init(&workers->order_lock);
workers->max_workers = max;
workers->idle_thresh = 32;
workers->name = name;
workers->ordered = 0;
workers->atomic_start_pending = 0;
workers->atomic_worker_start = async_helper;
}
/*
* starts new worker threads. This does not enforce the max worker
* count in case you need to temporarily go past it.
*/
static int __btrfs_start_workers(struct btrfs_workers *workers)
{
struct btrfs_worker_thread *worker;
int ret = 0;
worker = kzalloc(sizeof(*worker), GFP_NOFS);
if (!worker) {
ret = -ENOMEM;
goto fail;
}
INIT_LIST_HEAD(&worker->pending);
INIT_LIST_HEAD(&worker->prio_pending);
INIT_LIST_HEAD(&worker->worker_list);
spin_lock_init(&worker->lock);
atomic_set(&worker->num_pending, 0);
atomic_set(&worker->refs, 1);
worker->workers = workers;
worker->task = kthread_run(worker_loop, worker,
"btrfs-%s-%d", workers->name,
workers->num_workers + 1);
if (IS_ERR(worker->task)) {
ret = PTR_ERR(worker->task);
kfree(worker);
goto fail;
}
spin_lock_irq(&workers->lock);
list_add_tail(&worker->worker_list, &workers->idle_list);
worker->idle = 1;
workers->num_workers++;
workers->num_workers_starting--;
WARN_ON(workers->num_workers_starting < 0);
spin_unlock_irq(&workers->lock);
return 0;
fail:
spin_lock_irq(&workers->lock);
workers->num_workers_starting--;
spin_unlock_irq(&workers->lock);
return ret;
}
int btrfs_start_workers(struct btrfs_workers *workers)
{
spin_lock_irq(&workers->lock);
workers->num_workers_starting++;
spin_unlock_irq(&workers->lock);
return __btrfs_start_workers(workers);
}
/*
* run through the list and find a worker thread that doesn't have a lot
* to do right now. This can return null if we aren't yet at the thread
* count limit and all of the threads are busy.
*/
static struct btrfs_worker_thread *next_worker(struct btrfs_workers *workers)
{
struct btrfs_worker_thread *worker;
struct list_head *next;
int enforce_min;
enforce_min = (workers->num_workers + workers->num_workers_starting) <
workers->max_workers;
/*
* if we find an idle thread, don't move it to the end of the
* idle list. This improves the chance that the next submission
* will reuse the same thread, and maybe catch it while it is still
* working
*/
if (!list_empty(&workers->idle_list)) {
next = workers->idle_list.next;
worker = list_entry(next, struct btrfs_worker_thread,
worker_list);
return worker;
}
if (enforce_min || list_empty(&workers->worker_list))
return NULL;
/*
* if we pick a busy task, move the task to the end of the list.
* hopefully this will keep things somewhat evenly balanced.
* Do the move in batches based on the sequence number. This groups
* requests submitted at roughly the same time onto the same worker.
*/
next = workers->worker_list.next;
worker = list_entry(next, struct btrfs_worker_thread, worker_list);
worker->sequence++;
if (worker->sequence % workers->idle_thresh == 0)
list_move_tail(next, &workers->worker_list);
return worker;
}
/*
* selects a worker thread to take the next job. This will either find
* an idle worker, start a new worker up to the max count, or just return
* one of the existing busy workers.
*/
static struct btrfs_worker_thread *find_worker(struct btrfs_workers *workers)
{
struct btrfs_worker_thread *worker;
unsigned long flags;
struct list_head *fallback;
int ret;
spin_lock_irqsave(&workers->lock, flags);
again:
worker = next_worker(workers);
if (!worker) {
if (workers->num_workers + workers->num_workers_starting >=
workers->max_workers) {
goto fallback;
} else if (workers->atomic_worker_start) {
workers->atomic_start_pending = 1;
goto fallback;
} else {
workers->num_workers_starting++;
spin_unlock_irqrestore(&workers->lock, flags);
/* we're below the limit, start another worker */
ret = __btrfs_start_workers(workers);
spin_lock_irqsave(&workers->lock, flags);
if (ret)
goto fallback;
goto again;
}
}
goto found;
fallback:
fallback = NULL;
/*
* we have failed to find any workers, just
* return the first one we can find.
*/
if (!list_empty(&workers->worker_list))
fallback = workers->worker_list.next;
if (!list_empty(&workers->idle_list))
fallback = workers->idle_list.next;
BUG_ON(!fallback);
worker = list_entry(fallback,
struct btrfs_worker_thread, worker_list);
found:
/*
* this makes sure the worker doesn't exit before it is placed
* onto a busy/idle list
*/
atomic_inc(&worker->num_pending);
spin_unlock_irqrestore(&workers->lock, flags);
return worker;
}
/*
* btrfs_requeue_work just puts the work item back on the tail of the list
* it was taken from. It is intended for use with long running work functions
* that make some progress and want to give the cpu up for others.
*/
void btrfs_requeue_work(struct btrfs_work *work)
{
struct btrfs_worker_thread *worker = work->worker;
unsigned long flags;
int wake = 0;
if (test_and_set_bit(WORK_QUEUED_BIT, &work->flags))
return;
spin_lock_irqsave(&worker->lock, flags);
if (test_bit(WORK_HIGH_PRIO_BIT, &work->flags))
list_add_tail(&work->list, &worker->prio_pending);
else
list_add_tail(&work->list, &worker->pending);
atomic_inc(&worker->num_pending);
/* by definition we're busy, take ourselves off the idle
* list
*/
if (worker->idle) {
spin_lock(&worker->workers->lock);
worker->idle = 0;
list_move_tail(&worker->worker_list,
&worker->workers->worker_list);
spin_unlock(&worker->workers->lock);
}
if (!worker->working) {
wake = 1;
worker->working = 1;
}
if (wake)
wake_up_process(worker->task);
spin_unlock_irqrestore(&worker->lock, flags);
}
void btrfs_set_work_high_prio(struct btrfs_work *work)
{
set_bit(WORK_HIGH_PRIO_BIT, &work->flags);
}
/*
* places a struct btrfs_work into the pending queue of one of the kthreads
*/
void btrfs_queue_worker(struct btrfs_workers *workers, struct btrfs_work *work)
{
struct btrfs_worker_thread *worker;
unsigned long flags;
int wake = 0;
/* don't requeue something already on a list */
if (test_and_set_bit(WORK_QUEUED_BIT, &work->flags))
return;
worker = find_worker(workers);
if (workers->ordered) {
/*
* you're not allowed to do ordered queues from an
* interrupt handler
*/
spin_lock(&workers->order_lock);
if (test_bit(WORK_HIGH_PRIO_BIT, &work->flags)) {
list_add_tail(&work->order_list,
&workers->prio_order_list);
} else {
list_add_tail(&work->order_list, &workers->order_list);
}
spin_unlock(&workers->order_lock);
} else {
INIT_LIST_HEAD(&work->order_list);
}
spin_lock_irqsave(&worker->lock, flags);
if (test_bit(WORK_HIGH_PRIO_BIT, &work->flags))
list_add_tail(&work->list, &worker->prio_pending);
else
list_add_tail(&work->list, &worker->pending);
check_busy_worker(worker);
/*
* avoid calling into wake_up_process if this thread has already
* been kicked
*/
if (!worker->working)
wake = 1;
worker->working = 1;
if (wake)
wake_up_process(worker->task);
spin_unlock_irqrestore(&worker->lock, flags);
}
| gpl-2.0 |
rukin5197/android_kernel_htc_msm7x30 | arch/powerpc/platforms/85xx/stx_gp3.c | 2890 | 4080 | /*
* Based on MPC8560 ADS and arch/ppc stx_gp3 ports
*
* Maintained by Kumar Gala (see MAINTAINERS for contact information)
*
* Copyright 2008 Freescale Semiconductor Inc.
*
* Dan Malek <dan@embeddededge.com>
* Copyright 2004 Embedded Edge, LLC
*
* Copied from mpc8560_ads.c
* Copyright 2002, 2003 Motorola Inc.
*
* Ported to 2.6, Matt Porter <mporter@kernel.crashing.org>
* Copyright 2004-2005 MontaVista Software, Inc.
*
* 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/stddef.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/kdev_t.h>
#include <linux/delay.h>
#include <linux/seq_file.h>
#include <linux/of_platform.h>
#include <asm/system.h>
#include <asm/time.h>
#include <asm/machdep.h>
#include <asm/pci-bridge.h>
#include <asm/mpic.h>
#include <asm/prom.h>
#include <mm/mmu_decl.h>
#include <asm/udbg.h>
#include <sysdev/fsl_soc.h>
#include <sysdev/fsl_pci.h>
#ifdef CONFIG_CPM2
#include <asm/cpm2.h>
#include <sysdev/cpm2_pic.h>
static void cpm2_cascade(unsigned int irq, struct irq_desc *desc)
{
struct irq_chip *chip = irq_desc_get_chip(desc);
int cascade_irq;
while ((cascade_irq = cpm2_get_irq()) >= 0)
generic_handle_irq(cascade_irq);
chip->irq_eoi(&desc->irq_data);
}
#endif /* CONFIG_CPM2 */
static void __init stx_gp3_pic_init(void)
{
struct mpic *mpic;
struct resource r;
struct device_node *np;
#ifdef CONFIG_CPM2
int irq;
#endif
np = of_find_node_by_type(NULL, "open-pic");
if (!np) {
printk(KERN_ERR "Could not find open-pic node\n");
return;
}
if (of_address_to_resource(np, 0, &r)) {
printk(KERN_ERR "Could not map mpic register space\n");
of_node_put(np);
return;
}
mpic = mpic_alloc(np, r.start,
MPIC_PRIMARY | MPIC_WANTS_RESET | MPIC_BIG_ENDIAN,
0, 256, " OpenPIC ");
BUG_ON(mpic == NULL);
of_node_put(np);
mpic_init(mpic);
#ifdef CONFIG_CPM2
/* Setup CPM2 PIC */
np = of_find_compatible_node(NULL, NULL, "fsl,cpm2-pic");
if (np == NULL) {
printk(KERN_ERR "PIC init: can not find fsl,cpm2-pic node\n");
return;
}
irq = irq_of_parse_and_map(np, 0);
if (irq == NO_IRQ) {
of_node_put(np);
printk(KERN_ERR "PIC init: got no IRQ for cpm cascade\n");
return;
}
cpm2_pic_init(np);
of_node_put(np);
irq_set_chained_handler(irq, cpm2_cascade);
#endif
}
/*
* Setup the architecture
*/
static void __init stx_gp3_setup_arch(void)
{
#ifdef CONFIG_PCI
struct device_node *np;
#endif
if (ppc_md.progress)
ppc_md.progress("stx_gp3_setup_arch()", 0);
#ifdef CONFIG_CPM2
cpm2_reset();
#endif
#ifdef CONFIG_PCI
for_each_compatible_node(np, "pci", "fsl,mpc8540-pci")
fsl_add_bridge(np, 1);
#endif
}
static void stx_gp3_show_cpuinfo(struct seq_file *m)
{
uint pvid, svid, phid1;
pvid = mfspr(SPRN_PVR);
svid = mfspr(SPRN_SVR);
seq_printf(m, "Vendor\t\t: RPC Electronics STx\n");
seq_printf(m, "PVR\t\t: 0x%x\n", pvid);
seq_printf(m, "SVR\t\t: 0x%x\n", svid);
/* Display cpu Pll setting */
phid1 = mfspr(SPRN_HID1);
seq_printf(m, "PLL setting\t: 0x%x\n", ((phid1 >> 24) & 0x3f));
}
static struct of_device_id __initdata of_bus_ids[] = {
{ .compatible = "simple-bus", },
{ .compatible = "gianfar", },
{},
};
static int __init declare_of_platform_devices(void)
{
of_platform_bus_probe(NULL, of_bus_ids, NULL);
return 0;
}
machine_device_initcall(stx_gp3, declare_of_platform_devices);
/*
* Called very early, device-tree isn't unflattened
*/
static int __init stx_gp3_probe(void)
{
unsigned long root = of_get_flat_dt_root();
return of_flat_dt_is_compatible(root, "stx,gp3-8560");
}
define_machine(stx_gp3) {
.name = "STX GP3",
.probe = stx_gp3_probe,
.setup_arch = stx_gp3_setup_arch,
.init_IRQ = stx_gp3_pic_init,
.show_cpuinfo = stx_gp3_show_cpuinfo,
.get_irq = mpic_get_irq,
.restart = fsl_rstcr_restart,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
};
| gpl-2.0 |
AlmightyMegadeth00/kernel_tegra | tools/perf/builtin-help.c | 2890 | 11763 | /*
* builtin-help.c
*
* Builtin help command
*/
#include "perf.h"
#include "util/cache.h"
#include "builtin.h"
#include "util/exec_cmd.h"
#include "common-cmds.h"
#include "util/parse-options.h"
#include "util/run-command.h"
#include "util/help.h"
static struct man_viewer_list {
struct man_viewer_list *next;
char name[FLEX_ARRAY];
} *man_viewer_list;
static struct man_viewer_info_list {
struct man_viewer_info_list *next;
const char *info;
char name[FLEX_ARRAY];
} *man_viewer_info_list;
enum help_format {
HELP_FORMAT_NONE,
HELP_FORMAT_MAN,
HELP_FORMAT_INFO,
HELP_FORMAT_WEB,
};
static enum help_format parse_help_format(const char *format)
{
if (!strcmp(format, "man"))
return HELP_FORMAT_MAN;
if (!strcmp(format, "info"))
return HELP_FORMAT_INFO;
if (!strcmp(format, "web") || !strcmp(format, "html"))
return HELP_FORMAT_WEB;
pr_err("unrecognized help format '%s'", format);
return HELP_FORMAT_NONE;
}
static const char *get_man_viewer_info(const char *name)
{
struct man_viewer_info_list *viewer;
for (viewer = man_viewer_info_list; viewer; viewer = viewer->next) {
if (!strcasecmp(name, viewer->name))
return viewer->info;
}
return NULL;
}
static int check_emacsclient_version(void)
{
struct strbuf buffer = STRBUF_INIT;
struct child_process ec_process;
const char *argv_ec[] = { "emacsclient", "--version", NULL };
int version;
/* emacsclient prints its version number on stderr */
memset(&ec_process, 0, sizeof(ec_process));
ec_process.argv = argv_ec;
ec_process.err = -1;
ec_process.stdout_to_stderr = 1;
if (start_command(&ec_process)) {
fprintf(stderr, "Failed to start emacsclient.\n");
return -1;
}
strbuf_read(&buffer, ec_process.err, 20);
close(ec_process.err);
/*
* Don't bother checking return value, because "emacsclient --version"
* seems to always exits with code 1.
*/
finish_command(&ec_process);
if (prefixcmp(buffer.buf, "emacsclient")) {
fprintf(stderr, "Failed to parse emacsclient version.\n");
strbuf_release(&buffer);
return -1;
}
strbuf_remove(&buffer, 0, strlen("emacsclient"));
version = atoi(buffer.buf);
if (version < 22) {
fprintf(stderr,
"emacsclient version '%d' too old (< 22).\n",
version);
strbuf_release(&buffer);
return -1;
}
strbuf_release(&buffer);
return 0;
}
static void exec_woman_emacs(const char *path, const char *page)
{
if (!check_emacsclient_version()) {
/* This works only with emacsclient version >= 22. */
struct strbuf man_page = STRBUF_INIT;
if (!path)
path = "emacsclient";
strbuf_addf(&man_page, "(woman \"%s\")", page);
execlp(path, "emacsclient", "-e", man_page.buf, NULL);
warning("failed to exec '%s': %s", path, strerror(errno));
}
}
static void exec_man_konqueror(const char *path, const char *page)
{
const char *display = getenv("DISPLAY");
if (display && *display) {
struct strbuf man_page = STRBUF_INIT;
const char *filename = "kfmclient";
/* It's simpler to launch konqueror using kfmclient. */
if (path) {
const char *file = strrchr(path, '/');
if (file && !strcmp(file + 1, "konqueror")) {
char *new = strdup(path);
char *dest = strrchr(new, '/');
/* strlen("konqueror") == strlen("kfmclient") */
strcpy(dest + 1, "kfmclient");
path = new;
}
if (file)
filename = file;
} else
path = "kfmclient";
strbuf_addf(&man_page, "man:%s(1)", page);
execlp(path, filename, "newTab", man_page.buf, NULL);
warning("failed to exec '%s': %s", path, strerror(errno));
}
}
static void exec_man_man(const char *path, const char *page)
{
if (!path)
path = "man";
execlp(path, "man", page, NULL);
warning("failed to exec '%s': %s", path, strerror(errno));
}
static void exec_man_cmd(const char *cmd, const char *page)
{
struct strbuf shell_cmd = STRBUF_INIT;
strbuf_addf(&shell_cmd, "%s %s", cmd, page);
execl("/bin/sh", "sh", "-c", shell_cmd.buf, NULL);
warning("failed to exec '%s': %s", cmd, strerror(errno));
}
static void add_man_viewer(const char *name)
{
struct man_viewer_list **p = &man_viewer_list;
size_t len = strlen(name);
while (*p)
p = &((*p)->next);
*p = zalloc(sizeof(**p) + len + 1);
strncpy((*p)->name, name, len);
}
static int supported_man_viewer(const char *name, size_t len)
{
return (!strncasecmp("man", name, len) ||
!strncasecmp("woman", name, len) ||
!strncasecmp("konqueror", name, len));
}
static void do_add_man_viewer_info(const char *name,
size_t len,
const char *value)
{
struct man_viewer_info_list *new = zalloc(sizeof(*new) + len + 1);
strncpy(new->name, name, len);
new->info = strdup(value);
new->next = man_viewer_info_list;
man_viewer_info_list = new;
}
static int add_man_viewer_path(const char *name,
size_t len,
const char *value)
{
if (supported_man_viewer(name, len))
do_add_man_viewer_info(name, len, value);
else
warning("'%s': path for unsupported man viewer.\n"
"Please consider using 'man.<tool>.cmd' instead.",
name);
return 0;
}
static int add_man_viewer_cmd(const char *name,
size_t len,
const char *value)
{
if (supported_man_viewer(name, len))
warning("'%s': cmd for supported man viewer.\n"
"Please consider using 'man.<tool>.path' instead.",
name);
else
do_add_man_viewer_info(name, len, value);
return 0;
}
static int add_man_viewer_info(const char *var, const char *value)
{
const char *name = var + 4;
const char *subkey = strrchr(name, '.');
if (!subkey)
return error("Config with no key for man viewer: %s", name);
if (!strcmp(subkey, ".path")) {
if (!value)
return config_error_nonbool(var);
return add_man_viewer_path(name, subkey - name, value);
}
if (!strcmp(subkey, ".cmd")) {
if (!value)
return config_error_nonbool(var);
return add_man_viewer_cmd(name, subkey - name, value);
}
warning("'%s': unsupported man viewer sub key.", subkey);
return 0;
}
static int perf_help_config(const char *var, const char *value, void *cb)
{
enum help_format *help_formatp = cb;
if (!strcmp(var, "help.format")) {
if (!value)
return config_error_nonbool(var);
*help_formatp = parse_help_format(value);
if (*help_formatp == HELP_FORMAT_NONE)
return -1;
return 0;
}
if (!strcmp(var, "man.viewer")) {
if (!value)
return config_error_nonbool(var);
add_man_viewer(value);
return 0;
}
if (!prefixcmp(var, "man."))
return add_man_viewer_info(var, value);
return perf_default_config(var, value, cb);
}
static struct cmdnames main_cmds, other_cmds;
void list_common_cmds_help(void)
{
unsigned int i, longest = 0;
for (i = 0; i < ARRAY_SIZE(common_cmds); i++) {
if (longest < strlen(common_cmds[i].name))
longest = strlen(common_cmds[i].name);
}
puts(" The most commonly used perf commands are:");
for (i = 0; i < ARRAY_SIZE(common_cmds); i++) {
printf(" %-*s ", longest, common_cmds[i].name);
puts(common_cmds[i].help);
}
}
static int is_perf_command(const char *s)
{
return is_in_cmdlist(&main_cmds, s) ||
is_in_cmdlist(&other_cmds, s);
}
static const char *prepend(const char *prefix, const char *cmd)
{
size_t pre_len = strlen(prefix);
size_t cmd_len = strlen(cmd);
char *p = malloc(pre_len + cmd_len + 1);
memcpy(p, prefix, pre_len);
strcpy(p + pre_len, cmd);
return p;
}
static const char *cmd_to_page(const char *perf_cmd)
{
if (!perf_cmd)
return "perf";
else if (!prefixcmp(perf_cmd, "perf"))
return perf_cmd;
else
return prepend("perf-", perf_cmd);
}
static void setup_man_path(void)
{
struct strbuf new_path = STRBUF_INIT;
const char *old_path = getenv("MANPATH");
/* We should always put ':' after our path. If there is no
* old_path, the ':' at the end will let 'man' to try
* system-wide paths after ours to find the manual page. If
* there is old_path, we need ':' as delimiter. */
strbuf_addstr(&new_path, system_path(PERF_MAN_PATH));
strbuf_addch(&new_path, ':');
if (old_path)
strbuf_addstr(&new_path, old_path);
setenv("MANPATH", new_path.buf, 1);
strbuf_release(&new_path);
}
static void exec_viewer(const char *name, const char *page)
{
const char *info = get_man_viewer_info(name);
if (!strcasecmp(name, "man"))
exec_man_man(info, page);
else if (!strcasecmp(name, "woman"))
exec_woman_emacs(info, page);
else if (!strcasecmp(name, "konqueror"))
exec_man_konqueror(info, page);
else if (info)
exec_man_cmd(info, page);
else
warning("'%s': unknown man viewer.", name);
}
static int show_man_page(const char *perf_cmd)
{
struct man_viewer_list *viewer;
const char *page = cmd_to_page(perf_cmd);
const char *fallback = getenv("PERF_MAN_VIEWER");
setup_man_path();
for (viewer = man_viewer_list; viewer; viewer = viewer->next)
exec_viewer(viewer->name, page); /* will return when unable */
if (fallback)
exec_viewer(fallback, page);
exec_viewer("man", page);
pr_err("no man viewer handled the request");
return -1;
}
static int show_info_page(const char *perf_cmd)
{
const char *page = cmd_to_page(perf_cmd);
setenv("INFOPATH", system_path(PERF_INFO_PATH), 1);
execlp("info", "info", "perfman", page, NULL);
return -1;
}
static int get_html_page_path(struct strbuf *page_path, const char *page)
{
struct stat st;
const char *html_path = system_path(PERF_HTML_PATH);
/* Check that we have a perf documentation directory. */
if (stat(mkpath("%s/perf.html", html_path), &st)
|| !S_ISREG(st.st_mode)) {
pr_err("'%s': not a documentation directory.", html_path);
return -1;
}
strbuf_init(page_path, 0);
strbuf_addf(page_path, "%s/%s.html", html_path, page);
return 0;
}
/*
* If open_html is not defined in a platform-specific way (see for
* example compat/mingw.h), we use the script web--browse to display
* HTML.
*/
#ifndef open_html
static void open_html(const char *path)
{
execl_perf_cmd("web--browse", "-c", "help.browser", path, NULL);
}
#endif
static int show_html_page(const char *perf_cmd)
{
const char *page = cmd_to_page(perf_cmd);
struct strbuf page_path; /* it leaks but we exec bellow */
if (get_html_page_path(&page_path, page) != 0)
return -1;
open_html(page_path.buf);
return 0;
}
int cmd_help(int argc, const char **argv, const char *prefix __maybe_unused)
{
bool show_all = false;
enum help_format help_format = HELP_FORMAT_MAN;
struct option builtin_help_options[] = {
OPT_BOOLEAN('a', "all", &show_all, "print all available commands"),
OPT_SET_UINT('m', "man", &help_format, "show man page", HELP_FORMAT_MAN),
OPT_SET_UINT('w', "web", &help_format, "show manual in web browser",
HELP_FORMAT_WEB),
OPT_SET_UINT('i', "info", &help_format, "show info page",
HELP_FORMAT_INFO),
OPT_END(),
};
const char * const builtin_help_usage[] = {
"perf help [--all] [--man|--web|--info] [command]",
NULL
};
const char *alias;
int rc = 0;
load_command_list("perf-", &main_cmds, &other_cmds);
perf_config(perf_help_config, &help_format);
argc = parse_options(argc, argv, builtin_help_options,
builtin_help_usage, 0);
if (show_all) {
printf("\n usage: %s\n\n", perf_usage_string);
list_commands("perf commands", &main_cmds, &other_cmds);
printf(" %s\n\n", perf_more_info_string);
return 0;
}
if (!argv[0]) {
printf("\n usage: %s\n\n", perf_usage_string);
list_common_cmds_help();
printf("\n %s\n\n", perf_more_info_string);
return 0;
}
alias = alias_lookup(argv[0]);
if (alias && !is_perf_command(argv[0])) {
printf("`perf %s' is aliased to `%s'\n", argv[0], alias);
return 0;
}
switch (help_format) {
case HELP_FORMAT_MAN:
rc = show_man_page(argv[0]);
break;
case HELP_FORMAT_INFO:
rc = show_info_page(argv[0]);
break;
case HELP_FORMAT_WEB:
rc = show_html_page(argv[0]);
break;
case HELP_FORMAT_NONE:
/* fall-through */
default:
rc = -1;
break;
}
return rc;
}
| gpl-2.0 |
cubieboard/CC-A80-kernel-source | arch/arm/mach-highbank/highbank.c | 4682 | 3792 | /*
* Copyright 2010-2011 Calxeda, Inc.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include <linux/clk.h>
#include <linux/clkdev.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/of_address.h>
#include <linux/smp.h>
#include <asm/cacheflush.h>
#include <asm/smp_plat.h>
#include <asm/smp_scu.h>
#include <asm/smp_twd.h>
#include <asm/hardware/arm_timer.h>
#include <asm/hardware/timer-sp.h>
#include <asm/hardware/gic.h>
#include <asm/hardware/cache-l2x0.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/time.h>
#include "core.h"
#include "sysregs.h"
void __iomem *sregs_base;
#define HB_SCU_VIRT_BASE 0xfee00000
void __iomem *scu_base_addr = ((void __iomem *)(HB_SCU_VIRT_BASE));
static struct map_desc scu_io_desc __initdata = {
.virtual = HB_SCU_VIRT_BASE,
.pfn = 0, /* run-time */
.length = SZ_4K,
.type = MT_DEVICE,
};
static void __init highbank_scu_map_io(void)
{
unsigned long base;
/* Get SCU base */
asm("mrc p15, 4, %0, c15, c0, 0" : "=r" (base));
scu_io_desc.pfn = __phys_to_pfn(base);
iotable_init(&scu_io_desc, 1);
}
static void __init highbank_map_io(void)
{
highbank_scu_map_io();
highbank_lluart_map_io();
}
#define HB_JUMP_TABLE_PHYS(cpu) (0x40 + (0x10 * (cpu)))
#define HB_JUMP_TABLE_VIRT(cpu) phys_to_virt(HB_JUMP_TABLE_PHYS(cpu))
void highbank_set_cpu_jump(int cpu, void *jump_addr)
{
cpu = cpu_logical_map(cpu);
writel(virt_to_phys(jump_addr), HB_JUMP_TABLE_VIRT(cpu));
__cpuc_flush_dcache_area(HB_JUMP_TABLE_VIRT(cpu), 16);
outer_clean_range(HB_JUMP_TABLE_PHYS(cpu),
HB_JUMP_TABLE_PHYS(cpu) + 15);
}
const static struct of_device_id irq_match[] = {
{ .compatible = "arm,cortex-a9-gic", .data = gic_of_init, },
{}
};
static void __init highbank_init_irq(void)
{
of_irq_init(irq_match);
l2x0_of_init(0, ~0UL);
}
static void __init highbank_timer_init(void)
{
int irq;
struct device_node *np;
void __iomem *timer_base;
/* Map system registers */
np = of_find_compatible_node(NULL, NULL, "calxeda,hb-sregs");
sregs_base = of_iomap(np, 0);
WARN_ON(!sregs_base);
np = of_find_compatible_node(NULL, NULL, "arm,sp804");
timer_base = of_iomap(np, 0);
WARN_ON(!timer_base);
irq = irq_of_parse_and_map(np, 0);
highbank_clocks_init();
sp804_clocksource_and_sched_clock_init(timer_base + 0x20, "timer1");
sp804_clockevents_init(timer_base, irq, "timer0");
twd_local_timer_of_register();
}
static struct sys_timer highbank_timer = {
.init = highbank_timer_init,
};
static void highbank_power_off(void)
{
hignbank_set_pwr_shutdown();
scu_power_mode(scu_base_addr, SCU_PM_POWEROFF);
while (1)
cpu_do_idle();
}
static void __init highbank_init(void)
{
pm_power_off = highbank_power_off;
of_platform_populate(NULL, of_default_bus_match_table, NULL, NULL);
}
static const char *highbank_match[] __initconst = {
"calxeda,highbank",
NULL,
};
DT_MACHINE_START(HIGHBANK, "Highbank")
.map_io = highbank_map_io,
.init_irq = highbank_init_irq,
.timer = &highbank_timer,
.handle_irq = gic_handle_irq,
.init_machine = highbank_init,
.dt_compat = highbank_match,
.restart = highbank_restart,
MACHINE_END
| gpl-2.0 |
TV-LP51-Devices/kernel_lge_g3 | arch/arm/mach-highbank/highbank.c | 4682 | 3792 | /*
* Copyright 2010-2011 Calxeda, Inc.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include <linux/clk.h>
#include <linux/clkdev.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/of_address.h>
#include <linux/smp.h>
#include <asm/cacheflush.h>
#include <asm/smp_plat.h>
#include <asm/smp_scu.h>
#include <asm/smp_twd.h>
#include <asm/hardware/arm_timer.h>
#include <asm/hardware/timer-sp.h>
#include <asm/hardware/gic.h>
#include <asm/hardware/cache-l2x0.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/time.h>
#include "core.h"
#include "sysregs.h"
void __iomem *sregs_base;
#define HB_SCU_VIRT_BASE 0xfee00000
void __iomem *scu_base_addr = ((void __iomem *)(HB_SCU_VIRT_BASE));
static struct map_desc scu_io_desc __initdata = {
.virtual = HB_SCU_VIRT_BASE,
.pfn = 0, /* run-time */
.length = SZ_4K,
.type = MT_DEVICE,
};
static void __init highbank_scu_map_io(void)
{
unsigned long base;
/* Get SCU base */
asm("mrc p15, 4, %0, c15, c0, 0" : "=r" (base));
scu_io_desc.pfn = __phys_to_pfn(base);
iotable_init(&scu_io_desc, 1);
}
static void __init highbank_map_io(void)
{
highbank_scu_map_io();
highbank_lluart_map_io();
}
#define HB_JUMP_TABLE_PHYS(cpu) (0x40 + (0x10 * (cpu)))
#define HB_JUMP_TABLE_VIRT(cpu) phys_to_virt(HB_JUMP_TABLE_PHYS(cpu))
void highbank_set_cpu_jump(int cpu, void *jump_addr)
{
cpu = cpu_logical_map(cpu);
writel(virt_to_phys(jump_addr), HB_JUMP_TABLE_VIRT(cpu));
__cpuc_flush_dcache_area(HB_JUMP_TABLE_VIRT(cpu), 16);
outer_clean_range(HB_JUMP_TABLE_PHYS(cpu),
HB_JUMP_TABLE_PHYS(cpu) + 15);
}
const static struct of_device_id irq_match[] = {
{ .compatible = "arm,cortex-a9-gic", .data = gic_of_init, },
{}
};
static void __init highbank_init_irq(void)
{
of_irq_init(irq_match);
l2x0_of_init(0, ~0UL);
}
static void __init highbank_timer_init(void)
{
int irq;
struct device_node *np;
void __iomem *timer_base;
/* Map system registers */
np = of_find_compatible_node(NULL, NULL, "calxeda,hb-sregs");
sregs_base = of_iomap(np, 0);
WARN_ON(!sregs_base);
np = of_find_compatible_node(NULL, NULL, "arm,sp804");
timer_base = of_iomap(np, 0);
WARN_ON(!timer_base);
irq = irq_of_parse_and_map(np, 0);
highbank_clocks_init();
sp804_clocksource_and_sched_clock_init(timer_base + 0x20, "timer1");
sp804_clockevents_init(timer_base, irq, "timer0");
twd_local_timer_of_register();
}
static struct sys_timer highbank_timer = {
.init = highbank_timer_init,
};
static void highbank_power_off(void)
{
hignbank_set_pwr_shutdown();
scu_power_mode(scu_base_addr, SCU_PM_POWEROFF);
while (1)
cpu_do_idle();
}
static void __init highbank_init(void)
{
pm_power_off = highbank_power_off;
of_platform_populate(NULL, of_default_bus_match_table, NULL, NULL);
}
static const char *highbank_match[] __initconst = {
"calxeda,highbank",
NULL,
};
DT_MACHINE_START(HIGHBANK, "Highbank")
.map_io = highbank_map_io,
.init_irq = highbank_init_irq,
.timer = &highbank_timer,
.handle_irq = gic_handle_irq,
.init_machine = highbank_init,
.dt_compat = highbank_match,
.restart = highbank_restart,
MACHINE_END
| gpl-2.0 |
ariev7x/S7270_kernel_cm | drivers/power/da9052-battery.c | 4938 | 15480 | /*
* Batttery Driver for Dialog DA9052 PMICs
*
* Copyright(c) 2011 Dialog Semiconductor Ltd.
*
* Author: David Dajun Chen <dchen@diasemi.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/delay.h>
#include <linux/freezer.h>
#include <linux/fs.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/timer.h>
#include <linux/uaccess.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/mfd/da9052/da9052.h>
#include <linux/mfd/da9052/pdata.h>
#include <linux/mfd/da9052/reg.h>
/* STATIC CONFIGURATION */
#define DA9052_BAT_CUTOFF_VOLT 2800
#define DA9052_BAT_TSH 62000
#define DA9052_BAT_LOW_CAP 4
#define DA9052_AVG_SZ 4
#define DA9052_VC_TBL_SZ 68
#define DA9052_VC_TBL_REF_SZ 3
#define DA9052_ISET_USB_MASK 0x0F
#define DA9052_CHG_USB_ILIM_MASK 0x40
#define DA9052_CHG_LIM_COLS 16
#define DA9052_MEAN(x, y) ((x + y) / 2)
enum charger_type_enum {
DA9052_NOCHARGER = 1,
DA9052_CHARGER,
};
static const u16 da9052_chg_current_lim[2][DA9052_CHG_LIM_COLS] = {
{70, 80, 90, 100, 110, 120, 400, 450,
500, 550, 600, 650, 700, 900, 1100, 1300},
{80, 90, 100, 110, 120, 400, 450, 500,
550, 600, 800, 1000, 1200, 1400, 1600, 1800},
};
static const u16 vc_tbl_ref[3] = {10, 25, 40};
/* Lookup table for voltage vs capacity */
static u32 const vc_tbl[3][68][2] = {
/* For temperature 10 degree Celsius */
{
{4082, 100}, {4036, 98},
{4020, 96}, {4008, 95},
{3997, 93}, {3983, 91},
{3964, 90}, {3943, 88},
{3926, 87}, {3912, 85},
{3900, 84}, {3890, 82},
{3881, 80}, {3873, 79},
{3865, 77}, {3857, 76},
{3848, 74}, {3839, 73},
{3829, 71}, {3820, 70},
{3811, 68}, {3802, 67},
{3794, 65}, {3785, 64},
{3778, 62}, {3770, 61},
{3763, 59}, {3756, 58},
{3750, 56}, {3744, 55},
{3738, 53}, {3732, 52},
{3727, 50}, {3722, 49},
{3717, 47}, {3712, 46},
{3708, 44}, {3703, 43},
{3700, 41}, {3696, 40},
{3693, 38}, {3691, 37},
{3688, 35}, {3686, 34},
{3683, 32}, {3681, 31},
{3678, 29}, {3675, 28},
{3672, 26}, {3669, 25},
{3665, 23}, {3661, 22},
{3656, 21}, {3651, 19},
{3645, 18}, {3639, 16},
{3631, 15}, {3622, 13},
{3611, 12}, {3600, 10},
{3587, 9}, {3572, 7},
{3548, 6}, {3503, 5},
{3420, 3}, {3268, 2},
{2992, 1}, {2746, 0}
},
/* For temperature 25 degree Celsius */
{
{4102, 100}, {4065, 98},
{4048, 96}, {4034, 95},
{4021, 93}, {4011, 92},
{4001, 90}, {3986, 88},
{3968, 87}, {3952, 85},
{3938, 84}, {3926, 82},
{3916, 81}, {3908, 79},
{3900, 77}, {3892, 76},
{3883, 74}, {3874, 73},
{3864, 71}, {3855, 70},
{3846, 68}, {3836, 67},
{3827, 65}, {3819, 64},
{3810, 62}, {3801, 61},
{3793, 59}, {3786, 58},
{3778, 56}, {3772, 55},
{3765, 53}, {3759, 52},
{3754, 50}, {3748, 49},
{3743, 47}, {3738, 46},
{3733, 44}, {3728, 43},
{3724, 41}, {3720, 40},
{3716, 38}, {3712, 37},
{3709, 35}, {3706, 34},
{3703, 33}, {3701, 31},
{3698, 30}, {3696, 28},
{3693, 27}, {3690, 25},
{3687, 24}, {3683, 22},
{3680, 21}, {3675, 19},
{3671, 18}, {3666, 17},
{3660, 15}, {3654, 14},
{3647, 12}, {3639, 11},
{3630, 9}, {3621, 8},
{3613, 6}, {3606, 5},
{3597, 4}, {3582, 2},
{3546, 1}, {2747, 0}
},
/* For temperature 40 degree Celsius */
{
{4114, 100}, {4081, 98},
{4065, 96}, {4050, 95},
{4036, 93}, {4024, 92},
{4013, 90}, {4002, 88},
{3990, 87}, {3976, 85},
{3962, 84}, {3950, 82},
{3939, 81}, {3930, 79},
{3921, 77}, {3912, 76},
{3902, 74}, {3893, 73},
{3883, 71}, {3874, 70},
{3865, 68}, {3856, 67},
{3847, 65}, {3838, 64},
{3829, 62}, {3820, 61},
{3812, 59}, {3803, 58},
{3795, 56}, {3787, 55},
{3780, 53}, {3773, 52},
{3767, 50}, {3761, 49},
{3756, 47}, {3751, 46},
{3746, 44}, {3741, 43},
{3736, 41}, {3732, 40},
{3728, 38}, {3724, 37},
{3720, 35}, {3716, 34},
{3713, 33}, {3710, 31},
{3707, 30}, {3704, 28},
{3701, 27}, {3698, 25},
{3695, 24}, {3691, 22},
{3686, 21}, {3681, 19},
{3676, 18}, {3671, 17},
{3666, 15}, {3661, 14},
{3655, 12}, {3648, 11},
{3640, 9}, {3632, 8},
{3622, 6}, {3616, 5},
{3611, 4}, {3604, 2},
{3594, 1}, {2747, 0}
}
};
struct da9052_battery {
struct da9052 *da9052;
struct power_supply psy;
struct notifier_block nb;
int charger_type;
int status;
int health;
};
static inline int volt_reg_to_mV(int value)
{
return ((value * 1000) / 512) + 2500;
}
static inline int ichg_reg_to_mA(int value)
{
return (value * 3900) / 1000;
}
static int da9052_read_chgend_current(struct da9052_battery *bat,
int *current_mA)
{
int ret;
if (bat->status == POWER_SUPPLY_STATUS_DISCHARGING)
return -EINVAL;
ret = da9052_reg_read(bat->da9052, DA9052_ICHG_END_REG);
if (ret < 0)
return ret;
*current_mA = ichg_reg_to_mA(ret & DA9052_ICHGEND_ICHGEND);
return 0;
}
static int da9052_read_chg_current(struct da9052_battery *bat, int *current_mA)
{
int ret;
if (bat->status == POWER_SUPPLY_STATUS_DISCHARGING)
return -EINVAL;
ret = da9052_reg_read(bat->da9052, DA9052_ICHG_AV_REG);
if (ret < 0)
return ret;
*current_mA = ichg_reg_to_mA(ret & DA9052_ICHGAV_ICHGAV);
return 0;
}
static int da9052_bat_check_status(struct da9052_battery *bat, int *status)
{
u8 v[2] = {0, 0};
u8 bat_status;
u8 chg_end;
int ret;
int chg_current;
int chg_end_current;
bool dcinsel;
bool dcindet;
bool vbussel;
bool vbusdet;
bool dc;
bool vbus;
ret = da9052_group_read(bat->da9052, DA9052_STATUS_A_REG, 2, v);
if (ret < 0)
return ret;
bat_status = v[0];
chg_end = v[1];
dcinsel = bat_status & DA9052_STATUSA_DCINSEL;
dcindet = bat_status & DA9052_STATUSA_DCINDET;
vbussel = bat_status & DA9052_STATUSA_VBUSSEL;
vbusdet = bat_status & DA9052_STATUSA_VBUSDET;
dc = dcinsel && dcindet;
vbus = vbussel && vbusdet;
/* Preference to WALL(DCIN) charger unit */
if (dc || vbus) {
bat->charger_type = DA9052_CHARGER;
/* If charging end flag is set and Charging current is greater
* than charging end limit then battery is charging
*/
if ((chg_end & DA9052_STATUSB_CHGEND) != 0) {
ret = da9052_read_chg_current(bat, &chg_current);
if (ret < 0)
return ret;
ret = da9052_read_chgend_current(bat, &chg_end_current);
if (ret < 0)
return ret;
if (chg_current >= chg_end_current)
bat->status = POWER_SUPPLY_STATUS_CHARGING;
else
bat->status = POWER_SUPPLY_STATUS_NOT_CHARGING;
} else {
/* If Charging end flag is cleared then battery is
* charging
*/
bat->status = POWER_SUPPLY_STATUS_CHARGING;
}
} else if (dcindet || vbusdet) {
bat->charger_type = DA9052_CHARGER;
bat->status = POWER_SUPPLY_STATUS_NOT_CHARGING;
} else {
bat->charger_type = DA9052_NOCHARGER;
bat->status = POWER_SUPPLY_STATUS_DISCHARGING;
}
if (status != NULL)
*status = bat->status;
return 0;
}
static int da9052_bat_read_volt(struct da9052_battery *bat, int *volt_mV)
{
int volt;
volt = da9052_adc_manual_read(bat->da9052, DA9052_ADC_MAN_MUXSEL_VBAT);
if (volt < 0)
return volt;
*volt_mV = volt_reg_to_mV(volt);
return 0;
}
static int da9052_bat_check_presence(struct da9052_battery *bat, int *illegal)
{
int bat_temp;
bat_temp = da9052_adc_read_temp(bat->da9052);
if (bat_temp < 0)
return bat_temp;
if (bat_temp > DA9052_BAT_TSH)
*illegal = 1;
else
*illegal = 0;
return 0;
}
static int da9052_bat_interpolate(int vbat_lower, int vbat_upper,
int level_lower, int level_upper,
int bat_voltage)
{
int tmp;
tmp = ((level_upper - level_lower) * 1000) / (vbat_upper - vbat_lower);
tmp = level_lower + (((bat_voltage - vbat_lower) * tmp) / 1000);
return tmp;
}
unsigned char da9052_determine_vc_tbl_index(unsigned char adc_temp)
{
int i;
if (adc_temp <= vc_tbl_ref[0])
return 0;
if (adc_temp > vc_tbl_ref[DA9052_VC_TBL_REF_SZ - 1])
return DA9052_VC_TBL_REF_SZ - 1;
for (i = 0; i < DA9052_VC_TBL_REF_SZ; i++) {
if ((adc_temp > vc_tbl_ref[i]) &&
(adc_temp <= DA9052_MEAN(vc_tbl_ref[i], vc_tbl_ref[i + 1])))
return i;
if ((adc_temp > DA9052_MEAN(vc_tbl_ref[i], vc_tbl_ref[i + 1]))
&& (adc_temp <= vc_tbl_ref[i]))
return i + 1;
}
}
static int da9052_bat_read_capacity(struct da9052_battery *bat, int *capacity)
{
int adc_temp;
int bat_voltage;
int vbat_lower;
int vbat_upper;
int level_upper;
int level_lower;
int ret;
int flag;
int i = 0;
int j;
ret = da9052_bat_read_volt(bat, &bat_voltage);
if (ret < 0)
return ret;
adc_temp = da9052_adc_read_temp(bat->da9052);
if (adc_temp < 0)
return adc_temp;
i = da9052_determine_vc_tbl_index(adc_temp);
if (bat_voltage >= vc_tbl[i][0][0]) {
*capacity = 100;
return 0;
}
if (bat_voltage <= vc_tbl[i][DA9052_VC_TBL_SZ - 1][0]) {
*capacity = 0;
return 0;
}
flag = 0;
for (j = 0; j < (DA9052_VC_TBL_SZ-1); j++) {
if ((bat_voltage <= vc_tbl[i][j][0]) &&
(bat_voltage >= vc_tbl[i][j + 1][0])) {
vbat_upper = vc_tbl[i][j][0];
vbat_lower = vc_tbl[i][j + 1][0];
level_upper = vc_tbl[i][j][1];
level_lower = vc_tbl[i][j + 1][1];
flag = 1;
break;
}
}
if (!flag)
return -EIO;
*capacity = da9052_bat_interpolate(vbat_lower, vbat_upper, level_lower,
level_upper, bat_voltage);
return 0;
}
static int da9052_bat_check_health(struct da9052_battery *bat, int *health)
{
int ret;
int bat_illegal;
int capacity;
ret = da9052_bat_check_presence(bat, &bat_illegal);
if (ret < 0)
return ret;
if (bat_illegal) {
bat->health = POWER_SUPPLY_HEALTH_UNKNOWN;
return 0;
}
if (bat->health != POWER_SUPPLY_HEALTH_OVERHEAT) {
ret = da9052_bat_read_capacity(bat, &capacity);
if (ret < 0)
return ret;
if (capacity < DA9052_BAT_LOW_CAP)
bat->health = POWER_SUPPLY_HEALTH_DEAD;
else
bat->health = POWER_SUPPLY_HEALTH_GOOD;
}
*health = bat->health;
return 0;
}
static irqreturn_t da9052_bat_irq(int irq, void *data)
{
struct da9052_battery *bat = data;
irq -= bat->da9052->irq_base;
if (irq == DA9052_IRQ_CHGEND)
bat->status = POWER_SUPPLY_STATUS_FULL;
else
da9052_bat_check_status(bat, NULL);
if (irq == DA9052_IRQ_CHGEND || irq == DA9052_IRQ_DCIN ||
irq == DA9052_IRQ_VBUS || irq == DA9052_IRQ_TBAT) {
power_supply_changed(&bat->psy);
}
return IRQ_HANDLED;
}
static int da9052_USB_current_notifier(struct notifier_block *nb,
unsigned long events, void *data)
{
u8 row;
u8 col;
int *current_mA = data;
int ret;
struct da9052_battery *bat = container_of(nb, struct da9052_battery,
nb);
if (bat->status == POWER_SUPPLY_STATUS_DISCHARGING)
return -EPERM;
ret = da9052_reg_read(bat->da9052, DA9052_CHGBUCK_REG);
if (ret & DA9052_CHG_USB_ILIM_MASK)
return -EPERM;
if (bat->da9052->chip_id == DA9052)
row = 0;
else
row = 1;
if (*current_mA < da9052_chg_current_lim[row][0] ||
*current_mA > da9052_chg_current_lim[row][DA9052_CHG_LIM_COLS - 1])
return -EINVAL;
for (col = 0; col <= DA9052_CHG_LIM_COLS - 1 ; col++) {
if (*current_mA <= da9052_chg_current_lim[row][col])
break;
}
return da9052_reg_update(bat->da9052, DA9052_ISET_REG,
DA9052_ISET_USB_MASK, col);
}
static int da9052_bat_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
int ret;
int illegal;
struct da9052_battery *bat = container_of(psy, struct da9052_battery,
psy);
ret = da9052_bat_check_presence(bat, &illegal);
if (ret < 0)
return ret;
if (illegal && psp != POWER_SUPPLY_PROP_PRESENT)
return -ENODEV;
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
ret = da9052_bat_check_status(bat, &val->intval);
break;
case POWER_SUPPLY_PROP_ONLINE:
val->intval =
(bat->charger_type == DA9052_NOCHARGER) ? 0 : 1;
break;
case POWER_SUPPLY_PROP_PRESENT:
ret = da9052_bat_check_presence(bat, &val->intval);
break;
case POWER_SUPPLY_PROP_HEALTH:
ret = da9052_bat_check_health(bat, &val->intval);
break;
case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
val->intval = DA9052_BAT_CUTOFF_VOLT * 1000;
break;
case POWER_SUPPLY_PROP_VOLTAGE_AVG:
ret = da9052_bat_read_volt(bat, &val->intval);
break;
case POWER_SUPPLY_PROP_CURRENT_AVG:
ret = da9052_read_chg_current(bat, &val->intval);
break;
case POWER_SUPPLY_PROP_CAPACITY:
ret = da9052_bat_read_capacity(bat, &val->intval);
break;
case POWER_SUPPLY_PROP_TEMP:
val->intval = da9052_adc_read_temp(bat->da9052);
ret = val->intval;
break;
case POWER_SUPPLY_PROP_TECHNOLOGY:
val->intval = POWER_SUPPLY_TECHNOLOGY_LION;
break;
default:
return -EINVAL;
}
return ret;
}
static enum power_supply_property da9052_bat_props[] = {
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
POWER_SUPPLY_PROP_VOLTAGE_AVG,
POWER_SUPPLY_PROP_CURRENT_AVG,
POWER_SUPPLY_PROP_CAPACITY,
POWER_SUPPLY_PROP_TEMP,
POWER_SUPPLY_PROP_TECHNOLOGY,
};
static struct power_supply template_battery = {
.name = "da9052-bat",
.type = POWER_SUPPLY_TYPE_BATTERY,
.properties = da9052_bat_props,
.num_properties = ARRAY_SIZE(da9052_bat_props),
.get_property = da9052_bat_get_property,
};
static const char *const da9052_bat_irqs[] = {
"BATT TEMP",
"DCIN DET",
"DCIN REM",
"VBUS DET",
"VBUS REM",
"CHG END",
};
static s32 __devinit da9052_bat_probe(struct platform_device *pdev)
{
struct da9052_pdata *pdata;
struct da9052_battery *bat;
int ret;
int irq;
int i;
bat = kzalloc(sizeof(struct da9052_battery), GFP_KERNEL);
if (!bat)
return -ENOMEM;
bat->da9052 = dev_get_drvdata(pdev->dev.parent);
bat->psy = template_battery;
bat->charger_type = DA9052_NOCHARGER;
bat->status = POWER_SUPPLY_STATUS_UNKNOWN;
bat->health = POWER_SUPPLY_HEALTH_UNKNOWN;
bat->nb.notifier_call = da9052_USB_current_notifier;
pdata = bat->da9052->dev->platform_data;
if (pdata != NULL && pdata->use_for_apm)
bat->psy.use_for_apm = pdata->use_for_apm;
else
bat->psy.use_for_apm = 1;
for (i = 0; i < ARRAY_SIZE(da9052_bat_irqs); i++) {
irq = platform_get_irq_byname(pdev, da9052_bat_irqs[i]);
ret = request_threaded_irq(bat->da9052->irq_base + irq,
NULL, da9052_bat_irq,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
da9052_bat_irqs[i], bat);
if (ret != 0) {
dev_err(bat->da9052->dev,
"DA9052 failed to request %s IRQ %d: %d\n",
da9052_bat_irqs[i], irq, ret);
goto err;
}
}
ret = power_supply_register(&pdev->dev, &bat->psy);
if (ret)
goto err;
platform_set_drvdata(pdev, bat);
return 0;
err:
for (; i >= 0; i--) {
irq = platform_get_irq_byname(pdev, da9052_bat_irqs[i]);
free_irq(bat->da9052->irq_base + irq, bat);
}
kfree(bat);
return ret;
}
static int __devexit da9052_bat_remove(struct platform_device *pdev)
{
int i;
int irq;
struct da9052_battery *bat = platform_get_drvdata(pdev);
for (i = 0; i < ARRAY_SIZE(da9052_bat_irqs); i++) {
irq = platform_get_irq_byname(pdev, da9052_bat_irqs[i]);
free_irq(bat->da9052->irq_base + irq, bat);
}
power_supply_unregister(&bat->psy);
kfree(bat);
return 0;
}
static struct platform_driver da9052_bat_driver = {
.probe = da9052_bat_probe,
.remove = __devexit_p(da9052_bat_remove),
.driver = {
.name = "da9052-bat",
.owner = THIS_MODULE,
},
};
module_platform_driver(da9052_bat_driver);
MODULE_DESCRIPTION("DA9052 BAT Device Driver");
MODULE_AUTHOR("David Dajun Chen <dchen@diasemi.com>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:da9052-bat");
| gpl-2.0 |
CyanogenMod/android_kernel_sony_flamingo | drivers/video/omap2/vram.c | 4938 | 11810 | /*
* VRAM manager for OMAP
*
* Copyright (C) 2009 Nokia Corporation
* Author: Tomi Valkeinen <tomi.valkeinen@nokia.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.
*
* 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.
*/
/*#define DEBUG*/
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/memblock.h>
#include <linux/completion.h>
#include <linux/debugfs.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <asm/setup.h>
#include <plat/vram.h>
#include <plat/dma.h>
#ifdef DEBUG
#define DBG(format, ...) pr_debug("VRAM: " format, ## __VA_ARGS__)
#else
#define DBG(format, ...)
#endif
/* postponed regions are used to temporarily store region information at boot
* time when we cannot yet allocate the region list */
#define MAX_POSTPONED_REGIONS 10
static bool vram_initialized;
static int postponed_cnt;
static struct {
unsigned long paddr;
size_t size;
} postponed_regions[MAX_POSTPONED_REGIONS];
struct vram_alloc {
struct list_head list;
unsigned long paddr;
unsigned pages;
};
struct vram_region {
struct list_head list;
struct list_head alloc_list;
unsigned long paddr;
unsigned pages;
};
static DEFINE_MUTEX(region_mutex);
static LIST_HEAD(region_list);
static struct vram_region *omap_vram_create_region(unsigned long paddr,
unsigned pages)
{
struct vram_region *rm;
rm = kzalloc(sizeof(*rm), GFP_KERNEL);
if (rm) {
INIT_LIST_HEAD(&rm->alloc_list);
rm->paddr = paddr;
rm->pages = pages;
}
return rm;
}
#if 0
static void omap_vram_free_region(struct vram_region *vr)
{
list_del(&vr->list);
kfree(vr);
}
#endif
static struct vram_alloc *omap_vram_create_allocation(struct vram_region *vr,
unsigned long paddr, unsigned pages)
{
struct vram_alloc *va;
struct vram_alloc *new;
new = kzalloc(sizeof(*va), GFP_KERNEL);
if (!new)
return NULL;
new->paddr = paddr;
new->pages = pages;
list_for_each_entry(va, &vr->alloc_list, list) {
if (va->paddr > new->paddr)
break;
}
list_add_tail(&new->list, &va->list);
return new;
}
static void omap_vram_free_allocation(struct vram_alloc *va)
{
list_del(&va->list);
kfree(va);
}
int omap_vram_add_region(unsigned long paddr, size_t size)
{
struct vram_region *rm;
unsigned pages;
if (vram_initialized) {
DBG("adding region paddr %08lx size %d\n",
paddr, size);
size &= PAGE_MASK;
pages = size >> PAGE_SHIFT;
rm = omap_vram_create_region(paddr, pages);
if (rm == NULL)
return -ENOMEM;
list_add(&rm->list, ®ion_list);
} else {
if (postponed_cnt == MAX_POSTPONED_REGIONS)
return -ENOMEM;
postponed_regions[postponed_cnt].paddr = paddr;
postponed_regions[postponed_cnt].size = size;
++postponed_cnt;
}
return 0;
}
int omap_vram_free(unsigned long paddr, size_t size)
{
struct vram_region *rm;
struct vram_alloc *alloc;
unsigned start, end;
DBG("free mem paddr %08lx size %d\n", paddr, size);
size = PAGE_ALIGN(size);
mutex_lock(®ion_mutex);
list_for_each_entry(rm, ®ion_list, list) {
list_for_each_entry(alloc, &rm->alloc_list, list) {
start = alloc->paddr;
end = alloc->paddr + (alloc->pages >> PAGE_SHIFT);
if (start >= paddr && end < paddr + size)
goto found;
}
}
mutex_unlock(®ion_mutex);
return -EINVAL;
found:
omap_vram_free_allocation(alloc);
mutex_unlock(®ion_mutex);
return 0;
}
EXPORT_SYMBOL(omap_vram_free);
static int _omap_vram_reserve(unsigned long paddr, unsigned pages)
{
struct vram_region *rm;
struct vram_alloc *alloc;
size_t size;
size = pages << PAGE_SHIFT;
list_for_each_entry(rm, ®ion_list, list) {
unsigned long start, end;
DBG("checking region %lx %d\n", rm->paddr, rm->pages);
start = rm->paddr;
end = start + (rm->pages << PAGE_SHIFT) - 1;
if (start > paddr || end < paddr + size - 1)
continue;
DBG("block ok, checking allocs\n");
list_for_each_entry(alloc, &rm->alloc_list, list) {
end = alloc->paddr - 1;
if (start <= paddr && end >= paddr + size - 1)
goto found;
start = alloc->paddr + (alloc->pages << PAGE_SHIFT);
}
end = rm->paddr + (rm->pages << PAGE_SHIFT) - 1;
if (!(start <= paddr && end >= paddr + size - 1))
continue;
found:
DBG("found area start %lx, end %lx\n", start, end);
if (omap_vram_create_allocation(rm, paddr, pages) == NULL)
return -ENOMEM;
return 0;
}
return -ENOMEM;
}
int omap_vram_reserve(unsigned long paddr, size_t size)
{
unsigned pages;
int r;
DBG("reserve mem paddr %08lx size %d\n", paddr, size);
size = PAGE_ALIGN(size);
pages = size >> PAGE_SHIFT;
mutex_lock(®ion_mutex);
r = _omap_vram_reserve(paddr, pages);
mutex_unlock(®ion_mutex);
return r;
}
EXPORT_SYMBOL(omap_vram_reserve);
static void _omap_vram_dma_cb(int lch, u16 ch_status, void *data)
{
struct completion *compl = data;
complete(compl);
}
static int _omap_vram_clear(u32 paddr, unsigned pages)
{
struct completion compl;
unsigned elem_count;
unsigned frame_count;
int r;
int lch;
init_completion(&compl);
r = omap_request_dma(OMAP_DMA_NO_DEVICE, "VRAM DMA",
_omap_vram_dma_cb,
&compl, &lch);
if (r) {
pr_err("VRAM: request_dma failed for memory clear\n");
return -EBUSY;
}
elem_count = pages * PAGE_SIZE / 4;
frame_count = 1;
omap_set_dma_transfer_params(lch, OMAP_DMA_DATA_TYPE_S32,
elem_count, frame_count,
OMAP_DMA_SYNC_ELEMENT,
0, 0);
omap_set_dma_dest_params(lch, 0, OMAP_DMA_AMODE_POST_INC,
paddr, 0, 0);
omap_set_dma_color_mode(lch, OMAP_DMA_CONSTANT_FILL, 0x000000);
omap_start_dma(lch);
if (wait_for_completion_timeout(&compl, msecs_to_jiffies(1000)) == 0) {
omap_stop_dma(lch);
pr_err("VRAM: dma timeout while clearing memory\n");
r = -EIO;
goto err;
}
r = 0;
err:
omap_free_dma(lch);
return r;
}
static int _omap_vram_alloc(unsigned pages, unsigned long *paddr)
{
struct vram_region *rm;
struct vram_alloc *alloc;
list_for_each_entry(rm, ®ion_list, list) {
unsigned long start, end;
DBG("checking region %lx %d\n", rm->paddr, rm->pages);
start = rm->paddr;
list_for_each_entry(alloc, &rm->alloc_list, list) {
end = alloc->paddr;
if (end - start >= pages << PAGE_SHIFT)
goto found;
start = alloc->paddr + (alloc->pages << PAGE_SHIFT);
}
end = rm->paddr + (rm->pages << PAGE_SHIFT);
found:
if (end - start < pages << PAGE_SHIFT)
continue;
DBG("found %lx, end %lx\n", start, end);
alloc = omap_vram_create_allocation(rm, start, pages);
if (alloc == NULL)
return -ENOMEM;
*paddr = start;
_omap_vram_clear(start, pages);
return 0;
}
return -ENOMEM;
}
int omap_vram_alloc(size_t size, unsigned long *paddr)
{
unsigned pages;
int r;
BUG_ON(!size);
DBG("alloc mem size %d\n", size);
size = PAGE_ALIGN(size);
pages = size >> PAGE_SHIFT;
mutex_lock(®ion_mutex);
r = _omap_vram_alloc(pages, paddr);
mutex_unlock(®ion_mutex);
return r;
}
EXPORT_SYMBOL(omap_vram_alloc);
void omap_vram_get_info(unsigned long *vram,
unsigned long *free_vram,
unsigned long *largest_free_block)
{
struct vram_region *vr;
struct vram_alloc *va;
*vram = 0;
*free_vram = 0;
*largest_free_block = 0;
mutex_lock(®ion_mutex);
list_for_each_entry(vr, ®ion_list, list) {
unsigned free;
unsigned long pa;
pa = vr->paddr;
*vram += vr->pages << PAGE_SHIFT;
list_for_each_entry(va, &vr->alloc_list, list) {
free = va->paddr - pa;
*free_vram += free;
if (free > *largest_free_block)
*largest_free_block = free;
pa = va->paddr + (va->pages << PAGE_SHIFT);
}
free = vr->paddr + (vr->pages << PAGE_SHIFT) - pa;
*free_vram += free;
if (free > *largest_free_block)
*largest_free_block = free;
}
mutex_unlock(®ion_mutex);
}
EXPORT_SYMBOL(omap_vram_get_info);
#if defined(CONFIG_DEBUG_FS)
static int vram_debug_show(struct seq_file *s, void *unused)
{
struct vram_region *vr;
struct vram_alloc *va;
unsigned size;
mutex_lock(®ion_mutex);
list_for_each_entry(vr, ®ion_list, list) {
size = vr->pages << PAGE_SHIFT;
seq_printf(s, "%08lx-%08lx (%d bytes)\n",
vr->paddr, vr->paddr + size - 1,
size);
list_for_each_entry(va, &vr->alloc_list, list) {
size = va->pages << PAGE_SHIFT;
seq_printf(s, " %08lx-%08lx (%d bytes)\n",
va->paddr, va->paddr + size - 1,
size);
}
}
mutex_unlock(®ion_mutex);
return 0;
}
static int vram_debug_open(struct inode *inode, struct file *file)
{
return single_open(file, vram_debug_show, inode->i_private);
}
static const struct file_operations vram_debug_fops = {
.open = vram_debug_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init omap_vram_create_debugfs(void)
{
struct dentry *d;
d = debugfs_create_file("vram", S_IRUGO, NULL,
NULL, &vram_debug_fops);
if (IS_ERR(d))
return PTR_ERR(d);
return 0;
}
#endif
static __init int omap_vram_init(void)
{
int i;
vram_initialized = 1;
for (i = 0; i < postponed_cnt; i++)
omap_vram_add_region(postponed_regions[i].paddr,
postponed_regions[i].size);
#ifdef CONFIG_DEBUG_FS
if (omap_vram_create_debugfs())
pr_err("VRAM: Failed to create debugfs file\n");
#endif
return 0;
}
arch_initcall(omap_vram_init);
/* boottime vram alloc stuff */
/* set from board file */
static u32 omap_vram_sdram_start __initdata;
static u32 omap_vram_sdram_size __initdata;
/* set from kernel cmdline */
static u32 omap_vram_def_sdram_size __initdata;
static u32 omap_vram_def_sdram_start __initdata;
static int __init omap_vram_early_vram(char *p)
{
omap_vram_def_sdram_size = memparse(p, &p);
if (*p == ',')
omap_vram_def_sdram_start = simple_strtoul(p + 1, &p, 16);
return 0;
}
early_param("vram", omap_vram_early_vram);
/*
* Called from map_io. We need to call to this early enough so that we
* can reserve the fixed SDRAM regions before VM could get hold of them.
*/
void __init omap_vram_reserve_sdram_memblock(void)
{
u32 paddr;
u32 size = 0;
/* cmdline arg overrides the board file definition */
if (omap_vram_def_sdram_size) {
size = omap_vram_def_sdram_size;
paddr = omap_vram_def_sdram_start;
}
if (!size) {
size = omap_vram_sdram_size;
paddr = omap_vram_sdram_start;
}
#ifdef CONFIG_OMAP2_VRAM_SIZE
if (!size) {
size = CONFIG_OMAP2_VRAM_SIZE * 1024 * 1024;
paddr = 0;
}
#endif
if (!size)
return;
size = ALIGN(size, SZ_2M);
if (paddr) {
if (paddr & ~PAGE_MASK) {
pr_err("VRAM start address 0x%08x not page aligned\n",
paddr);
return;
}
if (!memblock_is_region_memory(paddr, size)) {
pr_err("Illegal SDRAM region 0x%08x..0x%08x for VRAM\n",
paddr, paddr + size - 1);
return;
}
if (memblock_is_region_reserved(paddr, size)) {
pr_err("FB: failed to reserve VRAM - busy\n");
return;
}
if (memblock_reserve(paddr, size) < 0) {
pr_err("FB: failed to reserve VRAM - no memory\n");
return;
}
} else {
paddr = memblock_alloc(size, SZ_2M);
}
memblock_free(paddr, size);
memblock_remove(paddr, size);
omap_vram_add_region(paddr, size);
pr_info("Reserving %u bytes SDRAM for VRAM\n", size);
}
void __init omap_vram_set_sdram_vram(u32 size, u32 start)
{
omap_vram_sdram_start = start;
omap_vram_sdram_size = size;
}
| gpl-2.0 |
SudaMod-devices/boeffla-kernel-cm-bacon | arch/m68k/atari/time.c | 4938 | 9928 | /*
* linux/arch/m68k/atari/time.c
*
* Atari time and real time clock stuff
*
* Assembled of parts of former atari/config.c 97-12-18 by Roman Hodek
*
* 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/types.h>
#include <linux/mc146818rtc.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/rtc.h>
#include <linux/bcd.h>
#include <linux/delay.h>
#include <linux/export.h>
#include <asm/atariints.h>
DEFINE_SPINLOCK(rtc_lock);
EXPORT_SYMBOL_GPL(rtc_lock);
void __init
atari_sched_init(irq_handler_t timer_routine)
{
/* set Timer C data Register */
st_mfp.tim_dt_c = INT_TICKS;
/* start timer C, div = 1:100 */
st_mfp.tim_ct_cd = (st_mfp.tim_ct_cd & 15) | 0x60;
/* install interrupt service routine for MFP Timer C */
if (request_irq(IRQ_MFP_TIMC, timer_routine, IRQ_TYPE_SLOW,
"timer", timer_routine))
pr_err("Couldn't register timer interrupt\n");
}
/* ++andreas: gettimeoffset fixed to check for pending interrupt */
#define TICK_SIZE 10000
/* This is always executed with interrupts disabled. */
unsigned long atari_gettimeoffset (void)
{
unsigned long ticks, offset = 0;
/* read MFP timer C current value */
ticks = st_mfp.tim_dt_c;
/* The probability of underflow is less than 2% */
if (ticks > INT_TICKS - INT_TICKS / 50)
/* Check for pending timer interrupt */
if (st_mfp.int_pn_b & (1 << 5))
offset = TICK_SIZE;
ticks = INT_TICKS - ticks;
ticks = ticks * 10000L / INT_TICKS;
return ticks + offset;
}
static void mste_read(struct MSTE_RTC *val)
{
#define COPY(v) val->v=(mste_rtc.v & 0xf)
do {
COPY(sec_ones) ; COPY(sec_tens) ; COPY(min_ones) ;
COPY(min_tens) ; COPY(hr_ones) ; COPY(hr_tens) ;
COPY(weekday) ; COPY(day_ones) ; COPY(day_tens) ;
COPY(mon_ones) ; COPY(mon_tens) ; COPY(year_ones) ;
COPY(year_tens) ;
/* prevent from reading the clock while it changed */
} while (val->sec_ones != (mste_rtc.sec_ones & 0xf));
#undef COPY
}
static void mste_write(struct MSTE_RTC *val)
{
#define COPY(v) mste_rtc.v=val->v
do {
COPY(sec_ones) ; COPY(sec_tens) ; COPY(min_ones) ;
COPY(min_tens) ; COPY(hr_ones) ; COPY(hr_tens) ;
COPY(weekday) ; COPY(day_ones) ; COPY(day_tens) ;
COPY(mon_ones) ; COPY(mon_tens) ; COPY(year_ones) ;
COPY(year_tens) ;
/* prevent from writing the clock while it changed */
} while (val->sec_ones != (mste_rtc.sec_ones & 0xf));
#undef COPY
}
#define RTC_READ(reg) \
({ unsigned char __val; \
(void) atari_writeb(reg,&tt_rtc.regsel); \
__val = tt_rtc.data; \
__val; \
})
#define RTC_WRITE(reg,val) \
do { \
atari_writeb(reg,&tt_rtc.regsel); \
tt_rtc.data = (val); \
} while(0)
#define HWCLK_POLL_INTERVAL 5
int atari_mste_hwclk( int op, struct rtc_time *t )
{
int hour, year;
int hr24=0;
struct MSTE_RTC val;
mste_rtc.mode=(mste_rtc.mode | 1);
hr24=mste_rtc.mon_tens & 1;
mste_rtc.mode=(mste_rtc.mode & ~1);
if (op) {
/* write: prepare values */
val.sec_ones = t->tm_sec % 10;
val.sec_tens = t->tm_sec / 10;
val.min_ones = t->tm_min % 10;
val.min_tens = t->tm_min / 10;
hour = t->tm_hour;
if (!hr24) {
if (hour > 11)
hour += 20 - 12;
if (hour == 0 || hour == 20)
hour += 12;
}
val.hr_ones = hour % 10;
val.hr_tens = hour / 10;
val.day_ones = t->tm_mday % 10;
val.day_tens = t->tm_mday / 10;
val.mon_ones = (t->tm_mon+1) % 10;
val.mon_tens = (t->tm_mon+1) / 10;
year = t->tm_year - 80;
val.year_ones = year % 10;
val.year_tens = year / 10;
val.weekday = t->tm_wday;
mste_write(&val);
mste_rtc.mode=(mste_rtc.mode | 1);
val.year_ones = (year % 4); /* leap year register */
mste_rtc.mode=(mste_rtc.mode & ~1);
}
else {
mste_read(&val);
t->tm_sec = val.sec_ones + val.sec_tens * 10;
t->tm_min = val.min_ones + val.min_tens * 10;
hour = val.hr_ones + val.hr_tens * 10;
if (!hr24) {
if (hour == 12 || hour == 12 + 20)
hour -= 12;
if (hour >= 20)
hour += 12 - 20;
}
t->tm_hour = hour;
t->tm_mday = val.day_ones + val.day_tens * 10;
t->tm_mon = val.mon_ones + val.mon_tens * 10 - 1;
t->tm_year = val.year_ones + val.year_tens * 10 + 80;
t->tm_wday = val.weekday;
}
return 0;
}
int atari_tt_hwclk( int op, struct rtc_time *t )
{
int sec=0, min=0, hour=0, day=0, mon=0, year=0, wday=0;
unsigned long flags;
unsigned char ctrl;
int pm = 0;
ctrl = RTC_READ(RTC_CONTROL); /* control registers are
* independent from the UIP */
if (op) {
/* write: prepare values */
sec = t->tm_sec;
min = t->tm_min;
hour = t->tm_hour;
day = t->tm_mday;
mon = t->tm_mon + 1;
year = t->tm_year - atari_rtc_year_offset;
wday = t->tm_wday + (t->tm_wday >= 0);
if (!(ctrl & RTC_24H)) {
if (hour > 11) {
pm = 0x80;
if (hour != 12)
hour -= 12;
}
else if (hour == 0)
hour = 12;
}
if (!(ctrl & RTC_DM_BINARY)) {
sec = bin2bcd(sec);
min = bin2bcd(min);
hour = bin2bcd(hour);
day = bin2bcd(day);
mon = bin2bcd(mon);
year = bin2bcd(year);
if (wday >= 0)
wday = bin2bcd(wday);
}
}
/* Reading/writing the clock registers is a bit critical due to
* the regular update cycle of the RTC. While an update is in
* progress, registers 0..9 shouldn't be touched.
* The problem is solved like that: If an update is currently in
* progress (the UIP bit is set), the process sleeps for a while
* (50ms). This really should be enough, since the update cycle
* normally needs 2 ms.
* If the UIP bit reads as 0, we have at least 244 usecs until the
* update starts. This should be enough... But to be sure,
* additionally the RTC_SET bit is set to prevent an update cycle.
*/
while( RTC_READ(RTC_FREQ_SELECT) & RTC_UIP ) {
if (in_atomic() || irqs_disabled())
mdelay(1);
else
schedule_timeout_interruptible(HWCLK_POLL_INTERVAL);
}
local_irq_save(flags);
RTC_WRITE( RTC_CONTROL, ctrl | RTC_SET );
if (!op) {
sec = RTC_READ( RTC_SECONDS );
min = RTC_READ( RTC_MINUTES );
hour = RTC_READ( RTC_HOURS );
day = RTC_READ( RTC_DAY_OF_MONTH );
mon = RTC_READ( RTC_MONTH );
year = RTC_READ( RTC_YEAR );
wday = RTC_READ( RTC_DAY_OF_WEEK );
}
else {
RTC_WRITE( RTC_SECONDS, sec );
RTC_WRITE( RTC_MINUTES, min );
RTC_WRITE( RTC_HOURS, hour + pm);
RTC_WRITE( RTC_DAY_OF_MONTH, day );
RTC_WRITE( RTC_MONTH, mon );
RTC_WRITE( RTC_YEAR, year );
if (wday >= 0) RTC_WRITE( RTC_DAY_OF_WEEK, wday );
}
RTC_WRITE( RTC_CONTROL, ctrl & ~RTC_SET );
local_irq_restore(flags);
if (!op) {
/* read: adjust values */
if (hour & 0x80) {
hour &= ~0x80;
pm = 1;
}
if (!(ctrl & RTC_DM_BINARY)) {
sec = bcd2bin(sec);
min = bcd2bin(min);
hour = bcd2bin(hour);
day = bcd2bin(day);
mon = bcd2bin(mon);
year = bcd2bin(year);
wday = bcd2bin(wday);
}
if (!(ctrl & RTC_24H)) {
if (!pm && hour == 12)
hour = 0;
else if (pm && hour != 12)
hour += 12;
}
t->tm_sec = sec;
t->tm_min = min;
t->tm_hour = hour;
t->tm_mday = day;
t->tm_mon = mon - 1;
t->tm_year = year + atari_rtc_year_offset;
t->tm_wday = wday - 1;
}
return( 0 );
}
int atari_mste_set_clock_mmss (unsigned long nowtime)
{
short real_seconds = nowtime % 60, real_minutes = (nowtime / 60) % 60;
struct MSTE_RTC val;
unsigned char rtc_minutes;
mste_read(&val);
rtc_minutes= val.min_ones + val.min_tens * 10;
if ((rtc_minutes < real_minutes
? real_minutes - rtc_minutes
: rtc_minutes - real_minutes) < 30)
{
val.sec_ones = real_seconds % 10;
val.sec_tens = real_seconds / 10;
val.min_ones = real_minutes % 10;
val.min_tens = real_minutes / 10;
mste_write(&val);
}
else
return -1;
return 0;
}
int atari_tt_set_clock_mmss (unsigned long nowtime)
{
int retval = 0;
short real_seconds = nowtime % 60, real_minutes = (nowtime / 60) % 60;
unsigned char save_control, save_freq_select, rtc_minutes;
save_control = RTC_READ (RTC_CONTROL); /* tell the clock it's being set */
RTC_WRITE (RTC_CONTROL, save_control | RTC_SET);
save_freq_select = RTC_READ (RTC_FREQ_SELECT); /* stop and reset prescaler */
RTC_WRITE (RTC_FREQ_SELECT, save_freq_select | RTC_DIV_RESET2);
rtc_minutes = RTC_READ (RTC_MINUTES);
if (!(save_control & RTC_DM_BINARY))
rtc_minutes = bcd2bin(rtc_minutes);
/* Since we're only adjusting minutes and seconds, don't interfere
with hour overflow. This avoids messing with unknown time zones
but requires your RTC not to be off by more than 30 minutes. */
if ((rtc_minutes < real_minutes
? real_minutes - rtc_minutes
: rtc_minutes - real_minutes) < 30)
{
if (!(save_control & RTC_DM_BINARY))
{
real_seconds = bin2bcd(real_seconds);
real_minutes = bin2bcd(real_minutes);
}
RTC_WRITE (RTC_SECONDS, real_seconds);
RTC_WRITE (RTC_MINUTES, real_minutes);
}
else
retval = -1;
RTC_WRITE (RTC_FREQ_SELECT, save_freq_select);
RTC_WRITE (RTC_CONTROL, save_control);
return retval;
}
/*
* Local variables:
* c-indent-level: 4
* tab-width: 8
* End:
*/
| gpl-2.0 |
pinpong/android_kernel_htc_m7-gpe | drivers/media/dvb/frontends/drxd_hard.c | 4938 | 76798 | /*
* drxd_hard.c: DVB-T Demodulator Micronas DRX3975D-A2,DRX397xD-B1
*
* Copyright (C) 2003-2007 Micronas
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/firmware.h>
#include <linux/i2c.h>
#include <asm/div64.h>
#include "dvb_frontend.h"
#include "drxd.h"
#include "drxd_firm.h"
#define DRX_FW_FILENAME_A2 "drxd-a2-1.1.fw"
#define DRX_FW_FILENAME_B1 "drxd-b1-1.1.fw"
#define CHUNK_SIZE 48
#define DRX_I2C_RMW 0x10
#define DRX_I2C_BROADCAST 0x20
#define DRX_I2C_CLEARCRC 0x80
#define DRX_I2C_SINGLE_MASTER 0xC0
#define DRX_I2C_MODEFLAGS 0xC0
#define DRX_I2C_FLAGS 0xF0
#ifndef SIZEOF_ARRAY
#define SIZEOF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#endif
#define DEFAULT_LOCK_TIMEOUT 1100
#define DRX_CHANNEL_AUTO 0
#define DRX_CHANNEL_HIGH 1
#define DRX_CHANNEL_LOW 2
#define DRX_LOCK_MPEG 1
#define DRX_LOCK_FEC 2
#define DRX_LOCK_DEMOD 4
/****************************************************************************/
enum CSCDState {
CSCD_INIT = 0,
CSCD_SET,
CSCD_SAVED
};
enum CDrxdState {
DRXD_UNINITIALIZED = 0,
DRXD_STOPPED,
DRXD_STARTED
};
enum AGC_CTRL_MODE {
AGC_CTRL_AUTO = 0,
AGC_CTRL_USER,
AGC_CTRL_OFF
};
enum OperationMode {
OM_Default,
OM_DVBT_Diversity_Front,
OM_DVBT_Diversity_End
};
struct SCfgAgc {
enum AGC_CTRL_MODE ctrlMode;
u16 outputLevel; /* range [0, ... , 1023], 1/n of fullscale range */
u16 settleLevel; /* range [0, ... , 1023], 1/n of fullscale range */
u16 minOutputLevel; /* range [0, ... , 1023], 1/n of fullscale range */
u16 maxOutputLevel; /* range [0, ... , 1023], 1/n of fullscale range */
u16 speed; /* range [0, ... , 1023], 1/n of fullscale range */
u16 R1;
u16 R2;
u16 R3;
};
struct SNoiseCal {
int cpOpt;
short cpNexpOfs;
short tdCal2k;
short tdCal8k;
};
enum app_env {
APPENV_STATIC = 0,
APPENV_PORTABLE = 1,
APPENV_MOBILE = 2
};
enum EIFFilter {
IFFILTER_SAW = 0,
IFFILTER_DISCRETE = 1
};
struct drxd_state {
struct dvb_frontend frontend;
struct dvb_frontend_ops ops;
struct dtv_frontend_properties props;
const struct firmware *fw;
struct device *dev;
struct i2c_adapter *i2c;
void *priv;
struct drxd_config config;
int i2c_access;
int init_done;
struct mutex mutex;
u8 chip_adr;
u16 hi_cfg_timing_div;
u16 hi_cfg_bridge_delay;
u16 hi_cfg_wakeup_key;
u16 hi_cfg_ctrl;
u16 intermediate_freq;
u16 osc_clock_freq;
enum CSCDState cscd_state;
enum CDrxdState drxd_state;
u16 sys_clock_freq;
s16 osc_clock_deviation;
u16 expected_sys_clock_freq;
u16 insert_rs_byte;
u16 enable_parallel;
int operation_mode;
struct SCfgAgc if_agc_cfg;
struct SCfgAgc rf_agc_cfg;
struct SNoiseCal noise_cal;
u32 fe_fs_add_incr;
u32 org_fe_fs_add_incr;
u16 current_fe_if_incr;
u16 m_FeAgRegAgPwd;
u16 m_FeAgRegAgAgcSio;
u16 m_EcOcRegOcModeLop;
u16 m_EcOcRegSncSncLvl;
u8 *m_InitAtomicRead;
u8 *m_HiI2cPatch;
u8 *m_ResetCEFR;
u8 *m_InitFE_1;
u8 *m_InitFE_2;
u8 *m_InitCP;
u8 *m_InitCE;
u8 *m_InitEQ;
u8 *m_InitSC;
u8 *m_InitEC;
u8 *m_ResetECRAM;
u8 *m_InitDiversityFront;
u8 *m_InitDiversityEnd;
u8 *m_DisableDiversity;
u8 *m_StartDiversityFront;
u8 *m_StartDiversityEnd;
u8 *m_DiversityDelay8MHZ;
u8 *m_DiversityDelay6MHZ;
u8 *microcode;
u32 microcode_length;
int type_A;
int PGA;
int diversity;
int tuner_mirrors;
enum app_env app_env_default;
enum app_env app_env_diversity;
};
/****************************************************************************/
/* I2C **********************************************************************/
/****************************************************************************/
static int i2c_write(struct i2c_adapter *adap, u8 adr, u8 * data, int len)
{
struct i2c_msg msg = {.addr = adr, .flags = 0, .buf = data, .len = len };
if (i2c_transfer(adap, &msg, 1) != 1)
return -1;
return 0;
}
static int i2c_read(struct i2c_adapter *adap,
u8 adr, u8 *msg, int len, u8 *answ, int alen)
{
struct i2c_msg msgs[2] = {
{
.addr = adr, .flags = 0,
.buf = msg, .len = len
}, {
.addr = adr, .flags = I2C_M_RD,
.buf = answ, .len = alen
}
};
if (i2c_transfer(adap, msgs, 2) != 2)
return -1;
return 0;
}
static inline u32 MulDiv32(u32 a, u32 b, u32 c)
{
u64 tmp64;
tmp64 = (u64)a * (u64)b;
do_div(tmp64, c);
return (u32) tmp64;
}
static int Read16(struct drxd_state *state, u32 reg, u16 *data, u8 flags)
{
u8 adr = state->config.demod_address;
u8 mm1[4] = { reg & 0xff, (reg >> 16) & 0xff,
flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff
};
u8 mm2[2];
if (i2c_read(state->i2c, adr, mm1, 4, mm2, 2) < 0)
return -1;
if (data)
*data = mm2[0] | (mm2[1] << 8);
return mm2[0] | (mm2[1] << 8);
}
static int Read32(struct drxd_state *state, u32 reg, u32 *data, u8 flags)
{
u8 adr = state->config.demod_address;
u8 mm1[4] = { reg & 0xff, (reg >> 16) & 0xff,
flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff
};
u8 mm2[4];
if (i2c_read(state->i2c, adr, mm1, 4, mm2, 4) < 0)
return -1;
if (data)
*data =
mm2[0] | (mm2[1] << 8) | (mm2[2] << 16) | (mm2[3] << 24);
return 0;
}
static int Write16(struct drxd_state *state, u32 reg, u16 data, u8 flags)
{
u8 adr = state->config.demod_address;
u8 mm[6] = { reg & 0xff, (reg >> 16) & 0xff,
flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff,
data & 0xff, (data >> 8) & 0xff
};
if (i2c_write(state->i2c, adr, mm, 6) < 0)
return -1;
return 0;
}
static int Write32(struct drxd_state *state, u32 reg, u32 data, u8 flags)
{
u8 adr = state->config.demod_address;
u8 mm[8] = { reg & 0xff, (reg >> 16) & 0xff,
flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff,
data & 0xff, (data >> 8) & 0xff,
(data >> 16) & 0xff, (data >> 24) & 0xff
};
if (i2c_write(state->i2c, adr, mm, 8) < 0)
return -1;
return 0;
}
static int write_chunk(struct drxd_state *state,
u32 reg, u8 *data, u32 len, u8 flags)
{
u8 adr = state->config.demod_address;
u8 mm[CHUNK_SIZE + 4] = { reg & 0xff, (reg >> 16) & 0xff,
flags | ((reg >> 24) & 0xff), (reg >> 8) & 0xff
};
int i;
for (i = 0; i < len; i++)
mm[4 + i] = data[i];
if (i2c_write(state->i2c, adr, mm, 4 + len) < 0) {
printk(KERN_ERR "error in write_chunk\n");
return -1;
}
return 0;
}
static int WriteBlock(struct drxd_state *state,
u32 Address, u16 BlockSize, u8 *pBlock, u8 Flags)
{
while (BlockSize > 0) {
u16 Chunk = BlockSize > CHUNK_SIZE ? CHUNK_SIZE : BlockSize;
if (write_chunk(state, Address, pBlock, Chunk, Flags) < 0)
return -1;
pBlock += Chunk;
Address += (Chunk >> 1);
BlockSize -= Chunk;
}
return 0;
}
static int WriteTable(struct drxd_state *state, u8 * pTable)
{
int status = 0;
if (pTable == NULL)
return 0;
while (!status) {
u16 Length;
u32 Address = pTable[0] | (pTable[1] << 8) |
(pTable[2] << 16) | (pTable[3] << 24);
if (Address == 0xFFFFFFFF)
break;
pTable += sizeof(u32);
Length = pTable[0] | (pTable[1] << 8);
pTable += sizeof(u16);
if (!Length)
break;
status = WriteBlock(state, Address, Length * 2, pTable, 0);
pTable += (Length * 2);
}
return status;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
static int ResetCEFR(struct drxd_state *state)
{
return WriteTable(state, state->m_ResetCEFR);
}
static int InitCP(struct drxd_state *state)
{
return WriteTable(state, state->m_InitCP);
}
static int InitCE(struct drxd_state *state)
{
int status;
enum app_env AppEnv = state->app_env_default;
do {
status = WriteTable(state, state->m_InitCE);
if (status < 0)
break;
if (state->operation_mode == OM_DVBT_Diversity_Front ||
state->operation_mode == OM_DVBT_Diversity_End) {
AppEnv = state->app_env_diversity;
}
if (AppEnv == APPENV_STATIC) {
status = Write16(state, CE_REG_TAPSET__A, 0x0000, 0);
if (status < 0)
break;
} else if (AppEnv == APPENV_PORTABLE) {
status = Write16(state, CE_REG_TAPSET__A, 0x0001, 0);
if (status < 0)
break;
} else if (AppEnv == APPENV_MOBILE && state->type_A) {
status = Write16(state, CE_REG_TAPSET__A, 0x0002, 0);
if (status < 0)
break;
} else if (AppEnv == APPENV_MOBILE && !state->type_A) {
status = Write16(state, CE_REG_TAPSET__A, 0x0006, 0);
if (status < 0)
break;
}
/* start ce */
status = Write16(state, B_CE_REG_COMM_EXEC__A, 0x0001, 0);
if (status < 0)
break;
} while (0);
return status;
}
static int StopOC(struct drxd_state *state)
{
int status = 0;
u16 ocSyncLvl = 0;
u16 ocModeLop = state->m_EcOcRegOcModeLop;
u16 dtoIncLop = 0;
u16 dtoIncHip = 0;
do {
/* Store output configuration */
status = Read16(state, EC_OC_REG_SNC_ISC_LVL__A, &ocSyncLvl, 0);
if (status < 0)
break;
/* CHK_ERROR(Read16(EC_OC_REG_OC_MODE_LOP__A, &ocModeLop)); */
state->m_EcOcRegSncSncLvl = ocSyncLvl;
/* m_EcOcRegOcModeLop = ocModeLop; */
/* Flush FIFO (byte-boundary) at fixed rate */
status = Read16(state, EC_OC_REG_RCN_MAP_LOP__A, &dtoIncLop, 0);
if (status < 0)
break;
status = Read16(state, EC_OC_REG_RCN_MAP_HIP__A, &dtoIncHip, 0);
if (status < 0)
break;
status = Write16(state, EC_OC_REG_DTO_INC_LOP__A, dtoIncLop, 0);
if (status < 0)
break;
status = Write16(state, EC_OC_REG_DTO_INC_HIP__A, dtoIncHip, 0);
if (status < 0)
break;
ocModeLop &= ~(EC_OC_REG_OC_MODE_LOP_DTO_CTR_SRC__M);
ocModeLop |= EC_OC_REG_OC_MODE_LOP_DTO_CTR_SRC_STATIC;
status = Write16(state, EC_OC_REG_OC_MODE_LOP__A, ocModeLop, 0);
if (status < 0)
break;
status = Write16(state, EC_OC_REG_COMM_EXEC__A, EC_OC_REG_COMM_EXEC_CTL_HOLD, 0);
if (status < 0)
break;
msleep(1);
/* Output pins to '0' */
status = Write16(state, EC_OC_REG_OCR_MPG_UOS__A, EC_OC_REG_OCR_MPG_UOS__M, 0);
if (status < 0)
break;
/* Force the OC out of sync */
ocSyncLvl &= ~(EC_OC_REG_SNC_ISC_LVL_OSC__M);
status = Write16(state, EC_OC_REG_SNC_ISC_LVL__A, ocSyncLvl, 0);
if (status < 0)
break;
ocModeLop &= ~(EC_OC_REG_OC_MODE_LOP_PAR_ENA__M);
ocModeLop |= EC_OC_REG_OC_MODE_LOP_PAR_ENA_ENABLE;
ocModeLop |= 0x2; /* Magically-out-of-sync */
status = Write16(state, EC_OC_REG_OC_MODE_LOP__A, ocModeLop, 0);
if (status < 0)
break;
status = Write16(state, EC_OC_REG_COMM_INT_STA__A, 0x0, 0);
if (status < 0)
break;
status = Write16(state, EC_OC_REG_COMM_EXEC__A, EC_OC_REG_COMM_EXEC_CTL_ACTIVE, 0);
if (status < 0)
break;
} while (0);
return status;
}
static int StartOC(struct drxd_state *state)
{
int status = 0;
do {
/* Stop OC */
status = Write16(state, EC_OC_REG_COMM_EXEC__A, EC_OC_REG_COMM_EXEC_CTL_HOLD, 0);
if (status < 0)
break;
/* Restore output configuration */
status = Write16(state, EC_OC_REG_SNC_ISC_LVL__A, state->m_EcOcRegSncSncLvl, 0);
if (status < 0)
break;
status = Write16(state, EC_OC_REG_OC_MODE_LOP__A, state->m_EcOcRegOcModeLop, 0);
if (status < 0)
break;
/* Output pins active again */
status = Write16(state, EC_OC_REG_OCR_MPG_UOS__A, EC_OC_REG_OCR_MPG_UOS_INIT, 0);
if (status < 0)
break;
/* Start OC */
status = Write16(state, EC_OC_REG_COMM_EXEC__A, EC_OC_REG_COMM_EXEC_CTL_ACTIVE, 0);
if (status < 0)
break;
} while (0);
return status;
}
static int InitEQ(struct drxd_state *state)
{
return WriteTable(state, state->m_InitEQ);
}
static int InitEC(struct drxd_state *state)
{
return WriteTable(state, state->m_InitEC);
}
static int InitSC(struct drxd_state *state)
{
return WriteTable(state, state->m_InitSC);
}
static int InitAtomicRead(struct drxd_state *state)
{
return WriteTable(state, state->m_InitAtomicRead);
}
static int CorrectSysClockDeviation(struct drxd_state *state);
static int DRX_GetLockStatus(struct drxd_state *state, u32 * pLockStatus)
{
u16 ScRaRamLock = 0;
const u16 mpeg_lock_mask = (SC_RA_RAM_LOCK_MPEG__M |
SC_RA_RAM_LOCK_FEC__M |
SC_RA_RAM_LOCK_DEMOD__M);
const u16 fec_lock_mask = (SC_RA_RAM_LOCK_FEC__M |
SC_RA_RAM_LOCK_DEMOD__M);
const u16 demod_lock_mask = SC_RA_RAM_LOCK_DEMOD__M;
int status;
*pLockStatus = 0;
status = Read16(state, SC_RA_RAM_LOCK__A, &ScRaRamLock, 0x0000);
if (status < 0) {
printk(KERN_ERR "Can't read SC_RA_RAM_LOCK__A status = %08x\n", status);
return status;
}
if (state->drxd_state != DRXD_STARTED)
return 0;
if ((ScRaRamLock & mpeg_lock_mask) == mpeg_lock_mask) {
*pLockStatus |= DRX_LOCK_MPEG;
CorrectSysClockDeviation(state);
}
if ((ScRaRamLock & fec_lock_mask) == fec_lock_mask)
*pLockStatus |= DRX_LOCK_FEC;
if ((ScRaRamLock & demod_lock_mask) == demod_lock_mask)
*pLockStatus |= DRX_LOCK_DEMOD;
return 0;
}
/****************************************************************************/
static int SetCfgIfAgc(struct drxd_state *state, struct SCfgAgc *cfg)
{
int status;
if (cfg->outputLevel > DRXD_FE_CTRL_MAX)
return -1;
if (cfg->ctrlMode == AGC_CTRL_USER) {
do {
u16 FeAgRegPm1AgcWri;
u16 FeAgRegAgModeLop;
status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &FeAgRegAgModeLop, 0);
if (status < 0)
break;
FeAgRegAgModeLop &= (~FE_AG_REG_AG_MODE_LOP_MODE_4__M);
FeAgRegAgModeLop |= FE_AG_REG_AG_MODE_LOP_MODE_4_STATIC;
status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, FeAgRegAgModeLop, 0);
if (status < 0)
break;
FeAgRegPm1AgcWri = (u16) (cfg->outputLevel &
FE_AG_REG_PM1_AGC_WRI__M);
status = Write16(state, FE_AG_REG_PM1_AGC_WRI__A, FeAgRegPm1AgcWri, 0);
if (status < 0)
break;
} while (0);
} else if (cfg->ctrlMode == AGC_CTRL_AUTO) {
if (((cfg->maxOutputLevel) < (cfg->minOutputLevel)) ||
((cfg->maxOutputLevel) > DRXD_FE_CTRL_MAX) ||
((cfg->speed) > DRXD_FE_CTRL_MAX) ||
((cfg->settleLevel) > DRXD_FE_CTRL_MAX)
)
return -1;
do {
u16 FeAgRegAgModeLop;
u16 FeAgRegEgcSetLvl;
u16 slope, offset;
/* == Mode == */
status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &FeAgRegAgModeLop, 0);
if (status < 0)
break;
FeAgRegAgModeLop &= (~FE_AG_REG_AG_MODE_LOP_MODE_4__M);
FeAgRegAgModeLop |=
FE_AG_REG_AG_MODE_LOP_MODE_4_DYNAMIC;
status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, FeAgRegAgModeLop, 0);
if (status < 0)
break;
/* == Settle level == */
FeAgRegEgcSetLvl = (u16) ((cfg->settleLevel >> 1) &
FE_AG_REG_EGC_SET_LVL__M);
status = Write16(state, FE_AG_REG_EGC_SET_LVL__A, FeAgRegEgcSetLvl, 0);
if (status < 0)
break;
/* == Min/Max == */
slope = (u16) ((cfg->maxOutputLevel -
cfg->minOutputLevel) / 2);
offset = (u16) ((cfg->maxOutputLevel +
cfg->minOutputLevel) / 2 - 511);
status = Write16(state, FE_AG_REG_GC1_AGC_RIC__A, slope, 0);
if (status < 0)
break;
status = Write16(state, FE_AG_REG_GC1_AGC_OFF__A, offset, 0);
if (status < 0)
break;
/* == Speed == */
{
const u16 maxRur = 8;
const u16 slowIncrDecLUT[] = { 3, 4, 4, 5, 6 };
const u16 fastIncrDecLUT[] = { 14, 15, 15, 16,
17, 18, 18, 19,
20, 21, 22, 23,
24, 26, 27, 28,
29, 31
};
u16 fineSteps = (DRXD_FE_CTRL_MAX + 1) /
(maxRur + 1);
u16 fineSpeed = (u16) (cfg->speed -
((cfg->speed /
fineSteps) *
fineSteps));
u16 invRurCount = (u16) (cfg->speed /
fineSteps);
u16 rurCount;
if (invRurCount > maxRur) {
rurCount = 0;
fineSpeed += fineSteps;
} else {
rurCount = maxRur - invRurCount;
}
/*
fastInc = default *
(2^(fineSpeed/fineSteps))
=> range[default...2*default>
slowInc = default *
(2^(fineSpeed/fineSteps))
*/
{
u16 fastIncrDec =
fastIncrDecLUT[fineSpeed /
((fineSteps /
(14 + 1)) + 1)];
u16 slowIncrDec =
slowIncrDecLUT[fineSpeed /
(fineSteps /
(3 + 1))];
status = Write16(state, FE_AG_REG_EGC_RUR_CNT__A, rurCount, 0);
if (status < 0)
break;
status = Write16(state, FE_AG_REG_EGC_FAS_INC__A, fastIncrDec, 0);
if (status < 0)
break;
status = Write16(state, FE_AG_REG_EGC_FAS_DEC__A, fastIncrDec, 0);
if (status < 0)
break;
status = Write16(state, FE_AG_REG_EGC_SLO_INC__A, slowIncrDec, 0);
if (status < 0)
break;
status = Write16(state, FE_AG_REG_EGC_SLO_DEC__A, slowIncrDec, 0);
if (status < 0)
break;
}
}
} while (0);
} else {
/* No OFF mode for IF control */
return -1;
}
return status;
}
static int SetCfgRfAgc(struct drxd_state *state, struct SCfgAgc *cfg)
{
int status = 0;
if (cfg->outputLevel > DRXD_FE_CTRL_MAX)
return -1;
if (cfg->ctrlMode == AGC_CTRL_USER) {
do {
u16 AgModeLop = 0;
u16 level = (cfg->outputLevel);
if (level == DRXD_FE_CTRL_MAX)
level++;
status = Write16(state, FE_AG_REG_PM2_AGC_WRI__A, level, 0x0000);
if (status < 0)
break;
/*==== Mode ====*/
/* Powerdown PD2, WRI source */
state->m_FeAgRegAgPwd &= ~(FE_AG_REG_AG_PWD_PWD_PD2__M);
state->m_FeAgRegAgPwd |=
FE_AG_REG_AG_PWD_PWD_PD2_DISABLE;
status = Write16(state, FE_AG_REG_AG_PWD__A, state->m_FeAgRegAgPwd, 0x0000);
if (status < 0)
break;
status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000);
if (status < 0)
break;
AgModeLop &= (~(FE_AG_REG_AG_MODE_LOP_MODE_5__M |
FE_AG_REG_AG_MODE_LOP_MODE_E__M));
AgModeLop |= (FE_AG_REG_AG_MODE_LOP_MODE_5_STATIC |
FE_AG_REG_AG_MODE_LOP_MODE_E_STATIC);
status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000);
if (status < 0)
break;
/* enable AGC2 pin */
{
u16 FeAgRegAgAgcSio = 0;
status = Read16(state, FE_AG_REG_AG_AGC_SIO__A, &FeAgRegAgAgcSio, 0x0000);
if (status < 0)
break;
FeAgRegAgAgcSio &=
~(FE_AG_REG_AG_AGC_SIO_AGC_SIO_2__M);
FeAgRegAgAgcSio |=
FE_AG_REG_AG_AGC_SIO_AGC_SIO_2_OUTPUT;
status = Write16(state, FE_AG_REG_AG_AGC_SIO__A, FeAgRegAgAgcSio, 0x0000);
if (status < 0)
break;
}
} while (0);
} else if (cfg->ctrlMode == AGC_CTRL_AUTO) {
u16 AgModeLop = 0;
do {
u16 level;
/* Automatic control */
/* Powerup PD2, AGC2 as output, TGC source */
(state->m_FeAgRegAgPwd) &=
~(FE_AG_REG_AG_PWD_PWD_PD2__M);
(state->m_FeAgRegAgPwd) |=
FE_AG_REG_AG_PWD_PWD_PD2_DISABLE;
status = Write16(state, FE_AG_REG_AG_PWD__A, (state->m_FeAgRegAgPwd), 0x0000);
if (status < 0)
break;
status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000);
if (status < 0)
break;
AgModeLop &= (~(FE_AG_REG_AG_MODE_LOP_MODE_5__M |
FE_AG_REG_AG_MODE_LOP_MODE_E__M));
AgModeLop |= (FE_AG_REG_AG_MODE_LOP_MODE_5_STATIC |
FE_AG_REG_AG_MODE_LOP_MODE_E_DYNAMIC);
status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000);
if (status < 0)
break;
/* Settle level */
level = (((cfg->settleLevel) >> 4) &
FE_AG_REG_TGC_SET_LVL__M);
status = Write16(state, FE_AG_REG_TGC_SET_LVL__A, level, 0x0000);
if (status < 0)
break;
/* Min/max: don't care */
/* Speed: TODO */
/* enable AGC2 pin */
{
u16 FeAgRegAgAgcSio = 0;
status = Read16(state, FE_AG_REG_AG_AGC_SIO__A, &FeAgRegAgAgcSio, 0x0000);
if (status < 0)
break;
FeAgRegAgAgcSio &=
~(FE_AG_REG_AG_AGC_SIO_AGC_SIO_2__M);
FeAgRegAgAgcSio |=
FE_AG_REG_AG_AGC_SIO_AGC_SIO_2_OUTPUT;
status = Write16(state, FE_AG_REG_AG_AGC_SIO__A, FeAgRegAgAgcSio, 0x0000);
if (status < 0)
break;
}
} while (0);
} else {
u16 AgModeLop = 0;
do {
/* No RF AGC control */
/* Powerdown PD2, AGC2 as output, WRI source */
(state->m_FeAgRegAgPwd) &=
~(FE_AG_REG_AG_PWD_PWD_PD2__M);
(state->m_FeAgRegAgPwd) |=
FE_AG_REG_AG_PWD_PWD_PD2_ENABLE;
status = Write16(state, FE_AG_REG_AG_PWD__A, (state->m_FeAgRegAgPwd), 0x0000);
if (status < 0)
break;
status = Read16(state, FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000);
if (status < 0)
break;
AgModeLop &= (~(FE_AG_REG_AG_MODE_LOP_MODE_5__M |
FE_AG_REG_AG_MODE_LOP_MODE_E__M));
AgModeLop |= (FE_AG_REG_AG_MODE_LOP_MODE_5_STATIC |
FE_AG_REG_AG_MODE_LOP_MODE_E_STATIC);
status = Write16(state, FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000);
if (status < 0)
break;
/* set FeAgRegAgAgcSio AGC2 (RF) as input */
{
u16 FeAgRegAgAgcSio = 0;
status = Read16(state, FE_AG_REG_AG_AGC_SIO__A, &FeAgRegAgAgcSio, 0x0000);
if (status < 0)
break;
FeAgRegAgAgcSio &=
~(FE_AG_REG_AG_AGC_SIO_AGC_SIO_2__M);
FeAgRegAgAgcSio |=
FE_AG_REG_AG_AGC_SIO_AGC_SIO_2_INPUT;
status = Write16(state, FE_AG_REG_AG_AGC_SIO__A, FeAgRegAgAgcSio, 0x0000);
if (status < 0)
break;
}
} while (0);
}
return status;
}
static int ReadIFAgc(struct drxd_state *state, u32 * pValue)
{
int status = 0;
*pValue = 0;
if (state->if_agc_cfg.ctrlMode != AGC_CTRL_OFF) {
u16 Value;
status = Read16(state, FE_AG_REG_GC1_AGC_DAT__A, &Value, 0);
Value &= FE_AG_REG_GC1_AGC_DAT__M;
if (status >= 0) {
/* 3.3V
|
R1
|
Vin - R3 - * -- Vout
|
R2
|
GND
*/
u32 R1 = state->if_agc_cfg.R1;
u32 R2 = state->if_agc_cfg.R2;
u32 R3 = state->if_agc_cfg.R3;
u32 Vmax, Rpar, Vmin, Vout;
if (R2 == 0 && (R1 == 0 || R3 == 0))
return 0;
Vmax = (3300 * R2) / (R1 + R2);
Rpar = (R2 * R3) / (R3 + R2);
Vmin = (3300 * Rpar) / (R1 + Rpar);
Vout = Vmin + ((Vmax - Vmin) * Value) / 1024;
*pValue = Vout;
}
}
return status;
}
static int load_firmware(struct drxd_state *state, const char *fw_name)
{
const struct firmware *fw;
if (request_firmware(&fw, fw_name, state->dev) < 0) {
printk(KERN_ERR "drxd: firmware load failure [%s]\n", fw_name);
return -EIO;
}
state->microcode = kmemdup(fw->data, fw->size, GFP_KERNEL);
if (state->microcode == NULL) {
release_firmware(fw);
printk(KERN_ERR "drxd: firmware load failure: no memory\n");
return -ENOMEM;
}
state->microcode_length = fw->size;
release_firmware(fw);
return 0;
}
static int DownloadMicrocode(struct drxd_state *state,
const u8 *pMCImage, u32 Length)
{
u8 *pSrc;
u32 Address;
u16 nBlocks;
u16 BlockSize;
u32 offset = 0;
int i, status = 0;
pSrc = (u8 *) pMCImage;
/* We're not using Flags */
/* Flags = (pSrc[0] << 8) | pSrc[1]; */
pSrc += sizeof(u16);
offset += sizeof(u16);
nBlocks = (pSrc[0] << 8) | pSrc[1];
pSrc += sizeof(u16);
offset += sizeof(u16);
for (i = 0; i < nBlocks; i++) {
Address = (pSrc[0] << 24) | (pSrc[1] << 16) |
(pSrc[2] << 8) | pSrc[3];
pSrc += sizeof(u32);
offset += sizeof(u32);
BlockSize = ((pSrc[0] << 8) | pSrc[1]) * sizeof(u16);
pSrc += sizeof(u16);
offset += sizeof(u16);
/* We're not using Flags */
/* u16 Flags = (pSrc[0] << 8) | pSrc[1]; */
pSrc += sizeof(u16);
offset += sizeof(u16);
/* We're not using BlockCRC */
/* u16 BlockCRC = (pSrc[0] << 8) | pSrc[1]; */
pSrc += sizeof(u16);
offset += sizeof(u16);
status = WriteBlock(state, Address, BlockSize,
pSrc, DRX_I2C_CLEARCRC);
if (status < 0)
break;
pSrc += BlockSize;
offset += BlockSize;
}
return status;
}
static int HI_Command(struct drxd_state *state, u16 cmd, u16 * pResult)
{
u32 nrRetries = 0;
u16 waitCmd;
int status;
status = Write16(state, HI_RA_RAM_SRV_CMD__A, cmd, 0);
if (status < 0)
return status;
do {
nrRetries += 1;
if (nrRetries > DRXD_MAX_RETRIES) {
status = -1;
break;
};
status = Read16(state, HI_RA_RAM_SRV_CMD__A, &waitCmd, 0);
} while (waitCmd != 0);
if (status >= 0)
status = Read16(state, HI_RA_RAM_SRV_RES__A, pResult, 0);
return status;
}
static int HI_CfgCommand(struct drxd_state *state)
{
int status = 0;
mutex_lock(&state->mutex);
Write16(state, HI_RA_RAM_SRV_CFG_KEY__A, HI_RA_RAM_SRV_RST_KEY_ACT, 0);
Write16(state, HI_RA_RAM_SRV_CFG_DIV__A, state->hi_cfg_timing_div, 0);
Write16(state, HI_RA_RAM_SRV_CFG_BDL__A, state->hi_cfg_bridge_delay, 0);
Write16(state, HI_RA_RAM_SRV_CFG_WUP__A, state->hi_cfg_wakeup_key, 0);
Write16(state, HI_RA_RAM_SRV_CFG_ACT__A, state->hi_cfg_ctrl, 0);
Write16(state, HI_RA_RAM_SRV_CFG_KEY__A, HI_RA_RAM_SRV_RST_KEY_ACT, 0);
if ((state->hi_cfg_ctrl & HI_RA_RAM_SRV_CFG_ACT_PWD_EXE) ==
HI_RA_RAM_SRV_CFG_ACT_PWD_EXE)
status = Write16(state, HI_RA_RAM_SRV_CMD__A,
HI_RA_RAM_SRV_CMD_CONFIG, 0);
else
status = HI_Command(state, HI_RA_RAM_SRV_CMD_CONFIG, 0);
mutex_unlock(&state->mutex);
return status;
}
static int InitHI(struct drxd_state *state)
{
state->hi_cfg_wakeup_key = (state->chip_adr);
/* port/bridge/power down ctrl */
state->hi_cfg_ctrl = HI_RA_RAM_SRV_CFG_ACT_SLV0_ON;
return HI_CfgCommand(state);
}
static int HI_ResetCommand(struct drxd_state *state)
{
int status;
mutex_lock(&state->mutex);
status = Write16(state, HI_RA_RAM_SRV_RST_KEY__A,
HI_RA_RAM_SRV_RST_KEY_ACT, 0);
if (status == 0)
status = HI_Command(state, HI_RA_RAM_SRV_CMD_RESET, 0);
mutex_unlock(&state->mutex);
msleep(1);
return status;
}
static int DRX_ConfigureI2CBridge(struct drxd_state *state, int bEnableBridge)
{
state->hi_cfg_ctrl &= (~HI_RA_RAM_SRV_CFG_ACT_BRD__M);
if (bEnableBridge)
state->hi_cfg_ctrl |= HI_RA_RAM_SRV_CFG_ACT_BRD_ON;
else
state->hi_cfg_ctrl |= HI_RA_RAM_SRV_CFG_ACT_BRD_OFF;
return HI_CfgCommand(state);
}
#define HI_TR_WRITE 0x9
#define HI_TR_READ 0xA
#define HI_TR_READ_WRITE 0xB
#define HI_TR_BROADCAST 0x4
#if 0
static int AtomicReadBlock(struct drxd_state *state,
u32 Addr, u16 DataSize, u8 *pData, u8 Flags)
{
int status;
int i = 0;
/* Parameter check */
if ((!pData) || ((DataSize & 1) != 0))
return -1;
mutex_lock(&state->mutex);
do {
/* Instruct HI to read n bytes */
/* TODO use proper names forthese egisters */
status = Write16(state, HI_RA_RAM_SRV_CFG_KEY__A, (HI_TR_FUNC_ADDR & 0xFFFF), 0);
if (status < 0)
break;
status = Write16(state, HI_RA_RAM_SRV_CFG_DIV__A, (u16) (Addr >> 16), 0);
if (status < 0)
break;
status = Write16(state, HI_RA_RAM_SRV_CFG_BDL__A, (u16) (Addr & 0xFFFF), 0);
if (status < 0)
break;
status = Write16(state, HI_RA_RAM_SRV_CFG_WUP__A, (u16) ((DataSize / 2) - 1), 0);
if (status < 0)
break;
status = Write16(state, HI_RA_RAM_SRV_CFG_ACT__A, HI_TR_READ, 0);
if (status < 0)
break;
status = HI_Command(state, HI_RA_RAM_SRV_CMD_EXECUTE, 0);
if (status < 0)
break;
} while (0);
if (status >= 0) {
for (i = 0; i < (DataSize / 2); i += 1) {
u16 word;
status = Read16(state, (HI_RA_RAM_USR_BEGIN__A + i),
&word, 0);
if (status < 0)
break;
pData[2 * i] = (u8) (word & 0xFF);
pData[(2 * i) + 1] = (u8) (word >> 8);
}
}
mutex_unlock(&state->mutex);
return status;
}
static int AtomicReadReg32(struct drxd_state *state,
u32 Addr, u32 *pData, u8 Flags)
{
u8 buf[sizeof(u32)];
int status;
if (!pData)
return -1;
status = AtomicReadBlock(state, Addr, sizeof(u32), buf, Flags);
*pData = (((u32) buf[0]) << 0) +
(((u32) buf[1]) << 8) +
(((u32) buf[2]) << 16) + (((u32) buf[3]) << 24);
return status;
}
#endif
static int StopAllProcessors(struct drxd_state *state)
{
return Write16(state, HI_COMM_EXEC__A,
SC_COMM_EXEC_CTL_STOP, DRX_I2C_BROADCAST);
}
static int EnableAndResetMB(struct drxd_state *state)
{
if (state->type_A) {
/* disable? monitor bus observe @ EC_OC */
Write16(state, EC_OC_REG_OC_MON_SIO__A, 0x0000, 0x0000);
}
/* do inverse broadcast, followed by explicit write to HI */
Write16(state, HI_COMM_MB__A, 0x0000, DRX_I2C_BROADCAST);
Write16(state, HI_COMM_MB__A, 0x0000, 0x0000);
return 0;
}
static int InitCC(struct drxd_state *state)
{
if (state->osc_clock_freq == 0 ||
state->osc_clock_freq > 20000 ||
(state->osc_clock_freq % 4000) != 0) {
printk(KERN_ERR "invalid osc frequency %d\n", state->osc_clock_freq);
return -1;
}
Write16(state, CC_REG_OSC_MODE__A, CC_REG_OSC_MODE_M20, 0);
Write16(state, CC_REG_PLL_MODE__A, CC_REG_PLL_MODE_BYPASS_PLL |
CC_REG_PLL_MODE_PUMP_CUR_12, 0);
Write16(state, CC_REG_REF_DIVIDE__A, state->osc_clock_freq / 4000, 0);
Write16(state, CC_REG_PWD_MODE__A, CC_REG_PWD_MODE_DOWN_PLL, 0);
Write16(state, CC_REG_UPDATE__A, CC_REG_UPDATE_KEY, 0);
return 0;
}
static int ResetECOD(struct drxd_state *state)
{
int status = 0;
if (state->type_A)
status = Write16(state, EC_OD_REG_SYNC__A, 0x0664, 0);
else
status = Write16(state, B_EC_OD_REG_SYNC__A, 0x0664, 0);
if (!(status < 0))
status = WriteTable(state, state->m_ResetECRAM);
if (!(status < 0))
status = Write16(state, EC_OD_REG_COMM_EXEC__A, 0x0001, 0);
return status;
}
/* Configure PGA switch */
static int SetCfgPga(struct drxd_state *state, int pgaSwitch)
{
int status;
u16 AgModeLop = 0;
u16 AgModeHip = 0;
do {
if (pgaSwitch) {
/* PGA on */
/* fine gain */
status = Read16(state, B_FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000);
if (status < 0)
break;
AgModeLop &= (~(B_FE_AG_REG_AG_MODE_LOP_MODE_C__M));
AgModeLop |= B_FE_AG_REG_AG_MODE_LOP_MODE_C_DYNAMIC;
status = Write16(state, B_FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000);
if (status < 0)
break;
/* coarse gain */
status = Read16(state, B_FE_AG_REG_AG_MODE_HIP__A, &AgModeHip, 0x0000);
if (status < 0)
break;
AgModeHip &= (~(B_FE_AG_REG_AG_MODE_HIP_MODE_J__M));
AgModeHip |= B_FE_AG_REG_AG_MODE_HIP_MODE_J_DYNAMIC;
status = Write16(state, B_FE_AG_REG_AG_MODE_HIP__A, AgModeHip, 0x0000);
if (status < 0)
break;
/* enable fine and coarse gain, enable AAF,
no ext resistor */
status = Write16(state, B_FE_AG_REG_AG_PGA_MODE__A, B_FE_AG_REG_AG_PGA_MODE_PFY_PCY_AFY_REN, 0x0000);
if (status < 0)
break;
} else {
/* PGA off, bypass */
/* fine gain */
status = Read16(state, B_FE_AG_REG_AG_MODE_LOP__A, &AgModeLop, 0x0000);
if (status < 0)
break;
AgModeLop &= (~(B_FE_AG_REG_AG_MODE_LOP_MODE_C__M));
AgModeLop |= B_FE_AG_REG_AG_MODE_LOP_MODE_C_STATIC;
status = Write16(state, B_FE_AG_REG_AG_MODE_LOP__A, AgModeLop, 0x0000);
if (status < 0)
break;
/* coarse gain */
status = Read16(state, B_FE_AG_REG_AG_MODE_HIP__A, &AgModeHip, 0x0000);
if (status < 0)
break;
AgModeHip &= (~(B_FE_AG_REG_AG_MODE_HIP_MODE_J__M));
AgModeHip |= B_FE_AG_REG_AG_MODE_HIP_MODE_J_STATIC;
status = Write16(state, B_FE_AG_REG_AG_MODE_HIP__A, AgModeHip, 0x0000);
if (status < 0)
break;
/* disable fine and coarse gain, enable AAF,
no ext resistor */
status = Write16(state, B_FE_AG_REG_AG_PGA_MODE__A, B_FE_AG_REG_AG_PGA_MODE_PFN_PCN_AFY_REN, 0x0000);
if (status < 0)
break;
}
} while (0);
return status;
}
static int InitFE(struct drxd_state *state)
{
int status;
do {
status = WriteTable(state, state->m_InitFE_1);
if (status < 0)
break;
if (state->type_A) {
status = Write16(state, FE_AG_REG_AG_PGA_MODE__A,
FE_AG_REG_AG_PGA_MODE_PFN_PCN_AFY_REN,
0);
} else {
if (state->PGA)
status = SetCfgPga(state, 0);
else
status =
Write16(state, B_FE_AG_REG_AG_PGA_MODE__A,
B_FE_AG_REG_AG_PGA_MODE_PFN_PCN_AFY_REN,
0);
}
if (status < 0)
break;
status = Write16(state, FE_AG_REG_AG_AGC_SIO__A, state->m_FeAgRegAgAgcSio, 0x0000);
if (status < 0)
break;
status = Write16(state, FE_AG_REG_AG_PWD__A, state->m_FeAgRegAgPwd, 0x0000);
if (status < 0)
break;
status = WriteTable(state, state->m_InitFE_2);
if (status < 0)
break;
} while (0);
return status;
}
static int InitFT(struct drxd_state *state)
{
/*
norm OFFSET, MB says =2 voor 8K en =3 voor 2K waarschijnlijk
SC stuff
*/
return Write16(state, FT_REG_COMM_EXEC__A, 0x0001, 0x0000);
}
static int SC_WaitForReady(struct drxd_state *state)
{
u16 curCmd;
int i;
for (i = 0; i < DRXD_MAX_RETRIES; i += 1) {
int status = Read16(state, SC_RA_RAM_CMD__A, &curCmd, 0);
if (status == 0 || curCmd == 0)
return status;
}
return -1;
}
static int SC_SendCommand(struct drxd_state *state, u16 cmd)
{
int status = 0;
u16 errCode;
Write16(state, SC_RA_RAM_CMD__A, cmd, 0);
SC_WaitForReady(state);
Read16(state, SC_RA_RAM_CMD_ADDR__A, &errCode, 0);
if (errCode == 0xFFFF) {
printk(KERN_ERR "Command Error\n");
status = -1;
}
return status;
}
static int SC_ProcStartCommand(struct drxd_state *state,
u16 subCmd, u16 param0, u16 param1)
{
int status = 0;
u16 scExec;
mutex_lock(&state->mutex);
do {
Read16(state, SC_COMM_EXEC__A, &scExec, 0);
if (scExec != 1) {
status = -1;
break;
}
SC_WaitForReady(state);
Write16(state, SC_RA_RAM_CMD_ADDR__A, subCmd, 0);
Write16(state, SC_RA_RAM_PARAM1__A, param1, 0);
Write16(state, SC_RA_RAM_PARAM0__A, param0, 0);
SC_SendCommand(state, SC_RA_RAM_CMD_PROC_START);
} while (0);
mutex_unlock(&state->mutex);
return status;
}
static int SC_SetPrefParamCommand(struct drxd_state *state,
u16 subCmd, u16 param0, u16 param1)
{
int status;
mutex_lock(&state->mutex);
do {
status = SC_WaitForReady(state);
if (status < 0)
break;
status = Write16(state, SC_RA_RAM_CMD_ADDR__A, subCmd, 0);
if (status < 0)
break;
status = Write16(state, SC_RA_RAM_PARAM1__A, param1, 0);
if (status < 0)
break;
status = Write16(state, SC_RA_RAM_PARAM0__A, param0, 0);
if (status < 0)
break;
status = SC_SendCommand(state, SC_RA_RAM_CMD_SET_PREF_PARAM);
if (status < 0)
break;
} while (0);
mutex_unlock(&state->mutex);
return status;
}
#if 0
static int SC_GetOpParamCommand(struct drxd_state *state, u16 * result)
{
int status = 0;
mutex_lock(&state->mutex);
do {
status = SC_WaitForReady(state);
if (status < 0)
break;
status = SC_SendCommand(state, SC_RA_RAM_CMD_GET_OP_PARAM);
if (status < 0)
break;
status = Read16(state, SC_RA_RAM_PARAM0__A, result, 0);
if (status < 0)
break;
} while (0);
mutex_unlock(&state->mutex);
return status;
}
#endif
static int ConfigureMPEGOutput(struct drxd_state *state, int bEnableOutput)
{
int status;
do {
u16 EcOcRegIprInvMpg = 0;
u16 EcOcRegOcModeLop = 0;
u16 EcOcRegOcModeHip = 0;
u16 EcOcRegOcMpgSio = 0;
/*CHK_ERROR(Read16(state, EC_OC_REG_OC_MODE_LOP__A, &EcOcRegOcModeLop, 0)); */
if (state->operation_mode == OM_DVBT_Diversity_Front) {
if (bEnableOutput) {
EcOcRegOcModeHip |=
B_EC_OC_REG_OC_MODE_HIP_MPG_BUS_SRC_MONITOR;
} else
EcOcRegOcMpgSio |= EC_OC_REG_OC_MPG_SIO__M;
EcOcRegOcModeLop |=
EC_OC_REG_OC_MODE_LOP_PAR_ENA_DISABLE;
} else {
EcOcRegOcModeLop = state->m_EcOcRegOcModeLop;
if (bEnableOutput)
EcOcRegOcMpgSio &= (~(EC_OC_REG_OC_MPG_SIO__M));
else
EcOcRegOcMpgSio |= EC_OC_REG_OC_MPG_SIO__M;
/* Don't Insert RS Byte */
if (state->insert_rs_byte) {
EcOcRegOcModeLop &=
(~(EC_OC_REG_OC_MODE_LOP_PAR_ENA__M));
EcOcRegOcModeHip &=
(~EC_OC_REG_OC_MODE_HIP_MPG_PAR_VAL__M);
EcOcRegOcModeHip |=
EC_OC_REG_OC_MODE_HIP_MPG_PAR_VAL_ENABLE;
} else {
EcOcRegOcModeLop |=
EC_OC_REG_OC_MODE_LOP_PAR_ENA_DISABLE;
EcOcRegOcModeHip &=
(~EC_OC_REG_OC_MODE_HIP_MPG_PAR_VAL__M);
EcOcRegOcModeHip |=
EC_OC_REG_OC_MODE_HIP_MPG_PAR_VAL_DISABLE;
}
/* Mode = Parallel */
if (state->enable_parallel)
EcOcRegOcModeLop &=
(~(EC_OC_REG_OC_MODE_LOP_MPG_TRM_MDE__M));
else
EcOcRegOcModeLop |=
EC_OC_REG_OC_MODE_LOP_MPG_TRM_MDE_SERIAL;
}
/* Invert Data */
/* EcOcRegIprInvMpg |= 0x00FF; */
EcOcRegIprInvMpg &= (~(0x00FF));
/* Invert Error ( we don't use the pin ) */
/* EcOcRegIprInvMpg |= 0x0100; */
EcOcRegIprInvMpg &= (~(0x0100));
/* Invert Start ( we don't use the pin ) */
/* EcOcRegIprInvMpg |= 0x0200; */
EcOcRegIprInvMpg &= (~(0x0200));
/* Invert Valid ( we don't use the pin ) */
/* EcOcRegIprInvMpg |= 0x0400; */
EcOcRegIprInvMpg &= (~(0x0400));
/* Invert Clock */
/* EcOcRegIprInvMpg |= 0x0800; */
EcOcRegIprInvMpg &= (~(0x0800));
/* EcOcRegOcModeLop =0x05; */
status = Write16(state, EC_OC_REG_IPR_INV_MPG__A, EcOcRegIprInvMpg, 0);
if (status < 0)
break;
status = Write16(state, EC_OC_REG_OC_MODE_LOP__A, EcOcRegOcModeLop, 0);
if (status < 0)
break;
status = Write16(state, EC_OC_REG_OC_MODE_HIP__A, EcOcRegOcModeHip, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_OC_REG_OC_MPG_SIO__A, EcOcRegOcMpgSio, 0);
if (status < 0)
break;
} while (0);
return status;
}
static int SetDeviceTypeId(struct drxd_state *state)
{
int status = 0;
u16 deviceId = 0;
do {
status = Read16(state, CC_REG_JTAGID_L__A, &deviceId, 0);
if (status < 0)
break;
/* TODO: why twice? */
status = Read16(state, CC_REG_JTAGID_L__A, &deviceId, 0);
if (status < 0)
break;
printk(KERN_INFO "drxd: deviceId = %04x\n", deviceId);
state->type_A = 0;
state->PGA = 0;
state->diversity = 0;
if (deviceId == 0) { /* on A2 only 3975 available */
state->type_A = 1;
printk(KERN_INFO "DRX3975D-A2\n");
} else {
deviceId >>= 12;
printk(KERN_INFO "DRX397%dD-B1\n", deviceId);
switch (deviceId) {
case 4:
state->diversity = 1;
case 3:
case 7:
state->PGA = 1;
break;
case 6:
state->diversity = 1;
case 5:
case 8:
break;
default:
status = -1;
break;
}
}
} while (0);
if (status < 0)
return status;
/* Init Table selection */
state->m_InitAtomicRead = DRXD_InitAtomicRead;
state->m_InitSC = DRXD_InitSC;
state->m_ResetECRAM = DRXD_ResetECRAM;
if (state->type_A) {
state->m_ResetCEFR = DRXD_ResetCEFR;
state->m_InitFE_1 = DRXD_InitFEA2_1;
state->m_InitFE_2 = DRXD_InitFEA2_2;
state->m_InitCP = DRXD_InitCPA2;
state->m_InitCE = DRXD_InitCEA2;
state->m_InitEQ = DRXD_InitEQA2;
state->m_InitEC = DRXD_InitECA2;
if (load_firmware(state, DRX_FW_FILENAME_A2))
return -EIO;
} else {
state->m_ResetCEFR = NULL;
state->m_InitFE_1 = DRXD_InitFEB1_1;
state->m_InitFE_2 = DRXD_InitFEB1_2;
state->m_InitCP = DRXD_InitCPB1;
state->m_InitCE = DRXD_InitCEB1;
state->m_InitEQ = DRXD_InitEQB1;
state->m_InitEC = DRXD_InitECB1;
if (load_firmware(state, DRX_FW_FILENAME_B1))
return -EIO;
}
if (state->diversity) {
state->m_InitDiversityFront = DRXD_InitDiversityFront;
state->m_InitDiversityEnd = DRXD_InitDiversityEnd;
state->m_DisableDiversity = DRXD_DisableDiversity;
state->m_StartDiversityFront = DRXD_StartDiversityFront;
state->m_StartDiversityEnd = DRXD_StartDiversityEnd;
state->m_DiversityDelay8MHZ = DRXD_DiversityDelay8MHZ;
state->m_DiversityDelay6MHZ = DRXD_DiversityDelay6MHZ;
} else {
state->m_InitDiversityFront = NULL;
state->m_InitDiversityEnd = NULL;
state->m_DisableDiversity = NULL;
state->m_StartDiversityFront = NULL;
state->m_StartDiversityEnd = NULL;
state->m_DiversityDelay8MHZ = NULL;
state->m_DiversityDelay6MHZ = NULL;
}
return status;
}
static int CorrectSysClockDeviation(struct drxd_state *state)
{
int status;
s32 incr = 0;
s32 nomincr = 0;
u32 bandwidth = 0;
u32 sysClockInHz = 0;
u32 sysClockFreq = 0; /* in kHz */
s16 oscClockDeviation;
s16 Diff;
do {
/* Retrieve bandwidth and incr, sanity check */
/* These accesses should be AtomicReadReg32, but that
causes trouble (at least for diversity */
status = Read32(state, LC_RA_RAM_IFINCR_NOM_L__A, ((u32 *) &nomincr), 0);
if (status < 0)
break;
status = Read32(state, FE_IF_REG_INCR0__A, (u32 *) &incr, 0);
if (status < 0)
break;
if (state->type_A) {
if ((nomincr - incr < -500) || (nomincr - incr > 500))
break;
} else {
if ((nomincr - incr < -2000) || (nomincr - incr > 2000))
break;
}
switch (state->props.bandwidth_hz) {
case 8000000:
bandwidth = DRXD_BANDWIDTH_8MHZ_IN_HZ;
break;
case 7000000:
bandwidth = DRXD_BANDWIDTH_7MHZ_IN_HZ;
break;
case 6000000:
bandwidth = DRXD_BANDWIDTH_6MHZ_IN_HZ;
break;
default:
return -1;
break;
}
/* Compute new sysclock value
sysClockFreq = (((incr + 2^23)*bandwidth)/2^21)/1000 */
incr += (1 << 23);
sysClockInHz = MulDiv32(incr, bandwidth, 1 << 21);
sysClockFreq = (u32) (sysClockInHz / 1000);
/* rounding */
if ((sysClockInHz % 1000) > 500)
sysClockFreq++;
/* Compute clock deviation in ppm */
oscClockDeviation = (u16) ((((s32) (sysClockFreq) -
(s32)
(state->expected_sys_clock_freq)) *
1000000L) /
(s32)
(state->expected_sys_clock_freq));
Diff = oscClockDeviation - state->osc_clock_deviation;
/*printk(KERN_INFO "sysclockdiff=%d\n", Diff); */
if (Diff >= -200 && Diff <= 200) {
state->sys_clock_freq = (u16) sysClockFreq;
if (oscClockDeviation != state->osc_clock_deviation) {
if (state->config.osc_deviation) {
state->config.osc_deviation(state->priv,
oscClockDeviation,
1);
state->osc_clock_deviation =
oscClockDeviation;
}
}
/* switch OFF SRMM scan in SC */
status = Write16(state, SC_RA_RAM_SAMPLE_RATE_COUNT__A, DRXD_OSCDEV_DONT_SCAN, 0);
if (status < 0)
break;
/* overrule FE_IF internal value for
proper re-locking */
status = Write16(state, SC_RA_RAM_IF_SAVE__AX, state->current_fe_if_incr, 0);
if (status < 0)
break;
state->cscd_state = CSCD_SAVED;
}
} while (0);
return status;
}
static int DRX_Stop(struct drxd_state *state)
{
int status;
if (state->drxd_state != DRXD_STARTED)
return 0;
do {
if (state->cscd_state != CSCD_SAVED) {
u32 lock;
status = DRX_GetLockStatus(state, &lock);
if (status < 0)
break;
}
status = StopOC(state);
if (status < 0)
break;
state->drxd_state = DRXD_STOPPED;
status = ConfigureMPEGOutput(state, 0);
if (status < 0)
break;
if (state->type_A) {
/* Stop relevant processors off the device */
status = Write16(state, EC_OD_REG_COMM_EXEC__A, 0x0000, 0x0000);
if (status < 0)
break;
status = Write16(state, SC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
status = Write16(state, LC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
} else {
/* Stop all processors except HI & CC & FE */
status = Write16(state, B_SC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
status = Write16(state, B_LC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
status = Write16(state, B_FT_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
status = Write16(state, B_CP_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
status = Write16(state, B_CE_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
status = Write16(state, B_EQ_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
status = Write16(state, EC_OD_REG_COMM_EXEC__A, 0x0000, 0);
if (status < 0)
break;
}
} while (0);
return status;
}
int SetOperationMode(struct drxd_state *state, int oMode)
{
int status;
do {
if (state->drxd_state != DRXD_STOPPED) {
status = -1;
break;
}
if (oMode == state->operation_mode) {
status = 0;
break;
}
if (oMode != OM_Default && !state->diversity) {
status = -1;
break;
}
switch (oMode) {
case OM_DVBT_Diversity_Front:
status = WriteTable(state, state->m_InitDiversityFront);
break;
case OM_DVBT_Diversity_End:
status = WriteTable(state, state->m_InitDiversityEnd);
break;
case OM_Default:
/* We need to check how to
get DRXD out of diversity */
default:
status = WriteTable(state, state->m_DisableDiversity);
break;
}
} while (0);
if (!status)
state->operation_mode = oMode;
return status;
}
static int StartDiversity(struct drxd_state *state)
{
int status = 0;
u16 rcControl;
do {
if (state->operation_mode == OM_DVBT_Diversity_Front) {
status = WriteTable(state, state->m_StartDiversityFront);
if (status < 0)
break;
} else if (state->operation_mode == OM_DVBT_Diversity_End) {
status = WriteTable(state, state->m_StartDiversityEnd);
if (status < 0)
break;
if (state->props.bandwidth_hz == 8000000) {
status = WriteTable(state, state->m_DiversityDelay8MHZ);
if (status < 0)
break;
} else {
status = WriteTable(state, state->m_DiversityDelay6MHZ);
if (status < 0)
break;
}
status = Read16(state, B_EQ_REG_RC_SEL_CAR__A, &rcControl, 0);
if (status < 0)
break;
rcControl &= ~(B_EQ_REG_RC_SEL_CAR_FFTMODE__M);
rcControl |= B_EQ_REG_RC_SEL_CAR_DIV_ON |
/* combining enabled */
B_EQ_REG_RC_SEL_CAR_MEAS_A_CC |
B_EQ_REG_RC_SEL_CAR_PASS_A_CC |
B_EQ_REG_RC_SEL_CAR_LOCAL_A_CC;
status = Write16(state, B_EQ_REG_RC_SEL_CAR__A, rcControl, 0);
if (status < 0)
break;
}
} while (0);
return status;
}
static int SetFrequencyShift(struct drxd_state *state,
u32 offsetFreq, int channelMirrored)
{
int negativeShift = (state->tuner_mirrors == channelMirrored);
/* Handle all mirroring
*
* Note: ADC mirroring (aliasing) is implictly handled by limiting
* feFsRegAddInc to 28 bits below
* (if the result before masking is more than 28 bits, this means
* that the ADC is mirroring.
* The masking is in fact the aliasing of the ADC)
*
*/
/* Compute register value, unsigned computation */
state->fe_fs_add_incr = MulDiv32(state->intermediate_freq +
offsetFreq,
1 << 28, state->sys_clock_freq);
/* Remove integer part */
state->fe_fs_add_incr &= 0x0FFFFFFFL;
if (negativeShift)
state->fe_fs_add_incr = ((1 << 28) - state->fe_fs_add_incr);
/* Save the frequency shift without tunerOffset compensation
for CtrlGetChannel. */
state->org_fe_fs_add_incr = MulDiv32(state->intermediate_freq,
1 << 28, state->sys_clock_freq);
/* Remove integer part */
state->org_fe_fs_add_incr &= 0x0FFFFFFFL;
if (negativeShift)
state->org_fe_fs_add_incr = ((1L << 28) -
state->org_fe_fs_add_incr);
return Write32(state, FE_FS_REG_ADD_INC_LOP__A,
state->fe_fs_add_incr, 0);
}
static int SetCfgNoiseCalibration(struct drxd_state *state,
struct SNoiseCal *noiseCal)
{
u16 beOptEna;
int status = 0;
do {
status = Read16(state, SC_RA_RAM_BE_OPT_ENA__A, &beOptEna, 0);
if (status < 0)
break;
if (noiseCal->cpOpt) {
beOptEna |= (1 << SC_RA_RAM_BE_OPT_ENA_CP_OPT);
} else {
beOptEna &= ~(1 << SC_RA_RAM_BE_OPT_ENA_CP_OPT);
status = Write16(state, CP_REG_AC_NEXP_OFFS__A, noiseCal->cpNexpOfs, 0);
if (status < 0)
break;
}
status = Write16(state, SC_RA_RAM_BE_OPT_ENA__A, beOptEna, 0);
if (status < 0)
break;
if (!state->type_A) {
status = Write16(state, B_SC_RA_RAM_CO_TD_CAL_2K__A, noiseCal->tdCal2k, 0);
if (status < 0)
break;
status = Write16(state, B_SC_RA_RAM_CO_TD_CAL_8K__A, noiseCal->tdCal8k, 0);
if (status < 0)
break;
}
} while (0);
return status;
}
static int DRX_Start(struct drxd_state *state, s32 off)
{
struct dtv_frontend_properties *p = &state->props;
int status;
u16 transmissionParams = 0;
u16 operationMode = 0;
u16 qpskTdTpsPwr = 0;
u16 qam16TdTpsPwr = 0;
u16 qam64TdTpsPwr = 0;
u32 feIfIncr = 0;
u32 bandwidth = 0;
int mirrorFreqSpect;
u16 qpskSnCeGain = 0;
u16 qam16SnCeGain = 0;
u16 qam64SnCeGain = 0;
u16 qpskIsGainMan = 0;
u16 qam16IsGainMan = 0;
u16 qam64IsGainMan = 0;
u16 qpskIsGainExp = 0;
u16 qam16IsGainExp = 0;
u16 qam64IsGainExp = 0;
u16 bandwidthParam = 0;
if (off < 0)
off = (off - 500) / 1000;
else
off = (off + 500) / 1000;
do {
if (state->drxd_state != DRXD_STOPPED)
return -1;
status = ResetECOD(state);
if (status < 0)
break;
if (state->type_A) {
status = InitSC(state);
if (status < 0)
break;
} else {
status = InitFT(state);
if (status < 0)
break;
status = InitCP(state);
if (status < 0)
break;
status = InitCE(state);
if (status < 0)
break;
status = InitEQ(state);
if (status < 0)
break;
status = InitSC(state);
if (status < 0)
break;
}
/* Restore current IF & RF AGC settings */
status = SetCfgIfAgc(state, &state->if_agc_cfg);
if (status < 0)
break;
status = SetCfgRfAgc(state, &state->rf_agc_cfg);
if (status < 0)
break;
mirrorFreqSpect = (state->props.inversion == INVERSION_ON);
switch (p->transmission_mode) {
default: /* Not set, detect it automatically */
operationMode |= SC_RA_RAM_OP_AUTO_MODE__M;
/* fall through , try first guess DRX_FFTMODE_8K */
case TRANSMISSION_MODE_8K:
transmissionParams |= SC_RA_RAM_OP_PARAM_MODE_8K;
if (state->type_A) {
status = Write16(state, EC_SB_REG_TR_MODE__A, EC_SB_REG_TR_MODE_8K, 0x0000);
if (status < 0)
break;
qpskSnCeGain = 99;
qam16SnCeGain = 83;
qam64SnCeGain = 67;
}
break;
case TRANSMISSION_MODE_2K:
transmissionParams |= SC_RA_RAM_OP_PARAM_MODE_2K;
if (state->type_A) {
status = Write16(state, EC_SB_REG_TR_MODE__A, EC_SB_REG_TR_MODE_2K, 0x0000);
if (status < 0)
break;
qpskSnCeGain = 97;
qam16SnCeGain = 71;
qam64SnCeGain = 65;
}
break;
}
switch (p->guard_interval) {
case GUARD_INTERVAL_1_4:
transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_4;
break;
case GUARD_INTERVAL_1_8:
transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_8;
break;
case GUARD_INTERVAL_1_16:
transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_16;
break;
case GUARD_INTERVAL_1_32:
transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_32;
break;
default: /* Not set, detect it automatically */
operationMode |= SC_RA_RAM_OP_AUTO_GUARD__M;
/* try first guess 1/4 */
transmissionParams |= SC_RA_RAM_OP_PARAM_GUARD_4;
break;
}
switch (p->hierarchy) {
case HIERARCHY_1:
transmissionParams |= SC_RA_RAM_OP_PARAM_HIER_A1;
if (state->type_A) {
status = Write16(state, EQ_REG_OT_ALPHA__A, 0x0001, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_ALPHA__A, 0x0001, 0x0000);
if (status < 0)
break;
qpskTdTpsPwr = EQ_TD_TPS_PWR_UNKNOWN;
qam16TdTpsPwr = EQ_TD_TPS_PWR_QAM16_ALPHA1;
qam64TdTpsPwr = EQ_TD_TPS_PWR_QAM64_ALPHA1;
qpskIsGainMan =
SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_MAN__PRE;
qam16IsGainMan =
SC_RA_RAM_EQ_IS_GAIN_16QAM_MAN__PRE;
qam64IsGainMan =
SC_RA_RAM_EQ_IS_GAIN_64QAM_MAN__PRE;
qpskIsGainExp =
SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_EXP__PRE;
qam16IsGainExp =
SC_RA_RAM_EQ_IS_GAIN_16QAM_EXP__PRE;
qam64IsGainExp =
SC_RA_RAM_EQ_IS_GAIN_64QAM_EXP__PRE;
}
break;
case HIERARCHY_2:
transmissionParams |= SC_RA_RAM_OP_PARAM_HIER_A2;
if (state->type_A) {
status = Write16(state, EQ_REG_OT_ALPHA__A, 0x0002, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_ALPHA__A, 0x0002, 0x0000);
if (status < 0)
break;
qpskTdTpsPwr = EQ_TD_TPS_PWR_UNKNOWN;
qam16TdTpsPwr = EQ_TD_TPS_PWR_QAM16_ALPHA2;
qam64TdTpsPwr = EQ_TD_TPS_PWR_QAM64_ALPHA2;
qpskIsGainMan =
SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_MAN__PRE;
qam16IsGainMan =
SC_RA_RAM_EQ_IS_GAIN_16QAM_A2_MAN__PRE;
qam64IsGainMan =
SC_RA_RAM_EQ_IS_GAIN_64QAM_A2_MAN__PRE;
qpskIsGainExp =
SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_EXP__PRE;
qam16IsGainExp =
SC_RA_RAM_EQ_IS_GAIN_16QAM_A2_EXP__PRE;
qam64IsGainExp =
SC_RA_RAM_EQ_IS_GAIN_64QAM_A2_EXP__PRE;
}
break;
case HIERARCHY_4:
transmissionParams |= SC_RA_RAM_OP_PARAM_HIER_A4;
if (state->type_A) {
status = Write16(state, EQ_REG_OT_ALPHA__A, 0x0003, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_ALPHA__A, 0x0003, 0x0000);
if (status < 0)
break;
qpskTdTpsPwr = EQ_TD_TPS_PWR_UNKNOWN;
qam16TdTpsPwr = EQ_TD_TPS_PWR_QAM16_ALPHA4;
qam64TdTpsPwr = EQ_TD_TPS_PWR_QAM64_ALPHA4;
qpskIsGainMan =
SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_MAN__PRE;
qam16IsGainMan =
SC_RA_RAM_EQ_IS_GAIN_16QAM_A4_MAN__PRE;
qam64IsGainMan =
SC_RA_RAM_EQ_IS_GAIN_64QAM_A4_MAN__PRE;
qpskIsGainExp =
SC_RA_RAM_EQ_IS_GAIN_UNKNOWN_EXP__PRE;
qam16IsGainExp =
SC_RA_RAM_EQ_IS_GAIN_16QAM_A4_EXP__PRE;
qam64IsGainExp =
SC_RA_RAM_EQ_IS_GAIN_64QAM_A4_EXP__PRE;
}
break;
case HIERARCHY_AUTO:
default:
/* Not set, detect it automatically, start with none */
operationMode |= SC_RA_RAM_OP_AUTO_HIER__M;
transmissionParams |= SC_RA_RAM_OP_PARAM_HIER_NO;
if (state->type_A) {
status = Write16(state, EQ_REG_OT_ALPHA__A, 0x0000, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_ALPHA__A, 0x0000, 0x0000);
if (status < 0)
break;
qpskTdTpsPwr = EQ_TD_TPS_PWR_QPSK;
qam16TdTpsPwr = EQ_TD_TPS_PWR_QAM16_ALPHAN;
qam64TdTpsPwr = EQ_TD_TPS_PWR_QAM64_ALPHAN;
qpskIsGainMan =
SC_RA_RAM_EQ_IS_GAIN_QPSK_MAN__PRE;
qam16IsGainMan =
SC_RA_RAM_EQ_IS_GAIN_16QAM_MAN__PRE;
qam64IsGainMan =
SC_RA_RAM_EQ_IS_GAIN_64QAM_MAN__PRE;
qpskIsGainExp =
SC_RA_RAM_EQ_IS_GAIN_QPSK_EXP__PRE;
qam16IsGainExp =
SC_RA_RAM_EQ_IS_GAIN_16QAM_EXP__PRE;
qam64IsGainExp =
SC_RA_RAM_EQ_IS_GAIN_64QAM_EXP__PRE;
}
break;
}
status = status;
if (status < 0)
break;
switch (p->modulation) {
default:
operationMode |= SC_RA_RAM_OP_AUTO_CONST__M;
/* fall through , try first guess
DRX_CONSTELLATION_QAM64 */
case QAM_64:
transmissionParams |= SC_RA_RAM_OP_PARAM_CONST_QAM64;
if (state->type_A) {
status = Write16(state, EQ_REG_OT_CONST__A, 0x0002, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_CONST__A, EC_SB_REG_CONST_64QAM, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_SCALE_MSB__A, 0x0020, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_SCALE_BIT2__A, 0x0008, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_SCALE_LSB__A, 0x0002, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_TD_TPS_PWR_OFS__A, qam64TdTpsPwr, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_SN_CEGAIN__A, qam64SnCeGain, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_IS_GAIN_MAN__A, qam64IsGainMan, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_IS_GAIN_EXP__A, qam64IsGainExp, 0x0000);
if (status < 0)
break;
}
break;
case QPSK:
transmissionParams |= SC_RA_RAM_OP_PARAM_CONST_QPSK;
if (state->type_A) {
status = Write16(state, EQ_REG_OT_CONST__A, 0x0000, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_CONST__A, EC_SB_REG_CONST_QPSK, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_SCALE_MSB__A, 0x0010, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_SCALE_BIT2__A, 0x0000, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_SCALE_LSB__A, 0x0000, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_TD_TPS_PWR_OFS__A, qpskTdTpsPwr, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_SN_CEGAIN__A, qpskSnCeGain, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_IS_GAIN_MAN__A, qpskIsGainMan, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_IS_GAIN_EXP__A, qpskIsGainExp, 0x0000);
if (status < 0)
break;
}
break;
case QAM_16:
transmissionParams |= SC_RA_RAM_OP_PARAM_CONST_QAM16;
if (state->type_A) {
status = Write16(state, EQ_REG_OT_CONST__A, 0x0001, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_CONST__A, EC_SB_REG_CONST_16QAM, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_SCALE_MSB__A, 0x0010, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_SCALE_BIT2__A, 0x0004, 0x0000);
if (status < 0)
break;
status = Write16(state, EC_SB_REG_SCALE_LSB__A, 0x0000, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_TD_TPS_PWR_OFS__A, qam16TdTpsPwr, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_SN_CEGAIN__A, qam16SnCeGain, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_IS_GAIN_MAN__A, qam16IsGainMan, 0x0000);
if (status < 0)
break;
status = Write16(state, EQ_REG_IS_GAIN_EXP__A, qam16IsGainExp, 0x0000);
if (status < 0)
break;
}
break;
}
status = status;
if (status < 0)
break;
switch (DRX_CHANNEL_HIGH) {
default:
case DRX_CHANNEL_AUTO:
case DRX_CHANNEL_LOW:
transmissionParams |= SC_RA_RAM_OP_PARAM_PRIO_LO;
status = Write16(state, EC_SB_REG_PRIOR__A, EC_SB_REG_PRIOR_LO, 0x0000);
if (status < 0)
break;
break;
case DRX_CHANNEL_HIGH:
transmissionParams |= SC_RA_RAM_OP_PARAM_PRIO_HI;
status = Write16(state, EC_SB_REG_PRIOR__A, EC_SB_REG_PRIOR_HI, 0x0000);
if (status < 0)
break;
break;
}
switch (p->code_rate_HP) {
case FEC_1_2:
transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_1_2;
if (state->type_A) {
status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C1_2, 0x0000);
if (status < 0)
break;
}
break;
default:
operationMode |= SC_RA_RAM_OP_AUTO_RATE__M;
case FEC_2_3:
transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_2_3;
if (state->type_A) {
status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C2_3, 0x0000);
if (status < 0)
break;
}
break;
case FEC_3_4:
transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_3_4;
if (state->type_A) {
status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C3_4, 0x0000);
if (status < 0)
break;
}
break;
case FEC_5_6:
transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_5_6;
if (state->type_A) {
status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C5_6, 0x0000);
if (status < 0)
break;
}
break;
case FEC_7_8:
transmissionParams |= SC_RA_RAM_OP_PARAM_RATE_7_8;
if (state->type_A) {
status = Write16(state, EC_VD_REG_SET_CODERATE__A, EC_VD_REG_SET_CODERATE_C7_8, 0x0000);
if (status < 0)
break;
}
break;
}
status = status;
if (status < 0)
break;
/* First determine real bandwidth (Hz) */
/* Also set delay for impulse noise cruncher (only A2) */
/* Also set parameters for EC_OC fix, note
EC_OC_REG_TMD_HIL_MAR is changed
by SC for fix for some 8K,1/8 guard but is restored by
InitEC and ResetEC
functions */
switch (p->bandwidth_hz) {
case 0:
p->bandwidth_hz = 8000000;
/* fall through */
case 8000000:
/* (64/7)*(8/8)*1000000 */
bandwidth = DRXD_BANDWIDTH_8MHZ_IN_HZ;
bandwidthParam = 0;
status = Write16(state,
FE_AG_REG_IND_DEL__A, 50, 0x0000);
break;
case 7000000:
/* (64/7)*(7/8)*1000000 */
bandwidth = DRXD_BANDWIDTH_7MHZ_IN_HZ;
bandwidthParam = 0x4807; /*binary:0100 1000 0000 0111 */
status = Write16(state,
FE_AG_REG_IND_DEL__A, 59, 0x0000);
break;
case 6000000:
/* (64/7)*(6/8)*1000000 */
bandwidth = DRXD_BANDWIDTH_6MHZ_IN_HZ;
bandwidthParam = 0x0F07; /*binary: 0000 1111 0000 0111 */
status = Write16(state,
FE_AG_REG_IND_DEL__A, 71, 0x0000);
break;
default:
status = -EINVAL;
}
if (status < 0)
break;
status = Write16(state, SC_RA_RAM_BAND__A, bandwidthParam, 0x0000);
if (status < 0)
break;
{
u16 sc_config;
status = Read16(state, SC_RA_RAM_CONFIG__A, &sc_config, 0);
if (status < 0)
break;
/* enable SLAVE mode in 2k 1/32 to
prevent timing change glitches */
if ((p->transmission_mode == TRANSMISSION_MODE_2K) &&
(p->guard_interval == GUARD_INTERVAL_1_32)) {
/* enable slave */
sc_config |= SC_RA_RAM_CONFIG_SLAVE__M;
} else {
/* disable slave */
sc_config &= ~SC_RA_RAM_CONFIG_SLAVE__M;
}
status = Write16(state, SC_RA_RAM_CONFIG__A, sc_config, 0);
if (status < 0)
break;
}
status = SetCfgNoiseCalibration(state, &state->noise_cal);
if (status < 0)
break;
if (state->cscd_state == CSCD_INIT) {
/* switch on SRMM scan in SC */
status = Write16(state, SC_RA_RAM_SAMPLE_RATE_COUNT__A, DRXD_OSCDEV_DO_SCAN, 0x0000);
if (status < 0)
break;
/* CHK_ERROR(Write16(SC_RA_RAM_SAMPLE_RATE_STEP__A, DRXD_OSCDEV_STEP, 0x0000));*/
state->cscd_state = CSCD_SET;
}
/* Now compute FE_IF_REG_INCR */
/*((( SysFreq/BandWidth)/2)/2) -1) * 2^23) =>
((SysFreq / BandWidth) * (2^21) ) - (2^23) */
feIfIncr = MulDiv32(state->sys_clock_freq * 1000,
(1ULL << 21), bandwidth) - (1 << 23);
status = Write16(state, FE_IF_REG_INCR0__A, (u16) (feIfIncr & FE_IF_REG_INCR0__M), 0x0000);
if (status < 0)
break;
status = Write16(state, FE_IF_REG_INCR1__A, (u16) ((feIfIncr >> FE_IF_REG_INCR0__W) & FE_IF_REG_INCR1__M), 0x0000);
if (status < 0)
break;
/* Bandwidth setting done */
/* Mirror & frequency offset */
SetFrequencyShift(state, off, mirrorFreqSpect);
/* Start SC, write channel settings to SC */
/* Enable SC after setting all other parameters */
status = Write16(state, SC_COMM_STATE__A, 0, 0x0000);
if (status < 0)
break;
status = Write16(state, SC_COMM_EXEC__A, 1, 0x0000);
if (status < 0)
break;
/* Write SC parameter registers, operation mode */
#if 1
operationMode = (SC_RA_RAM_OP_AUTO_MODE__M |
SC_RA_RAM_OP_AUTO_GUARD__M |
SC_RA_RAM_OP_AUTO_CONST__M |
SC_RA_RAM_OP_AUTO_HIER__M |
SC_RA_RAM_OP_AUTO_RATE__M);
#endif
status = SC_SetPrefParamCommand(state, 0x0000, transmissionParams, operationMode);
if (status < 0)
break;
/* Start correct processes to get in lock */
status = SC_ProcStartCommand(state, SC_RA_RAM_PROC_LOCKTRACK, SC_RA_RAM_SW_EVENT_RUN_NMASK__M, SC_RA_RAM_LOCKTRACK_MIN);
if (status < 0)
break;
status = StartOC(state);
if (status < 0)
break;
if (state->operation_mode != OM_Default) {
status = StartDiversity(state);
if (status < 0)
break;
}
state->drxd_state = DRXD_STARTED;
} while (0);
return status;
}
static int CDRXD(struct drxd_state *state, u32 IntermediateFrequency)
{
u32 ulRfAgcOutputLevel = 0xffffffff;
u32 ulRfAgcSettleLevel = 528; /* Optimum value for MT2060 */
u32 ulRfAgcMinLevel = 0; /* Currently unused */
u32 ulRfAgcMaxLevel = DRXD_FE_CTRL_MAX; /* Currently unused */
u32 ulRfAgcSpeed = 0; /* Currently unused */
u32 ulRfAgcMode = 0; /*2; Off */
u32 ulRfAgcR1 = 820;
u32 ulRfAgcR2 = 2200;
u32 ulRfAgcR3 = 150;
u32 ulIfAgcMode = 0; /* Auto */
u32 ulIfAgcOutputLevel = 0xffffffff;
u32 ulIfAgcSettleLevel = 0xffffffff;
u32 ulIfAgcMinLevel = 0xffffffff;
u32 ulIfAgcMaxLevel = 0xffffffff;
u32 ulIfAgcSpeed = 0xffffffff;
u32 ulIfAgcR1 = 820;
u32 ulIfAgcR2 = 2200;
u32 ulIfAgcR3 = 150;
u32 ulClock = state->config.clock;
u32 ulSerialMode = 0;
u32 ulEcOcRegOcModeLop = 4; /* Dynamic DTO source */
u32 ulHiI2cDelay = HI_I2C_DELAY;
u32 ulHiI2cBridgeDelay = HI_I2C_BRIDGE_DELAY;
u32 ulHiI2cPatch = 0;
u32 ulEnvironment = APPENV_PORTABLE;
u32 ulEnvironmentDiversity = APPENV_MOBILE;
u32 ulIFFilter = IFFILTER_SAW;
state->if_agc_cfg.ctrlMode = AGC_CTRL_AUTO;
state->if_agc_cfg.outputLevel = 0;
state->if_agc_cfg.settleLevel = 140;
state->if_agc_cfg.minOutputLevel = 0;
state->if_agc_cfg.maxOutputLevel = 1023;
state->if_agc_cfg.speed = 904;
if (ulIfAgcMode == 1 && ulIfAgcOutputLevel <= DRXD_FE_CTRL_MAX) {
state->if_agc_cfg.ctrlMode = AGC_CTRL_USER;
state->if_agc_cfg.outputLevel = (u16) (ulIfAgcOutputLevel);
}
if (ulIfAgcMode == 0 &&
ulIfAgcSettleLevel <= DRXD_FE_CTRL_MAX &&
ulIfAgcMinLevel <= DRXD_FE_CTRL_MAX &&
ulIfAgcMaxLevel <= DRXD_FE_CTRL_MAX &&
ulIfAgcSpeed <= DRXD_FE_CTRL_MAX) {
state->if_agc_cfg.ctrlMode = AGC_CTRL_AUTO;
state->if_agc_cfg.settleLevel = (u16) (ulIfAgcSettleLevel);
state->if_agc_cfg.minOutputLevel = (u16) (ulIfAgcMinLevel);
state->if_agc_cfg.maxOutputLevel = (u16) (ulIfAgcMaxLevel);
state->if_agc_cfg.speed = (u16) (ulIfAgcSpeed);
}
state->if_agc_cfg.R1 = (u16) (ulIfAgcR1);
state->if_agc_cfg.R2 = (u16) (ulIfAgcR2);
state->if_agc_cfg.R3 = (u16) (ulIfAgcR3);
state->rf_agc_cfg.R1 = (u16) (ulRfAgcR1);
state->rf_agc_cfg.R2 = (u16) (ulRfAgcR2);
state->rf_agc_cfg.R3 = (u16) (ulRfAgcR3);
state->rf_agc_cfg.ctrlMode = AGC_CTRL_AUTO;
/* rest of the RFAgcCfg structure currently unused */
if (ulRfAgcMode == 1 && ulRfAgcOutputLevel <= DRXD_FE_CTRL_MAX) {
state->rf_agc_cfg.ctrlMode = AGC_CTRL_USER;
state->rf_agc_cfg.outputLevel = (u16) (ulRfAgcOutputLevel);
}
if (ulRfAgcMode == 0 &&
ulRfAgcSettleLevel <= DRXD_FE_CTRL_MAX &&
ulRfAgcMinLevel <= DRXD_FE_CTRL_MAX &&
ulRfAgcMaxLevel <= DRXD_FE_CTRL_MAX &&
ulRfAgcSpeed <= DRXD_FE_CTRL_MAX) {
state->rf_agc_cfg.ctrlMode = AGC_CTRL_AUTO;
state->rf_agc_cfg.settleLevel = (u16) (ulRfAgcSettleLevel);
state->rf_agc_cfg.minOutputLevel = (u16) (ulRfAgcMinLevel);
state->rf_agc_cfg.maxOutputLevel = (u16) (ulRfAgcMaxLevel);
state->rf_agc_cfg.speed = (u16) (ulRfAgcSpeed);
}
if (ulRfAgcMode == 2)
state->rf_agc_cfg.ctrlMode = AGC_CTRL_OFF;
if (ulEnvironment <= 2)
state->app_env_default = (enum app_env)
(ulEnvironment);
if (ulEnvironmentDiversity <= 2)
state->app_env_diversity = (enum app_env)
(ulEnvironmentDiversity);
if (ulIFFilter == IFFILTER_DISCRETE) {
/* discrete filter */
state->noise_cal.cpOpt = 0;
state->noise_cal.cpNexpOfs = 40;
state->noise_cal.tdCal2k = -40;
state->noise_cal.tdCal8k = -24;
} else {
/* SAW filter */
state->noise_cal.cpOpt = 1;
state->noise_cal.cpNexpOfs = 0;
state->noise_cal.tdCal2k = -21;
state->noise_cal.tdCal8k = -24;
}
state->m_EcOcRegOcModeLop = (u16) (ulEcOcRegOcModeLop);
state->chip_adr = (state->config.demod_address << 1) | 1;
switch (ulHiI2cPatch) {
case 1:
state->m_HiI2cPatch = DRXD_HiI2cPatch_1;
break;
case 3:
state->m_HiI2cPatch = DRXD_HiI2cPatch_3;
break;
default:
state->m_HiI2cPatch = NULL;
}
/* modify tuner and clock attributes */
state->intermediate_freq = (u16) (IntermediateFrequency / 1000);
/* expected system clock frequency in kHz */
state->expected_sys_clock_freq = 48000;
/* real system clock frequency in kHz */
state->sys_clock_freq = 48000;
state->osc_clock_freq = (u16) ulClock;
state->osc_clock_deviation = 0;
state->cscd_state = CSCD_INIT;
state->drxd_state = DRXD_UNINITIALIZED;
state->PGA = 0;
state->type_A = 0;
state->tuner_mirrors = 0;
/* modify MPEG output attributes */
state->insert_rs_byte = state->config.insert_rs_byte;
state->enable_parallel = (ulSerialMode != 1);
/* Timing div, 250ns/Psys */
/* Timing div, = ( delay (nano seconds) * sysclk (kHz) )/ 1000 */
state->hi_cfg_timing_div = (u16) ((state->sys_clock_freq / 1000) *
ulHiI2cDelay) / 1000;
/* Bridge delay, uses oscilator clock */
/* Delay = ( delay (nano seconds) * oscclk (kHz) )/ 1000 */
state->hi_cfg_bridge_delay = (u16) ((state->osc_clock_freq / 1000) *
ulHiI2cBridgeDelay) / 1000;
state->m_FeAgRegAgPwd = DRXD_DEF_AG_PWD_CONSUMER;
/* state->m_FeAgRegAgPwd = DRXD_DEF_AG_PWD_PRO; */
state->m_FeAgRegAgAgcSio = DRXD_DEF_AG_AGC_SIO;
return 0;
}
int DRXD_init(struct drxd_state *state, const u8 * fw, u32 fw_size)
{
int status = 0;
u32 driverVersion;
if (state->init_done)
return 0;
CDRXD(state, state->config.IF ? state->config.IF : 36000000);
do {
state->operation_mode = OM_Default;
status = SetDeviceTypeId(state);
if (status < 0)
break;
/* Apply I2c address patch to B1 */
if (!state->type_A && state->m_HiI2cPatch != NULL)
status = WriteTable(state, state->m_HiI2cPatch);
if (status < 0)
break;
if (state->type_A) {
/* HI firmware patch for UIO readout,
avoid clearing of result register */
status = Write16(state, 0x43012D, 0x047f, 0);
if (status < 0)
break;
}
status = HI_ResetCommand(state);
if (status < 0)
break;
status = StopAllProcessors(state);
if (status < 0)
break;
status = InitCC(state);
if (status < 0)
break;
state->osc_clock_deviation = 0;
if (state->config.osc_deviation)
state->osc_clock_deviation =
state->config.osc_deviation(state->priv, 0, 0);
{
/* Handle clock deviation */
s32 devB;
s32 devA = (s32) (state->osc_clock_deviation) *
(s32) (state->expected_sys_clock_freq);
/* deviation in kHz */
s32 deviation = (devA / (1000000L));
/* rounding, signed */
if (devA > 0)
devB = (2);
else
devB = (-2);
if ((devB * (devA % 1000000L) > 1000000L)) {
/* add +1 or -1 */
deviation += (devB / 2);
}
state->sys_clock_freq =
(u16) ((state->expected_sys_clock_freq) +
deviation);
}
status = InitHI(state);
if (status < 0)
break;
status = InitAtomicRead(state);
if (status < 0)
break;
status = EnableAndResetMB(state);
if (status < 0)
break;
if (state->type_A)
status = ResetCEFR(state);
if (status < 0)
break;
if (fw) {
status = DownloadMicrocode(state, fw, fw_size);
if (status < 0)
break;
} else {
status = DownloadMicrocode(state, state->microcode, state->microcode_length);
if (status < 0)
break;
}
if (state->PGA) {
state->m_FeAgRegAgPwd = DRXD_DEF_AG_PWD_PRO;
SetCfgPga(state, 0); /* PGA = 0 dB */
} else {
state->m_FeAgRegAgPwd = DRXD_DEF_AG_PWD_CONSUMER;
}
state->m_FeAgRegAgAgcSio = DRXD_DEF_AG_AGC_SIO;
status = InitFE(state);
if (status < 0)
break;
status = InitFT(state);
if (status < 0)
break;
status = InitCP(state);
if (status < 0)
break;
status = InitCE(state);
if (status < 0)
break;
status = InitEQ(state);
if (status < 0)
break;
status = InitEC(state);
if (status < 0)
break;
status = InitSC(state);
if (status < 0)
break;
status = SetCfgIfAgc(state, &state->if_agc_cfg);
if (status < 0)
break;
status = SetCfgRfAgc(state, &state->rf_agc_cfg);
if (status < 0)
break;
state->cscd_state = CSCD_INIT;
status = Write16(state, SC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
status = Write16(state, LC_COMM_EXEC__A, SC_COMM_EXEC_CTL_STOP, 0);
if (status < 0)
break;
driverVersion = (((VERSION_MAJOR / 10) << 4) +
(VERSION_MAJOR % 10)) << 24;
driverVersion += (((VERSION_MINOR / 10) << 4) +
(VERSION_MINOR % 10)) << 16;
driverVersion += ((VERSION_PATCH / 1000) << 12) +
((VERSION_PATCH / 100) << 8) +
((VERSION_PATCH / 10) << 4) + (VERSION_PATCH % 10);
status = Write32(state, SC_RA_RAM_DRIVER_VERSION__AX, driverVersion, 0);
if (status < 0)
break;
status = StopOC(state);
if (status < 0)
break;
state->drxd_state = DRXD_STOPPED;
state->init_done = 1;
status = 0;
} while (0);
return status;
}
int DRXD_status(struct drxd_state *state, u32 * pLockStatus)
{
DRX_GetLockStatus(state, pLockStatus);
/*if (*pLockStatus&DRX_LOCK_MPEG) */
if (*pLockStatus & DRX_LOCK_FEC) {
ConfigureMPEGOutput(state, 1);
/* Get status again, in case we have MPEG lock now */
/*DRX_GetLockStatus(state, pLockStatus); */
}
return 0;
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
static int drxd_read_signal_strength(struct dvb_frontend *fe, u16 * strength)
{
struct drxd_state *state = fe->demodulator_priv;
u32 value;
int res;
res = ReadIFAgc(state, &value);
if (res < 0)
*strength = 0;
else
*strength = 0xffff - (value << 4);
return 0;
}
static int drxd_read_status(struct dvb_frontend *fe, fe_status_t * status)
{
struct drxd_state *state = fe->demodulator_priv;
u32 lock;
DRXD_status(state, &lock);
*status = 0;
/* No MPEG lock in V255 firmware, bug ? */
#if 1
if (lock & DRX_LOCK_MPEG)
*status |= FE_HAS_LOCK;
#else
if (lock & DRX_LOCK_FEC)
*status |= FE_HAS_LOCK;
#endif
if (lock & DRX_LOCK_FEC)
*status |= FE_HAS_VITERBI | FE_HAS_SYNC;
if (lock & DRX_LOCK_DEMOD)
*status |= FE_HAS_CARRIER | FE_HAS_SIGNAL;
return 0;
}
static int drxd_init(struct dvb_frontend *fe)
{
struct drxd_state *state = fe->demodulator_priv;
int err = 0;
/* if (request_firmware(&state->fw, "drxd.fw", state->dev)<0) */
return DRXD_init(state, 0, 0);
err = DRXD_init(state, state->fw->data, state->fw->size);
release_firmware(state->fw);
return err;
}
int drxd_config_i2c(struct dvb_frontend *fe, int onoff)
{
struct drxd_state *state = fe->demodulator_priv;
if (state->config.disable_i2c_gate_ctrl == 1)
return 0;
return DRX_ConfigureI2CBridge(state, onoff);
}
EXPORT_SYMBOL(drxd_config_i2c);
static int drxd_get_tune_settings(struct dvb_frontend *fe,
struct dvb_frontend_tune_settings *sets)
{
sets->min_delay_ms = 10000;
sets->max_drift = 0;
sets->step_size = 0;
return 0;
}
static int drxd_read_ber(struct dvb_frontend *fe, u32 * ber)
{
*ber = 0;
return 0;
}
static int drxd_read_snr(struct dvb_frontend *fe, u16 * snr)
{
*snr = 0;
return 0;
}
static int drxd_read_ucblocks(struct dvb_frontend *fe, u32 * ucblocks)
{
*ucblocks = 0;
return 0;
}
static int drxd_sleep(struct dvb_frontend *fe)
{
struct drxd_state *state = fe->demodulator_priv;
ConfigureMPEGOutput(state, 0);
return 0;
}
static int drxd_i2c_gate_ctrl(struct dvb_frontend *fe, int enable)
{
return drxd_config_i2c(fe, enable);
}
static int drxd_set_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct drxd_state *state = fe->demodulator_priv;
s32 off = 0;
state->props = *p;
DRX_Stop(state);
if (fe->ops.tuner_ops.set_params) {
fe->ops.tuner_ops.set_params(fe);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
}
msleep(200);
return DRX_Start(state, off);
}
static void drxd_release(struct dvb_frontend *fe)
{
struct drxd_state *state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops drxd_ops = {
.delsys = { SYS_DVBT},
.info = {
.name = "Micronas DRXD DVB-T",
.frequency_min = 47125000,
.frequency_max = 855250000,
.frequency_stepsize = 166667,
.frequency_tolerance = 0,
.caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 |
FE_CAN_FEC_3_4 | FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 |
FE_CAN_FEC_AUTO |
FE_CAN_QAM_16 | FE_CAN_QAM_64 |
FE_CAN_QAM_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_HIERARCHY_AUTO | FE_CAN_RECOVER | FE_CAN_MUTE_TS},
.release = drxd_release,
.init = drxd_init,
.sleep = drxd_sleep,
.i2c_gate_ctrl = drxd_i2c_gate_ctrl,
.set_frontend = drxd_set_frontend,
.get_tune_settings = drxd_get_tune_settings,
.read_status = drxd_read_status,
.read_ber = drxd_read_ber,
.read_signal_strength = drxd_read_signal_strength,
.read_snr = drxd_read_snr,
.read_ucblocks = drxd_read_ucblocks,
};
struct dvb_frontend *drxd_attach(const struct drxd_config *config,
void *priv, struct i2c_adapter *i2c,
struct device *dev)
{
struct drxd_state *state = NULL;
state = kmalloc(sizeof(struct drxd_state), GFP_KERNEL);
if (!state)
return NULL;
memset(state, 0, sizeof(*state));
memcpy(&state->ops, &drxd_ops, sizeof(struct dvb_frontend_ops));
state->dev = dev;
state->config = *config;
state->i2c = i2c;
state->priv = priv;
mutex_init(&state->mutex);
if (Read16(state, 0, 0, 0) < 0)
goto error;
memcpy(&state->frontend.ops, &drxd_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
ConfigureMPEGOutput(state, 0);
return &state->frontend;
error:
printk(KERN_ERR "drxd: not found\n");
kfree(state);
return NULL;
}
EXPORT_SYMBOL(drxd_attach);
MODULE_DESCRIPTION("DRXD driver");
MODULE_AUTHOR("Micronas");
MODULE_LICENSE("GPL");
| gpl-2.0 |
xiaognol/android_kernel_zte_nx503a | drivers/media/video/wm8739.c | 7242 | 7739 | /*
* wm8739
*
* Copyright (C) 2005 T. Adachi <tadachi@tadachi-net.com>
*
* Copyright (C) 2005 Hans Verkuil <hverkuil@xs4all.nl>
* - Cleanup
*
* 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/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/ioctl.h>
#include <asm/uaccess.h>
#include <linux/i2c.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-ctrls.h>
MODULE_DESCRIPTION("wm8739 driver");
MODULE_AUTHOR("T. Adachi, Hans Verkuil");
MODULE_LICENSE("GPL");
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Debug level (0-1)");
/* ------------------------------------------------------------------------ */
enum {
R0 = 0, R1,
R5 = 5, R6, R7, R8, R9, R15 = 15,
TOT_REGS
};
struct wm8739_state {
struct v4l2_subdev sd;
struct v4l2_ctrl_handler hdl;
struct {
/* audio cluster */
struct v4l2_ctrl *volume;
struct v4l2_ctrl *mute;
struct v4l2_ctrl *balance;
};
u32 clock_freq;
};
static inline struct wm8739_state *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct wm8739_state, sd);
}
static inline struct v4l2_subdev *to_sd(struct v4l2_ctrl *ctrl)
{
return &container_of(ctrl->handler, struct wm8739_state, hdl)->sd;
}
/* ------------------------------------------------------------------------ */
static int wm8739_write(struct v4l2_subdev *sd, int reg, u16 val)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
int i;
if (reg < 0 || reg >= TOT_REGS) {
v4l2_err(sd, "Invalid register R%d\n", reg);
return -1;
}
v4l2_dbg(1, debug, sd, "write: %02x %02x\n", reg, val);
for (i = 0; i < 3; i++)
if (i2c_smbus_write_byte_data(client,
(reg << 1) | (val >> 8), val & 0xff) == 0)
return 0;
v4l2_err(sd, "I2C: cannot write %03x to register R%d\n", val, reg);
return -1;
}
static int wm8739_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct v4l2_subdev *sd = to_sd(ctrl);
struct wm8739_state *state = to_state(sd);
unsigned int work_l, work_r;
u8 vol_l; /* +12dB to -34.5dB 1.5dB step (5bit) def:0dB */
u8 vol_r; /* +12dB to -34.5dB 1.5dB step (5bit) def:0dB */
u16 mute;
switch (ctrl->id) {
case V4L2_CID_AUDIO_VOLUME:
break;
default:
return -EINVAL;
}
/* normalize ( 65535 to 0 -> 31 to 0 (12dB to -34.5dB) ) */
work_l = (min(65536 - state->balance->val, 32768) * state->volume->val) / 32768;
work_r = (min(state->balance->val, 32768) * state->volume->val) / 32768;
vol_l = (long)work_l * 31 / 65535;
vol_r = (long)work_r * 31 / 65535;
/* set audio volume etc. */
mute = state->mute->val ? 0x80 : 0;
/* Volume setting: bits 0-4, 0x1f = 12 dB, 0x00 = -34.5 dB
* Default setting: 0x17 = 0 dB
*/
wm8739_write(sd, R0, (vol_l & 0x1f) | mute);
wm8739_write(sd, R1, (vol_r & 0x1f) | mute);
return 0;
}
/* ------------------------------------------------------------------------ */
static int wm8739_s_clock_freq(struct v4l2_subdev *sd, u32 audiofreq)
{
struct wm8739_state *state = to_state(sd);
state->clock_freq = audiofreq;
/* de-activate */
wm8739_write(sd, R9, 0x000);
switch (audiofreq) {
case 44100:
/* 256fps, fs=44.1k */
wm8739_write(sd, R8, 0x020);
break;
case 48000:
/* 256fps, fs=48k */
wm8739_write(sd, R8, 0x000);
break;
case 32000:
/* 256fps, fs=32k */
wm8739_write(sd, R8, 0x018);
break;
default:
break;
}
/* activate */
wm8739_write(sd, R9, 0x001);
return 0;
}
static int wm8739_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_WM8739, 0);
}
static int wm8739_log_status(struct v4l2_subdev *sd)
{
struct wm8739_state *state = to_state(sd);
v4l2_info(sd, "Frequency: %u Hz\n", state->clock_freq);
v4l2_ctrl_handler_log_status(&state->hdl, sd->name);
return 0;
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_ctrl_ops wm8739_ctrl_ops = {
.s_ctrl = wm8739_s_ctrl,
};
static const struct v4l2_subdev_core_ops wm8739_core_ops = {
.log_status = wm8739_log_status,
.g_chip_ident = wm8739_g_chip_ident,
.g_ext_ctrls = v4l2_subdev_g_ext_ctrls,
.try_ext_ctrls = v4l2_subdev_try_ext_ctrls,
.s_ext_ctrls = v4l2_subdev_s_ext_ctrls,
.g_ctrl = v4l2_subdev_g_ctrl,
.s_ctrl = v4l2_subdev_s_ctrl,
.queryctrl = v4l2_subdev_queryctrl,
.querymenu = v4l2_subdev_querymenu,
};
static const struct v4l2_subdev_audio_ops wm8739_audio_ops = {
.s_clock_freq = wm8739_s_clock_freq,
};
static const struct v4l2_subdev_ops wm8739_ops = {
.core = &wm8739_core_ops,
.audio = &wm8739_audio_ops,
};
/* ------------------------------------------------------------------------ */
/* i2c implementation */
static int wm8739_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct wm8739_state *state;
struct v4l2_subdev *sd;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
v4l_info(client, "chip found @ 0x%x (%s)\n",
client->addr << 1, client->adapter->name);
state = kzalloc(sizeof(struct wm8739_state), GFP_KERNEL);
if (state == NULL)
return -ENOMEM;
sd = &state->sd;
v4l2_i2c_subdev_init(sd, client, &wm8739_ops);
v4l2_ctrl_handler_init(&state->hdl, 2);
state->volume = v4l2_ctrl_new_std(&state->hdl, &wm8739_ctrl_ops,
V4L2_CID_AUDIO_VOLUME, 0, 65535, 65535 / 100, 50736);
state->mute = v4l2_ctrl_new_std(&state->hdl, &wm8739_ctrl_ops,
V4L2_CID_AUDIO_MUTE, 0, 1, 1, 0);
state->balance = v4l2_ctrl_new_std(&state->hdl, &wm8739_ctrl_ops,
V4L2_CID_AUDIO_BALANCE, 0, 65535, 65535 / 100, 32768);
sd->ctrl_handler = &state->hdl;
if (state->hdl.error) {
int err = state->hdl.error;
v4l2_ctrl_handler_free(&state->hdl);
kfree(state);
return err;
}
v4l2_ctrl_cluster(3, &state->volume);
state->clock_freq = 48000;
/* Initialize wm8739 */
/* reset */
wm8739_write(sd, R15, 0x00);
/* filter setting, high path, offet clear */
wm8739_write(sd, R5, 0x000);
/* ADC, OSC, Power Off mode Disable */
wm8739_write(sd, R6, 0x000);
/* Digital Audio interface format:
Enable Master mode, 24 bit, MSB first/left justified */
wm8739_write(sd, R7, 0x049);
/* sampling control: normal, 256fs, 48KHz sampling rate */
wm8739_write(sd, R8, 0x000);
/* activate */
wm8739_write(sd, R9, 0x001);
/* set volume/mute */
v4l2_ctrl_handler_setup(&state->hdl);
return 0;
}
static int wm8739_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct wm8739_state *state = to_state(sd);
v4l2_device_unregister_subdev(sd);
v4l2_ctrl_handler_free(&state->hdl);
kfree(to_state(sd));
return 0;
}
static const struct i2c_device_id wm8739_id[] = {
{ "wm8739", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8739_id);
static struct i2c_driver wm8739_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "wm8739",
},
.probe = wm8739_probe,
.remove = wm8739_remove,
.id_table = wm8739_id,
};
module_i2c_driver(wm8739_driver);
| gpl-2.0 |
boa19861105/android_LP5.0.2_kernel_htc_dlxub1 | drivers/media/video/adv7175.c | 7242 | 11906 | /*
* adv7175 - adv7175a video encoder driver version 0.0.3
*
* Copyright (C) 1998 Dave Perks <dperks@ibm.net>
* Copyright (C) 1999 Wolfgang Scherr <scherr@net4you.net>
* Copyright (C) 2000 Serguei Miridonov <mirsev@cicese.mx>
* - some corrections for Pinnacle Systems Inc. DC10plus card.
*
* Changes by Ronald Bultje <rbultje@ronald.bitfreak.net>
* - moved over to linux>=2.4.x i2c protocol (9/9/2002)
*
* 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/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/ioctl.h>
#include <asm/uaccess.h>
#include <linux/i2c.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
MODULE_DESCRIPTION("Analog Devices ADV7175 video encoder driver");
MODULE_AUTHOR("Dave Perks");
MODULE_LICENSE("GPL");
#define I2C_ADV7175 0xd4
#define I2C_ADV7176 0x54
static int debug;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0-1)");
/* ----------------------------------------------------------------------- */
struct adv7175 {
struct v4l2_subdev sd;
v4l2_std_id norm;
int input;
};
static inline struct adv7175 *to_adv7175(struct v4l2_subdev *sd)
{
return container_of(sd, struct adv7175, sd);
}
static char *inputs[] = { "pass_through", "play_back", "color_bar" };
static enum v4l2_mbus_pixelcode adv7175_codes[] = {
V4L2_MBUS_FMT_UYVY8_2X8,
V4L2_MBUS_FMT_UYVY8_1X16,
};
/* ----------------------------------------------------------------------- */
static inline int adv7175_write(struct v4l2_subdev *sd, u8 reg, u8 value)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return i2c_smbus_write_byte_data(client, reg, value);
}
static inline int adv7175_read(struct v4l2_subdev *sd, u8 reg)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return i2c_smbus_read_byte_data(client, reg);
}
static int adv7175_write_block(struct v4l2_subdev *sd,
const u8 *data, unsigned int len)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
int ret = -1;
u8 reg;
/* the adv7175 has an autoincrement function, use it if
* the adapter understands raw I2C */
if (i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
/* do raw I2C, not smbus compatible */
u8 block_data[32];
int block_len;
while (len >= 2) {
block_len = 0;
block_data[block_len++] = reg = data[0];
do {
block_data[block_len++] = data[1];
reg++;
len -= 2;
data += 2;
} while (len >= 2 && data[0] == reg && block_len < 32);
ret = i2c_master_send(client, block_data, block_len);
if (ret < 0)
break;
}
} else {
/* do some slow I2C emulation kind of thing */
while (len >= 2) {
reg = *data++;
ret = adv7175_write(sd, reg, *data++);
if (ret < 0)
break;
len -= 2;
}
}
return ret;
}
static void set_subcarrier_freq(struct v4l2_subdev *sd, int pass_through)
{
/* for some reason pass_through NTSC needs
* a different sub-carrier freq to remain stable. */
if (pass_through)
adv7175_write(sd, 0x02, 0x00);
else
adv7175_write(sd, 0x02, 0x55);
adv7175_write(sd, 0x03, 0x55);
adv7175_write(sd, 0x04, 0x55);
adv7175_write(sd, 0x05, 0x25);
}
/* ----------------------------------------------------------------------- */
/* Output filter: S-Video Composite */
#define MR050 0x11 /* 0x09 */
#define MR060 0x14 /* 0x0c */
/* ----------------------------------------------------------------------- */
#define TR0MODE 0x46
#define TR0RST 0x80
#define TR1CAPT 0x80
#define TR1PLAY 0x00
static const unsigned char init_common[] = {
0x00, MR050, /* MR0, PAL enabled */
0x01, 0x00, /* MR1 */
0x02, 0x0c, /* subc. freq. */
0x03, 0x8c, /* subc. freq. */
0x04, 0x79, /* subc. freq. */
0x05, 0x26, /* subc. freq. */
0x06, 0x40, /* subc. phase */
0x07, TR0MODE, /* TR0, 16bit */
0x08, 0x21, /* */
0x09, 0x00, /* */
0x0a, 0x00, /* */
0x0b, 0x00, /* */
0x0c, TR1CAPT, /* TR1 */
0x0d, 0x4f, /* MR2 */
0x0e, 0x00, /* */
0x0f, 0x00, /* */
0x10, 0x00, /* */
0x11, 0x00, /* */
};
static const unsigned char init_pal[] = {
0x00, MR050, /* MR0, PAL enabled */
0x01, 0x00, /* MR1 */
0x02, 0x0c, /* subc. freq. */
0x03, 0x8c, /* subc. freq. */
0x04, 0x79, /* subc. freq. */
0x05, 0x26, /* subc. freq. */
0x06, 0x40, /* subc. phase */
};
static const unsigned char init_ntsc[] = {
0x00, MR060, /* MR0, NTSC enabled */
0x01, 0x00, /* MR1 */
0x02, 0x55, /* subc. freq. */
0x03, 0x55, /* subc. freq. */
0x04, 0x55, /* subc. freq. */
0x05, 0x25, /* subc. freq. */
0x06, 0x1a, /* subc. phase */
};
static int adv7175_init(struct v4l2_subdev *sd, u32 val)
{
/* This is just for testing!!! */
adv7175_write_block(sd, init_common, sizeof(init_common));
adv7175_write(sd, 0x07, TR0MODE | TR0RST);
adv7175_write(sd, 0x07, TR0MODE);
return 0;
}
static int adv7175_s_std_output(struct v4l2_subdev *sd, v4l2_std_id std)
{
struct adv7175 *encoder = to_adv7175(sd);
if (std & V4L2_STD_NTSC) {
adv7175_write_block(sd, init_ntsc, sizeof(init_ntsc));
if (encoder->input == 0)
adv7175_write(sd, 0x0d, 0x4f); /* Enable genlock */
adv7175_write(sd, 0x07, TR0MODE | TR0RST);
adv7175_write(sd, 0x07, TR0MODE);
} else if (std & V4L2_STD_PAL) {
adv7175_write_block(sd, init_pal, sizeof(init_pal));
if (encoder->input == 0)
adv7175_write(sd, 0x0d, 0x4f); /* Enable genlock */
adv7175_write(sd, 0x07, TR0MODE | TR0RST);
adv7175_write(sd, 0x07, TR0MODE);
} else if (std & V4L2_STD_SECAM) {
/* This is an attempt to convert
* SECAM->PAL (typically it does not work
* due to genlock: when decoder is in SECAM
* and encoder in in PAL the subcarrier can
* not be syncronized with horizontal
* quency) */
adv7175_write_block(sd, init_pal, sizeof(init_pal));
if (encoder->input == 0)
adv7175_write(sd, 0x0d, 0x49); /* Disable genlock */
adv7175_write(sd, 0x07, TR0MODE | TR0RST);
adv7175_write(sd, 0x07, TR0MODE);
} else {
v4l2_dbg(1, debug, sd, "illegal norm: %llx\n",
(unsigned long long)std);
return -EINVAL;
}
v4l2_dbg(1, debug, sd, "switched to %llx\n", (unsigned long long)std);
encoder->norm = std;
return 0;
}
static int adv7175_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct adv7175 *encoder = to_adv7175(sd);
/* RJ: input = 0: input is from decoder
input = 1: input is from ZR36060
input = 2: color bar */
switch (input) {
case 0:
adv7175_write(sd, 0x01, 0x00);
if (encoder->norm & V4L2_STD_NTSC)
set_subcarrier_freq(sd, 1);
adv7175_write(sd, 0x0c, TR1CAPT); /* TR1 */
if (encoder->norm & V4L2_STD_SECAM)
adv7175_write(sd, 0x0d, 0x49); /* Disable genlock */
else
adv7175_write(sd, 0x0d, 0x4f); /* Enable genlock */
adv7175_write(sd, 0x07, TR0MODE | TR0RST);
adv7175_write(sd, 0x07, TR0MODE);
/*udelay(10);*/
break;
case 1:
adv7175_write(sd, 0x01, 0x00);
if (encoder->norm & V4L2_STD_NTSC)
set_subcarrier_freq(sd, 0);
adv7175_write(sd, 0x0c, TR1PLAY); /* TR1 */
adv7175_write(sd, 0x0d, 0x49);
adv7175_write(sd, 0x07, TR0MODE | TR0RST);
adv7175_write(sd, 0x07, TR0MODE);
/* udelay(10); */
break;
case 2:
adv7175_write(sd, 0x01, 0x80);
if (encoder->norm & V4L2_STD_NTSC)
set_subcarrier_freq(sd, 0);
adv7175_write(sd, 0x0d, 0x49);
adv7175_write(sd, 0x07, TR0MODE | TR0RST);
adv7175_write(sd, 0x07, TR0MODE);
/* udelay(10); */
break;
default:
v4l2_dbg(1, debug, sd, "illegal input: %d\n", input);
return -EINVAL;
}
v4l2_dbg(1, debug, sd, "switched to %s\n", inputs[input]);
encoder->input = input;
return 0;
}
static int adv7175_enum_fmt(struct v4l2_subdev *sd, unsigned int index,
enum v4l2_mbus_pixelcode *code)
{
if (index >= ARRAY_SIZE(adv7175_codes))
return -EINVAL;
*code = adv7175_codes[index];
return 0;
}
static int adv7175_g_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
u8 val = adv7175_read(sd, 0x7);
if ((val & 0x40) == (1 << 6))
mf->code = V4L2_MBUS_FMT_UYVY8_1X16;
else
mf->code = V4L2_MBUS_FMT_UYVY8_2X8;
mf->colorspace = V4L2_COLORSPACE_SMPTE170M;
mf->width = 0;
mf->height = 0;
mf->field = V4L2_FIELD_ANY;
return 0;
}
static int adv7175_s_fmt(struct v4l2_subdev *sd,
struct v4l2_mbus_framefmt *mf)
{
u8 val = adv7175_read(sd, 0x7);
int ret;
switch (mf->code) {
case V4L2_MBUS_FMT_UYVY8_2X8:
val &= ~0x40;
break;
case V4L2_MBUS_FMT_UYVY8_1X16:
val |= 0x40;
break;
default:
v4l2_dbg(1, debug, sd,
"illegal v4l2_mbus_framefmt code: %d\n", mf->code);
return -EINVAL;
}
ret = adv7175_write(sd, 0x7, val);
return ret;
}
static int adv7175_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_ADV7175, 0);
}
static int adv7175_s_power(struct v4l2_subdev *sd, int on)
{
if (on)
adv7175_write(sd, 0x01, 0x00);
else
adv7175_write(sd, 0x01, 0x78);
return 0;
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_subdev_core_ops adv7175_core_ops = {
.g_chip_ident = adv7175_g_chip_ident,
.init = adv7175_init,
.s_power = adv7175_s_power,
};
static const struct v4l2_subdev_video_ops adv7175_video_ops = {
.s_std_output = adv7175_s_std_output,
.s_routing = adv7175_s_routing,
.s_mbus_fmt = adv7175_s_fmt,
.g_mbus_fmt = adv7175_g_fmt,
.enum_mbus_fmt = adv7175_enum_fmt,
};
static const struct v4l2_subdev_ops adv7175_ops = {
.core = &adv7175_core_ops,
.video = &adv7175_video_ops,
};
/* ----------------------------------------------------------------------- */
static int adv7175_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int i;
struct adv7175 *encoder;
struct v4l2_subdev *sd;
/* Check if the adapter supports the needed features */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
v4l_info(client, "chip found @ 0x%x (%s)\n",
client->addr << 1, client->adapter->name);
encoder = kzalloc(sizeof(struct adv7175), GFP_KERNEL);
if (encoder == NULL)
return -ENOMEM;
sd = &encoder->sd;
v4l2_i2c_subdev_init(sd, client, &adv7175_ops);
encoder->norm = V4L2_STD_NTSC;
encoder->input = 0;
i = adv7175_write_block(sd, init_common, sizeof(init_common));
if (i >= 0) {
i = adv7175_write(sd, 0x07, TR0MODE | TR0RST);
i = adv7175_write(sd, 0x07, TR0MODE);
i = adv7175_read(sd, 0x12);
v4l2_dbg(1, debug, sd, "revision %d\n", i & 1);
}
if (i < 0)
v4l2_dbg(1, debug, sd, "init error 0x%x\n", i);
return 0;
}
static int adv7175_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
v4l2_device_unregister_subdev(sd);
kfree(to_adv7175(sd));
return 0;
}
/* ----------------------------------------------------------------------- */
static const struct i2c_device_id adv7175_id[] = {
{ "adv7175", 0 },
{ "adv7176", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, adv7175_id);
static struct i2c_driver adv7175_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "adv7175",
},
.probe = adv7175_probe,
.remove = adv7175_remove,
.id_table = adv7175_id,
};
module_i2c_driver(adv7175_driver);
| gpl-2.0 |
shakalaca/ASUS_ZenFone_ZE500CL | linux/kernel/drivers/hsi/hsi_boardinfo.c | 9546 | 1870 | /*
* HSI clients registration interface
*
* Copyright (C) 2010 Nokia Corporation. All rights reserved.
*
* Contact: Carlos Chinea <carlos.chinea@nokia.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.
*
* 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/hsi/hsi.h>
#include <linux/list.h>
#include <linux/slab.h>
#include "hsi_core.h"
/*
* hsi_board_list is only used internally by the HSI framework.
* No one else is allowed to make use of it.
*/
LIST_HEAD(hsi_board_list);
EXPORT_SYMBOL_GPL(hsi_board_list);
/**
* hsi_register_board_info - Register HSI clients information
* @info: Array of HSI clients on the board
* @len: Length of the array
*
* HSI clients are statically declared and registered on board files.
*
* HSI clients will be automatically registered to the HSI bus once the
* controller and the port where the clients wishes to attach are registered
* to it.
*
* Return -errno on failure, 0 on success.
*/
int __init hsi_register_board_info(struct hsi_board_info const *info,
unsigned int len)
{
struct hsi_cl_info *cl_info;
cl_info = kzalloc(sizeof(*cl_info) * len, GFP_KERNEL);
if (!cl_info)
return -ENOMEM;
for (; len; len--, info++, cl_info++) {
cl_info->info = *info;
list_add_tail(&cl_info->list, &hsi_board_list);
}
return 0;
}
| gpl-2.0 |
neighborhoodhacker/msm-3.4 | drivers/media/video/sn9c102/sn9c102_pas202bcb.c | 11082 | 9205 | /***************************************************************************
* Plug-in for PAS202BCB image sensor connected to the SN9C1xx PC Camera *
* Controllers *
* *
* Copyright (C) 2004 by Carlos Eduardo Medaglia Dyonisio *
* <medaglia@undl.org.br> *
* *
* Support for SN9C103, DAC Magnitude, exposure and green gain controls *
* added by Luca Risolia <luca.risolia@studio.unibo.it> *
* *
* 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/delay.h>
#include "sn9c102_sensor.h"
#include "sn9c102_devtable.h"
static int pas202bcb_init(struct sn9c102_device* cam)
{
int err = 0;
switch (sn9c102_get_bridge(cam)) {
case BRIDGE_SN9C101:
case BRIDGE_SN9C102:
err = sn9c102_write_const_regs(cam, {0x00, 0x10}, {0x00, 0x11},
{0x00, 0x14}, {0x20, 0x17},
{0x30, 0x19}, {0x09, 0x18});
break;
case BRIDGE_SN9C103:
err = sn9c102_write_const_regs(cam, {0x00, 0x02}, {0x00, 0x03},
{0x1a, 0x04}, {0x20, 0x05},
{0x20, 0x06}, {0x20, 0x07},
{0x00, 0x10}, {0x00, 0x11},
{0x00, 0x14}, {0x20, 0x17},
{0x30, 0x19}, {0x09, 0x18},
{0x02, 0x1c}, {0x03, 0x1d},
{0x0f, 0x1e}, {0x0c, 0x1f},
{0x00, 0x20}, {0x10, 0x21},
{0x20, 0x22}, {0x30, 0x23},
{0x40, 0x24}, {0x50, 0x25},
{0x60, 0x26}, {0x70, 0x27},
{0x80, 0x28}, {0x90, 0x29},
{0xa0, 0x2a}, {0xb0, 0x2b},
{0xc0, 0x2c}, {0xd0, 0x2d},
{0xe0, 0x2e}, {0xf0, 0x2f},
{0xff, 0x30});
break;
default:
break;
}
err += sn9c102_i2c_write(cam, 0x02, 0x14);
err += sn9c102_i2c_write(cam, 0x03, 0x40);
err += sn9c102_i2c_write(cam, 0x0d, 0x2c);
err += sn9c102_i2c_write(cam, 0x0e, 0x01);
err += sn9c102_i2c_write(cam, 0x0f, 0xa9);
err += sn9c102_i2c_write(cam, 0x10, 0x08);
err += sn9c102_i2c_write(cam, 0x13, 0x63);
err += sn9c102_i2c_write(cam, 0x15, 0x70);
err += sn9c102_i2c_write(cam, 0x11, 0x01);
msleep(400);
return err;
}
static int pas202bcb_get_ctrl(struct sn9c102_device* cam,
struct v4l2_control* ctrl)
{
switch (ctrl->id) {
case V4L2_CID_EXPOSURE:
{
int r1 = sn9c102_i2c_read(cam, 0x04),
r2 = sn9c102_i2c_read(cam, 0x05);
if (r1 < 0 || r2 < 0)
return -EIO;
ctrl->value = (r1 << 6) | (r2 & 0x3f);
}
return 0;
case V4L2_CID_RED_BALANCE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x09)) < 0)
return -EIO;
ctrl->value &= 0x0f;
return 0;
case V4L2_CID_BLUE_BALANCE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x07)) < 0)
return -EIO;
ctrl->value &= 0x0f;
return 0;
case V4L2_CID_GAIN:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x10)) < 0)
return -EIO;
ctrl->value &= 0x1f;
return 0;
case SN9C102_V4L2_CID_GREEN_BALANCE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x08)) < 0)
return -EIO;
ctrl->value &= 0x0f;
return 0;
case SN9C102_V4L2_CID_DAC_MAGNITUDE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x0c)) < 0)
return -EIO;
return 0;
default:
return -EINVAL;
}
}
static int pas202bcb_set_pix_format(struct sn9c102_device* cam,
const struct v4l2_pix_format* pix)
{
int err = 0;
if (pix->pixelformat == V4L2_PIX_FMT_SN9C10X)
err += sn9c102_write_reg(cam, 0x28, 0x17);
else
err += sn9c102_write_reg(cam, 0x20, 0x17);
return err;
}
static int pas202bcb_set_ctrl(struct sn9c102_device* cam,
const struct v4l2_control* ctrl)
{
int err = 0;
switch (ctrl->id) {
case V4L2_CID_EXPOSURE:
err += sn9c102_i2c_write(cam, 0x04, ctrl->value >> 6);
err += sn9c102_i2c_write(cam, 0x05, ctrl->value & 0x3f);
break;
case V4L2_CID_RED_BALANCE:
err += sn9c102_i2c_write(cam, 0x09, ctrl->value);
break;
case V4L2_CID_BLUE_BALANCE:
err += sn9c102_i2c_write(cam, 0x07, ctrl->value);
break;
case V4L2_CID_GAIN:
err += sn9c102_i2c_write(cam, 0x10, ctrl->value);
break;
case SN9C102_V4L2_CID_GREEN_BALANCE:
err += sn9c102_i2c_write(cam, 0x08, ctrl->value);
break;
case SN9C102_V4L2_CID_DAC_MAGNITUDE:
err += sn9c102_i2c_write(cam, 0x0c, ctrl->value);
break;
default:
return -EINVAL;
}
err += sn9c102_i2c_write(cam, 0x11, 0x01);
return err ? -EIO : 0;
}
static int pas202bcb_set_crop(struct sn9c102_device* cam,
const struct v4l2_rect* rect)
{
struct sn9c102_sensor* s = sn9c102_get_sensor(cam);
int err = 0;
u8 h_start = 0,
v_start = (u8)(rect->top - s->cropcap.bounds.top) + 3;
switch (sn9c102_get_bridge(cam)) {
case BRIDGE_SN9C101:
case BRIDGE_SN9C102:
h_start = (u8)(rect->left - s->cropcap.bounds.left) + 4;
break;
case BRIDGE_SN9C103:
h_start = (u8)(rect->left - s->cropcap.bounds.left) + 3;
break;
default:
break;
}
err += sn9c102_write_reg(cam, h_start, 0x12);
err += sn9c102_write_reg(cam, v_start, 0x13);
return err;
}
static const struct sn9c102_sensor pas202bcb = {
.name = "PAS202BCB",
.maintainer = "Luca Risolia <luca.risolia@studio.unibo.it>",
.supported_bridge = BRIDGE_SN9C101 | BRIDGE_SN9C102 | BRIDGE_SN9C103,
.sysfs_ops = SN9C102_I2C_READ | SN9C102_I2C_WRITE,
.frequency = SN9C102_I2C_400KHZ | SN9C102_I2C_100KHZ,
.interface = SN9C102_I2C_2WIRES,
.i2c_slave_id = 0x40,
.init = &pas202bcb_init,
.qctrl = {
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "exposure",
.minimum = 0x01e5,
.maximum = 0x3fff,
.step = 0x0001,
.default_value = 0x01e5,
.flags = 0,
},
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "global gain",
.minimum = 0x00,
.maximum = 0x1f,
.step = 0x01,
.default_value = 0x0b,
.flags = 0,
},
{
.id = V4L2_CID_RED_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "red balance",
.minimum = 0x00,
.maximum = 0x0f,
.step = 0x01,
.default_value = 0x00,
.flags = 0,
},
{
.id = V4L2_CID_BLUE_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "blue balance",
.minimum = 0x00,
.maximum = 0x0f,
.step = 0x01,
.default_value = 0x05,
.flags = 0,
},
{
.id = SN9C102_V4L2_CID_GREEN_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "green balance",
.minimum = 0x00,
.maximum = 0x0f,
.step = 0x01,
.default_value = 0x00,
.flags = 0,
},
{
.id = SN9C102_V4L2_CID_DAC_MAGNITUDE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "DAC magnitude",
.minimum = 0x00,
.maximum = 0xff,
.step = 0x01,
.default_value = 0x04,
.flags = 0,
},
},
.get_ctrl = &pas202bcb_get_ctrl,
.set_ctrl = &pas202bcb_set_ctrl,
.cropcap = {
.bounds = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
.defrect = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
},
.set_crop = &pas202bcb_set_crop,
.pix_format = {
.width = 640,
.height = 480,
.pixelformat = V4L2_PIX_FMT_SBGGR8,
.priv = 8,
},
.set_pix_format = &pas202bcb_set_pix_format
};
int sn9c102_probe_pas202bcb(struct sn9c102_device* cam)
{
int r0 = 0, r1 = 0, err = 0;
unsigned int pid = 0;
/*
* Minimal initialization to enable the I2C communication
* NOTE: do NOT change the values!
*/
switch (sn9c102_get_bridge(cam)) {
case BRIDGE_SN9C101:
case BRIDGE_SN9C102:
err = sn9c102_write_const_regs(cam,
{0x01, 0x01}, /* power down */
{0x40, 0x01}, /* power on */
{0x28, 0x17});/* clock 24 MHz */
break;
case BRIDGE_SN9C103: /* do _not_ change anything! */
err = sn9c102_write_const_regs(cam, {0x09, 0x01}, {0x44, 0x01},
{0x44, 0x02}, {0x29, 0x17});
break;
default:
break;
}
r0 = sn9c102_i2c_try_read(cam, &pas202bcb, 0x00);
r1 = sn9c102_i2c_try_read(cam, &pas202bcb, 0x01);
if (err || r0 < 0 || r1 < 0)
return -EIO;
pid = (r0 << 4) | ((r1 & 0xf0) >> 4);
if (pid != 0x017)
return -ENODEV;
sn9c102_attach_sensor(cam, &pas202bcb);
return 0;
}
| gpl-2.0 |
Luquidtester/DirtyKernel-3.0.101 | drivers/media/video/sn9c102/sn9c102_pas202bcb.c | 11082 | 9205 | /***************************************************************************
* Plug-in for PAS202BCB image sensor connected to the SN9C1xx PC Camera *
* Controllers *
* *
* Copyright (C) 2004 by Carlos Eduardo Medaglia Dyonisio *
* <medaglia@undl.org.br> *
* *
* Support for SN9C103, DAC Magnitude, exposure and green gain controls *
* added by Luca Risolia <luca.risolia@studio.unibo.it> *
* *
* 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/delay.h>
#include "sn9c102_sensor.h"
#include "sn9c102_devtable.h"
static int pas202bcb_init(struct sn9c102_device* cam)
{
int err = 0;
switch (sn9c102_get_bridge(cam)) {
case BRIDGE_SN9C101:
case BRIDGE_SN9C102:
err = sn9c102_write_const_regs(cam, {0x00, 0x10}, {0x00, 0x11},
{0x00, 0x14}, {0x20, 0x17},
{0x30, 0x19}, {0x09, 0x18});
break;
case BRIDGE_SN9C103:
err = sn9c102_write_const_regs(cam, {0x00, 0x02}, {0x00, 0x03},
{0x1a, 0x04}, {0x20, 0x05},
{0x20, 0x06}, {0x20, 0x07},
{0x00, 0x10}, {0x00, 0x11},
{0x00, 0x14}, {0x20, 0x17},
{0x30, 0x19}, {0x09, 0x18},
{0x02, 0x1c}, {0x03, 0x1d},
{0x0f, 0x1e}, {0x0c, 0x1f},
{0x00, 0x20}, {0x10, 0x21},
{0x20, 0x22}, {0x30, 0x23},
{0x40, 0x24}, {0x50, 0x25},
{0x60, 0x26}, {0x70, 0x27},
{0x80, 0x28}, {0x90, 0x29},
{0xa0, 0x2a}, {0xb0, 0x2b},
{0xc0, 0x2c}, {0xd0, 0x2d},
{0xe0, 0x2e}, {0xf0, 0x2f},
{0xff, 0x30});
break;
default:
break;
}
err += sn9c102_i2c_write(cam, 0x02, 0x14);
err += sn9c102_i2c_write(cam, 0x03, 0x40);
err += sn9c102_i2c_write(cam, 0x0d, 0x2c);
err += sn9c102_i2c_write(cam, 0x0e, 0x01);
err += sn9c102_i2c_write(cam, 0x0f, 0xa9);
err += sn9c102_i2c_write(cam, 0x10, 0x08);
err += sn9c102_i2c_write(cam, 0x13, 0x63);
err += sn9c102_i2c_write(cam, 0x15, 0x70);
err += sn9c102_i2c_write(cam, 0x11, 0x01);
msleep(400);
return err;
}
static int pas202bcb_get_ctrl(struct sn9c102_device* cam,
struct v4l2_control* ctrl)
{
switch (ctrl->id) {
case V4L2_CID_EXPOSURE:
{
int r1 = sn9c102_i2c_read(cam, 0x04),
r2 = sn9c102_i2c_read(cam, 0x05);
if (r1 < 0 || r2 < 0)
return -EIO;
ctrl->value = (r1 << 6) | (r2 & 0x3f);
}
return 0;
case V4L2_CID_RED_BALANCE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x09)) < 0)
return -EIO;
ctrl->value &= 0x0f;
return 0;
case V4L2_CID_BLUE_BALANCE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x07)) < 0)
return -EIO;
ctrl->value &= 0x0f;
return 0;
case V4L2_CID_GAIN:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x10)) < 0)
return -EIO;
ctrl->value &= 0x1f;
return 0;
case SN9C102_V4L2_CID_GREEN_BALANCE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x08)) < 0)
return -EIO;
ctrl->value &= 0x0f;
return 0;
case SN9C102_V4L2_CID_DAC_MAGNITUDE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x0c)) < 0)
return -EIO;
return 0;
default:
return -EINVAL;
}
}
static int pas202bcb_set_pix_format(struct sn9c102_device* cam,
const struct v4l2_pix_format* pix)
{
int err = 0;
if (pix->pixelformat == V4L2_PIX_FMT_SN9C10X)
err += sn9c102_write_reg(cam, 0x28, 0x17);
else
err += sn9c102_write_reg(cam, 0x20, 0x17);
return err;
}
static int pas202bcb_set_ctrl(struct sn9c102_device* cam,
const struct v4l2_control* ctrl)
{
int err = 0;
switch (ctrl->id) {
case V4L2_CID_EXPOSURE:
err += sn9c102_i2c_write(cam, 0x04, ctrl->value >> 6);
err += sn9c102_i2c_write(cam, 0x05, ctrl->value & 0x3f);
break;
case V4L2_CID_RED_BALANCE:
err += sn9c102_i2c_write(cam, 0x09, ctrl->value);
break;
case V4L2_CID_BLUE_BALANCE:
err += sn9c102_i2c_write(cam, 0x07, ctrl->value);
break;
case V4L2_CID_GAIN:
err += sn9c102_i2c_write(cam, 0x10, ctrl->value);
break;
case SN9C102_V4L2_CID_GREEN_BALANCE:
err += sn9c102_i2c_write(cam, 0x08, ctrl->value);
break;
case SN9C102_V4L2_CID_DAC_MAGNITUDE:
err += sn9c102_i2c_write(cam, 0x0c, ctrl->value);
break;
default:
return -EINVAL;
}
err += sn9c102_i2c_write(cam, 0x11, 0x01);
return err ? -EIO : 0;
}
static int pas202bcb_set_crop(struct sn9c102_device* cam,
const struct v4l2_rect* rect)
{
struct sn9c102_sensor* s = sn9c102_get_sensor(cam);
int err = 0;
u8 h_start = 0,
v_start = (u8)(rect->top - s->cropcap.bounds.top) + 3;
switch (sn9c102_get_bridge(cam)) {
case BRIDGE_SN9C101:
case BRIDGE_SN9C102:
h_start = (u8)(rect->left - s->cropcap.bounds.left) + 4;
break;
case BRIDGE_SN9C103:
h_start = (u8)(rect->left - s->cropcap.bounds.left) + 3;
break;
default:
break;
}
err += sn9c102_write_reg(cam, h_start, 0x12);
err += sn9c102_write_reg(cam, v_start, 0x13);
return err;
}
static const struct sn9c102_sensor pas202bcb = {
.name = "PAS202BCB",
.maintainer = "Luca Risolia <luca.risolia@studio.unibo.it>",
.supported_bridge = BRIDGE_SN9C101 | BRIDGE_SN9C102 | BRIDGE_SN9C103,
.sysfs_ops = SN9C102_I2C_READ | SN9C102_I2C_WRITE,
.frequency = SN9C102_I2C_400KHZ | SN9C102_I2C_100KHZ,
.interface = SN9C102_I2C_2WIRES,
.i2c_slave_id = 0x40,
.init = &pas202bcb_init,
.qctrl = {
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "exposure",
.minimum = 0x01e5,
.maximum = 0x3fff,
.step = 0x0001,
.default_value = 0x01e5,
.flags = 0,
},
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "global gain",
.minimum = 0x00,
.maximum = 0x1f,
.step = 0x01,
.default_value = 0x0b,
.flags = 0,
},
{
.id = V4L2_CID_RED_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "red balance",
.minimum = 0x00,
.maximum = 0x0f,
.step = 0x01,
.default_value = 0x00,
.flags = 0,
},
{
.id = V4L2_CID_BLUE_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "blue balance",
.minimum = 0x00,
.maximum = 0x0f,
.step = 0x01,
.default_value = 0x05,
.flags = 0,
},
{
.id = SN9C102_V4L2_CID_GREEN_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "green balance",
.minimum = 0x00,
.maximum = 0x0f,
.step = 0x01,
.default_value = 0x00,
.flags = 0,
},
{
.id = SN9C102_V4L2_CID_DAC_MAGNITUDE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "DAC magnitude",
.minimum = 0x00,
.maximum = 0xff,
.step = 0x01,
.default_value = 0x04,
.flags = 0,
},
},
.get_ctrl = &pas202bcb_get_ctrl,
.set_ctrl = &pas202bcb_set_ctrl,
.cropcap = {
.bounds = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
.defrect = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
},
.set_crop = &pas202bcb_set_crop,
.pix_format = {
.width = 640,
.height = 480,
.pixelformat = V4L2_PIX_FMT_SBGGR8,
.priv = 8,
},
.set_pix_format = &pas202bcb_set_pix_format
};
int sn9c102_probe_pas202bcb(struct sn9c102_device* cam)
{
int r0 = 0, r1 = 0, err = 0;
unsigned int pid = 0;
/*
* Minimal initialization to enable the I2C communication
* NOTE: do NOT change the values!
*/
switch (sn9c102_get_bridge(cam)) {
case BRIDGE_SN9C101:
case BRIDGE_SN9C102:
err = sn9c102_write_const_regs(cam,
{0x01, 0x01}, /* power down */
{0x40, 0x01}, /* power on */
{0x28, 0x17});/* clock 24 MHz */
break;
case BRIDGE_SN9C103: /* do _not_ change anything! */
err = sn9c102_write_const_regs(cam, {0x09, 0x01}, {0x44, 0x01},
{0x44, 0x02}, {0x29, 0x17});
break;
default:
break;
}
r0 = sn9c102_i2c_try_read(cam, &pas202bcb, 0x00);
r1 = sn9c102_i2c_try_read(cam, &pas202bcb, 0x01);
if (err || r0 < 0 || r1 < 0)
return -EIO;
pid = (r0 << 4) | ((r1 & 0xf0) >> 4);
if (pid != 0x017)
return -ENODEV;
sn9c102_attach_sensor(cam, &pas202bcb);
return 0;
}
| gpl-2.0 |
DirtyDevs/android_kernel_motorola_ghost | kernel/cpu.c | 75 | 16333 | /* CPU control.
* (C) 2001, 2002, 2003, 2004 Rusty Russell
*
* This code is licenced under the GPL.
*/
#include <linux/proc_fs.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/notifier.h>
#include <linux/sched.h>
#include <linux/unistd.h>
#include <linux/cpu.h>
#include <linux/export.h>
#include <linux/kthread.h>
#include <linux/stop_machine.h>
#include <linux/mutex.h>
#include <linux/gfp.h>
#include <linux/suspend.h>
#ifdef CONFIG_SMP
/* Serializes the updates to cpu_online_mask, cpu_present_mask */
static DEFINE_MUTEX(cpu_add_remove_lock);
/*
* The following two API's must be used when attempting
* to serialize the updates to cpu_online_mask, cpu_present_mask.
*/
void cpu_maps_update_begin(void)
{
mutex_lock(&cpu_add_remove_lock);
}
void cpu_maps_update_done(void)
{
mutex_unlock(&cpu_add_remove_lock);
}
static RAW_NOTIFIER_HEAD(cpu_chain);
/* If set, cpu_up and cpu_down will return -EBUSY and do nothing.
* Should always be manipulated under cpu_add_remove_lock
*/
static int cpu_hotplug_disabled;
#ifdef CONFIG_HOTPLUG_CPU
static struct {
struct task_struct *active_writer;
struct mutex lock; /* Synchronizes accesses to refcount, */
/*
* Also blocks the new readers during
* an ongoing cpu hotplug operation.
*/
int refcount;
} cpu_hotplug = {
.active_writer = NULL,
.lock = __MUTEX_INITIALIZER(cpu_hotplug.lock),
.refcount = 0,
};
void get_online_cpus(void)
{
might_sleep();
if (cpu_hotplug.active_writer == current)
return;
mutex_lock(&cpu_hotplug.lock);
cpu_hotplug.refcount++;
mutex_unlock(&cpu_hotplug.lock);
}
EXPORT_SYMBOL_GPL(get_online_cpus);
void put_online_cpus(void)
{
if (cpu_hotplug.active_writer == current)
return;
mutex_lock(&cpu_hotplug.lock);
if (!--cpu_hotplug.refcount && unlikely(cpu_hotplug.active_writer))
wake_up_process(cpu_hotplug.active_writer);
mutex_unlock(&cpu_hotplug.lock);
}
EXPORT_SYMBOL_GPL(put_online_cpus);
/*
* This ensures that the hotplug operation can begin only when the
* refcount goes to zero.
*
* Note that during a cpu-hotplug operation, the new readers, if any,
* will be blocked by the cpu_hotplug.lock
*
* Since cpu_hotplug_begin() is always called after invoking
* cpu_maps_update_begin(), we can be sure that only one writer is active.
*
* Note that theoretically, there is a possibility of a livelock:
* - Refcount goes to zero, last reader wakes up the sleeping
* writer.
* - Last reader unlocks the cpu_hotplug.lock.
* - A new reader arrives at this moment, bumps up the refcount.
* - The writer acquires the cpu_hotplug.lock finds the refcount
* non zero and goes to sleep again.
*
* However, this is very difficult to achieve in practice since
* get_online_cpus() not an api which is called all that often.
*
*/
static void cpu_hotplug_begin(void)
{
cpu_hotplug.active_writer = current;
for (;;) {
mutex_lock(&cpu_hotplug.lock);
if (likely(!cpu_hotplug.refcount))
break;
__set_current_state(TASK_UNINTERRUPTIBLE);
mutex_unlock(&cpu_hotplug.lock);
schedule();
}
}
static void cpu_hotplug_done(void)
{
cpu_hotplug.active_writer = NULL;
mutex_unlock(&cpu_hotplug.lock);
}
/*
* Wait for currently running CPU hotplug operations to complete (if any) and
* disable future CPU hotplug (from sysfs). The 'cpu_add_remove_lock' protects
* the 'cpu_hotplug_disabled' flag. The same lock is also acquired by the
* hotplug path before performing hotplug operations. So acquiring that lock
* guarantees mutual exclusion from any currently running hotplug operations.
*/
void cpu_hotplug_disable(void)
{
cpu_maps_update_begin();
cpu_hotplug_disabled = 1;
cpu_maps_update_done();
}
void cpu_hotplug_enable(void)
{
cpu_maps_update_begin();
cpu_hotplug_disabled = 0;
cpu_maps_update_done();
}
#else /* #if CONFIG_HOTPLUG_CPU */
static void cpu_hotplug_begin(void) {}
static void cpu_hotplug_done(void) {}
#endif /* #else #if CONFIG_HOTPLUG_CPU */
/* Need to know about CPUs going up/down? */
int __ref register_cpu_notifier(struct notifier_block *nb)
{
int ret;
cpu_maps_update_begin();
ret = raw_notifier_chain_register(&cpu_chain, nb);
cpu_maps_update_done();
return ret;
}
static int __cpu_notify(unsigned long val, void *v, int nr_to_call,
int *nr_calls)
{
int ret;
ret = __raw_notifier_call_chain(&cpu_chain, val, v, nr_to_call,
nr_calls);
return notifier_to_errno(ret);
}
static int cpu_notify(unsigned long val, void *v)
{
return __cpu_notify(val, v, -1, NULL);
}
#ifdef CONFIG_HOTPLUG_CPU
static void cpu_notify_nofail(unsigned long val, void *v)
{
BUG_ON(cpu_notify(val, v));
}
EXPORT_SYMBOL(register_cpu_notifier);
void __ref unregister_cpu_notifier(struct notifier_block *nb)
{
cpu_maps_update_begin();
raw_notifier_chain_unregister(&cpu_chain, nb);
cpu_maps_update_done();
}
EXPORT_SYMBOL(unregister_cpu_notifier);
static inline void check_for_tasks(int cpu)
{
struct task_struct *p;
write_lock_irq(&tasklist_lock);
for_each_process(p) {
if (task_cpu(p) == cpu && p->state == TASK_RUNNING &&
(p->utime || p->stime))
printk(KERN_WARNING "Task %s (pid = %d) is on cpu %d "
"(state = %ld, flags = %x)\n",
p->comm, task_pid_nr(p), cpu,
p->state, p->flags);
}
write_unlock_irq(&tasklist_lock);
}
struct take_cpu_down_param {
unsigned long mod;
void *hcpu;
};
/* Take this CPU down. */
static int __ref take_cpu_down(void *_param)
{
struct take_cpu_down_param *param = _param;
int err;
/* Ensure this CPU doesn't handle any more interrupts. */
err = __cpu_disable();
if (err < 0)
return err;
cpu_notify(CPU_DYING | param->mod, param->hcpu);
return 0;
}
/* Requires cpu_add_remove_lock to be held */
static int __ref _cpu_down(unsigned int cpu, int tasks_frozen)
{
int err, nr_calls = 0;
void *hcpu = (void *)(long)cpu;
unsigned long mod = tasks_frozen ? CPU_TASKS_FROZEN : 0;
struct take_cpu_down_param tcd_param = {
.mod = mod,
.hcpu = hcpu,
};
if (num_online_cpus() == 1)
return -EBUSY;
if (!cpu_online(cpu))
return -EINVAL;
cpu_hotplug_begin();
err = __cpu_notify(CPU_DOWN_PREPARE | mod, hcpu, -1, &nr_calls);
if (err) {
nr_calls--;
__cpu_notify(CPU_DOWN_FAILED | mod, hcpu, nr_calls, NULL);
printk("%s: attempt to take down CPU %u failed\n",
__func__, cpu);
goto out_release;
}
err = __stop_machine(take_cpu_down, &tcd_param, cpumask_of(cpu));
if (err) {
/* CPU didn't die: tell everyone. Can't complain. */
cpu_notify_nofail(CPU_DOWN_FAILED | mod, hcpu);
goto out_release;
}
BUG_ON(cpu_online(cpu));
/*
* The migration_call() CPU_DYING callback will have removed all
* runnable tasks from the cpu, there's only the idle task left now
* that the migration thread is done doing the stop_machine thing.
*
* Wait for the stop thread to go away.
*/
while (!idle_cpu(cpu))
cpu_relax();
/* This actually kills the CPU. */
__cpu_die(cpu);
/* CPU is completely dead: tell everyone. Too late to complain. */
cpu_notify_nofail(CPU_DEAD | mod, hcpu);
check_for_tasks(cpu);
out_release:
cpu_hotplug_done();
if (!err)
cpu_notify_nofail(CPU_POST_DEAD | mod, hcpu);
return err;
}
int __ref cpu_down(unsigned int cpu)
{
int err;
cpu_maps_update_begin();
if (cpu_hotplug_disabled) {
err = -EBUSY;
goto out;
}
err = _cpu_down(cpu, 0);
out:
cpu_maps_update_done();
return err;
}
EXPORT_SYMBOL(cpu_down);
#endif /*CONFIG_HOTPLUG_CPU*/
/* Requires cpu_add_remove_lock to be held */
static int __cpuinit _cpu_up(unsigned int cpu, int tasks_frozen)
{
int ret, nr_calls = 0;
void *hcpu = (void *)(long)cpu;
unsigned long mod = tasks_frozen ? CPU_TASKS_FROZEN : 0;
if (cpu_online(cpu) || !cpu_present(cpu))
return -EINVAL;
cpu_hotplug_begin();
ret = __cpu_notify(CPU_UP_PREPARE | mod, hcpu, -1, &nr_calls);
if (ret) {
nr_calls--;
printk(KERN_WARNING "%s: attempt to bring up CPU %u failed\n",
__func__, cpu);
goto out_notify;
}
/* Arch-specific enabling code. */
ret = __cpu_up(cpu);
if (ret != 0)
goto out_notify;
BUG_ON(!cpu_online(cpu));
/* Now call notifier in preparation. */
cpu_notify(CPU_ONLINE | mod, hcpu);
out_notify:
if (ret != 0)
__cpu_notify(CPU_UP_CANCELED | mod, hcpu, nr_calls, NULL);
cpu_hotplug_done();
return ret;
}
int __cpuinit cpu_up(unsigned int cpu)
{
int err = 0;
#ifdef CONFIG_MEMORY_HOTPLUG
int nid;
pg_data_t *pgdat;
#endif
if (!cpu_possible(cpu)) {
printk(KERN_ERR "can't online cpu %d because it is not "
"configured as may-hotadd at boot time\n", cpu);
#if defined(CONFIG_IA64)
printk(KERN_ERR "please check additional_cpus= boot "
"parameter\n");
#endif
return -EINVAL;
}
#ifdef CONFIG_MEMORY_HOTPLUG
nid = cpu_to_node(cpu);
if (!node_online(nid)) {
err = mem_online_node(nid);
if (err)
return err;
}
pgdat = NODE_DATA(nid);
if (!pgdat) {
printk(KERN_ERR
"Can't online cpu %d due to NULL pgdat\n", cpu);
return -ENOMEM;
}
if (pgdat->node_zonelists->_zonerefs->zone == NULL) {
mutex_lock(&zonelists_mutex);
build_all_zonelists(NULL);
mutex_unlock(&zonelists_mutex);
}
#endif
cpu_maps_update_begin();
if (cpu_hotplug_disabled) {
err = -EBUSY;
goto out;
}
err = _cpu_up(cpu, 0);
out:
cpu_maps_update_done();
return err;
}
EXPORT_SYMBOL_GPL(cpu_up);
#ifdef CONFIG_PM_SLEEP_SMP
static cpumask_var_t frozen_cpus;
void __weak arch_disable_nonboot_cpus_begin(void)
{
}
void __weak arch_disable_nonboot_cpus_end(void)
{
}
int disable_nonboot_cpus(void)
{
int cpu, first_cpu, error = 0;
cpu_maps_update_begin();
first_cpu = cpumask_first(cpu_online_mask);
/*
* We take down all of the non-boot CPUs in one shot to avoid races
* with the userspace trying to use the CPU hotplug at the same time
*/
cpumask_clear(frozen_cpus);
arch_disable_nonboot_cpus_begin();
printk("Disabling non-boot CPUs ...\n");
for_each_online_cpu(cpu) {
if (cpu == first_cpu)
continue;
error = _cpu_down(cpu, 1);
if (!error)
cpumask_set_cpu(cpu, frozen_cpus);
else {
printk(KERN_ERR "Error taking CPU%d down: %d\n",
cpu, error);
break;
}
}
arch_disable_nonboot_cpus_end();
if (!error) {
BUG_ON(num_online_cpus() > 1);
/* Make sure the CPUs won't be enabled by someone else */
cpu_hotplug_disabled = 1;
} else {
printk(KERN_ERR "Non-boot CPUs are not disabled\n");
}
cpu_maps_update_done();
return error;
}
void __weak arch_enable_nonboot_cpus_begin(void)
{
}
void __weak arch_enable_nonboot_cpus_end(void)
{
}
void __ref enable_nonboot_cpus(void)
{
int cpu, error;
/* Allow everyone to use the CPU hotplug again */
cpu_maps_update_begin();
cpu_hotplug_disabled = 0;
if (cpumask_empty(frozen_cpus))
goto out;
printk(KERN_INFO "Enabling non-boot CPUs ...\n");
arch_enable_nonboot_cpus_begin();
for_each_cpu(cpu, frozen_cpus) {
error = _cpu_up(cpu, 1);
if (!error) {
printk(KERN_INFO "CPU%d is up\n", cpu);
continue;
}
printk(KERN_WARNING "Error taking CPU%d up: %d\n", cpu, error);
}
arch_enable_nonboot_cpus_end();
cpumask_clear(frozen_cpus);
out:
cpu_maps_update_done();
}
static int __init alloc_frozen_cpus(void)
{
if (!alloc_cpumask_var(&frozen_cpus, GFP_KERNEL|__GFP_ZERO))
return -ENOMEM;
return 0;
}
core_initcall(alloc_frozen_cpus);
/*
* When callbacks for CPU hotplug notifications are being executed, we must
* ensure that the state of the system with respect to the tasks being frozen
* or not, as reported by the notification, remains unchanged *throughout the
* duration* of the execution of the callbacks.
* Hence we need to prevent the freezer from racing with regular CPU hotplug.
*
* This synchronization is implemented by mutually excluding regular CPU
* hotplug and Suspend/Hibernate call paths by hooking onto the Suspend/
* Hibernate notifications.
*/
static int
cpu_hotplug_pm_callback(struct notifier_block *nb,
unsigned long action, void *ptr)
{
switch (action) {
case PM_SUSPEND_PREPARE:
case PM_HIBERNATION_PREPARE:
cpu_hotplug_disable();
break;
case PM_POST_SUSPEND:
case PM_POST_HIBERNATION:
cpu_hotplug_enable();
break;
default:
return NOTIFY_DONE;
}
return NOTIFY_OK;
}
static int __init cpu_hotplug_pm_sync_init(void)
{
pm_notifier(cpu_hotplug_pm_callback, 0);
return 0;
}
core_initcall(cpu_hotplug_pm_sync_init);
#endif /* CONFIG_PM_SLEEP_SMP */
/**
* notify_cpu_starting(cpu) - call the CPU_STARTING notifiers
* @cpu: cpu that just started
*
* This function calls the cpu_chain notifiers with CPU_STARTING.
* It must be called by the arch code on the new cpu, before the new cpu
* enables interrupts and before the "boot" cpu returns from __cpu_up().
*/
void __cpuinit notify_cpu_starting(unsigned int cpu)
{
unsigned long val = CPU_STARTING;
#ifdef CONFIG_PM_SLEEP_SMP
if (frozen_cpus != NULL && cpumask_test_cpu(cpu, frozen_cpus))
val = CPU_STARTING_FROZEN;
#endif /* CONFIG_PM_SLEEP_SMP */
cpu_notify(val, (void *)(long)cpu);
}
#endif /* CONFIG_SMP */
/*
* cpu_bit_bitmap[] is a special, "compressed" data structure that
* represents all NR_CPUS bits binary values of 1<<nr.
*
* It is used by cpumask_of() to get a constant address to a CPU
* mask value that has a single bit set only.
*/
/* cpu_bit_bitmap[0] is empty - so we can back into it */
#define MASK_DECLARE_1(x) [x+1][0] = (1UL << (x))
#define MASK_DECLARE_2(x) MASK_DECLARE_1(x), MASK_DECLARE_1(x+1)
#define MASK_DECLARE_4(x) MASK_DECLARE_2(x), MASK_DECLARE_2(x+2)
#define MASK_DECLARE_8(x) MASK_DECLARE_4(x), MASK_DECLARE_4(x+4)
const unsigned long cpu_bit_bitmap[BITS_PER_LONG+1][BITS_TO_LONGS(NR_CPUS)] = {
MASK_DECLARE_8(0), MASK_DECLARE_8(8),
MASK_DECLARE_8(16), MASK_DECLARE_8(24),
#if BITS_PER_LONG > 32
MASK_DECLARE_8(32), MASK_DECLARE_8(40),
MASK_DECLARE_8(48), MASK_DECLARE_8(56),
#endif
};
EXPORT_SYMBOL_GPL(cpu_bit_bitmap);
const DECLARE_BITMAP(cpu_all_bits, NR_CPUS) = CPU_BITS_ALL;
EXPORT_SYMBOL(cpu_all_bits);
#ifdef CONFIG_INIT_ALL_POSSIBLE
static DECLARE_BITMAP(cpu_possible_bits, CONFIG_NR_CPUS) __read_mostly
= CPU_BITS_ALL;
#else
static DECLARE_BITMAP(cpu_possible_bits, CONFIG_NR_CPUS) __read_mostly;
#endif
const struct cpumask *const cpu_possible_mask = to_cpumask(cpu_possible_bits);
EXPORT_SYMBOL(cpu_possible_mask);
static DECLARE_BITMAP(cpu_online_bits, CONFIG_NR_CPUS) __read_mostly;
const struct cpumask *const cpu_online_mask = to_cpumask(cpu_online_bits);
EXPORT_SYMBOL(cpu_online_mask);
static DECLARE_BITMAP(cpu_present_bits, CONFIG_NR_CPUS) __read_mostly;
const struct cpumask *const cpu_present_mask = to_cpumask(cpu_present_bits);
EXPORT_SYMBOL(cpu_present_mask);
static DECLARE_BITMAP(cpu_active_bits, CONFIG_NR_CPUS) __read_mostly;
const struct cpumask *const cpu_active_mask = to_cpumask(cpu_active_bits);
EXPORT_SYMBOL(cpu_active_mask);
void set_cpu_possible(unsigned int cpu, bool possible)
{
if (possible)
cpumask_set_cpu(cpu, to_cpumask(cpu_possible_bits));
else
cpumask_clear_cpu(cpu, to_cpumask(cpu_possible_bits));
}
void set_cpu_present(unsigned int cpu, bool present)
{
if (present)
cpumask_set_cpu(cpu, to_cpumask(cpu_present_bits));
else
cpumask_clear_cpu(cpu, to_cpumask(cpu_present_bits));
}
void set_cpu_online(unsigned int cpu, bool online)
{
if (online) {
cpumask_set_cpu(cpu, to_cpumask(cpu_online_bits));
cpumask_set_cpu(cpu, to_cpumask(cpu_active_bits));
} else {
cpumask_clear_cpu(cpu, to_cpumask(cpu_online_bits));
}
}
void set_cpu_active(unsigned int cpu, bool active)
{
if (active)
cpumask_set_cpu(cpu, to_cpumask(cpu_active_bits));
else
cpumask_clear_cpu(cpu, to_cpumask(cpu_active_bits));
}
void init_cpu_present(const struct cpumask *src)
{
cpumask_copy(to_cpumask(cpu_present_bits), src);
}
void init_cpu_possible(const struct cpumask *src)
{
cpumask_copy(to_cpumask(cpu_possible_bits), src);
}
void init_cpu_online(const struct cpumask *src)
{
cpumask_copy(to_cpumask(cpu_online_bits), src);
}
static ATOMIC_NOTIFIER_HEAD(idle_notifier);
void idle_notifier_register(struct notifier_block *n)
{
atomic_notifier_chain_register(&idle_notifier, n);
}
EXPORT_SYMBOL_GPL(idle_notifier_register);
void idle_notifier_unregister(struct notifier_block *n)
{
atomic_notifier_chain_unregister(&idle_notifier, n);
}
EXPORT_SYMBOL_GPL(idle_notifier_unregister);
void idle_notifier_call_chain(unsigned long val)
{
atomic_notifier_call_chain(&idle_notifier, val, NULL);
}
EXPORT_SYMBOL_GPL(idle_notifier_call_chain);
| gpl-2.0 |
volk3/CS736 | kernel/trace/trace_output.c | 75 | 26725 | /*
* trace_output.c
*
* Copyright (C) 2008 Red Hat Inc, Steven Rostedt <srostedt@redhat.com>
*
*/
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/ftrace.h>
#include "trace_output.h"
/* must be a power of 2 */
#define EVENT_HASHSIZE 128
DECLARE_RWSEM(trace_event_sem);
static struct hlist_head event_hash[EVENT_HASHSIZE] __read_mostly;
static int next_event_type = __TRACE_LAST_TYPE + 1;
enum print_line_t trace_print_bputs_msg_only(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
struct trace_entry *entry = iter->ent;
struct bputs_entry *field;
trace_assign_type(field, entry);
trace_seq_puts(s, field->str);
return trace_handle_return(s);
}
enum print_line_t trace_print_bprintk_msg_only(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
struct trace_entry *entry = iter->ent;
struct bprint_entry *field;
trace_assign_type(field, entry);
trace_seq_bprintf(s, field->fmt, field->buf);
return trace_handle_return(s);
}
enum print_line_t trace_print_printk_msg_only(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
struct trace_entry *entry = iter->ent;
struct print_entry *field;
trace_assign_type(field, entry);
trace_seq_puts(s, field->buf);
return trace_handle_return(s);
}
const char *
ftrace_print_flags_seq(struct trace_seq *p, const char *delim,
unsigned long flags,
const struct trace_print_flags *flag_array)
{
unsigned long mask;
const char *str;
const char *ret = trace_seq_buffer_ptr(p);
int i, first = 1;
for (i = 0; flag_array[i].name && flags; i++) {
mask = flag_array[i].mask;
if ((flags & mask) != mask)
continue;
str = flag_array[i].name;
flags &= ~mask;
if (!first && delim)
trace_seq_puts(p, delim);
else
first = 0;
trace_seq_puts(p, str);
}
/* check for left over flags */
if (flags) {
if (!first && delim)
trace_seq_puts(p, delim);
trace_seq_printf(p, "0x%lx", flags);
}
trace_seq_putc(p, 0);
return ret;
}
EXPORT_SYMBOL(ftrace_print_flags_seq);
const char *
ftrace_print_symbols_seq(struct trace_seq *p, unsigned long val,
const struct trace_print_flags *symbol_array)
{
int i;
const char *ret = trace_seq_buffer_ptr(p);
for (i = 0; symbol_array[i].name; i++) {
if (val != symbol_array[i].mask)
continue;
trace_seq_puts(p, symbol_array[i].name);
break;
}
if (ret == (const char *)(trace_seq_buffer_ptr(p)))
trace_seq_printf(p, "0x%lx", val);
trace_seq_putc(p, 0);
return ret;
}
EXPORT_SYMBOL(ftrace_print_symbols_seq);
#if BITS_PER_LONG == 32
const char *
ftrace_print_symbols_seq_u64(struct trace_seq *p, unsigned long long val,
const struct trace_print_flags_u64 *symbol_array)
{
int i;
const char *ret = trace_seq_buffer_ptr(p);
for (i = 0; symbol_array[i].name; i++) {
if (val != symbol_array[i].mask)
continue;
trace_seq_puts(p, symbol_array[i].name);
break;
}
if (ret == (const char *)(trace_seq_buffer_ptr(p)))
trace_seq_printf(p, "0x%llx", val);
trace_seq_putc(p, 0);
return ret;
}
EXPORT_SYMBOL(ftrace_print_symbols_seq_u64);
#endif
const char *
ftrace_print_bitmask_seq(struct trace_seq *p, void *bitmask_ptr,
unsigned int bitmask_size)
{
const char *ret = trace_seq_buffer_ptr(p);
trace_seq_bitmask(p, bitmask_ptr, bitmask_size * 8);
trace_seq_putc(p, 0);
return ret;
}
EXPORT_SYMBOL_GPL(ftrace_print_bitmask_seq);
const char *
ftrace_print_hex_seq(struct trace_seq *p, const unsigned char *buf, int buf_len)
{
int i;
const char *ret = trace_seq_buffer_ptr(p);
for (i = 0; i < buf_len; i++)
trace_seq_printf(p, "%s%2.2x", i == 0 ? "" : " ", buf[i]);
trace_seq_putc(p, 0);
return ret;
}
EXPORT_SYMBOL(ftrace_print_hex_seq);
int ftrace_raw_output_prep(struct trace_iterator *iter,
struct trace_event *trace_event)
{
struct ftrace_event_call *event;
struct trace_seq *s = &iter->seq;
struct trace_seq *p = &iter->tmp_seq;
struct trace_entry *entry;
event = container_of(trace_event, struct ftrace_event_call, event);
entry = iter->ent;
if (entry->type != event->event.type) {
WARN_ON_ONCE(1);
return TRACE_TYPE_UNHANDLED;
}
trace_seq_init(p);
trace_seq_printf(s, "%s: ", ftrace_event_name(event));
return trace_handle_return(s);
}
EXPORT_SYMBOL(ftrace_raw_output_prep);
static int ftrace_output_raw(struct trace_iterator *iter, char *name,
char *fmt, va_list ap)
{
struct trace_seq *s = &iter->seq;
trace_seq_printf(s, "%s: ", name);
trace_seq_vprintf(s, fmt, ap);
return trace_handle_return(s);
}
int ftrace_output_call(struct trace_iterator *iter, char *name, char *fmt, ...)
{
va_list ap;
int ret;
va_start(ap, fmt);
ret = ftrace_output_raw(iter, name, fmt, ap);
va_end(ap);
return ret;
}
EXPORT_SYMBOL_GPL(ftrace_output_call);
#ifdef CONFIG_KRETPROBES
static inline const char *kretprobed(const char *name)
{
static const char tramp_name[] = "kretprobe_trampoline";
int size = sizeof(tramp_name);
if (strncmp(tramp_name, name, size) == 0)
return "[unknown/kretprobe'd]";
return name;
}
#else
static inline const char *kretprobed(const char *name)
{
return name;
}
#endif /* CONFIG_KRETPROBES */
static void
seq_print_sym_short(struct trace_seq *s, const char *fmt, unsigned long address)
{
#ifdef CONFIG_KALLSYMS
char str[KSYM_SYMBOL_LEN];
const char *name;
kallsyms_lookup(address, NULL, NULL, NULL, str);
name = kretprobed(str);
trace_seq_printf(s, fmt, name);
#endif
}
static void
seq_print_sym_offset(struct trace_seq *s, const char *fmt,
unsigned long address)
{
#ifdef CONFIG_KALLSYMS
char str[KSYM_SYMBOL_LEN];
const char *name;
sprint_symbol(str, address);
name = kretprobed(str);
trace_seq_printf(s, fmt, name);
#endif
}
#ifndef CONFIG_64BIT
# define IP_FMT "%08lx"
#else
# define IP_FMT "%016lx"
#endif
int seq_print_user_ip(struct trace_seq *s, struct mm_struct *mm,
unsigned long ip, unsigned long sym_flags)
{
struct file *file = NULL;
unsigned long vmstart = 0;
int ret = 1;
if (s->full)
return 0;
if (mm) {
const struct vm_area_struct *vma;
down_read(&mm->mmap_sem);
vma = find_vma(mm, ip);
if (vma) {
file = vma->vm_file;
vmstart = vma->vm_start;
}
if (file) {
ret = trace_seq_path(s, &file->f_path);
if (ret)
trace_seq_printf(s, "[+0x%lx]",
ip - vmstart);
}
up_read(&mm->mmap_sem);
}
if (ret && ((sym_flags & TRACE_ITER_SYM_ADDR) || !file))
trace_seq_printf(s, " <" IP_FMT ">", ip);
return !trace_seq_has_overflowed(s);
}
int
seq_print_userip_objs(const struct userstack_entry *entry, struct trace_seq *s,
unsigned long sym_flags)
{
struct mm_struct *mm = NULL;
unsigned int i;
if (trace_flags & TRACE_ITER_SYM_USEROBJ) {
struct task_struct *task;
/*
* we do the lookup on the thread group leader,
* since individual threads might have already quit!
*/
rcu_read_lock();
task = find_task_by_vpid(entry->tgid);
if (task)
mm = get_task_mm(task);
rcu_read_unlock();
}
for (i = 0; i < FTRACE_STACK_ENTRIES; i++) {
unsigned long ip = entry->caller[i];
if (ip == ULONG_MAX || trace_seq_has_overflowed(s))
break;
trace_seq_puts(s, " => ");
if (!ip) {
trace_seq_puts(s, "??");
trace_seq_putc(s, '\n');
continue;
}
seq_print_user_ip(s, mm, ip, sym_flags);
trace_seq_putc(s, '\n');
}
if (mm)
mmput(mm);
return !trace_seq_has_overflowed(s);
}
int
seq_print_ip_sym(struct trace_seq *s, unsigned long ip, unsigned long sym_flags)
{
if (!ip) {
trace_seq_putc(s, '0');
goto out;
}
if (sym_flags & TRACE_ITER_SYM_OFFSET)
seq_print_sym_offset(s, "%s", ip);
else
seq_print_sym_short(s, "%s", ip);
if (sym_flags & TRACE_ITER_SYM_ADDR)
trace_seq_printf(s, " <" IP_FMT ">", ip);
out:
return !trace_seq_has_overflowed(s);
}
/**
* trace_print_lat_fmt - print the irq, preempt and lockdep fields
* @s: trace seq struct to write to
* @entry: The trace entry field from the ring buffer
*
* Prints the generic fields of irqs off, in hard or softirq, preempt
* count.
*/
int trace_print_lat_fmt(struct trace_seq *s, struct trace_entry *entry)
{
char hardsoft_irq;
char need_resched;
char irqs_off;
int hardirq;
int softirq;
hardirq = entry->flags & TRACE_FLAG_HARDIRQ;
softirq = entry->flags & TRACE_FLAG_SOFTIRQ;
irqs_off =
(entry->flags & TRACE_FLAG_IRQS_OFF) ? 'd' :
(entry->flags & TRACE_FLAG_IRQS_NOSUPPORT) ? 'X' :
'.';
switch (entry->flags & (TRACE_FLAG_NEED_RESCHED |
TRACE_FLAG_PREEMPT_RESCHED)) {
case TRACE_FLAG_NEED_RESCHED | TRACE_FLAG_PREEMPT_RESCHED:
need_resched = 'N';
break;
case TRACE_FLAG_NEED_RESCHED:
need_resched = 'n';
break;
case TRACE_FLAG_PREEMPT_RESCHED:
need_resched = 'p';
break;
default:
need_resched = '.';
break;
}
hardsoft_irq =
(hardirq && softirq) ? 'H' :
hardirq ? 'h' :
softirq ? 's' :
'.';
trace_seq_printf(s, "%c%c%c",
irqs_off, need_resched, hardsoft_irq);
if (entry->preempt_count)
trace_seq_printf(s, "%x", entry->preempt_count);
else
trace_seq_putc(s, '.');
return !trace_seq_has_overflowed(s);
}
static int
lat_print_generic(struct trace_seq *s, struct trace_entry *entry, int cpu)
{
char comm[TASK_COMM_LEN];
trace_find_cmdline(entry->pid, comm);
trace_seq_printf(s, "%8.8s-%-5d %3d",
comm, entry->pid, cpu);
return trace_print_lat_fmt(s, entry);
}
#undef MARK
#define MARK(v, s) {.val = v, .sym = s}
/* trace overhead mark */
static const struct trace_mark {
unsigned long long val; /* unit: nsec */
char sym;
} mark[] = {
MARK(1000000000ULL , '$'), /* 1 sec */
MARK(1000000ULL , '#'), /* 1000 usecs */
MARK(100000ULL , '!'), /* 100 usecs */
MARK(10000ULL , '+'), /* 10 usecs */
};
#undef MARK
char trace_find_mark(unsigned long long d)
{
int i;
int size = ARRAY_SIZE(mark);
for (i = 0; i < size; i++) {
if (d >= mark[i].val)
break;
}
return (i == size) ? ' ' : mark[i].sym;
}
static int
lat_print_timestamp(struct trace_iterator *iter, u64 next_ts)
{
unsigned long verbose = trace_flags & TRACE_ITER_VERBOSE;
unsigned long in_ns = iter->iter_flags & TRACE_FILE_TIME_IN_NS;
unsigned long long abs_ts = iter->ts - iter->trace_buffer->time_start;
unsigned long long rel_ts = next_ts - iter->ts;
struct trace_seq *s = &iter->seq;
if (in_ns) {
abs_ts = ns2usecs(abs_ts);
rel_ts = ns2usecs(rel_ts);
}
if (verbose && in_ns) {
unsigned long abs_usec = do_div(abs_ts, USEC_PER_MSEC);
unsigned long abs_msec = (unsigned long)abs_ts;
unsigned long rel_usec = do_div(rel_ts, USEC_PER_MSEC);
unsigned long rel_msec = (unsigned long)rel_ts;
trace_seq_printf(
s, "[%08llx] %ld.%03ldms (+%ld.%03ldms): ",
ns2usecs(iter->ts),
abs_msec, abs_usec,
rel_msec, rel_usec);
} else if (verbose && !in_ns) {
trace_seq_printf(
s, "[%016llx] %lld (+%lld): ",
iter->ts, abs_ts, rel_ts);
} else if (!verbose && in_ns) {
trace_seq_printf(
s, " %4lldus%c: ",
abs_ts,
trace_find_mark(rel_ts * NSEC_PER_USEC));
} else { /* !verbose && !in_ns */
trace_seq_printf(s, " %4lld: ", abs_ts);
}
return !trace_seq_has_overflowed(s);
}
int trace_print_context(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
struct trace_entry *entry = iter->ent;
unsigned long long t;
unsigned long secs, usec_rem;
char comm[TASK_COMM_LEN];
trace_find_cmdline(entry->pid, comm);
trace_seq_printf(s, "%16s-%-5d [%03d] ",
comm, entry->pid, iter->cpu);
if (trace_flags & TRACE_ITER_IRQ_INFO)
trace_print_lat_fmt(s, entry);
if (iter->iter_flags & TRACE_FILE_TIME_IN_NS) {
t = ns2usecs(iter->ts);
usec_rem = do_div(t, USEC_PER_SEC);
secs = (unsigned long)t;
trace_seq_printf(s, " %5lu.%06lu: ", secs, usec_rem);
} else
trace_seq_printf(s, " %12llu: ", iter->ts);
return !trace_seq_has_overflowed(s);
}
int trace_print_lat_context(struct trace_iterator *iter)
{
u64 next_ts;
/* trace_find_next_entry will reset ent_size */
int ent_size = iter->ent_size;
struct trace_seq *s = &iter->seq;
struct trace_entry *entry = iter->ent,
*next_entry = trace_find_next_entry(iter, NULL,
&next_ts);
unsigned long verbose = (trace_flags & TRACE_ITER_VERBOSE);
/* Restore the original ent_size */
iter->ent_size = ent_size;
if (!next_entry)
next_ts = iter->ts;
if (verbose) {
char comm[TASK_COMM_LEN];
trace_find_cmdline(entry->pid, comm);
trace_seq_printf(
s, "%16s %5d %3d %d %08x %08lx ",
comm, entry->pid, iter->cpu, entry->flags,
entry->preempt_count, iter->idx);
} else {
lat_print_generic(s, entry, iter->cpu);
}
lat_print_timestamp(iter, next_ts);
return !trace_seq_has_overflowed(s);
}
static const char state_to_char[] = TASK_STATE_TO_CHAR_STR;
static int task_state_char(unsigned long state)
{
int bit = state ? __ffs(state) + 1 : 0;
return bit < sizeof(state_to_char) - 1 ? state_to_char[bit] : '?';
}
/**
* ftrace_find_event - find a registered event
* @type: the type of event to look for
*
* Returns an event of type @type otherwise NULL
* Called with trace_event_read_lock() held.
*/
struct trace_event *ftrace_find_event(int type)
{
struct trace_event *event;
unsigned key;
key = type & (EVENT_HASHSIZE - 1);
hlist_for_each_entry(event, &event_hash[key], node) {
if (event->type == type)
return event;
}
return NULL;
}
static LIST_HEAD(ftrace_event_list);
static int trace_search_list(struct list_head **list)
{
struct trace_event *e;
int last = __TRACE_LAST_TYPE;
if (list_empty(&ftrace_event_list)) {
*list = &ftrace_event_list;
return last + 1;
}
/*
* We used up all possible max events,
* lets see if somebody freed one.
*/
list_for_each_entry(e, &ftrace_event_list, list) {
if (e->type != last + 1)
break;
last++;
}
/* Did we used up all 65 thousand events??? */
if ((last + 1) > FTRACE_MAX_EVENT)
return 0;
*list = &e->list;
return last + 1;
}
void trace_event_read_lock(void)
{
down_read(&trace_event_sem);
}
void trace_event_read_unlock(void)
{
up_read(&trace_event_sem);
}
/**
* register_ftrace_event - register output for an event type
* @event: the event type to register
*
* Event types are stored in a hash and this hash is used to
* find a way to print an event. If the @event->type is set
* then it will use that type, otherwise it will assign a
* type to use.
*
* If you assign your own type, please make sure it is added
* to the trace_type enum in trace.h, to avoid collisions
* with the dynamic types.
*
* Returns the event type number or zero on error.
*/
int register_ftrace_event(struct trace_event *event)
{
unsigned key;
int ret = 0;
down_write(&trace_event_sem);
if (WARN_ON(!event))
goto out;
if (WARN_ON(!event->funcs))
goto out;
INIT_LIST_HEAD(&event->list);
if (!event->type) {
struct list_head *list = NULL;
if (next_event_type > FTRACE_MAX_EVENT) {
event->type = trace_search_list(&list);
if (!event->type)
goto out;
} else {
event->type = next_event_type++;
list = &ftrace_event_list;
}
if (WARN_ON(ftrace_find_event(event->type)))
goto out;
list_add_tail(&event->list, list);
} else if (event->type > __TRACE_LAST_TYPE) {
printk(KERN_WARNING "Need to add type to trace.h\n");
WARN_ON(1);
goto out;
} else {
/* Is this event already used */
if (ftrace_find_event(event->type))
goto out;
}
if (event->funcs->trace == NULL)
event->funcs->trace = trace_nop_print;
if (event->funcs->raw == NULL)
event->funcs->raw = trace_nop_print;
if (event->funcs->hex == NULL)
event->funcs->hex = trace_nop_print;
if (event->funcs->binary == NULL)
event->funcs->binary = trace_nop_print;
key = event->type & (EVENT_HASHSIZE - 1);
hlist_add_head(&event->node, &event_hash[key]);
ret = event->type;
out:
up_write(&trace_event_sem);
return ret;
}
EXPORT_SYMBOL_GPL(register_ftrace_event);
/*
* Used by module code with the trace_event_sem held for write.
*/
int __unregister_ftrace_event(struct trace_event *event)
{
hlist_del(&event->node);
list_del(&event->list);
return 0;
}
/**
* unregister_ftrace_event - remove a no longer used event
* @event: the event to remove
*/
int unregister_ftrace_event(struct trace_event *event)
{
down_write(&trace_event_sem);
__unregister_ftrace_event(event);
up_write(&trace_event_sem);
return 0;
}
EXPORT_SYMBOL_GPL(unregister_ftrace_event);
/*
* Standard events
*/
enum print_line_t trace_nop_print(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
trace_seq_printf(&iter->seq, "type: %d\n", iter->ent->type);
return trace_handle_return(&iter->seq);
}
/* TRACE_FN */
static enum print_line_t trace_fn_trace(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct ftrace_entry *field;
struct trace_seq *s = &iter->seq;
trace_assign_type(field, iter->ent);
seq_print_ip_sym(s, field->ip, flags);
if ((flags & TRACE_ITER_PRINT_PARENT) && field->parent_ip) {
trace_seq_puts(s, " <-");
seq_print_ip_sym(s, field->parent_ip, flags);
}
trace_seq_putc(s, '\n');
return trace_handle_return(s);
}
static enum print_line_t trace_fn_raw(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct ftrace_entry *field;
trace_assign_type(field, iter->ent);
trace_seq_printf(&iter->seq, "%lx %lx\n",
field->ip,
field->parent_ip);
return trace_handle_return(&iter->seq);
}
static enum print_line_t trace_fn_hex(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct ftrace_entry *field;
struct trace_seq *s = &iter->seq;
trace_assign_type(field, iter->ent);
SEQ_PUT_HEX_FIELD(s, field->ip);
SEQ_PUT_HEX_FIELD(s, field->parent_ip);
return trace_handle_return(s);
}
static enum print_line_t trace_fn_bin(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct ftrace_entry *field;
struct trace_seq *s = &iter->seq;
trace_assign_type(field, iter->ent);
SEQ_PUT_FIELD(s, field->ip);
SEQ_PUT_FIELD(s, field->parent_ip);
return trace_handle_return(s);
}
static struct trace_event_functions trace_fn_funcs = {
.trace = trace_fn_trace,
.raw = trace_fn_raw,
.hex = trace_fn_hex,
.binary = trace_fn_bin,
};
static struct trace_event trace_fn_event = {
.type = TRACE_FN,
.funcs = &trace_fn_funcs,
};
/* TRACE_CTX an TRACE_WAKE */
static enum print_line_t trace_ctxwake_print(struct trace_iterator *iter,
char *delim)
{
struct ctx_switch_entry *field;
char comm[TASK_COMM_LEN];
int S, T;
trace_assign_type(field, iter->ent);
T = task_state_char(field->next_state);
S = task_state_char(field->prev_state);
trace_find_cmdline(field->next_pid, comm);
trace_seq_printf(&iter->seq,
" %5d:%3d:%c %s [%03d] %5d:%3d:%c %s\n",
field->prev_pid,
field->prev_prio,
S, delim,
field->next_cpu,
field->next_pid,
field->next_prio,
T, comm);
return trace_handle_return(&iter->seq);
}
static enum print_line_t trace_ctx_print(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
return trace_ctxwake_print(iter, "==>");
}
static enum print_line_t trace_wake_print(struct trace_iterator *iter,
int flags, struct trace_event *event)
{
return trace_ctxwake_print(iter, " +");
}
static int trace_ctxwake_raw(struct trace_iterator *iter, char S)
{
struct ctx_switch_entry *field;
int T;
trace_assign_type(field, iter->ent);
if (!S)
S = task_state_char(field->prev_state);
T = task_state_char(field->next_state);
trace_seq_printf(&iter->seq, "%d %d %c %d %d %d %c\n",
field->prev_pid,
field->prev_prio,
S,
field->next_cpu,
field->next_pid,
field->next_prio,
T);
return trace_handle_return(&iter->seq);
}
static enum print_line_t trace_ctx_raw(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
return trace_ctxwake_raw(iter, 0);
}
static enum print_line_t trace_wake_raw(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
return trace_ctxwake_raw(iter, '+');
}
static int trace_ctxwake_hex(struct trace_iterator *iter, char S)
{
struct ctx_switch_entry *field;
struct trace_seq *s = &iter->seq;
int T;
trace_assign_type(field, iter->ent);
if (!S)
S = task_state_char(field->prev_state);
T = task_state_char(field->next_state);
SEQ_PUT_HEX_FIELD(s, field->prev_pid);
SEQ_PUT_HEX_FIELD(s, field->prev_prio);
SEQ_PUT_HEX_FIELD(s, S);
SEQ_PUT_HEX_FIELD(s, field->next_cpu);
SEQ_PUT_HEX_FIELD(s, field->next_pid);
SEQ_PUT_HEX_FIELD(s, field->next_prio);
SEQ_PUT_HEX_FIELD(s, T);
return trace_handle_return(s);
}
static enum print_line_t trace_ctx_hex(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
return trace_ctxwake_hex(iter, 0);
}
static enum print_line_t trace_wake_hex(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
return trace_ctxwake_hex(iter, '+');
}
static enum print_line_t trace_ctxwake_bin(struct trace_iterator *iter,
int flags, struct trace_event *event)
{
struct ctx_switch_entry *field;
struct trace_seq *s = &iter->seq;
trace_assign_type(field, iter->ent);
SEQ_PUT_FIELD(s, field->prev_pid);
SEQ_PUT_FIELD(s, field->prev_prio);
SEQ_PUT_FIELD(s, field->prev_state);
SEQ_PUT_FIELD(s, field->next_cpu);
SEQ_PUT_FIELD(s, field->next_pid);
SEQ_PUT_FIELD(s, field->next_prio);
SEQ_PUT_FIELD(s, field->next_state);
return trace_handle_return(s);
}
static struct trace_event_functions trace_ctx_funcs = {
.trace = trace_ctx_print,
.raw = trace_ctx_raw,
.hex = trace_ctx_hex,
.binary = trace_ctxwake_bin,
};
static struct trace_event trace_ctx_event = {
.type = TRACE_CTX,
.funcs = &trace_ctx_funcs,
};
static struct trace_event_functions trace_wake_funcs = {
.trace = trace_wake_print,
.raw = trace_wake_raw,
.hex = trace_wake_hex,
.binary = trace_ctxwake_bin,
};
static struct trace_event trace_wake_event = {
.type = TRACE_WAKE,
.funcs = &trace_wake_funcs,
};
/* TRACE_STACK */
static enum print_line_t trace_stack_print(struct trace_iterator *iter,
int flags, struct trace_event *event)
{
struct stack_entry *field;
struct trace_seq *s = &iter->seq;
unsigned long *p;
unsigned long *end;
trace_assign_type(field, iter->ent);
end = (unsigned long *)((long)iter->ent + iter->ent_size);
trace_seq_puts(s, "<stack trace>\n");
for (p = field->caller; p && *p != ULONG_MAX && p < end; p++) {
if (trace_seq_has_overflowed(s))
break;
trace_seq_puts(s, " => ");
seq_print_ip_sym(s, *p, flags);
trace_seq_putc(s, '\n');
}
return trace_handle_return(s);
}
static struct trace_event_functions trace_stack_funcs = {
.trace = trace_stack_print,
};
static struct trace_event trace_stack_event = {
.type = TRACE_STACK,
.funcs = &trace_stack_funcs,
};
/* TRACE_USER_STACK */
static enum print_line_t trace_user_stack_print(struct trace_iterator *iter,
int flags, struct trace_event *event)
{
struct userstack_entry *field;
struct trace_seq *s = &iter->seq;
trace_assign_type(field, iter->ent);
trace_seq_puts(s, "<user stack trace>\n");
seq_print_userip_objs(field, s, flags);
return trace_handle_return(s);
}
static struct trace_event_functions trace_user_stack_funcs = {
.trace = trace_user_stack_print,
};
static struct trace_event trace_user_stack_event = {
.type = TRACE_USER_STACK,
.funcs = &trace_user_stack_funcs,
};
/* TRACE_BPUTS */
static enum print_line_t
trace_bputs_print(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct trace_entry *entry = iter->ent;
struct trace_seq *s = &iter->seq;
struct bputs_entry *field;
trace_assign_type(field, entry);
seq_print_ip_sym(s, field->ip, flags);
trace_seq_puts(s, ": ");
trace_seq_puts(s, field->str);
return trace_handle_return(s);
}
static enum print_line_t
trace_bputs_raw(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct bputs_entry *field;
struct trace_seq *s = &iter->seq;
trace_assign_type(field, iter->ent);
trace_seq_printf(s, ": %lx : ", field->ip);
trace_seq_puts(s, field->str);
return trace_handle_return(s);
}
static struct trace_event_functions trace_bputs_funcs = {
.trace = trace_bputs_print,
.raw = trace_bputs_raw,
};
static struct trace_event trace_bputs_event = {
.type = TRACE_BPUTS,
.funcs = &trace_bputs_funcs,
};
/* TRACE_BPRINT */
static enum print_line_t
trace_bprint_print(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct trace_entry *entry = iter->ent;
struct trace_seq *s = &iter->seq;
struct bprint_entry *field;
trace_assign_type(field, entry);
seq_print_ip_sym(s, field->ip, flags);
trace_seq_puts(s, ": ");
trace_seq_bprintf(s, field->fmt, field->buf);
return trace_handle_return(s);
}
static enum print_line_t
trace_bprint_raw(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct bprint_entry *field;
struct trace_seq *s = &iter->seq;
trace_assign_type(field, iter->ent);
trace_seq_printf(s, ": %lx : ", field->ip);
trace_seq_bprintf(s, field->fmt, field->buf);
return trace_handle_return(s);
}
static struct trace_event_functions trace_bprint_funcs = {
.trace = trace_bprint_print,
.raw = trace_bprint_raw,
};
static struct trace_event trace_bprint_event = {
.type = TRACE_BPRINT,
.funcs = &trace_bprint_funcs,
};
/* TRACE_PRINT */
static enum print_line_t trace_print_print(struct trace_iterator *iter,
int flags, struct trace_event *event)
{
struct print_entry *field;
struct trace_seq *s = &iter->seq;
trace_assign_type(field, iter->ent);
seq_print_ip_sym(s, field->ip, flags);
trace_seq_printf(s, ": %s", field->buf);
return trace_handle_return(s);
}
static enum print_line_t trace_print_raw(struct trace_iterator *iter, int flags,
struct trace_event *event)
{
struct print_entry *field;
trace_assign_type(field, iter->ent);
trace_seq_printf(&iter->seq, "# %lx %s", field->ip, field->buf);
return trace_handle_return(&iter->seq);
}
static struct trace_event_functions trace_print_funcs = {
.trace = trace_print_print,
.raw = trace_print_raw,
};
static struct trace_event trace_print_event = {
.type = TRACE_PRINT,
.funcs = &trace_print_funcs,
};
static struct trace_event *events[] __initdata = {
&trace_fn_event,
&trace_ctx_event,
&trace_wake_event,
&trace_stack_event,
&trace_user_stack_event,
&trace_bputs_event,
&trace_bprint_event,
&trace_print_event,
NULL
};
__init static int init_events(void)
{
struct trace_event *event;
int i, ret;
for (i = 0; events[i]; i++) {
event = events[i];
ret = register_ftrace_event(event);
if (!ret) {
printk(KERN_WARNING "event %d failed to register\n",
event->type);
WARN_ON_ONCE(1);
}
}
return 0;
}
early_initcall(init_events);
| gpl-2.0 |
V6ser/QEMU-s5l89xx-port | hw/syborg_fb.c | 75 | 13475 | /*
* Syborg Framebuffer
*
* Copyright (c) 2009 CodeSourcery
*
* 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 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 "sysbus.h"
#include "console.h"
#include "syborg.h"
#include "framebuffer.h"
//#define DEBUG_SYBORG_FB
#ifdef DEBUG_SYBORG_FB
#define DPRINTF(fmt, ...) \
do { printf("syborg_fb: " fmt , ## __VA_ARGS__); } while (0)
#define BADF(fmt, ...) \
do { fprintf(stderr, "syborg_fb: error: " fmt , ## __VA_ARGS__); \
exit(1);} while (0)
#else
#define DPRINTF(fmt, ...) do {} while(0)
#define BADF(fmt, ...) \
do { fprintf(stderr, "syborg_fb: error: " fmt , ## __VA_ARGS__);} while (0)
#endif
enum {
FB_ID = 0,
FB_BASE = 1,
FB_HEIGHT = 2,
FB_WIDTH = 3,
FB_ORIENTATION = 4,
FB_BLANK = 5,
FB_INT_MASK = 6,
FB_INTERRUPT_CAUSE = 7,
FB_BPP = 8,
FB_COLOR_ORDER = 9,
FB_BYTE_ORDER = 10,
FB_PIXEL_ORDER = 11,
FB_ROW_PITCH = 12,
FB_ENABLED = 13,
FB_PALETTE_START = 0x400 >> 2,
FB_PALETTE_END = FB_PALETTE_START+256-1,
};
#define FB_INT_VSYNC (1U << 0)
#define FB_INT_BASE_UPDATE_DONE (1U << 1)
typedef struct {
SysBusDevice busdev;
DisplayState *ds;
/*QEMUConsole *console;*/
uint32_t need_update : 1;
uint32_t need_int : 1;
uint32_t enabled : 1;
uint32_t int_status;
uint32_t int_enable;
qemu_irq irq;
uint32_t base;
uint32_t pitch;
uint32_t rows;
uint32_t cols;
int blank;
int bpp;
int rgb; /* 0 = BGR, 1 = RGB */
int endian; /* 0 = Little, 1 = Big */
uint32_t raw_palette[256];
uint32_t palette[256];
} SyborgFBState;
enum {
BPP_SRC_1,
BPP_SRC_2,
BPP_SRC_4,
BPP_SRC_8,
BPP_SRC_16,
BPP_SRC_32,
/* TODO: Implement these. */
BPP_SRC_15 = -1,
BPP_SRC_24 = -2
};
#include "pixel_ops.h"
#define BITS 8
#include "pl110_template.h"
#define BITS 15
#include "pl110_template.h"
#define BITS 16
#include "pl110_template.h"
#define BITS 24
#include "pl110_template.h"
#define BITS 32
#include "pl110_template.h"
/* Update interrupts. */
static void syborg_fb_update(SyborgFBState *s)
{
if ((s->int_status & s->int_enable) != 0) {
DPRINTF("Raise IRQ\n");
qemu_irq_raise(s->irq);
} else {
DPRINTF("Lower IRQ\n");
qemu_irq_lower(s->irq);
}
}
static int syborg_fb_enabled(const SyborgFBState *s)
{
return s->enabled;
}
static void syborg_fb_update_palette(SyborgFBState *s)
{
int n, i;
uint32_t raw;
unsigned int r, g, b;
switch (s->bpp) {
case BPP_SRC_1: n = 2; break;
case BPP_SRC_2: n = 4; break;
case BPP_SRC_4: n = 16; break;
case BPP_SRC_8: n = 256; break;
default: return;
}
for (i = 0; i < n; i++) {
raw = s->raw_palette[i];
r = (raw >> 16) & 0xff;
g = (raw >> 8) & 0xff;
b = raw & 0xff;
switch (ds_get_bits_per_pixel(s->ds)) {
case 8:
s->palette[i] = rgb_to_pixel8(r, g, b);
break;
case 15:
s->palette[i] = rgb_to_pixel15(r, g, b);
break;
case 16:
s->palette[i] = rgb_to_pixel16(r, g, b);
break;
case 24:
case 32:
s->palette[i] = rgb_to_pixel32(r, g, b);
break;
default:
abort();
}
}
}
static void syborg_fb_update_display(void *opaque)
{
SyborgFBState *s = (SyborgFBState *)opaque;
drawfn* fntable;
drawfn fn;
int dest_width;
int src_width;
int bpp_offset;
int first;
int last;
if (!syborg_fb_enabled(s))
return;
switch (ds_get_bits_per_pixel(s->ds)) {
case 0:
return;
case 8:
fntable = pl110_draw_fn_8;
dest_width = 1;
break;
case 15:
fntable = pl110_draw_fn_15;
dest_width = 2;
break;
case 16:
fntable = pl110_draw_fn_16;
dest_width = 2;
break;
case 24:
fntable = pl110_draw_fn_24;
dest_width = 3;
break;
case 32:
fntable = pl110_draw_fn_32;
dest_width = 4;
break;
default:
fprintf(stderr, "syborg_fb: Bad color depth\n");
exit(1);
}
if (s->need_int) {
s->int_status |= FB_INT_BASE_UPDATE_DONE;
syborg_fb_update(s);
s->need_int = 0;
}
if (s->rgb) {
bpp_offset = 18;
} else {
bpp_offset = 0;
}
if (s->endian) {
bpp_offset += 6;
}
fn = fntable[s->bpp + bpp_offset];
if (s->pitch) {
src_width = s->pitch;
} else {
src_width = s->cols;
switch (s->bpp) {
case BPP_SRC_1:
src_width >>= 3;
break;
case BPP_SRC_2:
src_width >>= 2;
break;
case BPP_SRC_4:
src_width >>= 1;
break;
case BPP_SRC_8:
break;
case BPP_SRC_15:
case BPP_SRC_16:
src_width <<= 1;
break;
case BPP_SRC_24:
src_width *= 3;
break;
case BPP_SRC_32:
src_width <<= 2;
break;
}
}
dest_width *= s->cols;
first = 0;
/* TODO: Implement blanking. */
if (!s->blank) {
if (s->need_update && s->bpp <= BPP_SRC_8) {
syborg_fb_update_palette(s);
}
framebuffer_update_display(s->ds,
s->base, s->cols, s->rows,
src_width, dest_width, 0,
s->need_update,
fn, s->palette,
&first, &last);
if (first >= 0) {
dpy_update(s->ds, 0, first, s->cols, last - first + 1);
}
s->int_status |= FB_INT_VSYNC;
syborg_fb_update(s);
}
s->need_update = 0;
}
static void syborg_fb_invalidate_display(void * opaque)
{
SyborgFBState *s = (SyborgFBState *)opaque;
s->need_update = 1;
}
static uint32_t syborg_fb_read(void *opaque, target_phys_addr_t offset)
{
SyborgFBState *s = opaque;
DPRINTF("read reg %d\n", (int)offset);
offset &= 0xfff;
switch (offset >> 2) {
case FB_ID:
return SYBORG_ID_FRAMEBUFFER;
case FB_BASE:
return s->base;
case FB_HEIGHT:
return s->rows;
case FB_WIDTH:
return s->cols;
case FB_ORIENTATION:
return 0;
case FB_BLANK:
return s->blank;
case FB_INT_MASK:
return s->int_enable;
case FB_INTERRUPT_CAUSE:
return s->int_status;
case FB_BPP:
switch (s->bpp) {
case BPP_SRC_1: return 1;
case BPP_SRC_2: return 2;
case BPP_SRC_4: return 4;
case BPP_SRC_8: return 8;
case BPP_SRC_15: return 15;
case BPP_SRC_16: return 16;
case BPP_SRC_24: return 24;
case BPP_SRC_32: return 32;
default: return 0;
}
case FB_COLOR_ORDER:
return s->rgb;
case FB_BYTE_ORDER:
return s->endian;
case FB_PIXEL_ORDER:
return 0;
case FB_ROW_PITCH:
return s->pitch;
case FB_ENABLED:
return s->enabled;
default:
if ((offset >> 2) >= FB_PALETTE_START
&& (offset >> 2) <= FB_PALETTE_END) {
return s->raw_palette[(offset >> 2) - FB_PALETTE_START];
} else {
cpu_abort (cpu_single_env, "syborg_fb_read: Bad offset %x\n",
(int)offset);
}
return 0;
}
}
static void syborg_fb_write(void *opaque, target_phys_addr_t offset,
uint32_t val)
{
SyborgFBState *s = opaque;
DPRINTF("write reg %d = %d\n", (int)offset, val);
s->need_update = 1;
offset &= 0xfff;
switch (offset >> 2) {
case FB_BASE:
s->base = val;
s->need_int = 1;
s->need_update = 1;
syborg_fb_update(s);
break;
case FB_HEIGHT:
s->rows = val;
break;
case FB_WIDTH:
s->cols = val;
break;
case FB_ORIENTATION:
/* TODO: Implement rotation. */
break;
case FB_BLANK:
s->blank = val & 1;
break;
case FB_INT_MASK:
s->int_enable = val;
syborg_fb_update(s);
break;
case FB_INTERRUPT_CAUSE:
s->int_status &= ~val;
syborg_fb_update(s);
break;
case FB_BPP:
switch (val) {
case 1: val = BPP_SRC_1; break;
case 2: val = BPP_SRC_2; break;
case 4: val = BPP_SRC_4; break;
case 8: val = BPP_SRC_8; break;
/* case 15: val = BPP_SRC_15; break; */
case 16: val = BPP_SRC_16; break;
/* case 24: val = BPP_SRC_24; break; */
case 32: val = BPP_SRC_32; break;
default: val = s->bpp; break;
}
s->bpp = val;
break;
case FB_COLOR_ORDER:
s->rgb = (val != 0);
break;
case FB_BYTE_ORDER:
s->endian = (val != 0);
break;
case FB_PIXEL_ORDER:
/* TODO: Implement this. */
break;
case FB_ROW_PITCH:
s->pitch = val;
break;
case FB_ENABLED:
s->enabled = val;
break;
default:
if ((offset >> 2) >= FB_PALETTE_START
&& (offset >> 2) <= FB_PALETTE_END) {
s->raw_palette[(offset >> 2) - FB_PALETTE_START] = val;
} else {
cpu_abort (cpu_single_env, "syborg_fb_write: Bad offset %x\n",
(int)offset);
}
break;
}
}
static CPUReadMemoryFunc * const syborg_fb_readfn[] = {
syborg_fb_read,
syborg_fb_read,
syborg_fb_read
};
static CPUWriteMemoryFunc * const syborg_fb_writefn[] = {
syborg_fb_write,
syborg_fb_write,
syborg_fb_write
};
static void syborg_fb_save(QEMUFile *f, void *opaque)
{
SyborgFBState *s = opaque;
int i;
qemu_put_be32(f, s->need_int);
qemu_put_be32(f, s->int_status);
qemu_put_be32(f, s->int_enable);
qemu_put_be32(f, s->enabled);
qemu_put_be32(f, s->base);
qemu_put_be32(f, s->pitch);
qemu_put_be32(f, s->rows);
qemu_put_be32(f, s->cols);
qemu_put_be32(f, s->bpp);
qemu_put_be32(f, s->rgb);
for (i = 0; i < 256; i++) {
qemu_put_be32(f, s->raw_palette[i]);
}
}
static int syborg_fb_load(QEMUFile *f, void *opaque, int version_id)
{
SyborgFBState *s = opaque;
int i;
if (version_id != 1)
return -EINVAL;
s->need_int = qemu_get_be32(f);
s->int_status = qemu_get_be32(f);
s->int_enable = qemu_get_be32(f);
s->enabled = qemu_get_be32(f);
s->base = qemu_get_be32(f);
s->pitch = qemu_get_be32(f);
s->rows = qemu_get_be32(f);
s->cols = qemu_get_be32(f);
s->bpp = qemu_get_be32(f);
s->rgb = qemu_get_be32(f);
for (i = 0; i < 256; i++) {
s->raw_palette[i] = qemu_get_be32(f);
}
s->need_update = 1;
return 0;
}
static int syborg_fb_init(SysBusDevice *dev)
{
SyborgFBState *s = FROM_SYSBUS(SyborgFBState, dev);
int iomemtype;
sysbus_init_irq(dev, &s->irq);
iomemtype = cpu_register_io_memory(syborg_fb_readfn,
syborg_fb_writefn, s,
DEVICE_NATIVE_ENDIAN);
sysbus_init_mmio(dev, 0x1000, iomemtype);
s->ds = graphic_console_init(syborg_fb_update_display,
syborg_fb_invalidate_display,
NULL, NULL, s);
if (s->cols != 0 && s->rows != 0) {
qemu_console_resize(s->ds, s->cols, s->rows);
}
if (!s->cols)
s->cols = ds_get_width(s->ds);
if (!s->rows)
s->rows = ds_get_height(s->ds);
register_savevm(&dev->qdev, "syborg_framebuffer", -1, 1,
syborg_fb_save, syborg_fb_load, s);
return 0;
}
static SysBusDeviceInfo syborg_fb_info = {
.init = syborg_fb_init,
.qdev.name = "syborg,framebuffer",
.qdev.size = sizeof(SyborgFBState),
.qdev.props = (Property[]) {
DEFINE_PROP_UINT32("width", SyborgFBState, cols, 0),
DEFINE_PROP_UINT32("height", SyborgFBState, rows, 0),
DEFINE_PROP_END_OF_LIST(),
}
};
static void syborg_fb_register_devices(void)
{
sysbus_register_withprop(&syborg_fb_info);
}
device_init(syborg_fb_register_devices)
| gpl-2.0 |
rkfg/linux | drivers/input/misc/axp20x-pek.c | 75 | 7381 | /*
* axp20x power button driver.
*
* Copyright (C) 2013 Carlo Caione <carlo@caione.org>
*
* 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.
*
* 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/errno.h>
#include <linux/irq.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/mfd/axp20x.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#define AXP20X_PEK_STARTUP_MASK (0xc0)
#define AXP20X_PEK_SHUTDOWN_MASK (0x03)
struct axp20x_pek {
struct axp20x_dev *axp20x;
struct input_dev *input;
int irq_dbr;
int irq_dbf;
};
struct axp20x_time {
unsigned int time;
unsigned int idx;
};
static const struct axp20x_time startup_time[] = {
{ .time = 128, .idx = 0 },
{ .time = 1000, .idx = 2 },
{ .time = 3000, .idx = 1 },
{ .time = 2000, .idx = 3 },
};
static const struct axp20x_time shutdown_time[] = {
{ .time = 4000, .idx = 0 },
{ .time = 6000, .idx = 1 },
{ .time = 8000, .idx = 2 },
{ .time = 10000, .idx = 3 },
};
struct axp20x_pek_ext_attr {
const struct axp20x_time *p_time;
unsigned int mask;
};
static struct axp20x_pek_ext_attr axp20x_pek_startup_ext_attr = {
.p_time = startup_time,
.mask = AXP20X_PEK_STARTUP_MASK,
};
static struct axp20x_pek_ext_attr axp20x_pek_shutdown_ext_attr = {
.p_time = shutdown_time,
.mask = AXP20X_PEK_SHUTDOWN_MASK,
};
static struct axp20x_pek_ext_attr *get_axp_ext_attr(struct device_attribute *attr)
{
return container_of(attr, struct dev_ext_attribute, attr)->var;
}
static ssize_t axp20x_show_ext_attr(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev);
struct axp20x_pek_ext_attr *axp20x_ea = get_axp_ext_attr(attr);
unsigned int val;
int ret, i;
ret = regmap_read(axp20x_pek->axp20x->regmap, AXP20X_PEK_KEY, &val);
if (ret != 0)
return ret;
val &= axp20x_ea->mask;
val >>= ffs(axp20x_ea->mask) - 1;
for (i = 0; i < 4; i++)
if (val == axp20x_ea->p_time[i].idx)
val = axp20x_ea->p_time[i].time;
return sprintf(buf, "%u\n", val);
}
static ssize_t axp20x_store_ext_attr(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct axp20x_pek *axp20x_pek = dev_get_drvdata(dev);
struct axp20x_pek_ext_attr *axp20x_ea = get_axp_ext_attr(attr);
char val_str[20];
size_t len;
int ret, i;
unsigned int val, idx = 0;
unsigned int best_err = UINT_MAX;
val_str[sizeof(val_str) - 1] = '\0';
strncpy(val_str, buf, sizeof(val_str) - 1);
len = strlen(val_str);
if (len && val_str[len - 1] == '\n')
val_str[len - 1] = '\0';
ret = kstrtouint(val_str, 10, &val);
if (ret)
return ret;
for (i = 3; i >= 0; i--) {
unsigned int err;
err = abs(axp20x_ea->p_time[i].time - val);
if (err < best_err) {
best_err = err;
idx = axp20x_ea->p_time[i].idx;
}
if (!err)
break;
}
idx <<= ffs(axp20x_ea->mask) - 1;
ret = regmap_update_bits(axp20x_pek->axp20x->regmap,
AXP20X_PEK_KEY,
axp20x_ea->mask, idx);
if (ret != 0)
return -EINVAL;
return count;
}
static struct dev_ext_attribute axp20x_dev_attr_startup = {
.attr = __ATTR(startup, 0644, axp20x_show_ext_attr, axp20x_store_ext_attr),
.var = &axp20x_pek_startup_ext_attr,
};
static struct dev_ext_attribute axp20x_dev_attr_shutdown = {
.attr = __ATTR(shutdown, 0644, axp20x_show_ext_attr, axp20x_store_ext_attr),
.var = &axp20x_pek_shutdown_ext_attr,
};
static struct attribute *axp20x_attributes[] = {
&axp20x_dev_attr_startup.attr.attr,
&axp20x_dev_attr_shutdown.attr.attr,
NULL,
};
static const struct attribute_group axp20x_attribute_group = {
.attrs = axp20x_attributes,
};
static irqreturn_t axp20x_pek_irq(int irq, void *pwr)
{
struct input_dev *idev = pwr;
struct axp20x_pek *axp20x_pek = input_get_drvdata(idev);
/*
* The power-button is connected to ground so a falling edge (dbf)
* means it is pressed.
*/
if (irq == axp20x_pek->irq_dbf)
input_report_key(idev, KEY_POWER, true);
else if (irq == axp20x_pek->irq_dbr)
input_report_key(idev, KEY_POWER, false);
input_sync(idev);
return IRQ_HANDLED;
}
static void axp20x_remove_sysfs_group(void *_data)
{
struct device *dev = _data;
sysfs_remove_group(&dev->kobj, &axp20x_attribute_group);
}
static int axp20x_pek_probe(struct platform_device *pdev)
{
struct axp20x_pek *axp20x_pek;
struct axp20x_dev *axp20x;
struct input_dev *idev;
int error;
axp20x_pek = devm_kzalloc(&pdev->dev, sizeof(struct axp20x_pek),
GFP_KERNEL);
if (!axp20x_pek)
return -ENOMEM;
axp20x_pek->axp20x = dev_get_drvdata(pdev->dev.parent);
axp20x = axp20x_pek->axp20x;
axp20x_pek->irq_dbr = platform_get_irq_byname(pdev, "PEK_DBR");
if (axp20x_pek->irq_dbr < 0) {
dev_err(&pdev->dev, "No IRQ for PEK_DBR, error=%d\n",
axp20x_pek->irq_dbr);
return axp20x_pek->irq_dbr;
}
axp20x_pek->irq_dbr = regmap_irq_get_virq(axp20x->regmap_irqc,
axp20x_pek->irq_dbr);
axp20x_pek->irq_dbf = platform_get_irq_byname(pdev, "PEK_DBF");
if (axp20x_pek->irq_dbf < 0) {
dev_err(&pdev->dev, "No IRQ for PEK_DBF, error=%d\n",
axp20x_pek->irq_dbf);
return axp20x_pek->irq_dbf;
}
axp20x_pek->irq_dbf = regmap_irq_get_virq(axp20x->regmap_irqc,
axp20x_pek->irq_dbf);
axp20x_pek->input = devm_input_allocate_device(&pdev->dev);
if (!axp20x_pek->input)
return -ENOMEM;
idev = axp20x_pek->input;
idev->name = "axp20x-pek";
idev->phys = "m1kbd/input2";
idev->dev.parent = &pdev->dev;
input_set_capability(idev, EV_KEY, KEY_POWER);
input_set_drvdata(idev, axp20x_pek);
error = devm_request_any_context_irq(&pdev->dev, axp20x_pek->irq_dbr,
axp20x_pek_irq, 0,
"axp20x-pek-dbr", idev);
if (error < 0) {
dev_err(axp20x->dev, "Failed to request dbr IRQ#%d: %d\n",
axp20x_pek->irq_dbr, error);
return error;
}
error = devm_request_any_context_irq(&pdev->dev, axp20x_pek->irq_dbf,
axp20x_pek_irq, 0,
"axp20x-pek-dbf", idev);
if (error < 0) {
dev_err(axp20x->dev, "Failed to request dbf IRQ#%d: %d\n",
axp20x_pek->irq_dbf, error);
return error;
}
error = sysfs_create_group(&pdev->dev.kobj, &axp20x_attribute_group);
if (error) {
dev_err(axp20x->dev, "Failed to create sysfs attributes: %d\n",
error);
return error;
}
error = devm_add_action(&pdev->dev,
axp20x_remove_sysfs_group, &pdev->dev);
if (error) {
axp20x_remove_sysfs_group(&pdev->dev);
dev_err(&pdev->dev, "Failed to add sysfs cleanup action: %d\n",
error);
return error;
}
error = input_register_device(idev);
if (error) {
dev_err(axp20x->dev, "Can't register input device: %d\n",
error);
return error;
}
platform_set_drvdata(pdev, axp20x_pek);
return 0;
}
static struct platform_driver axp20x_pek_driver = {
.probe = axp20x_pek_probe,
.driver = {
.name = "axp20x-pek",
},
};
module_platform_driver(axp20x_pek_driver);
MODULE_DESCRIPTION("axp20x Power Button");
MODULE_AUTHOR("Carlo Caione <carlo@caione.org>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
xingrz/android_kernel_nubia_msm8996 | drivers/staging/vt6655/wroute.c | 331 | 5229 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, 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; 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* File: wroute.c
*
* Purpose: handle WMAC frame relay & filtering
*
* Author: Lyndon Chen
*
* Date: May 20, 2003
*
* Functions:
* ROUTEbRelay - Relay packet
*
* Revision History:
*
*/
#include "mac.h"
#include "tcrc.h"
#include "rxtx.h"
#include "wroute.h"
#include "card.h"
#include "baseband.h"
/*--------------------- Static Definitions -------------------------*/
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Functions --------------------------*/
/*--------------------- Export Variables --------------------------*/
/*
* Description:
* Relay packet. Return true if packet is copy to DMA1
*
* Parameters:
* In:
* pDevice -
* pbySkbData - rx packet skb data
* Out:
* true, false
*
* Return Value: true if packet duplicate; otherwise false
*
*/
bool ROUTEbRelay(struct vnt_private *pDevice, unsigned char *pbySkbData,
unsigned int uDataLen, unsigned int uNodeIndex)
{
PSMgmtObject pMgmt = pDevice->pMgmt;
PSTxDesc pHeadTD, pLastTD;
unsigned int cbFrameBodySize;
unsigned int uMACfragNum;
unsigned char byPktType;
bool bNeedEncryption = false;
SKeyItem STempKey;
PSKeyItem pTransmitKey = NULL;
unsigned int cbHeaderSize;
unsigned int ii;
unsigned char *pbyBSSID;
if (AVAIL_TD(pDevice, TYPE_AC0DMA) <= 0) {
pr_debug("Relay can't allocate TD1..\n");
return false;
}
pHeadTD = pDevice->apCurrTD[TYPE_AC0DMA];
pHeadTD->m_td1TD1.byTCR = (TCR_EDP | TCR_STP);
memcpy(pDevice->sTxEthHeader.abyDstAddr, pbySkbData, ETH_HLEN);
cbFrameBodySize = uDataLen - ETH_HLEN;
if (ntohs(pDevice->sTxEthHeader.wType) > ETH_DATA_LEN)
cbFrameBodySize += 8;
if (pDevice->bEncryptionEnable == true) {
bNeedEncryption = true;
// get group key
pbyBSSID = pDevice->abyBroadcastAddr;
if (KeybGetTransmitKey(&(pDevice->sKey), pbyBSSID,
GROUP_KEY, &pTransmitKey) == false) {
pTransmitKey = NULL;
pr_debug("KEY is NULL. [%d]\n",
pDevice->pMgmt->eCurrMode);
} else {
pr_debug("Get GTK\n");
}
}
if (pDevice->bEnableHostWEP) {
if (uNodeIndex < MAX_NODE_NUM + 1) {
pTransmitKey = &STempKey;
pTransmitKey->byCipherSuite = pMgmt->sNodeDBTable[uNodeIndex].byCipherSuite;
pTransmitKey->dwKeyIndex = pMgmt->sNodeDBTable[uNodeIndex].dwKeyIndex;
pTransmitKey->uKeyLength = pMgmt->sNodeDBTable[uNodeIndex].uWepKeyLength;
pTransmitKey->dwTSC47_16 = pMgmt->sNodeDBTable[uNodeIndex].dwTSC47_16;
pTransmitKey->wTSC15_0 = pMgmt->sNodeDBTable[uNodeIndex].wTSC15_0;
memcpy(pTransmitKey->abyKey,
&pMgmt->sNodeDBTable[uNodeIndex].abyWepKey[0],
pTransmitKey->uKeyLength);
}
}
uMACfragNum = cbGetFragCount(pDevice, pTransmitKey,
cbFrameBodySize, &pDevice->sTxEthHeader);
if (uMACfragNum > AVAIL_TD(pDevice, TYPE_AC0DMA))
return false;
byPktType = pDevice->byPacketType;
if (pDevice->bFixRate) {
if (pDevice->eCurrentPHYType == PHY_TYPE_11B) {
if (pDevice->uConnectionRate >= RATE_11M)
pDevice->wCurrentRate = RATE_11M;
else
pDevice->wCurrentRate = pDevice->uConnectionRate;
} else {
if ((pDevice->eCurrentPHYType == PHY_TYPE_11A) &&
(pDevice->uConnectionRate <= RATE_6M)) {
pDevice->wCurrentRate = RATE_6M;
} else {
if (pDevice->uConnectionRate >= RATE_54M)
pDevice->wCurrentRate = RATE_54M;
else
pDevice->wCurrentRate = pDevice->uConnectionRate;
}
}
} else {
pDevice->wCurrentRate = pDevice->pMgmt->sNodeDBTable[uNodeIndex].wTxDataRate;
}
if (pDevice->wCurrentRate <= RATE_11M)
byPktType = PK_TYPE_11B;
vGenerateFIFOHeader(pDevice, byPktType, pDevice->pbyTmpBuff,
bNeedEncryption, cbFrameBodySize, TYPE_AC0DMA,
pHeadTD, &pDevice->sTxEthHeader, pbySkbData,
pTransmitKey, uNodeIndex, &uMACfragNum,
&cbHeaderSize);
if (MACbIsRegBitsOn(pDevice->PortOffset, MAC_REG_PSCTL, PSCTL_PS)) {
// Disable PS
MACbPSWakeup(pDevice->PortOffset);
}
pDevice->bPWBitOn = false;
pLastTD = pHeadTD;
for (ii = 0; ii < uMACfragNum; ii++) {
// Poll Transmit the adapter
wmb();
pHeadTD->m_td0TD0.f1Owner = OWNED_BY_NIC;
wmb();
if (ii == (uMACfragNum - 1))
pLastTD = pHeadTD;
pHeadTD = pHeadTD->next;
}
pLastTD->pTDInfo->skb = NULL;
pLastTD->pTDInfo->byFlags = 0;
pDevice->apCurrTD[TYPE_AC0DMA] = pHeadTD;
MACvTransmitAC0(pDevice->PortOffset);
return true;
}
| gpl-2.0 |
project-magpie/linux-sh4-2.6.32.y | fs/coda/file.c | 587 | 6237 | /*
* File operations for Coda.
* Original version: (C) 1996 Peter Braam
* Rewritten for Linux 2.1: (C) 1997 Carnegie Mellon University
*
* Carnegie Mellon encourages users of this code to contribute improvements
* to the Coda project. Contact Peter Braam <coda@cs.cmu.edu>.
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/time.h>
#include <linux/file.h>
#include <linux/fs.h>
#include <linux/stat.h>
#include <linux/cred.h>
#include <linux/errno.h>
#include <linux/smp_lock.h>
#include <linux/string.h>
#include <asm/uaccess.h>
#include <linux/coda.h>
#include <linux/coda_linux.h>
#include <linux/coda_fs_i.h>
#include <linux/coda_psdev.h>
#include "coda_int.h"
static ssize_t
coda_file_read(struct file *coda_file, char __user *buf, size_t count, loff_t *ppos)
{
struct coda_file_info *cfi;
struct file *host_file;
cfi = CODA_FTOC(coda_file);
BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC);
host_file = cfi->cfi_container;
if (!host_file->f_op || !host_file->f_op->read)
return -EINVAL;
return host_file->f_op->read(host_file, buf, count, ppos);
}
static ssize_t
coda_file_splice_read(struct file *coda_file, loff_t *ppos,
struct pipe_inode_info *pipe, size_t count,
unsigned int flags)
{
ssize_t (*splice_read)(struct file *, loff_t *,
struct pipe_inode_info *, size_t, unsigned int);
struct coda_file_info *cfi;
struct file *host_file;
cfi = CODA_FTOC(coda_file);
BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC);
host_file = cfi->cfi_container;
splice_read = host_file->f_op->splice_read;
if (!splice_read)
splice_read = default_file_splice_read;
return splice_read(host_file, ppos, pipe, count, flags);
}
static ssize_t
coda_file_write(struct file *coda_file, const char __user *buf, size_t count, loff_t *ppos)
{
struct inode *host_inode, *coda_inode = coda_file->f_path.dentry->d_inode;
struct coda_file_info *cfi;
struct file *host_file;
ssize_t ret;
cfi = CODA_FTOC(coda_file);
BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC);
host_file = cfi->cfi_container;
if (!host_file->f_op || !host_file->f_op->write)
return -EINVAL;
host_inode = host_file->f_path.dentry->d_inode;
mutex_lock(&coda_inode->i_mutex);
ret = host_file->f_op->write(host_file, buf, count, ppos);
coda_inode->i_size = host_inode->i_size;
coda_inode->i_blocks = (coda_inode->i_size + 511) >> 9;
coda_inode->i_mtime = coda_inode->i_ctime = CURRENT_TIME_SEC;
mutex_unlock(&coda_inode->i_mutex);
return ret;
}
static int
coda_file_mmap(struct file *coda_file, struct vm_area_struct *vma)
{
struct coda_file_info *cfi;
struct coda_inode_info *cii;
struct file *host_file;
struct inode *coda_inode, *host_inode;
cfi = CODA_FTOC(coda_file);
BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC);
host_file = cfi->cfi_container;
if (!host_file->f_op || !host_file->f_op->mmap)
return -ENODEV;
coda_inode = coda_file->f_path.dentry->d_inode;
host_inode = host_file->f_path.dentry->d_inode;
coda_file->f_mapping = host_file->f_mapping;
if (coda_inode->i_mapping == &coda_inode->i_data)
coda_inode->i_mapping = host_inode->i_mapping;
/* only allow additional mmaps as long as userspace isn't changing
* the container file on us! */
else if (coda_inode->i_mapping != host_inode->i_mapping)
return -EBUSY;
/* keep track of how often the coda_inode/host_file has been mmapped */
cii = ITOC(coda_inode);
cii->c_mapcount++;
cfi->cfi_mapcount++;
return host_file->f_op->mmap(host_file, vma);
}
int coda_open(struct inode *coda_inode, struct file *coda_file)
{
struct file *host_file = NULL;
int error;
unsigned short flags = coda_file->f_flags & (~O_EXCL);
unsigned short coda_flags = coda_flags_to_cflags(flags);
struct coda_file_info *cfi;
cfi = kmalloc(sizeof(struct coda_file_info), GFP_KERNEL);
if (!cfi)
return -ENOMEM;
lock_kernel();
error = venus_open(coda_inode->i_sb, coda_i2f(coda_inode), coda_flags,
&host_file);
if (!host_file)
error = -EIO;
if (error) {
kfree(cfi);
unlock_kernel();
return error;
}
host_file->f_flags |= coda_file->f_flags & (O_APPEND | O_SYNC);
cfi->cfi_magic = CODA_MAGIC;
cfi->cfi_mapcount = 0;
cfi->cfi_container = host_file;
BUG_ON(coda_file->private_data != NULL);
coda_file->private_data = cfi;
unlock_kernel();
return 0;
}
int coda_release(struct inode *coda_inode, struct file *coda_file)
{
unsigned short flags = (coda_file->f_flags) & (~O_EXCL);
unsigned short coda_flags = coda_flags_to_cflags(flags);
struct coda_file_info *cfi;
struct coda_inode_info *cii;
struct inode *host_inode;
int err = 0;
lock_kernel();
cfi = CODA_FTOC(coda_file);
BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC);
err = venus_close(coda_inode->i_sb, coda_i2f(coda_inode),
coda_flags, coda_file->f_cred->fsuid);
host_inode = cfi->cfi_container->f_path.dentry->d_inode;
cii = ITOC(coda_inode);
/* did we mmap this file? */
if (coda_inode->i_mapping == &host_inode->i_data) {
cii->c_mapcount -= cfi->cfi_mapcount;
if (!cii->c_mapcount)
coda_inode->i_mapping = &coda_inode->i_data;
}
fput(cfi->cfi_container);
kfree(coda_file->private_data);
coda_file->private_data = NULL;
unlock_kernel();
/* VFS fput ignores the return value from file_operations->release, so
* there is no use returning an error here */
return 0;
}
int coda_fsync(struct file *coda_file, struct dentry *coda_dentry, int datasync)
{
struct file *host_file;
struct inode *coda_inode = coda_dentry->d_inode;
struct coda_file_info *cfi;
int err = 0;
if (!(S_ISREG(coda_inode->i_mode) || S_ISDIR(coda_inode->i_mode) ||
S_ISLNK(coda_inode->i_mode)))
return -EINVAL;
cfi = CODA_FTOC(coda_file);
BUG_ON(!cfi || cfi->cfi_magic != CODA_MAGIC);
host_file = cfi->cfi_container;
err = vfs_fsync(host_file, host_file->f_path.dentry, datasync);
if ( !err && !datasync ) {
lock_kernel();
err = venus_fsync(coda_inode->i_sb, coda_i2f(coda_inode));
unlock_kernel();
}
return err;
}
const struct file_operations coda_file_operations = {
.llseek = generic_file_llseek,
.read = coda_file_read,
.write = coda_file_write,
.mmap = coda_file_mmap,
.open = coda_open,
.release = coda_release,
.fsync = coda_fsync,
.splice_read = coda_file_splice_read,
};
| gpl-2.0 |
Split-Screen/android_kernel_cyanogen_msm8916 | arch/arm/mach-msm/clock-mmss-8974.c | 843 | 83436 | /* Copyright (c) 2013-2014, 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/kernel.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/io.h>
#include <linux/spinlock.h>
#include <linux/clk.h>
#include <linux/iopoll.h>
#include <linux/regulator/consumer.h>
#include <linux/regulator/rpm-smd-regulator.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/clk/msm-clock-generic.h>
#include <soc/qcom/clock-local2.h>
#include <soc/qcom/clock-pll.h>
#include <soc/qcom/clock-rpm.h>
#include <soc/qcom/clock-voter.h>
#include <dt-bindings/clock/msm-clocks-8974.h>
#include "clock-mdss-8974.h"
#include "clock.h"
enum {
MMSS_BASE,
N_BASES,
};
static void __iomem *virt_bases[N_BASES];
#define MMSS_REG_BASE(x) (void __iomem *)(virt_bases[MMSS_BASE] + (x))
#define MMPLL0_MODE_REG 0x0000
#define MMPLL0_L_REG 0x0004
#define MMPLL0_M_REG 0x0008
#define MMPLL0_N_REG 0x000C
#define MMPLL0_USER_CTL_REG 0x0010
#define MMPLL0_CONFIG_CTL_REG 0x0014
#define MMPLL0_TEST_CTL_REG 0x0018
#define MMPLL0_STATUS_REG 0x001C
#define MMPLL1_MODE_REG 0x0040
#define MMPLL1_L_REG 0x0044
#define MMPLL1_M_REG 0x0048
#define MMPLL1_N_REG 0x004C
#define MMPLL1_USER_CTL_REG 0x0050
#define MMPLL1_CONFIG_CTL_REG 0x0054
#define MMPLL1_TEST_CTL_REG 0x0058
#define MMPLL1_STATUS_REG 0x005C
#define MMPLL3_MODE_REG 0x0080
#define MMPLL3_L_REG 0x0084
#define MMPLL3_M_REG 0x0088
#define MMPLL3_N_REG 0x008C
#define MMPLL3_USER_CTL_REG 0x0090
#define MMPLL3_CONFIG_CTL_REG 0x0094
#define MMPLL3_TEST_CTL_REG 0x0098
#define MMPLL3_STATUS_REG 0x009C
#define GCC_DEBUG_CLK_CTL_REG 0x1880
#define CLOCK_FRQ_MEASURE_CTL_REG 0x1884
#define CLOCK_FRQ_MEASURE_STATUS_REG 0x1888
#define GCC_XO_DIV4_CBCR_REG 0x10C8
#define GCC_PLLTEST_PAD_CFG_REG 0x188C
#define APCS_GPLL_ENA_VOTE_REG 0x1480
#define MMSS_PLL_VOTE_APCS_REG 0x0100
#define MMSS_DEBUG_CLK_CTL_REG 0x0900
#define VCODEC0_CMD_RCGR 0x1000
#define PCLK0_CMD_RCGR 0x2000
#define PCLK1_CMD_RCGR 0x2020
#define MDP_CMD_RCGR 0x2040
#define EXTPCLK_CMD_RCGR 0x2060
#define VSYNC_CMD_RCGR 0x2080
#define EDPPIXEL_CMD_RCGR 0x20A0
#define EDPLINK_CMD_RCGR 0x20C0
#define EDPAUX_CMD_RCGR 0x20E0
#define HDMI_CMD_RCGR 0x2100
#define BYTE0_CMD_RCGR 0x2120
#define BYTE1_CMD_RCGR 0x2140
#define ESC0_CMD_RCGR 0x2160
#define ESC1_CMD_RCGR 0x2180
#define CSI0PHYTIMER_CMD_RCGR 0x3000
#define CSI1PHYTIMER_CMD_RCGR 0x3030
#define CSI2PHYTIMER_CMD_RCGR 0x3060
#define CSI0_CMD_RCGR 0x3090
#define CSI1_CMD_RCGR 0x3100
#define CSI2_CMD_RCGR 0x3160
#define CSI3_CMD_RCGR 0x31C0
#define CCI_CMD_RCGR 0x3300
#define MCLK0_CMD_RCGR 0x3360
#define MCLK1_CMD_RCGR 0x3390
#define MCLK2_CMD_RCGR 0x33C0
#define MCLK3_CMD_RCGR 0x33F0
#define MMSS_GP0_CMD_RCGR 0x3420
#define MMSS_GP1_CMD_RCGR 0x3450
#define JPEG0_CMD_RCGR 0x3500
#define JPEG1_CMD_RCGR 0x3520
#define JPEG2_CMD_RCGR 0x3540
#define VFE0_CMD_RCGR 0x3600
#define VFE1_CMD_RCGR 0x3620
#define CPP_CMD_RCGR 0x3640
#define GFX3D_CMD_RCGR 0x4000
#define RBCPR_CMD_RCGR 0x4060
#define AHB_CMD_RCGR 0x5000
#define AXI_CMD_RCGR 0x5040
#define OCMEMNOC_CMD_RCGR 0x5090
#define OCMEMCX_OCMEMNOC_CBCR 0x4058
#define VENUS0_BCR 0x1020
#define MDSS_BCR 0x2300
#define CAMSS_PHY0_BCR 0x3020
#define CAMSS_PHY1_BCR 0x3050
#define CAMSS_PHY2_BCR 0x3080
#define CAMSS_CSI0_BCR 0x30B0
#define CAMSS_CSI0PHY_BCR 0x30C0
#define CAMSS_CSI0RDI_BCR 0x30D0
#define CAMSS_CSI0PIX_BCR 0x30E0
#define CAMSS_CSI1_BCR 0x3120
#define CAMSS_CSI1PHY_BCR 0x3130
#define CAMSS_CSI1RDI_BCR 0x3140
#define CAMSS_CSI1PIX_BCR 0x3150
#define CAMSS_CSI2_BCR 0x3180
#define CAMSS_CSI2PHY_BCR 0x3190
#define CAMSS_CSI2RDI_BCR 0x31A0
#define CAMSS_CSI2PIX_BCR 0x31B0
#define CAMSS_CSI3_BCR 0x31E0
#define CAMSS_CSI3PHY_BCR 0x31F0
#define CAMSS_CSI3RDI_BCR 0x3200
#define CAMSS_CSI3PIX_BCR 0x3210
#define CAMSS_ISPIF_BCR 0x3220
#define CAMSS_CCI_BCR 0x3340
#define CAMSS_MCLK0_BCR 0x3380
#define CAMSS_MCLK1_BCR 0x33B0
#define CAMSS_MCLK2_BCR 0x33E0
#define CAMSS_MCLK3_BCR 0x3410
#define CAMSS_GP0_BCR 0x3440
#define CAMSS_GP1_BCR 0x3470
#define CAMSS_TOP_BCR 0x3480
#define CAMSS_MICRO_BCR 0x3490
#define CAMSS_JPEG_BCR 0x35A0
#define CAMSS_VFE_BCR 0x36A0
#define CAMSS_CSI_VFE0_BCR 0x3700
#define CAMSS_CSI_VFE1_BCR 0x3710
#define OCMEMNOC_BCR 0x50B0
#define MMSSNOCAHB_BCR 0x5020
#define MMSSNOCAXI_BCR 0x5060
#define OXILI_GFX3D_CBCR 0x4028
#define OXILICX_AHB_CBCR 0x403C
#define OXILICX_AXI_CBCR 0x4038
#define OXILI_BCR 0x4020
#define OXILICX_BCR 0x4030
#define OCMEM_SYS_NOC_AXI_CBCR 0x0244
#define OCMEM_NOC_CFG_AHB_CBCR 0x0248
#define MMSS_NOC_CFG_AHB_CBCR 0x024C
#define VENUS0_VCODEC0_CBCR 0x1028
#define VENUS0_AHB_CBCR 0x1030
#define VENUS0_AXI_CBCR 0x1034
#define VENUS0_OCMEMNOC_CBCR 0x1038
#define MDSS_AHB_CBCR 0x2308
#define MDSS_HDMI_AHB_CBCR 0x230C
#define MDSS_AXI_CBCR 0x2310
#define MDSS_PCLK0_CBCR 0x2314
#define MDSS_PCLK1_CBCR 0x2318
#define MDSS_MDP_CBCR 0x231C
#define MDSS_MDP_LUT_CBCR 0x2320
#define MDSS_EXTPCLK_CBCR 0x2324
#define MDSS_VSYNC_CBCR 0x2328
#define MDSS_EDPPIXEL_CBCR 0x232C
#define MDSS_EDPLINK_CBCR 0x2330
#define MDSS_EDPAUX_CBCR 0x2334
#define MDSS_HDMI_CBCR 0x2338
#define MDSS_BYTE0_CBCR 0x233C
#define MDSS_BYTE1_CBCR 0x2340
#define MDSS_ESC0_CBCR 0x2344
#define MDSS_ESC1_CBCR 0x2348
#define CAMSS_PHY0_CSI0PHYTIMER_CBCR 0x3024
#define CAMSS_PHY1_CSI1PHYTIMER_CBCR 0x3054
#define CAMSS_PHY2_CSI2PHYTIMER_CBCR 0x3084
#define CAMSS_CSI0_CBCR 0x30B4
#define CAMSS_CSI0_AHB_CBCR 0x30BC
#define CAMSS_CSI0PHY_CBCR 0x30C4
#define CAMSS_CSI0RDI_CBCR 0x30D4
#define CAMSS_CSI0PIX_CBCR 0x30E4
#define CAMSS_CSI1_CBCR 0x3124
#define CAMSS_CSI1_AHB_CBCR 0x3128
#define CAMSS_CSI1PHY_CBCR 0x3134
#define CAMSS_CSI1RDI_CBCR 0x3144
#define CAMSS_CSI1PIX_CBCR 0x3154
#define CAMSS_CSI2_CBCR 0x3184
#define CAMSS_CSI2_AHB_CBCR 0x3188
#define CAMSS_CSI2PHY_CBCR 0x3194
#define CAMSS_CSI2RDI_CBCR 0x31A4
#define CAMSS_CSI2PIX_CBCR 0x31B4
#define CAMSS_CSI3_CBCR 0x31E4
#define CAMSS_CSI3_AHB_CBCR 0x31E8
#define CAMSS_CSI3PHY_CBCR 0x31F4
#define CAMSS_CSI3RDI_CBCR 0x3204
#define CAMSS_CSI3PIX_CBCR 0x3214
#define CAMSS_ISPIF_AHB_CBCR 0x3224
#define CAMSS_CCI_CCI_CBCR 0x3344
#define CAMSS_CCI_CCI_AHB_CBCR 0x3348
#define CAMSS_MCLK0_CBCR 0x3384
#define CAMSS_MCLK1_CBCR 0x33B4
#define CAMSS_MCLK2_CBCR 0x33E4
#define CAMSS_MCLK3_CBCR 0x3414
#define CAMSS_GP0_CBCR 0x3444
#define CAMSS_GP1_CBCR 0x3474
#define CAMSS_TOP_AHB_CBCR 0x3484
#define CAMSS_MICRO_AHB_CBCR 0x3494
#define CAMSS_JPEG_JPEG0_CBCR 0x35A8
#define CAMSS_JPEG_JPEG1_CBCR 0x35AC
#define CAMSS_JPEG_JPEG2_CBCR 0x35B0
#define CAMSS_JPEG_JPEG_AHB_CBCR 0x35B4
#define CAMSS_JPEG_JPEG_AXI_CBCR 0x35B8
#define CAMSS_JPEG_JPEG_OCMEMNOC_CBCR 0x35BC
#define CAMSS_VFE_VFE0_CBCR 0x36A8
#define CAMSS_VFE_VFE1_CBCR 0x36AC
#define CAMSS_VFE_CPP_CBCR 0x36B0
#define CAMSS_VFE_CPP_AHB_CBCR 0x36B4
#define CAMSS_VFE_VFE_AHB_CBCR 0x36B8
#define CAMSS_VFE_VFE_AXI_CBCR 0x36BC
#define CAMSS_VFE_VFE_OCMEMNOC_CBCR 0x36C0
#define CAMSS_CSI_VFE0_CBCR 0x3704
#define CAMSS_CSI_VFE1_CBCR 0x3714
#define MMSS_MMSSNOC_AXI_CBCR 0x506C
#define MMSS_MMSSNOC_AHB_CBCR 0x5024
#define MMSS_MMSSNOC_BTO_AHB_CBCR 0x5028
#define MMSS_MISC_AHB_CBCR 0x502C
#define MMSS_S0_AXI_CBCR 0x5064
#define OCMEMNOC_CBCR 0x50B4
#define MMSS_DEBUG_CLK_CTL_REG 0x0900
#define mmpll0_mm_source_val 1
#define mmpll1_mm_source_val 2
#define mmpll3_mm_source_val 3
#define gpll0_mm_source_val 5
#define cxo_mm_source_val 0
#define mm_gnd_source_val 6
#define edp_mainlink_mm_source_val 4
#define edp_pixel_mm_source_val 5
#define edppll_350_mm_source_val 4
#define dsipll_750_mm_source_val 1
#define dsipll0_byte_mm_source_val 1
#define dsipll0_pixel_mm_source_val 1
#define hdmipll_mm_source_val 3
#define F_MM(f, s, div, m, n) \
{ \
.freq_hz = (f), \
.src_clk = &s##_clk_src.c, \
.m_val = (m), \
.n_val = ~((n)-(m)) * !!(n), \
.d_val = ~(n),\
.div_src_val = BVAL(4, 0, (int)(2*(div) - 1)) \
| BVAL(10, 8, s##_mm_source_val), \
}
#define F_EDP(f, s, div, m, n) \
{ \
.freq_hz = (f), \
.src_clk = &s##_clk_src.c, \
.m_val = (m), \
.n_val = ~((n)-(m)) * !!(n), \
.d_val = ~(n),\
.div_src_val = BVAL(4, 0, (int)(2*(div) - 1)) \
| BVAL(10, 8, s##_mm_source_val), \
}
#define F_MDSS(f, s, div, m, n) \
{ \
.freq_hz = (f), \
.m_val = (m), \
.n_val = ~((n)-(m)) * !!(n), \
.d_val = ~(n),\
.div_src_val = BVAL(4, 0, (int)(2*(div) - 1)) \
| BVAL(10, 8, s##_mm_source_val), \
}
#define VDD_DIG_FMAX_MAP1(l1, f1) \
.vdd_class = &vdd_dig, \
.fmax = (unsigned long[VDD_DIG_NUM]) { \
[VDD_DIG_##l1] = (f1), \
}, \
.num_fmax = VDD_DIG_NUM
#define VDD_DIG_FMAX_MAP2(l1, f1, l2, f2) \
.vdd_class = &vdd_dig, \
.fmax = (unsigned long[VDD_DIG_NUM]) { \
[VDD_DIG_##l1] = (f1), \
[VDD_DIG_##l2] = (f2), \
}, \
.num_fmax = VDD_DIG_NUM
#define VDD_DIG_FMAX_MAP3(l1, f1, l2, f2, l3, f3) \
.vdd_class = &vdd_dig, \
.fmax = (unsigned long[VDD_DIG_NUM]) { \
[VDD_DIG_##l1] = (f1), \
[VDD_DIG_##l2] = (f2), \
[VDD_DIG_##l3] = (f3), \
}, \
.num_fmax = VDD_DIG_NUM
enum vdd_dig_levels {
VDD_DIG_NONE,
VDD_DIG_LOW,
VDD_DIG_NOMINAL,
VDD_DIG_HIGH,
VDD_DIG_NUM
};
static int vdd_corner[] = {
RPM_REGULATOR_CORNER_NONE, /* VDD_DIG_NONE */
RPM_REGULATOR_CORNER_SVS_SOC, /* VDD_DIG_LOW */
RPM_REGULATOR_CORNER_NORMAL, /* VDD_DIG_NOMINAL */
RPM_REGULATOR_CORNER_SUPER_TURBO, /* VDD_DIG_HIGH */
};
static DEFINE_VDD_REGULATORS(vdd_dig, VDD_DIG_NUM, 1, vdd_corner, NULL);
DEFINE_EXT_CLK(cxo_clk_src, NULL);
DEFINE_EXT_CLK(gpll0_clk_src, NULL);
DEFINE_EXT_CLK(mmssnoc_ahb, NULL);
static struct pll_vote_clk mmpll0_clk_src = {
.en_reg = (void __iomem *)MMSS_PLL_VOTE_APCS_REG,
.en_mask = BIT(0),
.status_reg = (void __iomem *)MMPLL0_STATUS_REG,
.status_mask = BIT(17),
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &cxo_clk_src.c,
.dbg_name = "mmpll0_clk_src",
.rate = 800000000,
.ops = &clk_ops_pll_vote,
CLK_INIT(mmpll0_clk_src.c),
},
};
static struct pll_vote_clk mmpll1_clk_src = {
.en_reg = (void __iomem *)MMSS_PLL_VOTE_APCS_REG,
.en_mask = BIT(1),
.status_reg = (void __iomem *)MMPLL1_STATUS_REG,
.status_mask = BIT(17),
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &cxo_clk_src.c,
.dbg_name = "mmpll1_clk_src",
.rate = 846000000,
.ops = &clk_ops_pll_vote,
/* May be reassigned at runtime; alloc memory at compile time */
VDD_DIG_FMAX_MAP1(LOW, 846000000),
CLK_INIT(mmpll1_clk_src.c),
},
};
static struct pll_clk mmpll3_clk_src = {
.mode_reg = (void __iomem *)MMPLL3_MODE_REG,
.status_reg = (void __iomem *)MMPLL3_STATUS_REG,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &cxo_clk_src.c,
.dbg_name = "mmpll3_clk_src",
.rate = 820000000,
.ops = &clk_ops_local_pll,
CLK_INIT(mmpll3_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_mmss_axi_clk[] = {
F_MM( 19200000, cxo, 1, 0, 0),
F_MM( 37500000, gpll0, 16, 0, 0),
F_MM( 50000000, gpll0, 12, 0, 0),
F_MM( 75000000, gpll0, 8, 0, 0),
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(150000000, gpll0, 4, 0, 0),
F_MM(282000000, mmpll1, 3, 0, 0),
F_MM(400000000, mmpll0, 2, 0, 0),
F_END
};
static struct clk_freq_tbl ftbl_mmss_axi_v2_clk[] = {
F_MM( 19200000, cxo, 1, 0, 0),
F_MM( 37500000, gpll0, 16, 0, 0),
F_MM( 50000000, gpll0, 12, 0, 0),
F_MM( 75000000, gpll0, 8, 0, 0),
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(150000000, gpll0, 4, 0, 0),
F_MM(291750000, mmpll1, 4, 0, 0),
F_MM(400000000, mmpll0, 2, 0, 0),
F_MM(466800000, mmpll1, 2.5, 0, 0),
F_END
};
static struct rcg_clk axi_clk_src = {
.cmd_rcgr_reg = 0x5040,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_mmss_axi_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "axi_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 150000000, NOMINAL, 282000000,
HIGH, 400000000),
CLK_INIT(axi_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_ocmemnoc_clk[] = {
F_MM( 19200000, cxo, 1, 0, 0),
F_MM( 37500000, gpll0, 16, 0, 0),
F_MM( 50000000, gpll0, 12, 0, 0),
F_MM( 75000000, gpll0, 8, 0, 0),
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(150000000, gpll0, 4, 0, 0),
F_MM(282000000, mmpll1, 3, 0, 0),
F_MM(400000000, mmpll0, 2, 0, 0),
F_END
};
static struct clk_freq_tbl ftbl_ocmemnoc_v2_clk[] = {
F_MM( 19200000, cxo, 1, 0, 0),
F_MM( 37500000, gpll0, 16, 0, 0),
F_MM( 50000000, gpll0, 12, 0, 0),
F_MM( 75000000, gpll0, 8, 0, 0),
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(150000000, gpll0, 4, 0, 0),
F_MM(291750000, mmpll1, 4, 0, 0),
F_MM(400000000, mmpll0, 2, 0, 0),
F_END
};
struct rcg_clk ocmemnoc_clk_src = {
.cmd_rcgr_reg = OCMEMNOC_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_ocmemnoc_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "ocmemnoc_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 150000000, NOMINAL, 282000000,
HIGH, 400000000),
CLK_INIT(ocmemnoc_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_camss_csi0_3_clk[] = {
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(200000000, mmpll0, 4, 0, 0),
F_END
};
static struct rcg_clk csi0_clk_src = {
.cmd_rcgr_reg = CSI0_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_csi0_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "csi0_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi0_clk_src.c),
},
};
static struct rcg_clk csi1_clk_src = {
.cmd_rcgr_reg = CSI1_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_csi0_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "csi1_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi1_clk_src.c),
},
};
static struct rcg_clk csi2_clk_src = {
.cmd_rcgr_reg = CSI2_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_csi0_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "csi2_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi2_clk_src.c),
},
};
static struct rcg_clk csi3_clk_src = {
.cmd_rcgr_reg = CSI3_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_csi0_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "csi3_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi3_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_camss_vfe_vfe0_1_clk[] = {
F_MM( 37500000, gpll0, 16, 0, 0),
F_MM( 50000000, gpll0, 12, 0, 0),
F_MM( 60000000, gpll0, 10, 0, 0),
F_MM( 80000000, gpll0, 7.5, 0, 0),
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(109090000, gpll0, 5.5, 0, 0),
F_MM(150000000, gpll0, 4, 0, 0),
F_MM(200000000, gpll0, 3, 0, 0),
F_MM(228570000, mmpll0, 3.5, 0, 0),
F_MM(266670000, mmpll0, 3, 0, 0),
F_MM(320000000, mmpll0, 2.5, 0, 0),
F_MM(465000000, mmpll3, 2, 0, 0),
F_END
};
static struct rcg_clk vfe0_clk_src = {
.cmd_rcgr_reg = VFE0_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_vfe_vfe0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "vfe0_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 266670000,
HIGH, 320000000),
CLK_INIT(vfe0_clk_src.c),
},
};
static struct rcg_clk vfe1_clk_src = {
.cmd_rcgr_reg = VFE1_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_vfe_vfe0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "vfe1_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 266670000,
HIGH, 320000000),
CLK_INIT(vfe1_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_mdss_mdp_clk[] = {
F_MM( 37500000, gpll0, 16, 0, 0),
F_MM( 60000000, gpll0, 10, 0, 0),
F_MM( 75000000, gpll0, 8, 0, 0),
F_MM( 85710000, gpll0, 7, 0, 0),
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(133330000, mmpll0, 6, 0, 0),
F_MM(160000000, mmpll0, 5, 0, 0),
F_MM(200000000, mmpll0, 4, 0, 0),
F_MM(240000000, gpll0, 2.5, 0, 0),
F_MM(266670000, mmpll0, 3, 0, 0),
F_MM(320000000, mmpll0, 2.5, 0, 0),
F_END
};
static struct rcg_clk mdp_clk_src = {
.cmd_rcgr_reg = MDP_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_mdss_mdp_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mdp_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 266670000,
HIGH, 320000000),
CLK_INIT(mdp_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_camss_cci_cci_clk[] = {
F_MM(19200000, cxo, 1, 0, 0),
F_END
};
static struct rcg_clk cci_clk_src = {
.cmd_rcgr_reg = CCI_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_cci_cci_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "cci_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 20000000, NOMINAL, 40000000),
CLK_INIT(cci_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_camss_gp0_1_clk[] = {
F_MM( 10000, cxo, 16, 1, 120),
F_MM( 20000, cxo, 16, 1, 50),
F_MM( 6000000, gpll0, 10, 1, 10),
F_MM(12000000, gpll0, 10, 1, 5),
F_MM(13000000, gpll0, 10, 13, 60),
F_MM(24000000, gpll0, 5, 1, 5),
F_END
};
static struct rcg_clk mmss_gp0_clk_src = {
.cmd_rcgr_reg = MMSS_GP0_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_camss_gp0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mmss_gp0_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(mmss_gp0_clk_src.c),
},
};
static struct rcg_clk mmss_gp1_clk_src = {
.cmd_rcgr_reg = MMSS_GP1_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_camss_gp0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mmss_gp1_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(mmss_gp1_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_camss_jpeg_jpeg0_2_clk[] = {
F_MM( 75000000, gpll0, 8, 0, 0),
F_MM(150000000, gpll0, 4, 0, 0),
F_MM(200000000, gpll0, 3, 0, 0),
F_MM(228570000, mmpll0, 3.5, 0, 0),
F_MM(266670000, mmpll0, 3, 0, 0),
F_MM(320000000, mmpll0, 2.5, 0, 0),
F_END
};
static struct rcg_clk jpeg0_clk_src = {
.cmd_rcgr_reg = JPEG0_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_jpeg_jpeg0_2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "jpeg0_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 266670000,
HIGH, 320000000),
CLK_INIT(jpeg0_clk_src.c),
},
};
static struct rcg_clk jpeg1_clk_src = {
.cmd_rcgr_reg = JPEG1_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_jpeg_jpeg0_2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "jpeg1_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 266670000,
HIGH, 320000000),
CLK_INIT(jpeg1_clk_src.c),
},
};
static struct rcg_clk jpeg2_clk_src = {
.cmd_rcgr_reg = JPEG2_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_jpeg_jpeg0_2_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "jpeg2_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 266670000,
HIGH, 320000000),
CLK_INIT(jpeg2_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_camss_mclk0_3_clk[] = {
F_MM(19200000, cxo, 1, 0, 0),
F_MM(66670000, gpll0, 9, 0, 0),
F_END
};
static struct clk_freq_tbl ftbl_camss_mclk0_3_pro_clk[] = {
F_MM( 4800000, cxo, 4, 0, 0),
F_MM( 6000000, gpll0, 10, 1, 10),
F_MM( 8000000, gpll0, 15, 1, 5),
F_MM( 9600000, cxo, 2, 0, 0),
F_MM(16000000, gpll0, 12.5, 1, 3),
F_MM(19200000, cxo, 1, 0, 0),
F_MM(24000000, gpll0, 5, 1, 5),
F_MM(32000000, mmpll0, 5, 1, 5),
F_MM(48000000, gpll0, 12.5, 0, 0),
F_MM(64000000, mmpll0, 12.5, 0, 0),
F_MM(66670000, gpll0, 9, 0, 0),
F_END
};
static struct rcg_clk mclk0_clk_src = {
.cmd_rcgr_reg = MCLK0_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_mclk0_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mclk0_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 66670000),
CLK_INIT(mclk0_clk_src.c),
},
};
static struct rcg_clk mclk1_clk_src = {
.cmd_rcgr_reg = MCLK1_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_mclk0_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mclk1_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 66670000),
CLK_INIT(mclk1_clk_src.c),
},
};
static struct rcg_clk mclk2_clk_src = {
.cmd_rcgr_reg = MCLK2_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_mclk0_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mclk2_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 66670000),
CLK_INIT(mclk2_clk_src.c),
},
};
static struct rcg_clk mclk3_clk_src = {
.cmd_rcgr_reg = MCLK3_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_mclk0_3_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mclk3_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP1(LOW, 66670000),
CLK_INIT(mclk3_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_camss_phy0_2_csi0_2phytimer_clk[] = {
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(200000000, mmpll0, 4, 0, 0),
F_END
};
static struct rcg_clk csi0phytimer_clk_src = {
.cmd_rcgr_reg = CSI0PHYTIMER_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_phy0_2_csi0_2phytimer_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "csi0phytimer_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi0phytimer_clk_src.c),
},
};
static struct rcg_clk csi1phytimer_clk_src = {
.cmd_rcgr_reg = CSI1PHYTIMER_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_phy0_2_csi0_2phytimer_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "csi1phytimer_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi1phytimer_clk_src.c),
},
};
static struct rcg_clk csi2phytimer_clk_src = {
.cmd_rcgr_reg = CSI2PHYTIMER_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_phy0_2_csi0_2phytimer_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "csi2phytimer_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 100000000, NOMINAL, 200000000),
CLK_INIT(csi2phytimer_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_camss_vfe_cpp_clk[] = {
F_MM(150000000, gpll0, 4, 0, 0),
F_MM(266670000, mmpll0, 3, 0, 0),
F_MM(320000000, mmpll0, 2.5, 0, 0),
F_MM(465000000, mmpll3, 2, 0, 0),
F_END
};
static struct rcg_clk cpp_clk_src = {
.cmd_rcgr_reg = CPP_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_camss_vfe_cpp_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "cpp_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 266670000,
HIGH, 320000000),
CLK_INIT(cpp_clk_src.c),
},
};
static struct clk_freq_tbl byte_freq_tbl[] = {
{
.src_clk = &byte_clk_src_8974.c,
.div_src_val = BVAL(10, 8, dsipll0_byte_mm_source_val),
},
F_END
};
static struct rcg_clk byte0_clk_src = {
.cmd_rcgr_reg = BYTE0_CMD_RCGR,
.current_freq = byte_freq_tbl,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &byte_clk_src_8974.c,
.dbg_name = "byte0_clk_src",
.ops = &clk_ops_byte,
VDD_DIG_FMAX_MAP3(LOW, 93800000, NOMINAL, 187500000,
HIGH, 188000000),
CLK_INIT(byte0_clk_src.c),
},
};
static struct rcg_clk byte1_clk_src = {
.cmd_rcgr_reg = BYTE1_CMD_RCGR,
.current_freq = byte_freq_tbl,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &byte_clk_src_8974.c,
.dbg_name = "byte1_clk_src",
.ops = &clk_ops_byte,
VDD_DIG_FMAX_MAP3(LOW, 93800000, NOMINAL, 187500000,
HIGH, 188000000),
CLK_INIT(byte1_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_mdss_edpaux_clk[] = {
F_MM(19200000, cxo, 1, 0, 0),
F_END
};
static struct rcg_clk edpaux_clk_src = {
.cmd_rcgr_reg = EDPAUX_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_mdss_edpaux_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "edpaux_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 20000000, NOMINAL, 40000000),
CLK_INIT(edpaux_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_mdss_edplink_clk[] = {
F_EDP(162000000, edp_mainlink, 1, 0, 0),
F_EDP(270000000, edp_mainlink, 1, 0, 0),
F_END
};
static struct rcg_clk edplink_clk_src = {
.cmd_rcgr_reg = EDPLINK_CMD_RCGR,
.freq_tbl = ftbl_mdss_edplink_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "edplink_clk_src",
.ops = &clk_ops_rcg_edp,
VDD_DIG_FMAX_MAP2(LOW, 135000000, NOMINAL, 270000000),
CLK_INIT(edplink_clk_src.c),
},
};
static struct clk_freq_tbl edp_pixel_freq_tbl[] = {
{
.src_clk = &edp_pixel_clk_src.c,
.div_src_val = BVAL(10, 8, edp_pixel_mm_source_val)
| BVAL(4, 0, 0),
},
F_END
};
static struct rcg_clk edppixel_clk_src = {
.cmd_rcgr_reg = EDPPIXEL_CMD_RCGR,
.set_rate = set_rate_mnd,
.current_freq = edp_pixel_freq_tbl,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &edp_pixel_clk_src.c,
.dbg_name = "edppixel_clk_src",
.ops = &clk_ops_edppixel,
VDD_DIG_FMAX_MAP2(LOW, 175000000, NOMINAL, 350000000),
CLK_INIT(edppixel_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_mdss_esc0_1_clk[] = {
F_MM(19200000, cxo, 1, 0, 0),
F_END
};
static struct rcg_clk esc0_clk_src = {
.cmd_rcgr_reg = ESC0_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_mdss_esc0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "esc0_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 20000000, NOMINAL, 40000000),
CLK_INIT(esc0_clk_src.c),
},
};
static struct rcg_clk esc1_clk_src = {
.cmd_rcgr_reg = ESC1_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_mdss_esc0_1_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "esc1_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 20000000, NOMINAL, 40000000),
CLK_INIT(esc1_clk_src.c),
},
};
static struct clk_freq_tbl exptclk_freq_tbl[] = {
{
.src_clk = &hdmipll_clk_src.c,
.div_src_val = BVAL(10, 8, hdmipll_mm_source_val),
},
F_END
};
static struct rcg_clk extpclk_clk_src = {
.cmd_rcgr_reg = EXTPCLK_CMD_RCGR,
.current_freq = exptclk_freq_tbl,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "extpclk_clk_src",
.parent = &hdmipll_clk_src.c,
.ops = &clk_ops_byte,
VDD_DIG_FMAX_MAP2(LOW, 148500000, NOMINAL, 297000000),
CLK_INIT(extpclk_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_mdss_hdmi_clk[] = {
F_MDSS(19200000, cxo, 1, 0, 0),
F_END
};
static struct rcg_clk hdmi_clk_src = {
.cmd_rcgr_reg = HDMI_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_mdss_hdmi_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "hdmi_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 20000000, NOMINAL, 40000000),
CLK_INIT(hdmi_clk_src.c),
},
};
static struct clk_freq_tbl pixel_freq_tbl[] = {
{
.src_clk = &pixel_clk_src_8974.c,
.div_src_val = BVAL(10, 8, dsipll0_pixel_mm_source_val)
| BVAL(4, 0, 0),
},
F_END
};
static struct rcg_clk pclk0_clk_src = {
.cmd_rcgr_reg = PCLK0_CMD_RCGR,
.current_freq = pixel_freq_tbl,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &pixel_clk_src_8974.c,
.dbg_name = "pclk0_clk_src",
.ops = &clk_ops_pixel,
VDD_DIG_FMAX_MAP2(LOW, 125000000, NOMINAL, 250000000),
CLK_INIT(pclk0_clk_src.c),
},
};
static struct rcg_clk pclk1_clk_src = {
.cmd_rcgr_reg = PCLK1_CMD_RCGR,
.current_freq = pixel_freq_tbl,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &pixel_clk_src_8974.c,
.dbg_name = "pclk1_clk_src",
.ops = &clk_ops_pixel,
VDD_DIG_FMAX_MAP2(LOW, 125000000, NOMINAL, 250000000),
CLK_INIT(pclk1_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_mdss_vsync_clk[] = {
F_MDSS(19200000, cxo, 1, 0, 0),
F_END
};
static struct rcg_clk vsync_clk_src = {
.cmd_rcgr_reg = VSYNC_CMD_RCGR,
.set_rate = set_rate_hid,
.freq_tbl = ftbl_mdss_vsync_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "vsync_clk_src",
.ops = &clk_ops_rcg,
VDD_DIG_FMAX_MAP2(LOW, 20000000, NOMINAL, 40000000),
CLK_INIT(vsync_clk_src.c),
},
};
static struct clk_freq_tbl ftbl_venus0_vcodec0_clk[] = {
F_MM( 50000000, gpll0, 12, 0, 0),
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(133330000, mmpll0, 6, 0, 0),
F_MM(200000000, mmpll0, 4, 0, 0),
F_MM(266670000, mmpll0, 3, 0, 0),
F_MM(410000000, mmpll3, 2, 0, 0),
F_END
};
static struct clk_freq_tbl ftbl_venus0_vcodec0_v2_clk[] = {
F_MM( 50000000, gpll0, 12, 0, 0),
F_MM(100000000, gpll0, 6, 0, 0),
F_MM(133330000, mmpll0, 6, 0, 0),
F_MM(200000000, mmpll0, 4, 0, 0),
F_MM(266670000, mmpll0, 3, 0, 0),
F_MM(465000000, mmpll3, 2, 0, 0),
F_END
};
static struct rcg_clk vcodec0_clk_src = {
.cmd_rcgr_reg = VCODEC0_CMD_RCGR,
.set_rate = set_rate_mnd,
.freq_tbl = ftbl_venus0_vcodec0_clk,
.current_freq = &rcg_dummy_freq,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "vcodec0_clk_src",
.ops = &clk_ops_rcg_mnd,
VDD_DIG_FMAX_MAP3(LOW, 133330000, NOMINAL, 266670000,
HIGH, 410000000),
CLK_INIT(vcodec0_clk_src.c),
},
};
static struct branch_clk camss_cci_cci_ahb_clk = {
.cbcr_reg = CAMSS_CCI_CCI_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_cci_cci_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_cci_cci_ahb_clk.c),
},
};
static struct branch_clk camss_cci_cci_clk = {
.cbcr_reg = CAMSS_CCI_CCI_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &cci_clk_src.c,
.dbg_name = "camss_cci_cci_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_cci_cci_clk.c),
},
};
static struct branch_clk camss_csi0_ahb_clk = {
.cbcr_reg = CAMSS_CSI0_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_csi0_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi0_ahb_clk.c),
},
};
static struct branch_clk camss_csi0_clk = {
.cbcr_reg = CAMSS_CSI0_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi0_clk_src.c,
.dbg_name = "camss_csi0_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi0_clk.c),
},
};
static struct branch_clk camss_csi0phy_clk = {
.cbcr_reg = CAMSS_CSI0PHY_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi0_clk_src.c,
.dbg_name = "camss_csi0phy_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi0phy_clk.c),
},
};
static struct branch_clk camss_csi0pix_clk = {
.cbcr_reg = CAMSS_CSI0PIX_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi0_clk_src.c,
.dbg_name = "camss_csi0pix_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi0pix_clk.c),
},
};
static struct branch_clk camss_csi0rdi_clk = {
.cbcr_reg = CAMSS_CSI0RDI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi0_clk_src.c,
.dbg_name = "camss_csi0rdi_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi0rdi_clk.c),
},
};
static struct branch_clk camss_csi1_ahb_clk = {
.cbcr_reg = CAMSS_CSI1_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_csi1_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi1_ahb_clk.c),
},
};
static struct branch_clk camss_csi1_clk = {
.cbcr_reg = CAMSS_CSI1_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi1_clk_src.c,
.dbg_name = "camss_csi1_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi1_clk.c),
},
};
static struct branch_clk camss_csi1phy_clk = {
.cbcr_reg = CAMSS_CSI1PHY_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi1_clk_src.c,
.dbg_name = "camss_csi1phy_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi1phy_clk.c),
},
};
static struct branch_clk camss_csi1pix_clk = {
.cbcr_reg = CAMSS_CSI1PIX_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi1_clk_src.c,
.dbg_name = "camss_csi1pix_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi1pix_clk.c),
},
};
static struct branch_clk camss_csi1rdi_clk = {
.cbcr_reg = CAMSS_CSI1RDI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi1_clk_src.c,
.dbg_name = "camss_csi1rdi_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi1rdi_clk.c),
},
};
static struct branch_clk camss_csi2_ahb_clk = {
.cbcr_reg = CAMSS_CSI2_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_csi2_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi2_ahb_clk.c),
},
};
static struct branch_clk camss_csi2_clk = {
.cbcr_reg = CAMSS_CSI2_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi2_clk_src.c,
.dbg_name = "camss_csi2_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi2_clk.c),
},
};
static struct branch_clk camss_csi2phy_clk = {
.cbcr_reg = CAMSS_CSI2PHY_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi2_clk_src.c,
.dbg_name = "camss_csi2phy_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi2phy_clk.c),
},
};
static struct branch_clk camss_csi2pix_clk = {
.cbcr_reg = CAMSS_CSI2PIX_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi2_clk_src.c,
.dbg_name = "camss_csi2pix_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi2pix_clk.c),
},
};
static struct branch_clk camss_csi2rdi_clk = {
.cbcr_reg = CAMSS_CSI2RDI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi2_clk_src.c,
.dbg_name = "camss_csi2rdi_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi2rdi_clk.c),
},
};
static struct branch_clk camss_csi3_ahb_clk = {
.cbcr_reg = CAMSS_CSI3_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_csi3_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi3_ahb_clk.c),
},
};
static struct branch_clk camss_csi3_clk = {
.cbcr_reg = CAMSS_CSI3_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi3_clk_src.c,
.dbg_name = "camss_csi3_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi3_clk.c),
},
};
static struct branch_clk camss_csi3phy_clk = {
.cbcr_reg = CAMSS_CSI3PHY_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi3_clk_src.c,
.dbg_name = "camss_csi3phy_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi3phy_clk.c),
},
};
static struct branch_clk camss_csi3pix_clk = {
.cbcr_reg = CAMSS_CSI3PIX_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi3_clk_src.c,
.dbg_name = "camss_csi3pix_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi3pix_clk.c),
},
};
static struct branch_clk camss_csi3rdi_clk = {
.cbcr_reg = CAMSS_CSI3RDI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi3_clk_src.c,
.dbg_name = "camss_csi3rdi_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi3rdi_clk.c),
},
};
static struct branch_clk camss_csi_vfe0_clk = {
.cbcr_reg = CAMSS_CSI_VFE0_CBCR,
.bcr_reg = CAMSS_CSI_VFE0_BCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &vfe0_clk_src.c,
.dbg_name = "camss_csi_vfe0_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi_vfe0_clk.c),
},
};
static struct branch_clk camss_csi_vfe1_clk = {
.cbcr_reg = CAMSS_CSI_VFE1_CBCR,
.bcr_reg = CAMSS_CSI_VFE1_BCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &vfe1_clk_src.c,
.dbg_name = "camss_csi_vfe1_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_csi_vfe1_clk.c),
},
};
static struct branch_clk camss_gp0_clk = {
.cbcr_reg = CAMSS_GP0_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &mmss_gp0_clk_src.c,
.dbg_name = "camss_gp0_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_gp0_clk.c),
},
};
static struct branch_clk camss_gp1_clk = {
.cbcr_reg = CAMSS_GP1_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &mmss_gp1_clk_src.c,
.dbg_name = "camss_gp1_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_gp1_clk.c),
},
};
static struct branch_clk camss_ispif_ahb_clk = {
.cbcr_reg = CAMSS_ISPIF_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_ispif_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_ispif_ahb_clk.c),
},
};
static struct branch_clk camss_jpeg_jpeg0_clk = {
.cbcr_reg = CAMSS_JPEG_JPEG0_CBCR,
.bcr_reg = CAMSS_JPEG_BCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &jpeg0_clk_src.c,
.dbg_name = "camss_jpeg_jpeg0_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_jpeg_jpeg0_clk.c),
},
};
static struct branch_clk camss_jpeg_jpeg1_clk = {
.cbcr_reg = CAMSS_JPEG_JPEG1_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &jpeg1_clk_src.c,
.dbg_name = "camss_jpeg_jpeg1_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_jpeg_jpeg1_clk.c),
},
};
static struct branch_clk camss_jpeg_jpeg2_clk = {
.cbcr_reg = CAMSS_JPEG_JPEG2_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &jpeg2_clk_src.c,
.dbg_name = "camss_jpeg_jpeg2_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_jpeg_jpeg2_clk.c),
},
};
static struct branch_clk camss_jpeg_jpeg_ahb_clk = {
.cbcr_reg = CAMSS_JPEG_JPEG_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_jpeg_jpeg_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_jpeg_jpeg_ahb_clk.c),
},
};
static struct branch_clk camss_jpeg_jpeg_axi_clk = {
.cbcr_reg = CAMSS_JPEG_JPEG_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &axi_clk_src.c,
.dbg_name = "camss_jpeg_jpeg_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_jpeg_jpeg_axi_clk.c),
},
};
static struct branch_clk camss_jpeg_jpeg_ocmemnoc_clk = {
.cbcr_reg = CAMSS_JPEG_JPEG_OCMEMNOC_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &ocmemnoc_clk_src.c,
.dbg_name = "camss_jpeg_jpeg_ocmemnoc_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_jpeg_jpeg_ocmemnoc_clk.c),
},
};
static struct branch_clk camss_mclk0_clk = {
.cbcr_reg = CAMSS_MCLK0_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &mclk0_clk_src.c,
.dbg_name = "camss_mclk0_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_mclk0_clk.c),
},
};
static struct branch_clk camss_mclk1_clk = {
.cbcr_reg = CAMSS_MCLK1_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &mclk1_clk_src.c,
.dbg_name = "camss_mclk1_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_mclk1_clk.c),
},
};
static struct branch_clk camss_mclk2_clk = {
.cbcr_reg = CAMSS_MCLK2_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &mclk2_clk_src.c,
.dbg_name = "camss_mclk2_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_mclk2_clk.c),
},
};
static struct branch_clk camss_mclk3_clk = {
.cbcr_reg = CAMSS_MCLK3_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &mclk3_clk_src.c,
.dbg_name = "camss_mclk3_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_mclk3_clk.c),
},
};
static struct branch_clk camss_micro_ahb_clk = {
.cbcr_reg = CAMSS_MICRO_AHB_CBCR,
.has_sibling = 1,
.bcr_reg = CAMSS_MICRO_BCR,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_micro_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_micro_ahb_clk.c),
},
};
static struct branch_clk camss_phy0_csi0phytimer_clk = {
.cbcr_reg = CAMSS_PHY0_CSI0PHYTIMER_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi0phytimer_clk_src.c,
.dbg_name = "camss_phy0_csi0phytimer_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_phy0_csi0phytimer_clk.c),
},
};
static struct branch_clk camss_phy1_csi1phytimer_clk = {
.cbcr_reg = CAMSS_PHY1_CSI1PHYTIMER_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi1phytimer_clk_src.c,
.dbg_name = "camss_phy1_csi1phytimer_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_phy1_csi1phytimer_clk.c),
},
};
static struct branch_clk camss_phy2_csi2phytimer_clk = {
.cbcr_reg = CAMSS_PHY2_CSI2PHYTIMER_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &csi2phytimer_clk_src.c,
.dbg_name = "camss_phy2_csi2phytimer_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_phy2_csi2phytimer_clk.c),
},
};
static struct branch_clk camss_top_ahb_clk = {
.cbcr_reg = CAMSS_TOP_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_top_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_top_ahb_clk.c),
},
};
static struct branch_clk camss_vfe_cpp_ahb_clk = {
.cbcr_reg = CAMSS_VFE_CPP_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_vfe_cpp_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_vfe_cpp_ahb_clk.c),
},
};
static struct branch_clk camss_vfe_cpp_clk = {
.cbcr_reg = CAMSS_VFE_CPP_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &cpp_clk_src.c,
.dbg_name = "camss_vfe_cpp_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_vfe_cpp_clk.c),
},
};
static struct branch_clk camss_vfe_vfe0_clk = {
.cbcr_reg = CAMSS_VFE_VFE0_CBCR,
.bcr_reg = CAMSS_VFE_BCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &vfe0_clk_src.c,
.dbg_name = "camss_vfe_vfe0_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_vfe_vfe0_clk.c),
},
};
static struct branch_clk camss_vfe_vfe1_clk = {
.cbcr_reg = CAMSS_VFE_VFE1_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &vfe1_clk_src.c,
.dbg_name = "camss_vfe_vfe1_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_vfe_vfe1_clk.c),
},
};
static struct branch_clk camss_vfe_vfe_ahb_clk = {
.cbcr_reg = CAMSS_VFE_VFE_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "camss_vfe_vfe_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_vfe_vfe_ahb_clk.c),
},
};
static struct branch_clk camss_vfe_vfe_axi_clk = {
.cbcr_reg = CAMSS_VFE_VFE_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &axi_clk_src.c,
.dbg_name = "camss_vfe_vfe_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_vfe_vfe_axi_clk.c),
},
};
static struct branch_clk camss_vfe_vfe_ocmemnoc_clk = {
.cbcr_reg = CAMSS_VFE_VFE_OCMEMNOC_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &ocmemnoc_clk_src.c,
.dbg_name = "camss_vfe_vfe_ocmemnoc_clk",
.ops = &clk_ops_branch,
CLK_INIT(camss_vfe_vfe_ocmemnoc_clk.c),
},
};
static struct branch_clk mdss_ahb_clk = {
.cbcr_reg = MDSS_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mdss_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_ahb_clk.c),
},
};
static struct branch_clk mdss_axi_clk = {
.cbcr_reg = MDSS_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &axi_clk_src.c,
.dbg_name = "mdss_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_axi_clk.c),
},
};
static struct branch_clk mdss_byte0_clk = {
.cbcr_reg = MDSS_BYTE0_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &byte0_clk_src.c,
.dbg_name = "mdss_byte0_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_byte0_clk.c),
},
};
static struct branch_clk mdss_byte1_clk = {
.cbcr_reg = MDSS_BYTE1_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &byte1_clk_src.c,
.dbg_name = "mdss_byte1_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_byte1_clk.c),
},
};
static struct branch_clk mdss_edpaux_clk = {
.cbcr_reg = MDSS_EDPAUX_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &edpaux_clk_src.c,
.dbg_name = "mdss_edpaux_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_edpaux_clk.c),
},
};
static struct branch_clk mdss_edplink_clk = {
.cbcr_reg = MDSS_EDPLINK_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &edplink_clk_src.c,
.dbg_name = "mdss_edplink_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_edplink_clk.c),
},
};
static struct branch_clk mdss_edppixel_clk = {
.cbcr_reg = MDSS_EDPPIXEL_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &edppixel_clk_src.c,
.dbg_name = "mdss_edppixel_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_edppixel_clk.c),
},
};
static struct branch_clk mdss_esc0_clk = {
.cbcr_reg = MDSS_ESC0_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &esc0_clk_src.c,
.dbg_name = "mdss_esc0_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_esc0_clk.c),
},
};
static struct branch_clk mdss_esc1_clk = {
.cbcr_reg = MDSS_ESC1_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &esc1_clk_src.c,
.dbg_name = "mdss_esc1_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_esc1_clk.c),
},
};
static struct branch_clk mdss_extpclk_clk = {
.cbcr_reg = MDSS_EXTPCLK_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &extpclk_clk_src.c,
.dbg_name = "mdss_extpclk_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_extpclk_clk.c),
},
};
static struct branch_clk mdss_hdmi_ahb_clk = {
.cbcr_reg = MDSS_HDMI_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mdss_hdmi_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_hdmi_ahb_clk.c),
},
};
static struct branch_clk mdss_hdmi_clk = {
.cbcr_reg = MDSS_HDMI_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &hdmi_clk_src.c,
.dbg_name = "mdss_hdmi_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_hdmi_clk.c),
},
};
static struct branch_clk mdss_mdp_clk = {
.cbcr_reg = MDSS_MDP_CBCR,
.bcr_reg = MDSS_BCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &mdp_clk_src.c,
.dbg_name = "mdss_mdp_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_mdp_clk.c),
},
};
static struct branch_clk mdss_mdp_lut_clk = {
.cbcr_reg = MDSS_MDP_LUT_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &mdp_clk_src.c,
.dbg_name = "mdss_mdp_lut_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_mdp_lut_clk.c),
},
};
static struct branch_clk mdss_pclk0_clk = {
.cbcr_reg = MDSS_PCLK0_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &pclk0_clk_src.c,
.dbg_name = "mdss_pclk0_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_pclk0_clk.c),
},
};
static struct branch_clk mdss_pclk1_clk = {
.cbcr_reg = MDSS_PCLK1_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &pclk1_clk_src.c,
.dbg_name = "mdss_pclk1_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_pclk1_clk.c),
},
};
static struct branch_clk mdss_vsync_clk = {
.cbcr_reg = MDSS_VSYNC_CBCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &vsync_clk_src.c,
.dbg_name = "mdss_vsync_clk",
.ops = &clk_ops_branch,
CLK_INIT(mdss_vsync_clk.c),
},
};
static struct branch_clk mmss_misc_ahb_clk = {
.cbcr_reg = MMSS_MISC_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "mmss_misc_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(mmss_misc_ahb_clk.c),
},
};
static struct branch_clk mmss_mmssnoc_axi_clk = {
.cbcr_reg = MMSS_MMSSNOC_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &axi_clk_src.c,
.dbg_name = "mmss_mmssnoc_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(mmss_mmssnoc_axi_clk.c),
},
};
static struct branch_clk mmss_s0_axi_clk = {
.cbcr_reg = MMSS_S0_AXI_CBCR,
/* The bus driver needs set_rate to go through to the parent */
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &axi_clk_src.c,
.dbg_name = "mmss_s0_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(mmss_s0_axi_clk.c),
.depends = &mmss_mmssnoc_axi_clk.c,
},
};
struct branch_clk ocmemnoc_clk = {
.cbcr_reg = OCMEMNOC_CBCR,
.has_sibling = 0,
.bcr_reg = 0x50b0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &ocmemnoc_clk_src.c,
.dbg_name = "ocmemnoc_clk",
.ops = &clk_ops_branch,
CLK_INIT(ocmemnoc_clk.c),
},
};
struct branch_clk ocmemcx_ocmemnoc_clk = {
.cbcr_reg = OCMEMCX_OCMEMNOC_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &ocmemnoc_clk_src.c,
.dbg_name = "ocmemcx_ocmemnoc_clk",
.ops = &clk_ops_branch,
CLK_INIT(ocmemcx_ocmemnoc_clk.c),
},
};
static struct branch_clk venus0_ahb_clk = {
.cbcr_reg = VENUS0_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "venus0_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(venus0_ahb_clk.c),
},
};
static struct branch_clk venus0_axi_clk = {
.cbcr_reg = VENUS0_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &axi_clk_src.c,
.dbg_name = "venus0_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(venus0_axi_clk.c),
},
};
static struct branch_clk venus0_ocmemnoc_clk = {
.cbcr_reg = VENUS0_OCMEMNOC_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &ocmemnoc_clk_src.c,
.dbg_name = "venus0_ocmemnoc_clk",
.ops = &clk_ops_branch,
CLK_INIT(venus0_ocmemnoc_clk.c),
},
};
static struct branch_clk venus0_vcodec0_clk = {
.cbcr_reg = VENUS0_VCODEC0_CBCR,
.bcr_reg = VENUS0_BCR,
.has_sibling = 0,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &vcodec0_clk_src.c,
.dbg_name = "venus0_vcodec0_clk",
.ops = &clk_ops_branch,
CLK_INIT(venus0_vcodec0_clk.c),
},
};
static struct branch_clk oxilicx_axi_clk = {
.cbcr_reg = OXILICX_AXI_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.parent = &axi_clk_src.c,
.dbg_name = "oxilicx_axi_clk",
.ops = &clk_ops_branch,
CLK_INIT(oxilicx_axi_clk.c),
},
};
static struct branch_clk oxili_gfx3d_clk = {
.cbcr_reg = OXILI_GFX3D_CBCR,
.bcr_reg = OXILI_BCR,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "oxili_gfx3d_clk",
.ops = &clk_ops_branch,
CLK_INIT(oxili_gfx3d_clk.c),
.depends = &oxilicx_axi_clk.c,
},
};
static struct branch_clk oxilicx_ahb_clk = {
.cbcr_reg = OXILICX_AHB_CBCR,
.has_sibling = 1,
.base = &virt_bases[MMSS_BASE],
.c = {
.dbg_name = "oxilicx_ahb_clk",
.ops = &clk_ops_branch,
CLK_INIT(oxilicx_ahb_clk.c),
},
};
static struct pll_config_regs mmpll0_regs = {
.l_reg = (void __iomem *)MMPLL0_L_REG,
.m_reg = (void __iomem *)MMPLL0_M_REG,
.n_reg = (void __iomem *)MMPLL0_N_REG,
.config_reg = (void __iomem *)MMPLL0_USER_CTL_REG,
.mode_reg = (void __iomem *)MMPLL0_MODE_REG,
.base = &virt_bases[MMSS_BASE],
};
/* MMPLL0 at 800 MHz, main output enabled. */
static struct pll_config mmpll0_config = {
.l = 0x29,
.m = 0x2,
.n = 0x3,
.vco_val = 0x0,
.vco_mask = BM(21, 20),
.pre_div_val = 0x0,
.pre_div_mask = BM(14, 12),
.post_div_val = 0x0,
.post_div_mask = BM(9, 8),
.mn_ena_val = BIT(24),
.mn_ena_mask = BIT(24),
.main_output_val = BIT(0),
.main_output_mask = BIT(0),
};
static struct pll_config_regs mmpll1_regs = {
.l_reg = (void __iomem *)MMPLL1_L_REG,
.m_reg = (void __iomem *)MMPLL1_M_REG,
.n_reg = (void __iomem *)MMPLL1_N_REG,
.config_reg = (void __iomem *)MMPLL1_USER_CTL_REG,
.mode_reg = (void __iomem *)MMPLL1_MODE_REG,
.base = &virt_bases[MMSS_BASE],
};
/* MMPLL1 at 846 MHz, main output enabled. */
static struct pll_config mmpll1_config = {
.l = 0x2C,
.m = 0x1,
.n = 0x10,
.vco_val = 0x0,
.vco_mask = BM(21, 20),
.pre_div_val = 0x0,
.pre_div_mask = BM(14, 12),
.post_div_val = 0x0,
.post_div_mask = BM(9, 8),
.mn_ena_val = BIT(24),
.mn_ena_mask = BIT(24),
.main_output_val = BIT(0),
.main_output_mask = BIT(0),
};
/* MMPLL1 at 1167 MHz, main output enabled. */
static struct pll_config mmpll1_v2_config = {
.l = 60,
.m = 25,
.n = 32,
.vco_val = 0x0,
.vco_mask = BM(21, 20),
.pre_div_val = 0x0,
.pre_div_mask = BM(14, 12),
.post_div_val = 0x0,
.post_div_mask = BM(9, 8),
.mn_ena_val = BIT(24),
.mn_ena_mask = BIT(24),
.main_output_val = BIT(0),
.main_output_mask = BIT(0),
};
static struct pll_config_regs mmpll3_regs = {
.l_reg = (void __iomem *)MMPLL3_L_REG,
.m_reg = (void __iomem *)MMPLL3_M_REG,
.n_reg = (void __iomem *)MMPLL3_N_REG,
.config_reg = (void __iomem *)MMPLL3_USER_CTL_REG,
.mode_reg = (void __iomem *)MMPLL3_MODE_REG,
.base = &virt_bases[MMSS_BASE],
};
/* MMPLL3 at 820 MHz, main output enabled. */
static struct pll_config mmpll3_config = {
.l = 0x2A,
.m = 0x11,
.n = 0x18,
.vco_val = 0x0,
.vco_mask = BM(21, 20),
.pre_div_val = 0x0,
.pre_div_mask = BM(14, 12),
.post_div_val = 0x0,
.post_div_mask = BM(9, 8),
.mn_ena_val = BIT(24),
.mn_ena_mask = BIT(24),
.main_output_val = BIT(0),
.main_output_mask = BIT(0),
};
/* MMPLL3 at 930 MHz, main output enabled. */
static struct pll_config mmpll3_v2_config = {
.l = 48,
.m = 7,
.n = 16,
.vco_val = 0x0,
.vco_mask = BM(21, 20),
.pre_div_val = 0x0,
.pre_div_mask = BM(14, 12),
.post_div_val = 0x0,
.post_div_mask = BM(9, 8),
.mn_ena_val = BIT(24),
.mn_ena_mask = BIT(24),
.main_output_val = BIT(0),
.main_output_mask = BIT(0),
};
static int mmss_dbg_set_mux_sel(struct mux_clk *clk, int sel)
{
unsigned long flags;
u32 regval;
spin_lock_irqsave(&local_clock_reg_lock, flags);
/* Set debug mux clock index */
regval = BVAL(11, 0, sel);
writel_relaxed(regval, MMSS_REG_BASE(MMSS_DEBUG_CLK_CTL_REG));
spin_unlock_irqrestore(&local_clock_reg_lock, flags);
return 0;
}
static int mmss_dbg_get_mux_sel(struct mux_clk *clk)
{
return readl_relaxed(MMSS_REG_BASE(MMSS_DEBUG_CLK_CTL_REG)) & BM(11, 0);
}
static int mmss_dbg_mux_enable(struct mux_clk *clk)
{
u32 regval;
regval = readl_relaxed(MMSS_REG_BASE(MMSS_DEBUG_CLK_CTL_REG));
writel_relaxed(regval | BIT(16), MMSS_REG_BASE(MMSS_DEBUG_CLK_CTL_REG));
mb();
return 0;
}
static void mmss_dbg_mux_disable(struct mux_clk *clk)
{
u32 regval;
regval = readl_relaxed(MMSS_REG_BASE(MMSS_DEBUG_CLK_CTL_REG));
writel_relaxed(regval & ~BIT(16),
MMSS_REG_BASE(MMSS_DEBUG_CLK_CTL_REG));
mb();
}
static struct clk_mux_ops debug_mux_ops = {
.enable = mmss_dbg_mux_enable,
.disable = mmss_dbg_mux_disable,
.set_mux_sel = mmss_dbg_set_mux_sel,
.get_mux_sel = mmss_dbg_get_mux_sel,
};
static struct mux_clk mmss_debug_mux = {
.ops = &debug_mux_ops,
MUX_SRC_LIST(
{&mmssnoc_ahb.c, 0x0001},
{&mmss_mmssnoc_axi_clk.c, 0x0004},
{&ocmemnoc_clk.c, 0x0007},
{&ocmemcx_ocmemnoc_clk.c, 0x0009},
{&camss_cci_cci_ahb_clk.c, 0x002e},
{&camss_cci_cci_clk.c, 0x002d},
{&camss_csi0_ahb_clk.c, 0x0042},
{&camss_csi0_clk.c, 0x0041},
{&camss_csi0phy_clk.c, 0x0043},
{&camss_csi0pix_clk.c, 0x0045},
{&camss_csi0rdi_clk.c, 0x0044},
{&camss_csi1_ahb_clk.c, 0x0047},
{&camss_csi1_clk.c, 0x0046},
{&camss_csi1phy_clk.c, 0x0048},
{&camss_csi1pix_clk.c, 0x004a},
{&camss_csi1rdi_clk.c, 0x0049},
{&camss_csi2_ahb_clk.c, 0x004c},
{&camss_csi2_clk.c, 0x004b},
{&camss_csi2phy_clk.c, 0x004d},
{&camss_csi2pix_clk.c, 0x004f},
{&camss_csi2rdi_clk.c, 0x004e},
{&camss_csi3_ahb_clk.c, 0x0051},
{&camss_csi3_clk.c, 0x0050},
{&camss_csi3phy_clk.c, 0x0052},
{&camss_csi3pix_clk.c, 0x0054},
{&camss_csi3rdi_clk.c, 0x0053},
{&camss_csi_vfe0_clk.c, 0x003f},
{&camss_csi_vfe1_clk.c, 0x0040},
{&camss_gp0_clk.c, 0x0027},
{&camss_gp1_clk.c, 0x0028},
{&camss_ispif_ahb_clk.c, 0x0055},
{&camss_jpeg_jpeg0_clk.c, 0x0032},
{&camss_jpeg_jpeg1_clk.c, 0x0033},
{&camss_jpeg_jpeg2_clk.c, 0x0034},
{&camss_jpeg_jpeg_ahb_clk.c, 0x0035},
{&camss_jpeg_jpeg_axi_clk.c, 0x0036},
{&camss_jpeg_jpeg_ocmemnoc_clk.c, 0x0037},
{&camss_mclk0_clk.c, 0x0029},
{&camss_mclk1_clk.c, 0x002a},
{&camss_mclk2_clk.c, 0x002b},
{&camss_mclk3_clk.c, 0x002c},
{&camss_micro_ahb_clk.c, 0x0026},
{&camss_phy0_csi0phytimer_clk.c, 0x002f},
{&camss_phy1_csi1phytimer_clk.c, 0x0030},
{&camss_phy2_csi2phytimer_clk.c, 0x0031},
{&camss_top_ahb_clk.c, 0x0025},
{&camss_vfe_cpp_ahb_clk.c, 0x003b},
{&camss_vfe_cpp_clk.c, 0x003a},
{&camss_vfe_vfe0_clk.c, 0x0038},
{&camss_vfe_vfe1_clk.c, 0x0039},
{&camss_vfe_vfe_ahb_clk.c, 0x003c},
{&camss_vfe_vfe_axi_clk.c, 0x003d},
{&camss_vfe_vfe_ocmemnoc_clk.c, 0x003e},
{&oxilicx_axi_clk.c, 0x000b},
{&oxilicx_ahb_clk.c, 0x000c},
{&ocmemcx_ocmemnoc_clk.c, 0x0009},
{&oxili_gfx3d_clk.c, 0x000d},
{&venus0_axi_clk.c, 0x000f},
{&venus0_ocmemnoc_clk.c, 0x0010},
{&venus0_ahb_clk.c, 0x0011},
{&venus0_vcodec0_clk.c, 0x000e},
{&mmss_s0_axi_clk.c, 0x0005},
{&mdss_ahb_clk.c, 0x0022},
{&mdss_hdmi_clk.c, 0x001d},
{&mdss_mdp_clk.c, 0x0014},
{&mdss_mdp_lut_clk.c, 0x0015},
{&mdss_axi_clk.c, 0x0024},
{&mdss_vsync_clk.c, 0x001c},
{&mdss_esc0_clk.c, 0x0020},
{&mdss_esc1_clk.c, 0x0021},
{&mdss_edpaux_clk.c, 0x001b},
{&mdss_byte0_clk.c, 0x001e},
{&mdss_byte1_clk.c, 0x001f},
{&mdss_edplink_clk.c, 0x001a},
{&mdss_edppixel_clk.c, 0x0019},
{&mdss_extpclk_clk.c, 0x0018},
{&mdss_hdmi_ahb_clk.c, 0x0023},
{&mdss_pclk0_clk.c, 0x0016},
{&mdss_pclk1_clk.c, 0x0017},
),
.c = {
.dbg_name = "mmss_debug_mux",
.ops = &clk_ops_gen_mux,
.flags = CLKFLAG_NO_RATE_CACHE,
CLK_INIT(mmss_debug_mux.c),
},
};
static struct clk_lookup msm_camera_clocks_8974pro_only[] = {
CLK_LOOKUP_OF("cam_src_clk", mclk1_clk_src, "90.qcom,camera"),
CLK_LOOKUP_OF("cam_clk", camss_mclk1_clk, "90.qcom,camera"),
CLK_LOOKUP_OF("cam_src_clk", mclk0_clk_src, "0.qcom,camera"),
CLK_LOOKUP_OF("cam_src_clk", mclk1_clk_src, "1.qcom,camera"),
CLK_LOOKUP_OF("cam_src_clk", mclk2_clk_src, "2.qcom,camera"),
CLK_LOOKUP_OF("cam_clk", camss_mclk0_clk, "0.qcom,camera"),
CLK_LOOKUP_OF("cam_clk", camss_mclk1_clk, "1.qcom,camera"),
CLK_LOOKUP_OF("cam_clk", camss_mclk2_clk, "2.qcom,camera"),
};
static struct clk_lookup msm_camera_clocks_8974_only[] = {
CLK_LOOKUP_OF("cam_src_clk", mmss_gp1_clk_src, "90.qcom,camera"),
CLK_LOOKUP_OF("cam_clk", camss_gp1_clk, "90.qcom,camera"),
CLK_LOOKUP_OF("cam_src_clk", mmss_gp0_clk_src, "0.qcom,camera"),
CLK_LOOKUP_OF("cam_src_clk", mmss_gp1_clk_src, "1.qcom,camera"),
CLK_LOOKUP_OF("cam_clk", camss_gp0_clk, "0.qcom,camera"),
CLK_LOOKUP_OF("cam_clk", camss_gp1_clk, "1.qcom,camera"),
};
static struct clk_lookup msm_clocks_mmss_8974[] = {
CLK_LOOKUP_OF("mmss_debug_mux", mmss_debug_mux,
"fc401880.qcom,cc-debug"),
CLK_LOOKUP_OF("bus_clk_src", axi_clk_src, ""),
CLK_LOOKUP_OF("bus_clk", mmss_mmssnoc_axi_clk, ""),
CLK_LOOKUP_OF("core_clk", mdss_edpaux_clk, "fd923400.qcom,mdss_edp"),
CLK_LOOKUP_OF("pixel_clk", mdss_edppixel_clk, "fd923400.qcom,mdss_edp"),
CLK_LOOKUP_OF("link_clk", mdss_edplink_clk, "fd923400.qcom,mdss_edp"),
CLK_LOOKUP_OF("mdp_core_clk", mdss_mdp_clk, "fd923400.qcom,mdss_edp"),
CLK_LOOKUP_OF("byte_clk", mdss_byte0_clk, "fd922800.qcom,mdss_dsi"),
CLK_LOOKUP_OF("byte_clk", mdss_byte1_clk, "fd922e00.qcom,mdss_dsi"),
CLK_LOOKUP_OF("core_clk", mdss_esc0_clk, "fd922800.qcom,mdss_dsi"),
CLK_LOOKUP_OF("core_clk", mdss_esc1_clk, "fd922e00.qcom,mdss_dsi"),
CLK_LOOKUP_OF("iface_clk", mdss_ahb_clk, "fd922800.qcom,mdss_dsi"),
CLK_LOOKUP_OF("iface_clk", mdss_ahb_clk, "fd922e00.qcom,mdss_dsi"),
CLK_LOOKUP_OF("bus_clk", mdss_axi_clk, "fd922800.qcom,mdss_dsi"),
CLK_LOOKUP_OF("bus_clk", mdss_axi_clk, "fd922e00.qcom,mdss_dsi"),
CLK_LOOKUP_OF("pixel_clk", mdss_pclk0_clk, "fd922800.qcom,mdss_dsi"),
CLK_LOOKUP_OF("pixel_clk", mdss_pclk1_clk, "fd922e00.qcom,mdss_dsi"),
CLK_LOOKUP_OF("mdp_core_clk", mdss_mdp_clk, "fd922800.qcom,mdss_dsi"),
CLK_LOOKUP_OF("mdp_core_clk", mdss_mdp_clk, "fd922e00.qcom,mdss_dsi"),
CLK_LOOKUP("core_mmss_clk", mmss_misc_ahb_clk.c,
"fd922800.qcom,mdss_dsi"),
CLK_LOOKUP("core_mmss_clk", mmss_misc_ahb_clk.c,
"fd922e00.qcom,mdss_dsi"),
CLK_LOOKUP_OF("iface_clk", mdss_ahb_clk, "fd922100.qcom,hdmi_tx"),
CLK_LOOKUP_OF("alt_iface_clk", mdss_hdmi_ahb_clk,
"fd922100.qcom,hdmi_tx"),
CLK_LOOKUP_OF("core_clk", mdss_hdmi_clk, "fd922100.qcom,hdmi_tx"),
CLK_LOOKUP_OF("mdp_core_clk", mdss_mdp_clk, "fd922100.qcom,hdmi_tx"),
CLK_LOOKUP_OF("extp_clk", mdss_extpclk_clk, "fd922100.qcom,hdmi_tx"),
CLK_LOOKUP_OF("core_clk", mdss_mdp_clk, "mdp.0"),
CLK_LOOKUP_OF("lut_clk", mdss_mdp_lut_clk, "mdp.0"),
CLK_LOOKUP_OF("core_clk_src", mdp_clk_src, "mdp.0"),
CLK_LOOKUP_OF("vsync_clk", mdss_vsync_clk, "mdp.0"),
/* MM sensor clocks placeholder */
CLK_LOOKUP_OF("", camss_mclk0_clk, ""),
CLK_LOOKUP_OF("", camss_mclk1_clk, ""),
CLK_LOOKUP_OF("", camss_mclk2_clk, ""),
CLK_LOOKUP_OF("", camss_mclk3_clk, ""),
CLK_LOOKUP_OF("", mmss_gp0_clk_src, ""),
CLK_LOOKUP_OF("", mmss_gp1_clk_src, ""),
CLK_LOOKUP_OF("", camss_gp0_clk, ""),
CLK_LOOKUP_OF("", camss_gp1_clk, ""),
/* CCI clocks */
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda0c000.qcom,cci"),
CLK_LOOKUP_OF("cci_ahb_clk", camss_cci_cci_ahb_clk,
"fda0c000.qcom,cci"),
CLK_LOOKUP_OF("cci_src_clk", cci_clk_src, "fda0c000.qcom,cci"),
CLK_LOOKUP_OF("cci_clk", camss_cci_cci_clk, "fda0c000.qcom,cci"),
/* CSIPHY clocks */
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda0ac00.qcom,csiphy"),
CLK_LOOKUP_OF("ispif_ahb_clk", camss_ispif_ahb_clk,
"fda0ac00.qcom,csiphy"),
CLK_LOOKUP_OF("csiphy_timer_src_clk", csi0phytimer_clk_src,
"fda0ac00.qcom,csiphy"),
CLK_LOOKUP_OF("csiphy_timer_clk", camss_phy0_csi0phytimer_clk,
"fda0ac00.qcom,csiphy"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda0b000.qcom,csiphy"),
CLK_LOOKUP_OF("ispif_ahb_clk", camss_ispif_ahb_clk,
"fda0b000.qcom,csiphy"),
CLK_LOOKUP_OF("csiphy_timer_src_clk", csi1phytimer_clk_src,
"fda0b000.qcom,csiphy"),
CLK_LOOKUP_OF("csiphy_timer_clk", camss_phy1_csi1phytimer_clk,
"fda0b000.qcom,csiphy"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda0b400.qcom,csiphy"),
CLK_LOOKUP_OF("ispif_ahb_clk", camss_ispif_ahb_clk,
"fda0b400.qcom,csiphy"),
CLK_LOOKUP_OF("csiphy_timer_src_clk", csi2phytimer_clk_src,
"fda0b400.qcom,csiphy"),
CLK_LOOKUP_OF("csiphy_timer_clk", camss_phy2_csi2phytimer_clk,
"fda0b400.qcom,csiphy"),
/* CSID clocks */
CLK_LOOKUP_OF("ispif_ahb_clk", camss_ispif_ahb_clk,
"fda08000.qcom,csid"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda08000.qcom,csid"),
CLK_LOOKUP_OF("csi_ahb_clk", camss_csi0_ahb_clk,
"fda08000.qcom,csid"),
CLK_LOOKUP_OF("csi_src_clk", csi0_clk_src,
"fda08000.qcom,csid"),
CLK_LOOKUP_OF("csi_phy_clk", camss_csi0phy_clk,
"fda08000.qcom,csid"),
CLK_LOOKUP_OF("csi_clk", camss_csi0_clk,
"fda08000.qcom,csid"),
CLK_LOOKUP_OF("csi_pix_clk", camss_csi0pix_clk,
"fda08000.qcom,csid"),
CLK_LOOKUP_OF("csi_rdi_clk", camss_csi0rdi_clk,
"fda08000.qcom,csid"),
CLK_LOOKUP_OF("ispif_ahb_clk", camss_ispif_ahb_clk,
"fda08400.qcom,csid"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda08400.qcom,csid"),
CLK_LOOKUP_OF("csi_ahb_clk", camss_csi1_ahb_clk,
"fda08400.qcom,csid"),
CLK_LOOKUP_OF("csi_src_clk", csi1_clk_src,
"fda08400.qcom,csid"),
CLK_LOOKUP_OF("csi_phy_clk", camss_csi1phy_clk,
"fda08400.qcom,csid"),
CLK_LOOKUP_OF("csi_clk", camss_csi1_clk,
"fda08400.qcom,csid"),
CLK_LOOKUP_OF("csi_pix_clk", camss_csi1pix_clk,
"fda08400.qcom,csid"),
CLK_LOOKUP_OF("csi_rdi_clk", camss_csi1rdi_clk,
"fda08400.qcom,csid"),
CLK_LOOKUP_OF("ispif_ahb_clk", camss_ispif_ahb_clk,
"fda08800.qcom,csid"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda08800.qcom,csid"),
CLK_LOOKUP_OF("csi_ahb_clk", camss_csi2_ahb_clk,
"fda08800.qcom,csid"),
CLK_LOOKUP_OF("csi_src_clk", csi2_clk_src,
"fda08800.qcom,csid"),
CLK_LOOKUP_OF("csi_phy_clk", camss_csi2phy_clk,
"fda08800.qcom,csid"),
CLK_LOOKUP_OF("csi_clk", camss_csi2_clk,
"fda08800.qcom,csid"),
CLK_LOOKUP_OF("csi_pix_clk", camss_csi2pix_clk,
"fda08800.qcom,csid"),
CLK_LOOKUP_OF("csi_rdi_clk", camss_csi2rdi_clk,
"fda08800.qcom,csid"),
CLK_LOOKUP_OF("ispif_ahb_clk", camss_ispif_ahb_clk,
"fda08c00.qcom,csid"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda08c00.qcom,csid"),
CLK_LOOKUP_OF("csi_ahb_clk", camss_csi3_ahb_clk,
"fda08c00.qcom,csid"),
CLK_LOOKUP_OF("csi_src_clk", csi3_clk_src,
"fda08c00.qcom,csid"),
CLK_LOOKUP_OF("csi_phy_clk", camss_csi3phy_clk,
"fda08c00.qcom,csid"),
CLK_LOOKUP_OF("csi_clk", camss_csi3_clk,
"fda08c00.qcom,csid"),
CLK_LOOKUP_OF("csi_pix_clk", camss_csi3pix_clk,
"fda08c00.qcom,csid"),
CLK_LOOKUP_OF("csi_rdi_clk", camss_csi3rdi_clk,
"fda08c00.qcom,csid"),
/* ISPIF clocks */
CLK_LOOKUP_OF("ispif_ahb_clk", camss_ispif_ahb_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("vfe0_clk_src", vfe0_clk_src, "fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("camss_vfe_vfe0_clk", camss_vfe_vfe0_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("camss_csi_vfe0_clk", camss_csi_vfe0_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("vfe1_clk_src", vfe1_clk_src, "fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("camss_vfe_vfe1_clk", camss_vfe_vfe1_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("camss_csi_vfe1_clk", camss_csi_vfe1_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi0_src_clk", csi0_clk_src,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi0_clk", camss_csi0_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi0_pix_clk", camss_csi0pix_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi0_rdi_clk", camss_csi0rdi_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi1_src_clk", csi1_clk_src,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi1_clk", camss_csi1_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi1_pix_clk", camss_csi1pix_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi1_rdi_clk", camss_csi1rdi_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi2_src_clk", csi2_clk_src,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi2_clk", camss_csi2_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi2_pix_clk", camss_csi2pix_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi2_rdi_clk", camss_csi2rdi_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi3_src_clk", csi3_clk_src,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi3_clk", camss_csi3_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi3_pix_clk", camss_csi3pix_clk,
"fda0a000.qcom,ispif"),
CLK_LOOKUP_OF("csi3_rdi_clk", camss_csi3rdi_clk,
"fda0a000.qcom,ispif"),
/*VFE clocks*/
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda10000.qcom,vfe"),
CLK_LOOKUP_OF("vfe_clk_src", vfe0_clk_src, "fda10000.qcom,vfe"),
CLK_LOOKUP_OF("camss_vfe_vfe_clk", camss_vfe_vfe0_clk,
"fda10000.qcom,vfe"),
CLK_LOOKUP_OF("camss_csi_vfe_clk", camss_csi_vfe0_clk,
"fda10000.qcom,vfe"),
CLK_LOOKUP_OF("iface_clk", camss_vfe_vfe_ahb_clk, "fda10000.qcom,vfe"),
CLK_LOOKUP_OF("bus_clk", camss_vfe_vfe_axi_clk, "fda10000.qcom,vfe"),
CLK_LOOKUP_OF("alt_bus_clk", camss_vfe_vfe_ocmemnoc_clk,
"fda10000.qcom,vfe"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda14000.qcom,vfe"),
CLK_LOOKUP_OF("vfe_clk_src", vfe1_clk_src, "fda14000.qcom,vfe"),
CLK_LOOKUP_OF("camss_vfe_vfe_clk", camss_vfe_vfe1_clk,
"fda14000.qcom,vfe"),
CLK_LOOKUP_OF("camss_csi_vfe_clk", camss_csi_vfe1_clk,
"fda14000.qcom,vfe"),
CLK_LOOKUP_OF("iface_clk", camss_vfe_vfe_ahb_clk, "fda14000.qcom,vfe"),
CLK_LOOKUP_OF("bus_clk", camss_vfe_vfe_axi_clk, "fda14000.qcom,vfe"),
CLK_LOOKUP_OF("alt_bus_clk", camss_vfe_vfe_ocmemnoc_clk,
"fda14000.qcom,vfe"),
/*Jpeg Clocks*/
CLK_LOOKUP_OF("core_clk", camss_jpeg_jpeg0_clk, "fda1c000.qcom,jpeg"),
CLK_LOOKUP_OF("core_clk", camss_jpeg_jpeg1_clk, "fda20000.qcom,jpeg"),
CLK_LOOKUP_OF("core_clk", camss_jpeg_jpeg2_clk, "fda24000.qcom,jpeg"),
CLK_LOOKUP_OF("iface_clk", camss_jpeg_jpeg_ahb_clk,
"fda1c000.qcom,jpeg"),
CLK_LOOKUP_OF("iface_clk", camss_jpeg_jpeg_ahb_clk,
"fda20000.qcom,jpeg"),
CLK_LOOKUP_OF("iface_clk", camss_jpeg_jpeg_ahb_clk,
"fda24000.qcom,jpeg"),
CLK_LOOKUP_OF("iface_clk", camss_jpeg_jpeg_ahb_clk,
"fda64000.qcom,iommu"),
CLK_LOOKUP_OF("core_clk", camss_jpeg_jpeg_axi_clk,
"fda64000.qcom,iommu"),
CLK_LOOKUP_OF("alt_core_clk", camss_top_ahb_clk, "fda64000.qcom,iommu"),
CLK_LOOKUP_OF("bus_clk0", camss_jpeg_jpeg_axi_clk,
"fda1c000.qcom,jpeg"),
CLK_LOOKUP_OF("bus_clk0", camss_jpeg_jpeg_axi_clk,
"fda20000.qcom,jpeg"),
CLK_LOOKUP_OF("bus_clk0", camss_jpeg_jpeg_axi_clk,
"fda24000.qcom,jpeg"),
CLK_LOOKUP_OF("alt_bus_clk", camss_jpeg_jpeg_ocmemnoc_clk,
"fda1c000.qcom,jpeg"),
CLK_LOOKUP_OF("alt_bus_clk", camss_jpeg_jpeg_ocmemnoc_clk,
"fda20000.qcom,jpeg"),
CLK_LOOKUP_OF("alt_bus_clk", camss_jpeg_jpeg_ocmemnoc_clk,
"fda24000.qcom,jpeg"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda1c000.qcom,jpeg"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda20000.qcom,jpeg"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda24000.qcom,jpeg"),
CLK_LOOKUP_OF("micro_iface_clk", camss_micro_ahb_clk,
"fda04000.qcom,cpp"),
CLK_LOOKUP_OF("camss_top_ahb_clk", camss_top_ahb_clk,
"fda04000.qcom,cpp"),
CLK_LOOKUP_OF("cpp_iface_clk", camss_vfe_cpp_ahb_clk,
"fda04000.qcom,cpp"),
CLK_LOOKUP_OF("cpp_core_clk", camss_vfe_cpp_clk, "fda04000.qcom,cpp"),
CLK_LOOKUP_OF("cpp_bus_clk", camss_vfe_vfe_axi_clk,
"fda04000.qcom,cpp"),
CLK_LOOKUP_OF("vfe_clk_src", vfe0_clk_src, "fda04000.qcom,cpp"),
CLK_LOOKUP_OF("camss_vfe_vfe_clk", camss_vfe_vfe0_clk,
"fda04000.qcom,cpp"),
CLK_LOOKUP_OF("iface_clk", camss_vfe_vfe_ahb_clk, "fda04000.qcom,cpp"),
CLK_LOOKUP_OF("iface_clk", camss_micro_ahb_clk, ""),
CLK_LOOKUP_OF("iface_clk", camss_vfe_vfe_ahb_clk,
"fda44000.qcom,iommu"),
CLK_LOOKUP_OF("core_clk", camss_vfe_vfe_axi_clk, "fda44000.qcom,iommu"),
CLK_LOOKUP_OF("alt_core_clk", camss_top_ahb_clk, "fda44000.qcom,iommu"),
CLK_LOOKUP_OF("iface_clk", mdss_ahb_clk, "mdp.0"),
CLK_LOOKUP_OF("iface_clk", mdss_ahb_clk, "fd923400.qcom,mdss_edp"),
CLK_LOOKUP_OF("iface_clk", mdss_ahb_clk, "fd928000.qcom,iommu"),
CLK_LOOKUP_OF("core_clk", mdss_axi_clk, "fd928000.qcom,iommu"),
CLK_LOOKUP_OF("bus_clk", mdss_axi_clk, "mdp.0"),
CLK_LOOKUP_OF("core_clk", oxili_gfx3d_clk, "fdb00000.qcom,kgsl-3d0"),
CLK_LOOKUP_OF("iface_clk", oxilicx_ahb_clk, "fdb00000.qcom,kgsl-3d0"),
CLK_LOOKUP_OF("mem_iface_clk", ocmemcx_ocmemnoc_clk,
"fdb00000.qcom,kgsl-3d0"),
CLK_LOOKUP_OF("core_clk", oxilicx_axi_clk, "fdb10000.qcom,iommu"),
CLK_LOOKUP_OF("iface_clk", oxilicx_ahb_clk, "fdb10000.qcom,iommu"),
CLK_LOOKUP_OF("alt_core_clk", oxili_gfx3d_clk, "fdb10000.qcom,iommu"),
CLK_LOOKUP_OF("iface_clk", ocmemcx_ocmemnoc_clk, "fdd00000.qcom,ocmem"),
CLK_LOOKUP_OF("iface_clk", venus0_ahb_clk, "fdc84000.qcom,iommu"),
CLK_LOOKUP_OF("alt_core_clk", venus0_vcodec0_clk,
"fdc84000.qcom,iommu"),
CLK_LOOKUP_OF("core_clk", venus0_axi_clk, "fdc84000.qcom,iommu"),
CLK_LOOKUP_OF("bus_clk", venus0_axi_clk, ""),
CLK_LOOKUP_OF("src_clk", vcodec0_clk_src, "fdce0000.qcom,venus"),
CLK_LOOKUP_OF("core_clk", venus0_vcodec0_clk, "fdce0000.qcom,venus"),
CLK_LOOKUP_OF("iface_clk", venus0_ahb_clk, "fdce0000.qcom,venus"),
CLK_LOOKUP_OF("bus_clk", venus0_axi_clk, "fdce0000.qcom,venus"),
CLK_LOOKUP_OF("mem_clk", venus0_ocmemnoc_clk, "fdce0000.qcom,venus"),
CLK_LOOKUP_OF("core_clk", venus0_vcodec0_clk, "fdc00000.qcom,vidc"),
CLK_LOOKUP_OF("iface_clk", venus0_ahb_clk, "fdc00000.qcom,vidc"),
CLK_LOOKUP_OF("bus_clk", venus0_axi_clk, "fdc00000.qcom,vidc"),
CLK_LOOKUP_OF("mem_clk", venus0_ocmemnoc_clk, "fdc00000.qcom,vidc"),
CLK_LOOKUP_OF("core_mmss_clk", mmss_misc_ahb_clk, "fdf30018.hwevent"),
CLK_LOOKUP_OF("bus_clk", ocmemnoc_clk, "msm_ocmem_noc"),
CLK_LOOKUP_OF("bus_a_clk", ocmemnoc_clk, "msm_ocmem_noc"),
CLK_LOOKUP_OF("bus_clk", mmss_s0_axi_clk, "msm_mmss_noc"),
CLK_LOOKUP_OF("bus_a_clk", mmss_s0_axi_clk, "msm_mmss_noc"),
CLK_LOOKUP_OF("", mmssnoc_ahb, ""),
/* DSI PLL clocks */
CLK_LOOKUP_OF("", dsi_vco_clk_8974, ""),
CLK_LOOKUP_OF("", analog_postdiv_clk_8974, ""),
CLK_LOOKUP_OF("", indirect_path_div2_clk_8974, ""),
CLK_LOOKUP_OF("", pixel_clk_src_8974, ""),
CLK_LOOKUP_OF("", byte_mux_8974, ""),
CLK_LOOKUP_OF("", byte_clk_src_8974, ""),
};
/* v1 to v2 clock changes */
void msm8974_mmss_v2_clock_override(void)
{
mmpll3_clk_src.c.rate = 930000000;
mmpll1_clk_src.c.rate = 1167000000;
mmpll1_clk_src.c.fmax[VDD_DIG_NOMINAL] = 1167000000;
ocmemnoc_clk_src.freq_tbl = ftbl_ocmemnoc_v2_clk;
ocmemnoc_clk_src.c.fmax[VDD_DIG_NOMINAL] = 291750000;
axi_clk_src.freq_tbl = ftbl_mmss_axi_v2_clk;
axi_clk_src.c.fmax[VDD_DIG_NOMINAL] = 291750000;
axi_clk_src.c.fmax[VDD_DIG_HIGH] = 466800000;
vcodec0_clk_src.freq_tbl = ftbl_venus0_vcodec0_v2_clk;
vcodec0_clk_src.c.fmax[VDD_DIG_HIGH] = 465000000;
mdp_clk_src.c.fmax[VDD_DIG_NOMINAL] = 240000000;
}
/* v2 to pro clock changes */
void msm8974_mmss_pro_clock_override(bool aa, bool ab, bool ac)
{
vfe0_clk_src.c.fmax[VDD_DIG_LOW] = 150000000;
vfe0_clk_src.c.fmax[VDD_DIG_NOMINAL] = 320000000;
vfe1_clk_src.c.fmax[VDD_DIG_LOW] = 150000000;
vfe1_clk_src.c.fmax[VDD_DIG_NOMINAL] = 320000000;
cpp_clk_src.c.fmax[VDD_DIG_LOW] = 150000000;
cpp_clk_src.c.fmax[VDD_DIG_NOMINAL] = 320000000;
if (ab || ac) {
vfe0_clk_src.c.fmax[VDD_DIG_HIGH] = 465000000;
vfe1_clk_src.c.fmax[VDD_DIG_HIGH] = 465000000;
cpp_clk_src.c.fmax[VDD_DIG_HIGH] = 465000000;
} else if (aa) {
vfe0_clk_src.c.fmax[VDD_DIG_HIGH] = 320000000;
vfe1_clk_src.c.fmax[VDD_DIG_HIGH] = 320000000;
cpp_clk_src.c.fmax[VDD_DIG_HIGH] = 320000000;
}
mdp_clk_src.c.fmax[VDD_DIG_NOMINAL] = 266670000;
mclk0_clk_src.freq_tbl = ftbl_camss_mclk0_3_pro_clk;
mclk1_clk_src.freq_tbl = ftbl_camss_mclk0_3_pro_clk;
mclk2_clk_src.freq_tbl = ftbl_camss_mclk0_3_pro_clk;
mclk3_clk_src.freq_tbl = ftbl_camss_mclk0_3_pro_clk;
mclk0_clk_src.set_rate = set_rate_mnd;
mclk1_clk_src.set_rate = set_rate_mnd;
mclk2_clk_src.set_rate = set_rate_mnd;
mclk3_clk_src.set_rate = set_rate_mnd;
mclk0_clk_src.c.ops = &clk_ops_rcg_mnd;
mclk1_clk_src.c.ops = &clk_ops_rcg_mnd;
mclk2_clk_src.c.ops = &clk_ops_rcg_mnd;
mclk3_clk_src.c.ops = &clk_ops_rcg_mnd;
}
static struct of_device_id msm_clock_mmsscc_match_table[] = {
{ .compatible = "qcom,mmsscc-8974" },
{ .compatible = "qcom,mmsscc-8974v2" },
{ .compatible = "qcom,mmsscc-8974pro" },
{ .compatible = "qcom,mmsscc-8974pro-ac" },
{}
};
static int msm_mmsscc_8974_probe(struct platform_device *pdev)
{
struct resource *res;
struct clk *cxo_mmss, *gpll0_mmss;
int ret;
int compatlen;
const char *compat = NULL;
bool v2 = false, pro = false;
bool pro_aa = false, pro_ab = false, pro_ac = false;
compat = of_get_property(pdev->dev.of_node, "compatible", &compatlen);
if (!compat)
return -EINVAL;
pro_ac = !strcmp(compat, "qcom,mmsscc-8974pro-ac");
pro_ab = !strcmp(compat, "qcom,mmsscc-8974pro-ab");
pro_aa = !strcmp(compat, "qcom,mmsscc-8974pro-aa");
pro = pro_ac || pro_ab || pro_aa ||
!strcmp(compat, "qcom,mmsscc-8974pro");
v2 = pro || !strcmp(compat, "qcom,mmsscc-8974v2");
res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "cc_base");
if (!res) {
dev_err(&pdev->dev, "Unable to retrieve register base.\n");
return -ENOMEM;
}
virt_bases[MMSS_BASE] = devm_ioremap(&pdev->dev, res->start,
resource_size(res));
if (!virt_bases[MMSS_BASE]) {
dev_err(&pdev->dev, "Failed to map in CC registers.\n");
return -ENOMEM;
}
vdd_dig.regulator[0] = devm_regulator_get(&pdev->dev, "vdd_dig");
if (IS_ERR(vdd_dig.regulator[0])) {
if (!(PTR_ERR(vdd_dig.regulator[0]) == -EPROBE_DEFER))
dev_err(&pdev->dev, "Unable to get the vdd_dig regulator!");
return PTR_ERR(vdd_dig.regulator[0]);
}
cxo_mmss = cxo_clk_src.c.parent = devm_clk_get(&pdev->dev, "xo");
if (IS_ERR(cxo_mmss)) {
if (!(PTR_ERR(cxo_mmss) == -EPROBE_DEFER))
dev_err(&pdev->dev, "Unable to get the the cxo clock!");
return PTR_ERR(cxo_mmss);
}
gpll0_mmss = gpll0_clk_src.c.parent = devm_clk_get(&pdev->dev, "gpll0");
if (IS_ERR(gpll0_mmss)) {
if (!(PTR_ERR(gpll0_mmss) == -EPROBE_DEFER))
dev_err(&pdev->dev, "Unable to get the the gpll0 clock!");
return PTR_ERR(gpll0_mmss);
}
oxili_gfx3d_clk.c.parent = devm_clk_get(&pdev->dev, "gfx3d_src_clk");
if (IS_ERR(oxili_gfx3d_clk.c.parent)) {
if (!(PTR_ERR(oxili_gfx3d_clk.c.parent) == -EPROBE_DEFER))
dev_err(&pdev->dev, "Unable to get the the gfx3d source clock!");
return PTR_ERR(oxili_gfx3d_clk.c.parent);
}
mmssnoc_ahb.c.parent = devm_clk_get(&pdev->dev, "mmssnoc_ahb");
if (IS_ERR(mmssnoc_ahb.c.parent)) {
if (!(PTR_ERR(mmssnoc_ahb.c.parent) == -EPROBE_DEFER))
dev_err(&pdev->dev, "Unable to get the the MMSSNOC AHB clock!");
return PTR_ERR(mmssnoc_ahb.c.parent);
}
configure_sr_hpm_lp_pll(&mmpll0_config, &mmpll0_regs, 1);
if (v2) {
configure_sr_hpm_lp_pll(&mmpll1_v2_config, &mmpll1_regs, 1);
configure_sr_hpm_lp_pll(&mmpll3_v2_config, &mmpll3_regs, 0);
msm8974_mmss_v2_clock_override();
if (pro)
msm8974_mmss_pro_clock_override(pro_aa, pro_ab, pro_ac);
} else {
configure_sr_hpm_lp_pll(&mmpll1_config, &mmpll1_regs, 1);
configure_sr_hpm_lp_pll(&mmpll3_config, &mmpll3_regs, 0);
}
/*
* MDSS needs the ahb clock and needs to init before we register the
* lookup table.
*/
mdss_clk_ctrl_pre_init(&mdss_ahb_clk.c);
ret = of_msm_clock_register(pdev->dev.of_node, msm_clocks_mmss_8974,
ARRAY_SIZE(msm_clocks_mmss_8974));
if (ret)
return ret;
if (pro) {
ret = of_msm_clock_register(pdev->dev.of_node,
msm_camera_clocks_8974pro_only,
ARRAY_SIZE(msm_camera_clocks_8974pro_only));
if (ret)
return ret;
} else {
ret = of_msm_clock_register(pdev->dev.of_node,
msm_camera_clocks_8974_only,
ARRAY_SIZE(msm_camera_clocks_8974_only));
if (ret)
return ret;
}
if (v2) {
ret = clk_set_rate(&axi_clk_src.c, 291750000);
ret = clk_set_rate(&ocmemnoc_clk_src.c, 291750000);
} else {
clk_set_rate(&axi_clk_src.c, 282000000);
clk_set_rate(&ocmemnoc_clk_src.c, 282000000);
}
dev_info(&pdev->dev, "Registered MMSS clocks.\n");
return 0;
}
static struct platform_driver msm_clock_mmsscc_driver = {
.probe = msm_mmsscc_8974_probe,
.driver = {
.name = "qcom,mmsscc-8974",
.of_match_table = msm_clock_mmsscc_match_table,
.owner = THIS_MODULE,
},
};
int __init msm_mmsscc_8974_init(void)
{
return platform_driver_register(&msm_clock_mmsscc_driver);
}
arch_initcall(msm_mmsscc_8974_init);
| gpl-2.0 |
NTSK13/forlinux | arch/sh/kernel/irq.c | 843 | 7689 | /*
* linux/arch/sh/kernel/irq.c
*
* Copyright (C) 1992, 1998 Linus Torvalds, Ingo Molnar
*
*
* SuperH version: Copyright (C) 1999 Niibe Yutaka
*/
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/kernel_stat.h>
#include <linux/seq_file.h>
#include <linux/ftrace.h>
#include <linux/delay.h>
#include <asm/processor.h>
#include <asm/machvec.h>
#include <asm/uaccess.h>
#include <asm/thread_info.h>
#include <cpu/mmu_context.h>
atomic_t irq_err_count;
/*
* 'what should we do if we get a hw irq event on an illegal vector'.
* each architecture has to answer this themselves, it doesn't deserve
* a generic callback i think.
*/
void ack_bad_irq(unsigned int irq)
{
atomic_inc(&irq_err_count);
printk("unexpected IRQ trap at vector %02x\n", irq);
}
#if defined(CONFIG_PROC_FS)
/*
* /proc/interrupts printing:
*/
static int show_other_interrupts(struct seq_file *p, int prec)
{
int j;
seq_printf(p, "%*s: ", prec, "NMI");
for_each_online_cpu(j)
seq_printf(p, "%10u ", irq_stat[j].__nmi_count);
seq_printf(p, " Non-maskable interrupts\n");
seq_printf(p, "%*s: %10u\n", prec, "ERR", atomic_read(&irq_err_count));
return 0;
}
int show_interrupts(struct seq_file *p, void *v)
{
unsigned long flags, any_count = 0;
int i = *(loff_t *)v, j, prec;
struct irqaction *action;
struct irq_desc *desc;
if (i > nr_irqs)
return 0;
for (prec = 3, j = 1000; prec < 10 && j <= nr_irqs; ++prec)
j *= 10;
if (i == nr_irqs)
return show_other_interrupts(p, prec);
if (i == 0) {
seq_printf(p, "%*s", prec + 8, "");
for_each_online_cpu(j)
seq_printf(p, "CPU%-8d", j);
seq_putc(p, '\n');
}
desc = irq_to_desc(i);
if (!desc)
return 0;
raw_spin_lock_irqsave(&desc->lock, flags);
for_each_online_cpu(j)
any_count |= kstat_irqs_cpu(i, j);
action = desc->action;
if (!action && !any_count)
goto out;
seq_printf(p, "%*d: ", prec, i);
for_each_online_cpu(j)
seq_printf(p, "%10u ", kstat_irqs_cpu(i, j));
seq_printf(p, " %14s", desc->chip->name);
seq_printf(p, "-%-8s", desc->name);
if (action) {
seq_printf(p, " %s", action->name);
while ((action = action->next) != NULL)
seq_printf(p, ", %s", action->name);
}
seq_putc(p, '\n');
out:
raw_spin_unlock_irqrestore(&desc->lock, flags);
return 0;
}
#endif
#ifdef CONFIG_IRQSTACKS
/*
* per-CPU IRQ handling contexts (thread information and stack)
*/
union irq_ctx {
struct thread_info tinfo;
u32 stack[THREAD_SIZE/sizeof(u32)];
};
static union irq_ctx *hardirq_ctx[NR_CPUS] __read_mostly;
static union irq_ctx *softirq_ctx[NR_CPUS] __read_mostly;
static char softirq_stack[NR_CPUS * THREAD_SIZE] __page_aligned_bss;
static char hardirq_stack[NR_CPUS * THREAD_SIZE] __page_aligned_bss;
static inline void handle_one_irq(unsigned int irq)
{
union irq_ctx *curctx, *irqctx;
curctx = (union irq_ctx *)current_thread_info();
irqctx = hardirq_ctx[smp_processor_id()];
/*
* this is where we switch to the IRQ stack. However, if we are
* already using the IRQ stack (because we interrupted a hardirq
* handler) we can't do that and just have to keep using the
* current stack (which is the irq stack already after all)
*/
if (curctx != irqctx) {
u32 *isp;
isp = (u32 *)((char *)irqctx + sizeof(*irqctx));
irqctx->tinfo.task = curctx->tinfo.task;
irqctx->tinfo.previous_sp = current_stack_pointer;
/*
* Copy the softirq bits in preempt_count so that the
* softirq checks work in the hardirq context.
*/
irqctx->tinfo.preempt_count =
(irqctx->tinfo.preempt_count & ~SOFTIRQ_MASK) |
(curctx->tinfo.preempt_count & SOFTIRQ_MASK);
__asm__ __volatile__ (
"mov %0, r4 \n"
"mov r15, r8 \n"
"jsr @%1 \n"
/* swith to the irq stack */
" mov %2, r15 \n"
/* restore the stack (ring zero) */
"mov r8, r15 \n"
: /* no outputs */
: "r" (irq), "r" (generic_handle_irq), "r" (isp)
: "memory", "r0", "r1", "r2", "r3", "r4",
"r5", "r6", "r7", "r8", "t", "pr"
);
} else
generic_handle_irq(irq);
}
/*
* allocate per-cpu stacks for hardirq and for softirq processing
*/
void irq_ctx_init(int cpu)
{
union irq_ctx *irqctx;
if (hardirq_ctx[cpu])
return;
irqctx = (union irq_ctx *)&hardirq_stack[cpu * THREAD_SIZE];
irqctx->tinfo.task = NULL;
irqctx->tinfo.exec_domain = NULL;
irqctx->tinfo.cpu = cpu;
irqctx->tinfo.preempt_count = HARDIRQ_OFFSET;
irqctx->tinfo.addr_limit = MAKE_MM_SEG(0);
hardirq_ctx[cpu] = irqctx;
irqctx = (union irq_ctx *)&softirq_stack[cpu * THREAD_SIZE];
irqctx->tinfo.task = NULL;
irqctx->tinfo.exec_domain = NULL;
irqctx->tinfo.cpu = cpu;
irqctx->tinfo.preempt_count = 0;
irqctx->tinfo.addr_limit = MAKE_MM_SEG(0);
softirq_ctx[cpu] = irqctx;
printk("CPU %u irqstacks, hard=%p soft=%p\n",
cpu, hardirq_ctx[cpu], softirq_ctx[cpu]);
}
void irq_ctx_exit(int cpu)
{
hardirq_ctx[cpu] = NULL;
}
asmlinkage void do_softirq(void)
{
unsigned long flags;
struct thread_info *curctx;
union irq_ctx *irqctx;
u32 *isp;
if (in_interrupt())
return;
local_irq_save(flags);
if (local_softirq_pending()) {
curctx = current_thread_info();
irqctx = softirq_ctx[smp_processor_id()];
irqctx->tinfo.task = curctx->task;
irqctx->tinfo.previous_sp = current_stack_pointer;
/* build the stack frame on the softirq stack */
isp = (u32 *)((char *)irqctx + sizeof(*irqctx));
__asm__ __volatile__ (
"mov r15, r9 \n"
"jsr @%0 \n"
/* switch to the softirq stack */
" mov %1, r15 \n"
/* restore the thread stack */
"mov r9, r15 \n"
: /* no outputs */
: "r" (__do_softirq), "r" (isp)
: "memory", "r0", "r1", "r2", "r3", "r4",
"r5", "r6", "r7", "r8", "r9", "r15", "t", "pr"
);
/*
* Shouldnt happen, we returned above if in_interrupt():
*/
WARN_ON_ONCE(softirq_count());
}
local_irq_restore(flags);
}
#else
static inline void handle_one_irq(unsigned int irq)
{
generic_handle_irq(irq);
}
#endif
asmlinkage __irq_entry int do_IRQ(unsigned int irq, struct pt_regs *regs)
{
struct pt_regs *old_regs = set_irq_regs(regs);
irq_enter();
irq = irq_demux(irq_lookup(irq));
if (irq != NO_IRQ_IGNORE) {
handle_one_irq(irq);
irq_finish(irq);
}
irq_exit();
set_irq_regs(old_regs);
return IRQ_HANDLED;
}
void __init init_IRQ(void)
{
plat_irq_setup();
/*
* Pin any of the legacy IRQ vectors that haven't already been
* grabbed by the platform
*/
reserve_irq_legacy();
/* Perform the machine specific initialisation */
if (sh_mv.mv_init_irq)
sh_mv.mv_init_irq();
irq_ctx_init(smp_processor_id());
}
#ifdef CONFIG_SPARSE_IRQ
int __init arch_probe_nr_irqs(void)
{
nr_irqs = sh_mv.mv_nr_irqs;
return 0;
}
#endif
#ifdef CONFIG_HOTPLUG_CPU
static void route_irq(struct irq_desc *desc, unsigned int irq, unsigned int cpu)
{
printk(KERN_INFO "IRQ%u: moving from cpu%u to cpu%u\n",
irq, desc->node, cpu);
raw_spin_lock_irq(&desc->lock);
desc->chip->set_affinity(irq, cpumask_of(cpu));
raw_spin_unlock_irq(&desc->lock);
}
/*
* The CPU has been marked offline. Migrate IRQs off this CPU. If
* the affinity settings do not allow other CPUs, force them onto any
* available CPU.
*/
void migrate_irqs(void)
{
struct irq_desc *desc;
unsigned int irq, cpu = smp_processor_id();
for_each_irq_desc(irq, desc) {
if (desc->node == cpu) {
unsigned int newcpu = cpumask_any_and(desc->affinity,
cpu_online_mask);
if (newcpu >= nr_cpu_ids) {
if (printk_ratelimit())
printk(KERN_INFO "IRQ%u no longer affine to CPU%u\n",
irq, cpu);
cpumask_setall(desc->affinity);
newcpu = cpumask_any_and(desc->affinity,
cpu_online_mask);
}
route_irq(desc, irq, newcpu);
}
}
}
#endif
| gpl-2.0 |
wulsic/Hyper_CM11 | drivers/net/qlge/qlge_main.c | 2379 | 137529 | /*
* QLogic qlge NIC HBA Driver
* Copyright (c) 2003-2008 QLogic Corporation
* See LICENSE.qlge for copyright and licensing details.
* Author: Linux qlge network device driver by
* Ron Mercer <ron.mercer@qlogic.com>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/pagemap.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/dmapool.h>
#include <linux/mempool.h>
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/interrupt.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <net/ipv6.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/skbuff.h>
#include <linux/if_vlan.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/prefetch.h>
#include <net/ip6_checksum.h>
#include "qlge.h"
char qlge_driver_name[] = DRV_NAME;
const char qlge_driver_version[] = DRV_VERSION;
MODULE_AUTHOR("Ron Mercer <ron.mercer@qlogic.com>");
MODULE_DESCRIPTION(DRV_STRING " ");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
static const u32 default_msg =
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 |
/* NETIF_MSG_TX_QUEUED | */
/* NETIF_MSG_INTR | NETIF_MSG_TX_DONE | NETIF_MSG_RX_STATUS | */
/* NETIF_MSG_PKTDATA | */
NETIF_MSG_HW | NETIF_MSG_WOL | 0;
static int debug = -1; /* defaults above */
module_param(debug, int, 0664);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
#define MSIX_IRQ 0
#define MSI_IRQ 1
#define LEG_IRQ 2
static int qlge_irq_type = MSIX_IRQ;
module_param(qlge_irq_type, int, 0664);
MODULE_PARM_DESC(qlge_irq_type, "0 = MSI-X, 1 = MSI, 2 = Legacy.");
static int qlge_mpi_coredump;
module_param(qlge_mpi_coredump, int, 0);
MODULE_PARM_DESC(qlge_mpi_coredump,
"Option to enable MPI firmware dump. "
"Default is OFF - Do Not allocate memory. ");
static int qlge_force_coredump;
module_param(qlge_force_coredump, int, 0);
MODULE_PARM_DESC(qlge_force_coredump,
"Option to allow force of firmware core dump. "
"Default is OFF - Do not allow.");
static DEFINE_PCI_DEVICE_TABLE(qlge_pci_tbl) = {
{PCI_DEVICE(PCI_VENDOR_ID_QLOGIC, QLGE_DEVICE_ID_8012)},
{PCI_DEVICE(PCI_VENDOR_ID_QLOGIC, QLGE_DEVICE_ID_8000)},
/* required last entry */
{0,}
};
MODULE_DEVICE_TABLE(pci, qlge_pci_tbl);
static int ql_wol(struct ql_adapter *qdev);
static void qlge_set_multicast_list(struct net_device *ndev);
/* This hardware semaphore causes exclusive access to
* resources shared between the NIC driver, MPI firmware,
* FCOE firmware and the FC driver.
*/
static int ql_sem_trylock(struct ql_adapter *qdev, u32 sem_mask)
{
u32 sem_bits = 0;
switch (sem_mask) {
case SEM_XGMAC0_MASK:
sem_bits = SEM_SET << SEM_XGMAC0_SHIFT;
break;
case SEM_XGMAC1_MASK:
sem_bits = SEM_SET << SEM_XGMAC1_SHIFT;
break;
case SEM_ICB_MASK:
sem_bits = SEM_SET << SEM_ICB_SHIFT;
break;
case SEM_MAC_ADDR_MASK:
sem_bits = SEM_SET << SEM_MAC_ADDR_SHIFT;
break;
case SEM_FLASH_MASK:
sem_bits = SEM_SET << SEM_FLASH_SHIFT;
break;
case SEM_PROBE_MASK:
sem_bits = SEM_SET << SEM_PROBE_SHIFT;
break;
case SEM_RT_IDX_MASK:
sem_bits = SEM_SET << SEM_RT_IDX_SHIFT;
break;
case SEM_PROC_REG_MASK:
sem_bits = SEM_SET << SEM_PROC_REG_SHIFT;
break;
default:
netif_alert(qdev, probe, qdev->ndev, "bad Semaphore mask!.\n");
return -EINVAL;
}
ql_write32(qdev, SEM, sem_bits | sem_mask);
return !(ql_read32(qdev, SEM) & sem_bits);
}
int ql_sem_spinlock(struct ql_adapter *qdev, u32 sem_mask)
{
unsigned int wait_count = 30;
do {
if (!ql_sem_trylock(qdev, sem_mask))
return 0;
udelay(100);
} while (--wait_count);
return -ETIMEDOUT;
}
void ql_sem_unlock(struct ql_adapter *qdev, u32 sem_mask)
{
ql_write32(qdev, SEM, sem_mask);
ql_read32(qdev, SEM); /* flush */
}
/* This function waits for a specific bit to come ready
* in a given register. It is used mostly by the initialize
* process, but is also used in kernel thread API such as
* netdev->set_multi, netdev->set_mac_address, netdev->vlan_rx_add_vid.
*/
int ql_wait_reg_rdy(struct ql_adapter *qdev, u32 reg, u32 bit, u32 err_bit)
{
u32 temp;
int count = UDELAY_COUNT;
while (count) {
temp = ql_read32(qdev, reg);
/* check for errors */
if (temp & err_bit) {
netif_alert(qdev, probe, qdev->ndev,
"register 0x%.08x access error, value = 0x%.08x!.\n",
reg, temp);
return -EIO;
} else if (temp & bit)
return 0;
udelay(UDELAY_DELAY);
count--;
}
netif_alert(qdev, probe, qdev->ndev,
"Timed out waiting for reg %x to come ready.\n", reg);
return -ETIMEDOUT;
}
/* The CFG register is used to download TX and RX control blocks
* to the chip. This function waits for an operation to complete.
*/
static int ql_wait_cfg(struct ql_adapter *qdev, u32 bit)
{
int count = UDELAY_COUNT;
u32 temp;
while (count) {
temp = ql_read32(qdev, CFG);
if (temp & CFG_LE)
return -EIO;
if (!(temp & bit))
return 0;
udelay(UDELAY_DELAY);
count--;
}
return -ETIMEDOUT;
}
/* Used to issue init control blocks to hw. Maps control block,
* sets address, triggers download, waits for completion.
*/
int ql_write_cfg(struct ql_adapter *qdev, void *ptr, int size, u32 bit,
u16 q_id)
{
u64 map;
int status = 0;
int direction;
u32 mask;
u32 value;
direction =
(bit & (CFG_LRQ | CFG_LR | CFG_LCQ)) ? PCI_DMA_TODEVICE :
PCI_DMA_FROMDEVICE;
map = pci_map_single(qdev->pdev, ptr, size, direction);
if (pci_dma_mapping_error(qdev->pdev, map)) {
netif_err(qdev, ifup, qdev->ndev, "Couldn't map DMA area.\n");
return -ENOMEM;
}
status = ql_sem_spinlock(qdev, SEM_ICB_MASK);
if (status)
return status;
status = ql_wait_cfg(qdev, bit);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Timed out waiting for CFG to come ready.\n");
goto exit;
}
ql_write32(qdev, ICB_L, (u32) map);
ql_write32(qdev, ICB_H, (u32) (map >> 32));
mask = CFG_Q_MASK | (bit << 16);
value = bit | (q_id << CFG_Q_SHIFT);
ql_write32(qdev, CFG, (mask | value));
/*
* Wait for the bit to clear after signaling hw.
*/
status = ql_wait_cfg(qdev, bit);
exit:
ql_sem_unlock(qdev, SEM_ICB_MASK); /* does flush too */
pci_unmap_single(qdev->pdev, map, size, direction);
return status;
}
/* Get a specific MAC address from the CAM. Used for debug and reg dump. */
int ql_get_mac_addr_reg(struct ql_adapter *qdev, u32 type, u16 index,
u32 *value)
{
u32 offset = 0;
int status;
switch (type) {
case MAC_ADDR_TYPE_MULTI_MAC:
case MAC_ADDR_TYPE_CAM_MAC:
{
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
ql_write32(qdev, MAC_ADDR_IDX, (offset++) | /* offset */
(index << MAC_ADDR_IDX_SHIFT) | /* index */
MAC_ADDR_ADR | MAC_ADDR_RS | type); /* type */
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MR, 0);
if (status)
goto exit;
*value++ = ql_read32(qdev, MAC_ADDR_DATA);
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
ql_write32(qdev, MAC_ADDR_IDX, (offset++) | /* offset */
(index << MAC_ADDR_IDX_SHIFT) | /* index */
MAC_ADDR_ADR | MAC_ADDR_RS | type); /* type */
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MR, 0);
if (status)
goto exit;
*value++ = ql_read32(qdev, MAC_ADDR_DATA);
if (type == MAC_ADDR_TYPE_CAM_MAC) {
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
ql_write32(qdev, MAC_ADDR_IDX, (offset++) | /* offset */
(index << MAC_ADDR_IDX_SHIFT) | /* index */
MAC_ADDR_ADR | MAC_ADDR_RS | type); /* type */
status =
ql_wait_reg_rdy(qdev, MAC_ADDR_IDX,
MAC_ADDR_MR, 0);
if (status)
goto exit;
*value++ = ql_read32(qdev, MAC_ADDR_DATA);
}
break;
}
case MAC_ADDR_TYPE_VLAN:
case MAC_ADDR_TYPE_MULTI_FLTR:
default:
netif_crit(qdev, ifup, qdev->ndev,
"Address type %d not yet supported.\n", type);
status = -EPERM;
}
exit:
return status;
}
/* Set up a MAC, multicast or VLAN address for the
* inbound frame matching.
*/
static int ql_set_mac_addr_reg(struct ql_adapter *qdev, u8 *addr, u32 type,
u16 index)
{
u32 offset = 0;
int status = 0;
switch (type) {
case MAC_ADDR_TYPE_MULTI_MAC:
{
u32 upper = (addr[0] << 8) | addr[1];
u32 lower = (addr[2] << 24) | (addr[3] << 16) |
(addr[4] << 8) | (addr[5]);
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
ql_write32(qdev, MAC_ADDR_IDX, (offset++) |
(index << MAC_ADDR_IDX_SHIFT) |
type | MAC_ADDR_E);
ql_write32(qdev, MAC_ADDR_DATA, lower);
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
ql_write32(qdev, MAC_ADDR_IDX, (offset++) |
(index << MAC_ADDR_IDX_SHIFT) |
type | MAC_ADDR_E);
ql_write32(qdev, MAC_ADDR_DATA, upper);
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
break;
}
case MAC_ADDR_TYPE_CAM_MAC:
{
u32 cam_output;
u32 upper = (addr[0] << 8) | addr[1];
u32 lower =
(addr[2] << 24) | (addr[3] << 16) | (addr[4] << 8) |
(addr[5]);
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Adding %s address %pM at index %d in the CAM.\n",
type == MAC_ADDR_TYPE_MULTI_MAC ?
"MULTICAST" : "UNICAST",
addr, index);
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
ql_write32(qdev, MAC_ADDR_IDX, (offset++) | /* offset */
(index << MAC_ADDR_IDX_SHIFT) | /* index */
type); /* type */
ql_write32(qdev, MAC_ADDR_DATA, lower);
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
ql_write32(qdev, MAC_ADDR_IDX, (offset++) | /* offset */
(index << MAC_ADDR_IDX_SHIFT) | /* index */
type); /* type */
ql_write32(qdev, MAC_ADDR_DATA, upper);
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
ql_write32(qdev, MAC_ADDR_IDX, (offset) | /* offset */
(index << MAC_ADDR_IDX_SHIFT) | /* index */
type); /* type */
/* This field should also include the queue id
and possibly the function id. Right now we hardcode
the route field to NIC core.
*/
cam_output = (CAM_OUT_ROUTE_NIC |
(qdev->
func << CAM_OUT_FUNC_SHIFT) |
(0 << CAM_OUT_CQ_ID_SHIFT));
if (qdev->vlgrp)
cam_output |= CAM_OUT_RV;
/* route to NIC core */
ql_write32(qdev, MAC_ADDR_DATA, cam_output);
break;
}
case MAC_ADDR_TYPE_VLAN:
{
u32 enable_bit = *((u32 *) &addr[0]);
/* For VLAN, the addr actually holds a bit that
* either enables or disables the vlan id we are
* addressing. It's either MAC_ADDR_E on or off.
* That's bit-27 we're talking about.
*/
netif_info(qdev, ifup, qdev->ndev,
"%s VLAN ID %d %s the CAM.\n",
enable_bit ? "Adding" : "Removing",
index,
enable_bit ? "to" : "from");
status =
ql_wait_reg_rdy(qdev,
MAC_ADDR_IDX, MAC_ADDR_MW, 0);
if (status)
goto exit;
ql_write32(qdev, MAC_ADDR_IDX, offset | /* offset */
(index << MAC_ADDR_IDX_SHIFT) | /* index */
type | /* type */
enable_bit); /* enable/disable */
break;
}
case MAC_ADDR_TYPE_MULTI_FLTR:
default:
netif_crit(qdev, ifup, qdev->ndev,
"Address type %d not yet supported.\n", type);
status = -EPERM;
}
exit:
return status;
}
/* Set or clear MAC address in hardware. We sometimes
* have to clear it to prevent wrong frame routing
* especially in a bonding environment.
*/
static int ql_set_mac_addr(struct ql_adapter *qdev, int set)
{
int status;
char zero_mac_addr[ETH_ALEN];
char *addr;
if (set) {
addr = &qdev->current_mac_addr[0];
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Set Mac addr %pM\n", addr);
} else {
memset(zero_mac_addr, 0, ETH_ALEN);
addr = &zero_mac_addr[0];
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Clearing MAC address\n");
}
status = ql_sem_spinlock(qdev, SEM_MAC_ADDR_MASK);
if (status)
return status;
status = ql_set_mac_addr_reg(qdev, (u8 *) addr,
MAC_ADDR_TYPE_CAM_MAC, qdev->func * MAX_CQ);
ql_sem_unlock(qdev, SEM_MAC_ADDR_MASK);
if (status)
netif_err(qdev, ifup, qdev->ndev,
"Failed to init mac address.\n");
return status;
}
void ql_link_on(struct ql_adapter *qdev)
{
netif_err(qdev, link, qdev->ndev, "Link is up.\n");
netif_carrier_on(qdev->ndev);
ql_set_mac_addr(qdev, 1);
}
void ql_link_off(struct ql_adapter *qdev)
{
netif_err(qdev, link, qdev->ndev, "Link is down.\n");
netif_carrier_off(qdev->ndev);
ql_set_mac_addr(qdev, 0);
}
/* Get a specific frame routing value from the CAM.
* Used for debug and reg dump.
*/
int ql_get_routing_reg(struct ql_adapter *qdev, u32 index, u32 *value)
{
int status = 0;
status = ql_wait_reg_rdy(qdev, RT_IDX, RT_IDX_MW, 0);
if (status)
goto exit;
ql_write32(qdev, RT_IDX,
RT_IDX_TYPE_NICQ | RT_IDX_RS | (index << RT_IDX_IDX_SHIFT));
status = ql_wait_reg_rdy(qdev, RT_IDX, RT_IDX_MR, 0);
if (status)
goto exit;
*value = ql_read32(qdev, RT_DATA);
exit:
return status;
}
/* The NIC function for this chip has 16 routing indexes. Each one can be used
* to route different frame types to various inbound queues. We send broadcast/
* multicast/error frames to the default queue for slow handling,
* and CAM hit/RSS frames to the fast handling queues.
*/
static int ql_set_routing_reg(struct ql_adapter *qdev, u32 index, u32 mask,
int enable)
{
int status = -EINVAL; /* Return error if no mask match. */
u32 value = 0;
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"%s %s mask %s the routing reg.\n",
enable ? "Adding" : "Removing",
index == RT_IDX_ALL_ERR_SLOT ? "MAC ERROR/ALL ERROR" :
index == RT_IDX_IP_CSUM_ERR_SLOT ? "IP CSUM ERROR" :
index == RT_IDX_TCP_UDP_CSUM_ERR_SLOT ? "TCP/UDP CSUM ERROR" :
index == RT_IDX_BCAST_SLOT ? "BROADCAST" :
index == RT_IDX_MCAST_MATCH_SLOT ? "MULTICAST MATCH" :
index == RT_IDX_ALLMULTI_SLOT ? "ALL MULTICAST MATCH" :
index == RT_IDX_UNUSED6_SLOT ? "UNUSED6" :
index == RT_IDX_UNUSED7_SLOT ? "UNUSED7" :
index == RT_IDX_RSS_MATCH_SLOT ? "RSS ALL/IPV4 MATCH" :
index == RT_IDX_RSS_IPV6_SLOT ? "RSS IPV6" :
index == RT_IDX_RSS_TCP4_SLOT ? "RSS TCP4" :
index == RT_IDX_RSS_TCP6_SLOT ? "RSS TCP6" :
index == RT_IDX_CAM_HIT_SLOT ? "CAM HIT" :
index == RT_IDX_UNUSED013 ? "UNUSED13" :
index == RT_IDX_UNUSED014 ? "UNUSED14" :
index == RT_IDX_PROMISCUOUS_SLOT ? "PROMISCUOUS" :
"(Bad index != RT_IDX)",
enable ? "to" : "from");
switch (mask) {
case RT_IDX_CAM_HIT:
{
value = RT_IDX_DST_CAM_Q | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(RT_IDX_CAM_HIT_SLOT << RT_IDX_IDX_SHIFT);/* index */
break;
}
case RT_IDX_VALID: /* Promiscuous Mode frames. */
{
value = RT_IDX_DST_DFLT_Q | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(RT_IDX_PROMISCUOUS_SLOT << RT_IDX_IDX_SHIFT);/* index */
break;
}
case RT_IDX_ERR: /* Pass up MAC,IP,TCP/UDP error frames. */
{
value = RT_IDX_DST_DFLT_Q | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(RT_IDX_ALL_ERR_SLOT << RT_IDX_IDX_SHIFT);/* index */
break;
}
case RT_IDX_IP_CSUM_ERR: /* Pass up IP CSUM error frames. */
{
value = RT_IDX_DST_DFLT_Q | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(RT_IDX_IP_CSUM_ERR_SLOT <<
RT_IDX_IDX_SHIFT); /* index */
break;
}
case RT_IDX_TU_CSUM_ERR: /* Pass up TCP/UDP CSUM error frames. */
{
value = RT_IDX_DST_DFLT_Q | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(RT_IDX_TCP_UDP_CSUM_ERR_SLOT <<
RT_IDX_IDX_SHIFT); /* index */
break;
}
case RT_IDX_BCAST: /* Pass up Broadcast frames to default Q. */
{
value = RT_IDX_DST_DFLT_Q | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(RT_IDX_BCAST_SLOT << RT_IDX_IDX_SHIFT);/* index */
break;
}
case RT_IDX_MCAST: /* Pass up All Multicast frames. */
{
value = RT_IDX_DST_DFLT_Q | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(RT_IDX_ALLMULTI_SLOT << RT_IDX_IDX_SHIFT);/* index */
break;
}
case RT_IDX_MCAST_MATCH: /* Pass up matched Multicast frames. */
{
value = RT_IDX_DST_DFLT_Q | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(RT_IDX_MCAST_MATCH_SLOT << RT_IDX_IDX_SHIFT);/* index */
break;
}
case RT_IDX_RSS_MATCH: /* Pass up matched RSS frames. */
{
value = RT_IDX_DST_RSS | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(RT_IDX_RSS_MATCH_SLOT << RT_IDX_IDX_SHIFT);/* index */
break;
}
case 0: /* Clear the E-bit on an entry. */
{
value = RT_IDX_DST_DFLT_Q | /* dest */
RT_IDX_TYPE_NICQ | /* type */
(index << RT_IDX_IDX_SHIFT);/* index */
break;
}
default:
netif_err(qdev, ifup, qdev->ndev,
"Mask type %d not yet supported.\n", mask);
status = -EPERM;
goto exit;
}
if (value) {
status = ql_wait_reg_rdy(qdev, RT_IDX, RT_IDX_MW, 0);
if (status)
goto exit;
value |= (enable ? RT_IDX_E : 0);
ql_write32(qdev, RT_IDX, value);
ql_write32(qdev, RT_DATA, enable ? mask : 0);
}
exit:
return status;
}
static void ql_enable_interrupts(struct ql_adapter *qdev)
{
ql_write32(qdev, INTR_EN, (INTR_EN_EI << 16) | INTR_EN_EI);
}
static void ql_disable_interrupts(struct ql_adapter *qdev)
{
ql_write32(qdev, INTR_EN, (INTR_EN_EI << 16));
}
/* If we're running with multiple MSI-X vectors then we enable on the fly.
* Otherwise, we may have multiple outstanding workers and don't want to
* enable until the last one finishes. In this case, the irq_cnt gets
* incremented every time we queue a worker and decremented every time
* a worker finishes. Once it hits zero we enable the interrupt.
*/
u32 ql_enable_completion_interrupt(struct ql_adapter *qdev, u32 intr)
{
u32 var = 0;
unsigned long hw_flags = 0;
struct intr_context *ctx = qdev->intr_context + intr;
if (likely(test_bit(QL_MSIX_ENABLED, &qdev->flags) && intr)) {
/* Always enable if we're MSIX multi interrupts and
* it's not the default (zeroeth) interrupt.
*/
ql_write32(qdev, INTR_EN,
ctx->intr_en_mask);
var = ql_read32(qdev, STS);
return var;
}
spin_lock_irqsave(&qdev->hw_lock, hw_flags);
if (atomic_dec_and_test(&ctx->irq_cnt)) {
ql_write32(qdev, INTR_EN,
ctx->intr_en_mask);
var = ql_read32(qdev, STS);
}
spin_unlock_irqrestore(&qdev->hw_lock, hw_flags);
return var;
}
static u32 ql_disable_completion_interrupt(struct ql_adapter *qdev, u32 intr)
{
u32 var = 0;
struct intr_context *ctx;
/* HW disables for us if we're MSIX multi interrupts and
* it's not the default (zeroeth) interrupt.
*/
if (likely(test_bit(QL_MSIX_ENABLED, &qdev->flags) && intr))
return 0;
ctx = qdev->intr_context + intr;
spin_lock(&qdev->hw_lock);
if (!atomic_read(&ctx->irq_cnt)) {
ql_write32(qdev, INTR_EN,
ctx->intr_dis_mask);
var = ql_read32(qdev, STS);
}
atomic_inc(&ctx->irq_cnt);
spin_unlock(&qdev->hw_lock);
return var;
}
static void ql_enable_all_completion_interrupts(struct ql_adapter *qdev)
{
int i;
for (i = 0; i < qdev->intr_count; i++) {
/* The enable call does a atomic_dec_and_test
* and enables only if the result is zero.
* So we precharge it here.
*/
if (unlikely(!test_bit(QL_MSIX_ENABLED, &qdev->flags) ||
i == 0))
atomic_set(&qdev->intr_context[i].irq_cnt, 1);
ql_enable_completion_interrupt(qdev, i);
}
}
static int ql_validate_flash(struct ql_adapter *qdev, u32 size, const char *str)
{
int status, i;
u16 csum = 0;
__le16 *flash = (__le16 *)&qdev->flash;
status = strncmp((char *)&qdev->flash, str, 4);
if (status) {
netif_err(qdev, ifup, qdev->ndev, "Invalid flash signature.\n");
return status;
}
for (i = 0; i < size; i++)
csum += le16_to_cpu(*flash++);
if (csum)
netif_err(qdev, ifup, qdev->ndev,
"Invalid flash checksum, csum = 0x%.04x.\n", csum);
return csum;
}
static int ql_read_flash_word(struct ql_adapter *qdev, int offset, __le32 *data)
{
int status = 0;
/* wait for reg to come ready */
status = ql_wait_reg_rdy(qdev,
FLASH_ADDR, FLASH_ADDR_RDY, FLASH_ADDR_ERR);
if (status)
goto exit;
/* set up for reg read */
ql_write32(qdev, FLASH_ADDR, FLASH_ADDR_R | offset);
/* wait for reg to come ready */
status = ql_wait_reg_rdy(qdev,
FLASH_ADDR, FLASH_ADDR_RDY, FLASH_ADDR_ERR);
if (status)
goto exit;
/* This data is stored on flash as an array of
* __le32. Since ql_read32() returns cpu endian
* we need to swap it back.
*/
*data = cpu_to_le32(ql_read32(qdev, FLASH_DATA));
exit:
return status;
}
static int ql_get_8000_flash_params(struct ql_adapter *qdev)
{
u32 i, size;
int status;
__le32 *p = (__le32 *)&qdev->flash;
u32 offset;
u8 mac_addr[6];
/* Get flash offset for function and adjust
* for dword access.
*/
if (!qdev->port)
offset = FUNC0_FLASH_OFFSET / sizeof(u32);
else
offset = FUNC1_FLASH_OFFSET / sizeof(u32);
if (ql_sem_spinlock(qdev, SEM_FLASH_MASK))
return -ETIMEDOUT;
size = sizeof(struct flash_params_8000) / sizeof(u32);
for (i = 0; i < size; i++, p++) {
status = ql_read_flash_word(qdev, i+offset, p);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Error reading flash.\n");
goto exit;
}
}
status = ql_validate_flash(qdev,
sizeof(struct flash_params_8000) / sizeof(u16),
"8000");
if (status) {
netif_err(qdev, ifup, qdev->ndev, "Invalid flash.\n");
status = -EINVAL;
goto exit;
}
/* Extract either manufacturer or BOFM modified
* MAC address.
*/
if (qdev->flash.flash_params_8000.data_type1 == 2)
memcpy(mac_addr,
qdev->flash.flash_params_8000.mac_addr1,
qdev->ndev->addr_len);
else
memcpy(mac_addr,
qdev->flash.flash_params_8000.mac_addr,
qdev->ndev->addr_len);
if (!is_valid_ether_addr(mac_addr)) {
netif_err(qdev, ifup, qdev->ndev, "Invalid MAC address.\n");
status = -EINVAL;
goto exit;
}
memcpy(qdev->ndev->dev_addr,
mac_addr,
qdev->ndev->addr_len);
exit:
ql_sem_unlock(qdev, SEM_FLASH_MASK);
return status;
}
static int ql_get_8012_flash_params(struct ql_adapter *qdev)
{
int i;
int status;
__le32 *p = (__le32 *)&qdev->flash;
u32 offset = 0;
u32 size = sizeof(struct flash_params_8012) / sizeof(u32);
/* Second function's parameters follow the first
* function's.
*/
if (qdev->port)
offset = size;
if (ql_sem_spinlock(qdev, SEM_FLASH_MASK))
return -ETIMEDOUT;
for (i = 0; i < size; i++, p++) {
status = ql_read_flash_word(qdev, i+offset, p);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Error reading flash.\n");
goto exit;
}
}
status = ql_validate_flash(qdev,
sizeof(struct flash_params_8012) / sizeof(u16),
"8012");
if (status) {
netif_err(qdev, ifup, qdev->ndev, "Invalid flash.\n");
status = -EINVAL;
goto exit;
}
if (!is_valid_ether_addr(qdev->flash.flash_params_8012.mac_addr)) {
status = -EINVAL;
goto exit;
}
memcpy(qdev->ndev->dev_addr,
qdev->flash.flash_params_8012.mac_addr,
qdev->ndev->addr_len);
exit:
ql_sem_unlock(qdev, SEM_FLASH_MASK);
return status;
}
/* xgmac register are located behind the xgmac_addr and xgmac_data
* register pair. Each read/write requires us to wait for the ready
* bit before reading/writing the data.
*/
static int ql_write_xgmac_reg(struct ql_adapter *qdev, u32 reg, u32 data)
{
int status;
/* wait for reg to come ready */
status = ql_wait_reg_rdy(qdev,
XGMAC_ADDR, XGMAC_ADDR_RDY, XGMAC_ADDR_XME);
if (status)
return status;
/* write the data to the data reg */
ql_write32(qdev, XGMAC_DATA, data);
/* trigger the write */
ql_write32(qdev, XGMAC_ADDR, reg);
return status;
}
/* xgmac register are located behind the xgmac_addr and xgmac_data
* register pair. Each read/write requires us to wait for the ready
* bit before reading/writing the data.
*/
int ql_read_xgmac_reg(struct ql_adapter *qdev, u32 reg, u32 *data)
{
int status = 0;
/* wait for reg to come ready */
status = ql_wait_reg_rdy(qdev,
XGMAC_ADDR, XGMAC_ADDR_RDY, XGMAC_ADDR_XME);
if (status)
goto exit;
/* set up for reg read */
ql_write32(qdev, XGMAC_ADDR, reg | XGMAC_ADDR_R);
/* wait for reg to come ready */
status = ql_wait_reg_rdy(qdev,
XGMAC_ADDR, XGMAC_ADDR_RDY, XGMAC_ADDR_XME);
if (status)
goto exit;
/* get the data */
*data = ql_read32(qdev, XGMAC_DATA);
exit:
return status;
}
/* This is used for reading the 64-bit statistics regs. */
int ql_read_xgmac_reg64(struct ql_adapter *qdev, u32 reg, u64 *data)
{
int status = 0;
u32 hi = 0;
u32 lo = 0;
status = ql_read_xgmac_reg(qdev, reg, &lo);
if (status)
goto exit;
status = ql_read_xgmac_reg(qdev, reg + 4, &hi);
if (status)
goto exit;
*data = (u64) lo | ((u64) hi << 32);
exit:
return status;
}
static int ql_8000_port_initialize(struct ql_adapter *qdev)
{
int status;
/*
* Get MPI firmware version for driver banner
* and ethool info.
*/
status = ql_mb_about_fw(qdev);
if (status)
goto exit;
status = ql_mb_get_fw_state(qdev);
if (status)
goto exit;
/* Wake up a worker to get/set the TX/RX frame sizes. */
queue_delayed_work(qdev->workqueue, &qdev->mpi_port_cfg_work, 0);
exit:
return status;
}
/* Take the MAC Core out of reset.
* Enable statistics counting.
* Take the transmitter/receiver out of reset.
* This functionality may be done in the MPI firmware at a
* later date.
*/
static int ql_8012_port_initialize(struct ql_adapter *qdev)
{
int status = 0;
u32 data;
if (ql_sem_trylock(qdev, qdev->xg_sem_mask)) {
/* Another function has the semaphore, so
* wait for the port init bit to come ready.
*/
netif_info(qdev, link, qdev->ndev,
"Another function has the semaphore, so wait for the port init bit to come ready.\n");
status = ql_wait_reg_rdy(qdev, STS, qdev->port_init, 0);
if (status) {
netif_crit(qdev, link, qdev->ndev,
"Port initialize timed out.\n");
}
return status;
}
netif_info(qdev, link, qdev->ndev, "Got xgmac semaphore!.\n");
/* Set the core reset. */
status = ql_read_xgmac_reg(qdev, GLOBAL_CFG, &data);
if (status)
goto end;
data |= GLOBAL_CFG_RESET;
status = ql_write_xgmac_reg(qdev, GLOBAL_CFG, data);
if (status)
goto end;
/* Clear the core reset and turn on jumbo for receiver. */
data &= ~GLOBAL_CFG_RESET; /* Clear core reset. */
data |= GLOBAL_CFG_JUMBO; /* Turn on jumbo. */
data |= GLOBAL_CFG_TX_STAT_EN;
data |= GLOBAL_CFG_RX_STAT_EN;
status = ql_write_xgmac_reg(qdev, GLOBAL_CFG, data);
if (status)
goto end;
/* Enable transmitter, and clear it's reset. */
status = ql_read_xgmac_reg(qdev, TX_CFG, &data);
if (status)
goto end;
data &= ~TX_CFG_RESET; /* Clear the TX MAC reset. */
data |= TX_CFG_EN; /* Enable the transmitter. */
status = ql_write_xgmac_reg(qdev, TX_CFG, data);
if (status)
goto end;
/* Enable receiver and clear it's reset. */
status = ql_read_xgmac_reg(qdev, RX_CFG, &data);
if (status)
goto end;
data &= ~RX_CFG_RESET; /* Clear the RX MAC reset. */
data |= RX_CFG_EN; /* Enable the receiver. */
status = ql_write_xgmac_reg(qdev, RX_CFG, data);
if (status)
goto end;
/* Turn on jumbo. */
status =
ql_write_xgmac_reg(qdev, MAC_TX_PARAMS, MAC_TX_PARAMS_JUMBO | (0x2580 << 16));
if (status)
goto end;
status =
ql_write_xgmac_reg(qdev, MAC_RX_PARAMS, 0x2580);
if (status)
goto end;
/* Signal to the world that the port is enabled. */
ql_write32(qdev, STS, ((qdev->port_init << 16) | qdev->port_init));
end:
ql_sem_unlock(qdev, qdev->xg_sem_mask);
return status;
}
static inline unsigned int ql_lbq_block_size(struct ql_adapter *qdev)
{
return PAGE_SIZE << qdev->lbq_buf_order;
}
/* Get the next large buffer. */
static struct bq_desc *ql_get_curr_lbuf(struct rx_ring *rx_ring)
{
struct bq_desc *lbq_desc = &rx_ring->lbq[rx_ring->lbq_curr_idx];
rx_ring->lbq_curr_idx++;
if (rx_ring->lbq_curr_idx == rx_ring->lbq_len)
rx_ring->lbq_curr_idx = 0;
rx_ring->lbq_free_cnt++;
return lbq_desc;
}
static struct bq_desc *ql_get_curr_lchunk(struct ql_adapter *qdev,
struct rx_ring *rx_ring)
{
struct bq_desc *lbq_desc = ql_get_curr_lbuf(rx_ring);
pci_dma_sync_single_for_cpu(qdev->pdev,
dma_unmap_addr(lbq_desc, mapaddr),
rx_ring->lbq_buf_size,
PCI_DMA_FROMDEVICE);
/* If it's the last chunk of our master page then
* we unmap it.
*/
if ((lbq_desc->p.pg_chunk.offset + rx_ring->lbq_buf_size)
== ql_lbq_block_size(qdev))
pci_unmap_page(qdev->pdev,
lbq_desc->p.pg_chunk.map,
ql_lbq_block_size(qdev),
PCI_DMA_FROMDEVICE);
return lbq_desc;
}
/* Get the next small buffer. */
static struct bq_desc *ql_get_curr_sbuf(struct rx_ring *rx_ring)
{
struct bq_desc *sbq_desc = &rx_ring->sbq[rx_ring->sbq_curr_idx];
rx_ring->sbq_curr_idx++;
if (rx_ring->sbq_curr_idx == rx_ring->sbq_len)
rx_ring->sbq_curr_idx = 0;
rx_ring->sbq_free_cnt++;
return sbq_desc;
}
/* Update an rx ring index. */
static void ql_update_cq(struct rx_ring *rx_ring)
{
rx_ring->cnsmr_idx++;
rx_ring->curr_entry++;
if (unlikely(rx_ring->cnsmr_idx == rx_ring->cq_len)) {
rx_ring->cnsmr_idx = 0;
rx_ring->curr_entry = rx_ring->cq_base;
}
}
static void ql_write_cq_idx(struct rx_ring *rx_ring)
{
ql_write_db_reg(rx_ring->cnsmr_idx, rx_ring->cnsmr_idx_db_reg);
}
static int ql_get_next_chunk(struct ql_adapter *qdev, struct rx_ring *rx_ring,
struct bq_desc *lbq_desc)
{
if (!rx_ring->pg_chunk.page) {
u64 map;
rx_ring->pg_chunk.page = alloc_pages(__GFP_COLD | __GFP_COMP |
GFP_ATOMIC,
qdev->lbq_buf_order);
if (unlikely(!rx_ring->pg_chunk.page)) {
netif_err(qdev, drv, qdev->ndev,
"page allocation failed.\n");
return -ENOMEM;
}
rx_ring->pg_chunk.offset = 0;
map = pci_map_page(qdev->pdev, rx_ring->pg_chunk.page,
0, ql_lbq_block_size(qdev),
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(qdev->pdev, map)) {
__free_pages(rx_ring->pg_chunk.page,
qdev->lbq_buf_order);
netif_err(qdev, drv, qdev->ndev,
"PCI mapping failed.\n");
return -ENOMEM;
}
rx_ring->pg_chunk.map = map;
rx_ring->pg_chunk.va = page_address(rx_ring->pg_chunk.page);
}
/* Copy the current master pg_chunk info
* to the current descriptor.
*/
lbq_desc->p.pg_chunk = rx_ring->pg_chunk;
/* Adjust the master page chunk for next
* buffer get.
*/
rx_ring->pg_chunk.offset += rx_ring->lbq_buf_size;
if (rx_ring->pg_chunk.offset == ql_lbq_block_size(qdev)) {
rx_ring->pg_chunk.page = NULL;
lbq_desc->p.pg_chunk.last_flag = 1;
} else {
rx_ring->pg_chunk.va += rx_ring->lbq_buf_size;
get_page(rx_ring->pg_chunk.page);
lbq_desc->p.pg_chunk.last_flag = 0;
}
return 0;
}
/* Process (refill) a large buffer queue. */
static void ql_update_lbq(struct ql_adapter *qdev, struct rx_ring *rx_ring)
{
u32 clean_idx = rx_ring->lbq_clean_idx;
u32 start_idx = clean_idx;
struct bq_desc *lbq_desc;
u64 map;
int i;
while (rx_ring->lbq_free_cnt > 32) {
for (i = 0; i < 16; i++) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"lbq: try cleaning clean_idx = %d.\n",
clean_idx);
lbq_desc = &rx_ring->lbq[clean_idx];
if (ql_get_next_chunk(qdev, rx_ring, lbq_desc)) {
netif_err(qdev, ifup, qdev->ndev,
"Could not get a page chunk.\n");
return;
}
map = lbq_desc->p.pg_chunk.map +
lbq_desc->p.pg_chunk.offset;
dma_unmap_addr_set(lbq_desc, mapaddr, map);
dma_unmap_len_set(lbq_desc, maplen,
rx_ring->lbq_buf_size);
*lbq_desc->addr = cpu_to_le64(map);
pci_dma_sync_single_for_device(qdev->pdev, map,
rx_ring->lbq_buf_size,
PCI_DMA_FROMDEVICE);
clean_idx++;
if (clean_idx == rx_ring->lbq_len)
clean_idx = 0;
}
rx_ring->lbq_clean_idx = clean_idx;
rx_ring->lbq_prod_idx += 16;
if (rx_ring->lbq_prod_idx == rx_ring->lbq_len)
rx_ring->lbq_prod_idx = 0;
rx_ring->lbq_free_cnt -= 16;
}
if (start_idx != clean_idx) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"lbq: updating prod idx = %d.\n",
rx_ring->lbq_prod_idx);
ql_write_db_reg(rx_ring->lbq_prod_idx,
rx_ring->lbq_prod_idx_db_reg);
}
}
/* Process (refill) a small buffer queue. */
static void ql_update_sbq(struct ql_adapter *qdev, struct rx_ring *rx_ring)
{
u32 clean_idx = rx_ring->sbq_clean_idx;
u32 start_idx = clean_idx;
struct bq_desc *sbq_desc;
u64 map;
int i;
while (rx_ring->sbq_free_cnt > 16) {
for (i = 0; i < 16; i++) {
sbq_desc = &rx_ring->sbq[clean_idx];
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"sbq: try cleaning clean_idx = %d.\n",
clean_idx);
if (sbq_desc->p.skb == NULL) {
netif_printk(qdev, rx_status, KERN_DEBUG,
qdev->ndev,
"sbq: getting new skb for index %d.\n",
sbq_desc->index);
sbq_desc->p.skb =
netdev_alloc_skb(qdev->ndev,
SMALL_BUFFER_SIZE);
if (sbq_desc->p.skb == NULL) {
netif_err(qdev, probe, qdev->ndev,
"Couldn't get an skb.\n");
rx_ring->sbq_clean_idx = clean_idx;
return;
}
skb_reserve(sbq_desc->p.skb, QLGE_SB_PAD);
map = pci_map_single(qdev->pdev,
sbq_desc->p.skb->data,
rx_ring->sbq_buf_size,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(qdev->pdev, map)) {
netif_err(qdev, ifup, qdev->ndev,
"PCI mapping failed.\n");
rx_ring->sbq_clean_idx = clean_idx;
dev_kfree_skb_any(sbq_desc->p.skb);
sbq_desc->p.skb = NULL;
return;
}
dma_unmap_addr_set(sbq_desc, mapaddr, map);
dma_unmap_len_set(sbq_desc, maplen,
rx_ring->sbq_buf_size);
*sbq_desc->addr = cpu_to_le64(map);
}
clean_idx++;
if (clean_idx == rx_ring->sbq_len)
clean_idx = 0;
}
rx_ring->sbq_clean_idx = clean_idx;
rx_ring->sbq_prod_idx += 16;
if (rx_ring->sbq_prod_idx == rx_ring->sbq_len)
rx_ring->sbq_prod_idx = 0;
rx_ring->sbq_free_cnt -= 16;
}
if (start_idx != clean_idx) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"sbq: updating prod idx = %d.\n",
rx_ring->sbq_prod_idx);
ql_write_db_reg(rx_ring->sbq_prod_idx,
rx_ring->sbq_prod_idx_db_reg);
}
}
static void ql_update_buffer_queues(struct ql_adapter *qdev,
struct rx_ring *rx_ring)
{
ql_update_sbq(qdev, rx_ring);
ql_update_lbq(qdev, rx_ring);
}
/* Unmaps tx buffers. Can be called from send() if a pci mapping
* fails at some stage, or from the interrupt when a tx completes.
*/
static void ql_unmap_send(struct ql_adapter *qdev,
struct tx_ring_desc *tx_ring_desc, int mapped)
{
int i;
for (i = 0; i < mapped; i++) {
if (i == 0 || (i == 7 && mapped > 7)) {
/*
* Unmap the skb->data area, or the
* external sglist (AKA the Outbound
* Address List (OAL)).
* If its the zeroeth element, then it's
* the skb->data area. If it's the 7th
* element and there is more than 6 frags,
* then its an OAL.
*/
if (i == 7) {
netif_printk(qdev, tx_done, KERN_DEBUG,
qdev->ndev,
"unmapping OAL area.\n");
}
pci_unmap_single(qdev->pdev,
dma_unmap_addr(&tx_ring_desc->map[i],
mapaddr),
dma_unmap_len(&tx_ring_desc->map[i],
maplen),
PCI_DMA_TODEVICE);
} else {
netif_printk(qdev, tx_done, KERN_DEBUG, qdev->ndev,
"unmapping frag %d.\n", i);
pci_unmap_page(qdev->pdev,
dma_unmap_addr(&tx_ring_desc->map[i],
mapaddr),
dma_unmap_len(&tx_ring_desc->map[i],
maplen), PCI_DMA_TODEVICE);
}
}
}
/* Map the buffers for this transmit. This will return
* NETDEV_TX_BUSY or NETDEV_TX_OK based on success.
*/
static int ql_map_send(struct ql_adapter *qdev,
struct ob_mac_iocb_req *mac_iocb_ptr,
struct sk_buff *skb, struct tx_ring_desc *tx_ring_desc)
{
int len = skb_headlen(skb);
dma_addr_t map;
int frag_idx, err, map_idx = 0;
struct tx_buf_desc *tbd = mac_iocb_ptr->tbd;
int frag_cnt = skb_shinfo(skb)->nr_frags;
if (frag_cnt) {
netif_printk(qdev, tx_queued, KERN_DEBUG, qdev->ndev,
"frag_cnt = %d.\n", frag_cnt);
}
/*
* Map the skb buffer first.
*/
map = pci_map_single(qdev->pdev, skb->data, len, PCI_DMA_TODEVICE);
err = pci_dma_mapping_error(qdev->pdev, map);
if (err) {
netif_err(qdev, tx_queued, qdev->ndev,
"PCI mapping failed with error: %d\n", err);
return NETDEV_TX_BUSY;
}
tbd->len = cpu_to_le32(len);
tbd->addr = cpu_to_le64(map);
dma_unmap_addr_set(&tx_ring_desc->map[map_idx], mapaddr, map);
dma_unmap_len_set(&tx_ring_desc->map[map_idx], maplen, len);
map_idx++;
/*
* This loop fills the remainder of the 8 address descriptors
* in the IOCB. If there are more than 7 fragments, then the
* eighth address desc will point to an external list (OAL).
* When this happens, the remainder of the frags will be stored
* in this list.
*/
for (frag_idx = 0; frag_idx < frag_cnt; frag_idx++, map_idx++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[frag_idx];
tbd++;
if (frag_idx == 6 && frag_cnt > 7) {
/* Let's tack on an sglist.
* Our control block will now
* look like this:
* iocb->seg[0] = skb->data
* iocb->seg[1] = frag[0]
* iocb->seg[2] = frag[1]
* iocb->seg[3] = frag[2]
* iocb->seg[4] = frag[3]
* iocb->seg[5] = frag[4]
* iocb->seg[6] = frag[5]
* iocb->seg[7] = ptr to OAL (external sglist)
* oal->seg[0] = frag[6]
* oal->seg[1] = frag[7]
* oal->seg[2] = frag[8]
* oal->seg[3] = frag[9]
* oal->seg[4] = frag[10]
* etc...
*/
/* Tack on the OAL in the eighth segment of IOCB. */
map = pci_map_single(qdev->pdev, &tx_ring_desc->oal,
sizeof(struct oal),
PCI_DMA_TODEVICE);
err = pci_dma_mapping_error(qdev->pdev, map);
if (err) {
netif_err(qdev, tx_queued, qdev->ndev,
"PCI mapping outbound address list with error: %d\n",
err);
goto map_error;
}
tbd->addr = cpu_to_le64(map);
/*
* The length is the number of fragments
* that remain to be mapped times the length
* of our sglist (OAL).
*/
tbd->len =
cpu_to_le32((sizeof(struct tx_buf_desc) *
(frag_cnt - frag_idx)) | TX_DESC_C);
dma_unmap_addr_set(&tx_ring_desc->map[map_idx], mapaddr,
map);
dma_unmap_len_set(&tx_ring_desc->map[map_idx], maplen,
sizeof(struct oal));
tbd = (struct tx_buf_desc *)&tx_ring_desc->oal;
map_idx++;
}
map =
pci_map_page(qdev->pdev, frag->page,
frag->page_offset, frag->size,
PCI_DMA_TODEVICE);
err = pci_dma_mapping_error(qdev->pdev, map);
if (err) {
netif_err(qdev, tx_queued, qdev->ndev,
"PCI mapping frags failed with error: %d.\n",
err);
goto map_error;
}
tbd->addr = cpu_to_le64(map);
tbd->len = cpu_to_le32(frag->size);
dma_unmap_addr_set(&tx_ring_desc->map[map_idx], mapaddr, map);
dma_unmap_len_set(&tx_ring_desc->map[map_idx], maplen,
frag->size);
}
/* Save the number of segments we've mapped. */
tx_ring_desc->map_cnt = map_idx;
/* Terminate the last segment. */
tbd->len = cpu_to_le32(le32_to_cpu(tbd->len) | TX_DESC_E);
return NETDEV_TX_OK;
map_error:
/*
* If the first frag mapping failed, then i will be zero.
* This causes the unmap of the skb->data area. Otherwise
* we pass in the number of frags that mapped successfully
* so they can be umapped.
*/
ql_unmap_send(qdev, tx_ring_desc, map_idx);
return NETDEV_TX_BUSY;
}
/* Process an inbound completion from an rx ring. */
static void ql_process_mac_rx_gro_page(struct ql_adapter *qdev,
struct rx_ring *rx_ring,
struct ib_mac_iocb_rsp *ib_mac_rsp,
u32 length,
u16 vlan_id)
{
struct sk_buff *skb;
struct bq_desc *lbq_desc = ql_get_curr_lchunk(qdev, rx_ring);
struct skb_frag_struct *rx_frag;
int nr_frags;
struct napi_struct *napi = &rx_ring->napi;
napi->dev = qdev->ndev;
skb = napi_get_frags(napi);
if (!skb) {
netif_err(qdev, drv, qdev->ndev,
"Couldn't get an skb, exiting.\n");
rx_ring->rx_dropped++;
put_page(lbq_desc->p.pg_chunk.page);
return;
}
prefetch(lbq_desc->p.pg_chunk.va);
rx_frag = skb_shinfo(skb)->frags;
nr_frags = skb_shinfo(skb)->nr_frags;
rx_frag += nr_frags;
rx_frag->page = lbq_desc->p.pg_chunk.page;
rx_frag->page_offset = lbq_desc->p.pg_chunk.offset;
rx_frag->size = length;
skb->len += length;
skb->data_len += length;
skb->truesize += length;
skb_shinfo(skb)->nr_frags++;
rx_ring->rx_packets++;
rx_ring->rx_bytes += length;
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb_record_rx_queue(skb, rx_ring->cq_id);
if (qdev->vlgrp && (vlan_id != 0xffff))
vlan_gro_frags(&rx_ring->napi, qdev->vlgrp, vlan_id);
else
napi_gro_frags(napi);
}
/* Process an inbound completion from an rx ring. */
static void ql_process_mac_rx_page(struct ql_adapter *qdev,
struct rx_ring *rx_ring,
struct ib_mac_iocb_rsp *ib_mac_rsp,
u32 length,
u16 vlan_id)
{
struct net_device *ndev = qdev->ndev;
struct sk_buff *skb = NULL;
void *addr;
struct bq_desc *lbq_desc = ql_get_curr_lchunk(qdev, rx_ring);
struct napi_struct *napi = &rx_ring->napi;
skb = netdev_alloc_skb(ndev, length);
if (!skb) {
netif_err(qdev, drv, qdev->ndev,
"Couldn't get an skb, need to unwind!.\n");
rx_ring->rx_dropped++;
put_page(lbq_desc->p.pg_chunk.page);
return;
}
addr = lbq_desc->p.pg_chunk.va;
prefetch(addr);
/* Frame error, so drop the packet. */
if (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_ERR_MASK) {
netif_info(qdev, drv, qdev->ndev,
"Receive error, flags2 = 0x%x\n", ib_mac_rsp->flags2);
rx_ring->rx_errors++;
goto err_out;
}
/* The max framesize filter on this chip is set higher than
* MTU since FCoE uses 2k frames.
*/
if (skb->len > ndev->mtu + ETH_HLEN) {
netif_err(qdev, drv, qdev->ndev,
"Segment too small, dropping.\n");
rx_ring->rx_dropped++;
goto err_out;
}
memcpy(skb_put(skb, ETH_HLEN), addr, ETH_HLEN);
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"%d bytes of headers and data in large. Chain page to new skb and pull tail.\n",
length);
skb_fill_page_desc(skb, 0, lbq_desc->p.pg_chunk.page,
lbq_desc->p.pg_chunk.offset+ETH_HLEN,
length-ETH_HLEN);
skb->len += length-ETH_HLEN;
skb->data_len += length-ETH_HLEN;
skb->truesize += length-ETH_HLEN;
rx_ring->rx_packets++;
rx_ring->rx_bytes += skb->len;
skb->protocol = eth_type_trans(skb, ndev);
skb_checksum_none_assert(skb);
if ((ndev->features & NETIF_F_RXCSUM) &&
!(ib_mac_rsp->flags1 & IB_MAC_CSUM_ERR_MASK)) {
/* TCP frame. */
if (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_T) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"TCP checksum done!\n");
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else if ((ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_U) &&
(ib_mac_rsp->flags3 & IB_MAC_IOCB_RSP_V4)) {
/* Unfragmented ipv4 UDP frame. */
struct iphdr *iph = (struct iphdr *) skb->data;
if (!(iph->frag_off &
cpu_to_be16(IP_MF|IP_OFFSET))) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
netif_printk(qdev, rx_status, KERN_DEBUG,
qdev->ndev,
"TCP checksum done!\n");
}
}
}
skb_record_rx_queue(skb, rx_ring->cq_id);
if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
if (qdev->vlgrp && (vlan_id != 0xffff))
vlan_gro_receive(napi, qdev->vlgrp, vlan_id, skb);
else
napi_gro_receive(napi, skb);
} else {
if (qdev->vlgrp && (vlan_id != 0xffff))
vlan_hwaccel_receive_skb(skb, qdev->vlgrp, vlan_id);
else
netif_receive_skb(skb);
}
return;
err_out:
dev_kfree_skb_any(skb);
put_page(lbq_desc->p.pg_chunk.page);
}
/* Process an inbound completion from an rx ring. */
static void ql_process_mac_rx_skb(struct ql_adapter *qdev,
struct rx_ring *rx_ring,
struct ib_mac_iocb_rsp *ib_mac_rsp,
u32 length,
u16 vlan_id)
{
struct net_device *ndev = qdev->ndev;
struct sk_buff *skb = NULL;
struct sk_buff *new_skb = NULL;
struct bq_desc *sbq_desc = ql_get_curr_sbuf(rx_ring);
skb = sbq_desc->p.skb;
/* Allocate new_skb and copy */
new_skb = netdev_alloc_skb(qdev->ndev, length + NET_IP_ALIGN);
if (new_skb == NULL) {
netif_err(qdev, probe, qdev->ndev,
"No skb available, drop the packet.\n");
rx_ring->rx_dropped++;
return;
}
skb_reserve(new_skb, NET_IP_ALIGN);
memcpy(skb_put(new_skb, length), skb->data, length);
skb = new_skb;
/* Frame error, so drop the packet. */
if (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_ERR_MASK) {
netif_info(qdev, drv, qdev->ndev,
"Receive error, flags2 = 0x%x\n", ib_mac_rsp->flags2);
dev_kfree_skb_any(skb);
rx_ring->rx_errors++;
return;
}
/* loopback self test for ethtool */
if (test_bit(QL_SELFTEST, &qdev->flags)) {
ql_check_lb_frame(qdev, skb);
dev_kfree_skb_any(skb);
return;
}
/* The max framesize filter on this chip is set higher than
* MTU since FCoE uses 2k frames.
*/
if (skb->len > ndev->mtu + ETH_HLEN) {
dev_kfree_skb_any(skb);
rx_ring->rx_dropped++;
return;
}
prefetch(skb->data);
skb->dev = ndev;
if (ib_mac_rsp->flags1 & IB_MAC_IOCB_RSP_M_MASK) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"%s Multicast.\n",
(ib_mac_rsp->flags1 & IB_MAC_IOCB_RSP_M_MASK) ==
IB_MAC_IOCB_RSP_M_HASH ? "Hash" :
(ib_mac_rsp->flags1 & IB_MAC_IOCB_RSP_M_MASK) ==
IB_MAC_IOCB_RSP_M_REG ? "Registered" :
(ib_mac_rsp->flags1 & IB_MAC_IOCB_RSP_M_MASK) ==
IB_MAC_IOCB_RSP_M_PROM ? "Promiscuous" : "");
}
if (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_P)
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Promiscuous Packet.\n");
rx_ring->rx_packets++;
rx_ring->rx_bytes += skb->len;
skb->protocol = eth_type_trans(skb, ndev);
skb_checksum_none_assert(skb);
/* If rx checksum is on, and there are no
* csum or frame errors.
*/
if ((ndev->features & NETIF_F_RXCSUM) &&
!(ib_mac_rsp->flags1 & IB_MAC_CSUM_ERR_MASK)) {
/* TCP frame. */
if (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_T) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"TCP checksum done!\n");
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else if ((ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_U) &&
(ib_mac_rsp->flags3 & IB_MAC_IOCB_RSP_V4)) {
/* Unfragmented ipv4 UDP frame. */
struct iphdr *iph = (struct iphdr *) skb->data;
if (!(iph->frag_off &
ntohs(IP_MF|IP_OFFSET))) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
netif_printk(qdev, rx_status, KERN_DEBUG,
qdev->ndev,
"TCP checksum done!\n");
}
}
}
skb_record_rx_queue(skb, rx_ring->cq_id);
if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
if (qdev->vlgrp && (vlan_id != 0xffff))
vlan_gro_receive(&rx_ring->napi, qdev->vlgrp,
vlan_id, skb);
else
napi_gro_receive(&rx_ring->napi, skb);
} else {
if (qdev->vlgrp && (vlan_id != 0xffff))
vlan_hwaccel_receive_skb(skb, qdev->vlgrp, vlan_id);
else
netif_receive_skb(skb);
}
}
static void ql_realign_skb(struct sk_buff *skb, int len)
{
void *temp_addr = skb->data;
/* Undo the skb_reserve(skb,32) we did before
* giving to hardware, and realign data on
* a 2-byte boundary.
*/
skb->data -= QLGE_SB_PAD - NET_IP_ALIGN;
skb->tail -= QLGE_SB_PAD - NET_IP_ALIGN;
skb_copy_to_linear_data(skb, temp_addr,
(unsigned int)len);
}
/*
* This function builds an skb for the given inbound
* completion. It will be rewritten for readability in the near
* future, but for not it works well.
*/
static struct sk_buff *ql_build_rx_skb(struct ql_adapter *qdev,
struct rx_ring *rx_ring,
struct ib_mac_iocb_rsp *ib_mac_rsp)
{
struct bq_desc *lbq_desc;
struct bq_desc *sbq_desc;
struct sk_buff *skb = NULL;
u32 length = le32_to_cpu(ib_mac_rsp->data_len);
u32 hdr_len = le32_to_cpu(ib_mac_rsp->hdr_len);
/*
* Handle the header buffer if present.
*/
if (ib_mac_rsp->flags4 & IB_MAC_IOCB_RSP_HV &&
ib_mac_rsp->flags4 & IB_MAC_IOCB_RSP_HS) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Header of %d bytes in small buffer.\n", hdr_len);
/*
* Headers fit nicely into a small buffer.
*/
sbq_desc = ql_get_curr_sbuf(rx_ring);
pci_unmap_single(qdev->pdev,
dma_unmap_addr(sbq_desc, mapaddr),
dma_unmap_len(sbq_desc, maplen),
PCI_DMA_FROMDEVICE);
skb = sbq_desc->p.skb;
ql_realign_skb(skb, hdr_len);
skb_put(skb, hdr_len);
sbq_desc->p.skb = NULL;
}
/*
* Handle the data buffer(s).
*/
if (unlikely(!length)) { /* Is there data too? */
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"No Data buffer in this packet.\n");
return skb;
}
if (ib_mac_rsp->flags3 & IB_MAC_IOCB_RSP_DS) {
if (ib_mac_rsp->flags4 & IB_MAC_IOCB_RSP_HS) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Headers in small, data of %d bytes in small, combine them.\n",
length);
/*
* Data is less than small buffer size so it's
* stuffed in a small buffer.
* For this case we append the data
* from the "data" small buffer to the "header" small
* buffer.
*/
sbq_desc = ql_get_curr_sbuf(rx_ring);
pci_dma_sync_single_for_cpu(qdev->pdev,
dma_unmap_addr
(sbq_desc, mapaddr),
dma_unmap_len
(sbq_desc, maplen),
PCI_DMA_FROMDEVICE);
memcpy(skb_put(skb, length),
sbq_desc->p.skb->data, length);
pci_dma_sync_single_for_device(qdev->pdev,
dma_unmap_addr
(sbq_desc,
mapaddr),
dma_unmap_len
(sbq_desc,
maplen),
PCI_DMA_FROMDEVICE);
} else {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"%d bytes in a single small buffer.\n",
length);
sbq_desc = ql_get_curr_sbuf(rx_ring);
skb = sbq_desc->p.skb;
ql_realign_skb(skb, length);
skb_put(skb, length);
pci_unmap_single(qdev->pdev,
dma_unmap_addr(sbq_desc,
mapaddr),
dma_unmap_len(sbq_desc,
maplen),
PCI_DMA_FROMDEVICE);
sbq_desc->p.skb = NULL;
}
} else if (ib_mac_rsp->flags3 & IB_MAC_IOCB_RSP_DL) {
if (ib_mac_rsp->flags4 & IB_MAC_IOCB_RSP_HS) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Header in small, %d bytes in large. Chain large to small!\n",
length);
/*
* The data is in a single large buffer. We
* chain it to the header buffer's skb and let
* it rip.
*/
lbq_desc = ql_get_curr_lchunk(qdev, rx_ring);
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Chaining page at offset = %d, for %d bytes to skb.\n",
lbq_desc->p.pg_chunk.offset, length);
skb_fill_page_desc(skb, 0, lbq_desc->p.pg_chunk.page,
lbq_desc->p.pg_chunk.offset,
length);
skb->len += length;
skb->data_len += length;
skb->truesize += length;
} else {
/*
* The headers and data are in a single large buffer. We
* copy it to a new skb and let it go. This can happen with
* jumbo mtu on a non-TCP/UDP frame.
*/
lbq_desc = ql_get_curr_lchunk(qdev, rx_ring);
skb = netdev_alloc_skb(qdev->ndev, length);
if (skb == NULL) {
netif_printk(qdev, probe, KERN_DEBUG, qdev->ndev,
"No skb available, drop the packet.\n");
return NULL;
}
pci_unmap_page(qdev->pdev,
dma_unmap_addr(lbq_desc,
mapaddr),
dma_unmap_len(lbq_desc, maplen),
PCI_DMA_FROMDEVICE);
skb_reserve(skb, NET_IP_ALIGN);
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"%d bytes of headers and data in large. Chain page to new skb and pull tail.\n",
length);
skb_fill_page_desc(skb, 0,
lbq_desc->p.pg_chunk.page,
lbq_desc->p.pg_chunk.offset,
length);
skb->len += length;
skb->data_len += length;
skb->truesize += length;
length -= length;
__pskb_pull_tail(skb,
(ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_V) ?
VLAN_ETH_HLEN : ETH_HLEN);
}
} else {
/*
* The data is in a chain of large buffers
* pointed to by a small buffer. We loop
* thru and chain them to the our small header
* buffer's skb.
* frags: There are 18 max frags and our small
* buffer will hold 32 of them. The thing is,
* we'll use 3 max for our 9000 byte jumbo
* frames. If the MTU goes up we could
* eventually be in trouble.
*/
int size, i = 0;
sbq_desc = ql_get_curr_sbuf(rx_ring);
pci_unmap_single(qdev->pdev,
dma_unmap_addr(sbq_desc, mapaddr),
dma_unmap_len(sbq_desc, maplen),
PCI_DMA_FROMDEVICE);
if (!(ib_mac_rsp->flags4 & IB_MAC_IOCB_RSP_HS)) {
/*
* This is an non TCP/UDP IP frame, so
* the headers aren't split into a small
* buffer. We have to use the small buffer
* that contains our sg list as our skb to
* send upstairs. Copy the sg list here to
* a local buffer and use it to find the
* pages to chain.
*/
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"%d bytes of headers & data in chain of large.\n",
length);
skb = sbq_desc->p.skb;
sbq_desc->p.skb = NULL;
skb_reserve(skb, NET_IP_ALIGN);
}
while (length > 0) {
lbq_desc = ql_get_curr_lchunk(qdev, rx_ring);
size = (length < rx_ring->lbq_buf_size) ? length :
rx_ring->lbq_buf_size;
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Adding page %d to skb for %d bytes.\n",
i, size);
skb_fill_page_desc(skb, i,
lbq_desc->p.pg_chunk.page,
lbq_desc->p.pg_chunk.offset,
size);
skb->len += size;
skb->data_len += size;
skb->truesize += size;
length -= size;
i++;
}
__pskb_pull_tail(skb, (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_V) ?
VLAN_ETH_HLEN : ETH_HLEN);
}
return skb;
}
/* Process an inbound completion from an rx ring. */
static void ql_process_mac_split_rx_intr(struct ql_adapter *qdev,
struct rx_ring *rx_ring,
struct ib_mac_iocb_rsp *ib_mac_rsp,
u16 vlan_id)
{
struct net_device *ndev = qdev->ndev;
struct sk_buff *skb = NULL;
QL_DUMP_IB_MAC_RSP(ib_mac_rsp);
skb = ql_build_rx_skb(qdev, rx_ring, ib_mac_rsp);
if (unlikely(!skb)) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"No skb available, drop packet.\n");
rx_ring->rx_dropped++;
return;
}
/* Frame error, so drop the packet. */
if (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_ERR_MASK) {
netif_info(qdev, drv, qdev->ndev,
"Receive error, flags2 = 0x%x\n", ib_mac_rsp->flags2);
dev_kfree_skb_any(skb);
rx_ring->rx_errors++;
return;
}
/* The max framesize filter on this chip is set higher than
* MTU since FCoE uses 2k frames.
*/
if (skb->len > ndev->mtu + ETH_HLEN) {
dev_kfree_skb_any(skb);
rx_ring->rx_dropped++;
return;
}
/* loopback self test for ethtool */
if (test_bit(QL_SELFTEST, &qdev->flags)) {
ql_check_lb_frame(qdev, skb);
dev_kfree_skb_any(skb);
return;
}
prefetch(skb->data);
skb->dev = ndev;
if (ib_mac_rsp->flags1 & IB_MAC_IOCB_RSP_M_MASK) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev, "%s Multicast.\n",
(ib_mac_rsp->flags1 & IB_MAC_IOCB_RSP_M_MASK) ==
IB_MAC_IOCB_RSP_M_HASH ? "Hash" :
(ib_mac_rsp->flags1 & IB_MAC_IOCB_RSP_M_MASK) ==
IB_MAC_IOCB_RSP_M_REG ? "Registered" :
(ib_mac_rsp->flags1 & IB_MAC_IOCB_RSP_M_MASK) ==
IB_MAC_IOCB_RSP_M_PROM ? "Promiscuous" : "");
rx_ring->rx_multicast++;
}
if (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_P) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Promiscuous Packet.\n");
}
skb->protocol = eth_type_trans(skb, ndev);
skb_checksum_none_assert(skb);
/* If rx checksum is on, and there are no
* csum or frame errors.
*/
if ((ndev->features & NETIF_F_RXCSUM) &&
!(ib_mac_rsp->flags1 & IB_MAC_CSUM_ERR_MASK)) {
/* TCP frame. */
if (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_T) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"TCP checksum done!\n");
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else if ((ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_U) &&
(ib_mac_rsp->flags3 & IB_MAC_IOCB_RSP_V4)) {
/* Unfragmented ipv4 UDP frame. */
struct iphdr *iph = (struct iphdr *) skb->data;
if (!(iph->frag_off &
ntohs(IP_MF|IP_OFFSET))) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"TCP checksum done!\n");
}
}
}
rx_ring->rx_packets++;
rx_ring->rx_bytes += skb->len;
skb_record_rx_queue(skb, rx_ring->cq_id);
if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
if (qdev->vlgrp &&
(ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_V) &&
(vlan_id != 0))
vlan_gro_receive(&rx_ring->napi, qdev->vlgrp,
vlan_id, skb);
else
napi_gro_receive(&rx_ring->napi, skb);
} else {
if (qdev->vlgrp &&
(ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_V) &&
(vlan_id != 0))
vlan_hwaccel_receive_skb(skb, qdev->vlgrp, vlan_id);
else
netif_receive_skb(skb);
}
}
/* Process an inbound completion from an rx ring. */
static unsigned long ql_process_mac_rx_intr(struct ql_adapter *qdev,
struct rx_ring *rx_ring,
struct ib_mac_iocb_rsp *ib_mac_rsp)
{
u32 length = le32_to_cpu(ib_mac_rsp->data_len);
u16 vlan_id = (ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_V) ?
((le16_to_cpu(ib_mac_rsp->vlan_id) &
IB_MAC_IOCB_RSP_VLAN_MASK)) : 0xffff;
QL_DUMP_IB_MAC_RSP(ib_mac_rsp);
if (ib_mac_rsp->flags4 & IB_MAC_IOCB_RSP_HV) {
/* The data and headers are split into
* separate buffers.
*/
ql_process_mac_split_rx_intr(qdev, rx_ring, ib_mac_rsp,
vlan_id);
} else if (ib_mac_rsp->flags3 & IB_MAC_IOCB_RSP_DS) {
/* The data fit in a single small buffer.
* Allocate a new skb, copy the data and
* return the buffer to the free pool.
*/
ql_process_mac_rx_skb(qdev, rx_ring, ib_mac_rsp,
length, vlan_id);
} else if ((ib_mac_rsp->flags3 & IB_MAC_IOCB_RSP_DL) &&
!(ib_mac_rsp->flags1 & IB_MAC_CSUM_ERR_MASK) &&
(ib_mac_rsp->flags2 & IB_MAC_IOCB_RSP_T)) {
/* TCP packet in a page chunk that's been checksummed.
* Tack it on to our GRO skb and let it go.
*/
ql_process_mac_rx_gro_page(qdev, rx_ring, ib_mac_rsp,
length, vlan_id);
} else if (ib_mac_rsp->flags3 & IB_MAC_IOCB_RSP_DL) {
/* Non-TCP packet in a page chunk. Allocate an
* skb, tack it on frags, and send it up.
*/
ql_process_mac_rx_page(qdev, rx_ring, ib_mac_rsp,
length, vlan_id);
} else {
/* Non-TCP/UDP large frames that span multiple buffers
* can be processed corrrectly by the split frame logic.
*/
ql_process_mac_split_rx_intr(qdev, rx_ring, ib_mac_rsp,
vlan_id);
}
return (unsigned long)length;
}
/* Process an outbound completion from an rx ring. */
static void ql_process_mac_tx_intr(struct ql_adapter *qdev,
struct ob_mac_iocb_rsp *mac_rsp)
{
struct tx_ring *tx_ring;
struct tx_ring_desc *tx_ring_desc;
QL_DUMP_OB_MAC_RSP(mac_rsp);
tx_ring = &qdev->tx_ring[mac_rsp->txq_idx];
tx_ring_desc = &tx_ring->q[mac_rsp->tid];
ql_unmap_send(qdev, tx_ring_desc, tx_ring_desc->map_cnt);
tx_ring->tx_bytes += (tx_ring_desc->skb)->len;
tx_ring->tx_packets++;
dev_kfree_skb(tx_ring_desc->skb);
tx_ring_desc->skb = NULL;
if (unlikely(mac_rsp->flags1 & (OB_MAC_IOCB_RSP_E |
OB_MAC_IOCB_RSP_S |
OB_MAC_IOCB_RSP_L |
OB_MAC_IOCB_RSP_P | OB_MAC_IOCB_RSP_B))) {
if (mac_rsp->flags1 & OB_MAC_IOCB_RSP_E) {
netif_warn(qdev, tx_done, qdev->ndev,
"Total descriptor length did not match transfer length.\n");
}
if (mac_rsp->flags1 & OB_MAC_IOCB_RSP_S) {
netif_warn(qdev, tx_done, qdev->ndev,
"Frame too short to be valid, not sent.\n");
}
if (mac_rsp->flags1 & OB_MAC_IOCB_RSP_L) {
netif_warn(qdev, tx_done, qdev->ndev,
"Frame too long, but sent anyway.\n");
}
if (mac_rsp->flags1 & OB_MAC_IOCB_RSP_B) {
netif_warn(qdev, tx_done, qdev->ndev,
"PCI backplane error. Frame not sent.\n");
}
}
atomic_inc(&tx_ring->tx_count);
}
/* Fire up a handler to reset the MPI processor. */
void ql_queue_fw_error(struct ql_adapter *qdev)
{
ql_link_off(qdev);
queue_delayed_work(qdev->workqueue, &qdev->mpi_reset_work, 0);
}
void ql_queue_asic_error(struct ql_adapter *qdev)
{
ql_link_off(qdev);
ql_disable_interrupts(qdev);
/* Clear adapter up bit to signal the recovery
* process that it shouldn't kill the reset worker
* thread
*/
clear_bit(QL_ADAPTER_UP, &qdev->flags);
/* Set asic recovery bit to indicate reset process that we are
* in fatal error recovery process rather than normal close
*/
set_bit(QL_ASIC_RECOVERY, &qdev->flags);
queue_delayed_work(qdev->workqueue, &qdev->asic_reset_work, 0);
}
static void ql_process_chip_ae_intr(struct ql_adapter *qdev,
struct ib_ae_iocb_rsp *ib_ae_rsp)
{
switch (ib_ae_rsp->event) {
case MGMT_ERR_EVENT:
netif_err(qdev, rx_err, qdev->ndev,
"Management Processor Fatal Error.\n");
ql_queue_fw_error(qdev);
return;
case CAM_LOOKUP_ERR_EVENT:
netdev_err(qdev->ndev, "Multiple CAM hits lookup occurred.\n");
netdev_err(qdev->ndev, "This event shouldn't occur.\n");
ql_queue_asic_error(qdev);
return;
case SOFT_ECC_ERROR_EVENT:
netdev_err(qdev->ndev, "Soft ECC error detected.\n");
ql_queue_asic_error(qdev);
break;
case PCI_ERR_ANON_BUF_RD:
netdev_err(qdev->ndev, "PCI error occurred when reading "
"anonymous buffers from rx_ring %d.\n",
ib_ae_rsp->q_id);
ql_queue_asic_error(qdev);
break;
default:
netif_err(qdev, drv, qdev->ndev, "Unexpected event %d.\n",
ib_ae_rsp->event);
ql_queue_asic_error(qdev);
break;
}
}
static int ql_clean_outbound_rx_ring(struct rx_ring *rx_ring)
{
struct ql_adapter *qdev = rx_ring->qdev;
u32 prod = ql_read_sh_reg(rx_ring->prod_idx_sh_reg);
struct ob_mac_iocb_rsp *net_rsp = NULL;
int count = 0;
struct tx_ring *tx_ring;
/* While there are entries in the completion queue. */
while (prod != rx_ring->cnsmr_idx) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"cq_id = %d, prod = %d, cnsmr = %d.\n.",
rx_ring->cq_id, prod, rx_ring->cnsmr_idx);
net_rsp = (struct ob_mac_iocb_rsp *)rx_ring->curr_entry;
rmb();
switch (net_rsp->opcode) {
case OPCODE_OB_MAC_TSO_IOCB:
case OPCODE_OB_MAC_IOCB:
ql_process_mac_tx_intr(qdev, net_rsp);
break;
default:
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Hit default case, not handled! dropping the packet, opcode = %x.\n",
net_rsp->opcode);
}
count++;
ql_update_cq(rx_ring);
prod = ql_read_sh_reg(rx_ring->prod_idx_sh_reg);
}
if (!net_rsp)
return 0;
ql_write_cq_idx(rx_ring);
tx_ring = &qdev->tx_ring[net_rsp->txq_idx];
if (__netif_subqueue_stopped(qdev->ndev, tx_ring->wq_id)) {
if (atomic_read(&tx_ring->queue_stopped) &&
(atomic_read(&tx_ring->tx_count) > (tx_ring->wq_len / 4)))
/*
* The queue got stopped because the tx_ring was full.
* Wake it up, because it's now at least 25% empty.
*/
netif_wake_subqueue(qdev->ndev, tx_ring->wq_id);
}
return count;
}
static int ql_clean_inbound_rx_ring(struct rx_ring *rx_ring, int budget)
{
struct ql_adapter *qdev = rx_ring->qdev;
u32 prod = ql_read_sh_reg(rx_ring->prod_idx_sh_reg);
struct ql_net_rsp_iocb *net_rsp;
int count = 0;
/* While there are entries in the completion queue. */
while (prod != rx_ring->cnsmr_idx) {
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"cq_id = %d, prod = %d, cnsmr = %d.\n.",
rx_ring->cq_id, prod, rx_ring->cnsmr_idx);
net_rsp = rx_ring->curr_entry;
rmb();
switch (net_rsp->opcode) {
case OPCODE_IB_MAC_IOCB:
ql_process_mac_rx_intr(qdev, rx_ring,
(struct ib_mac_iocb_rsp *)
net_rsp);
break;
case OPCODE_IB_AE_IOCB:
ql_process_chip_ae_intr(qdev, (struct ib_ae_iocb_rsp *)
net_rsp);
break;
default:
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Hit default case, not handled! dropping the packet, opcode = %x.\n",
net_rsp->opcode);
break;
}
count++;
ql_update_cq(rx_ring);
prod = ql_read_sh_reg(rx_ring->prod_idx_sh_reg);
if (count == budget)
break;
}
ql_update_buffer_queues(qdev, rx_ring);
ql_write_cq_idx(rx_ring);
return count;
}
static int ql_napi_poll_msix(struct napi_struct *napi, int budget)
{
struct rx_ring *rx_ring = container_of(napi, struct rx_ring, napi);
struct ql_adapter *qdev = rx_ring->qdev;
struct rx_ring *trx_ring;
int i, work_done = 0;
struct intr_context *ctx = &qdev->intr_context[rx_ring->cq_id];
netif_printk(qdev, rx_status, KERN_DEBUG, qdev->ndev,
"Enter, NAPI POLL cq_id = %d.\n", rx_ring->cq_id);
/* Service the TX rings first. They start
* right after the RSS rings. */
for (i = qdev->rss_ring_count; i < qdev->rx_ring_count; i++) {
trx_ring = &qdev->rx_ring[i];
/* If this TX completion ring belongs to this vector and
* it's not empty then service it.
*/
if ((ctx->irq_mask & (1 << trx_ring->cq_id)) &&
(ql_read_sh_reg(trx_ring->prod_idx_sh_reg) !=
trx_ring->cnsmr_idx)) {
netif_printk(qdev, intr, KERN_DEBUG, qdev->ndev,
"%s: Servicing TX completion ring %d.\n",
__func__, trx_ring->cq_id);
ql_clean_outbound_rx_ring(trx_ring);
}
}
/*
* Now service the RSS ring if it's active.
*/
if (ql_read_sh_reg(rx_ring->prod_idx_sh_reg) !=
rx_ring->cnsmr_idx) {
netif_printk(qdev, intr, KERN_DEBUG, qdev->ndev,
"%s: Servicing RX completion ring %d.\n",
__func__, rx_ring->cq_id);
work_done = ql_clean_inbound_rx_ring(rx_ring, budget);
}
if (work_done < budget) {
napi_complete(napi);
ql_enable_completion_interrupt(qdev, rx_ring->irq);
}
return work_done;
}
static void qlge_vlan_rx_register(struct net_device *ndev, struct vlan_group *grp)
{
struct ql_adapter *qdev = netdev_priv(ndev);
qdev->vlgrp = grp;
if (grp) {
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Turning on VLAN in NIC_RCV_CFG.\n");
ql_write32(qdev, NIC_RCV_CFG, NIC_RCV_CFG_VLAN_MASK |
NIC_RCV_CFG_VLAN_MATCH_AND_NON);
} else {
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Turning off VLAN in NIC_RCV_CFG.\n");
ql_write32(qdev, NIC_RCV_CFG, NIC_RCV_CFG_VLAN_MASK);
}
}
static void qlge_vlan_rx_add_vid(struct net_device *ndev, u16 vid)
{
struct ql_adapter *qdev = netdev_priv(ndev);
u32 enable_bit = MAC_ADDR_E;
int status;
status = ql_sem_spinlock(qdev, SEM_MAC_ADDR_MASK);
if (status)
return;
if (ql_set_mac_addr_reg
(qdev, (u8 *) &enable_bit, MAC_ADDR_TYPE_VLAN, vid)) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to init vlan address.\n");
}
ql_sem_unlock(qdev, SEM_MAC_ADDR_MASK);
}
static void qlge_vlan_rx_kill_vid(struct net_device *ndev, u16 vid)
{
struct ql_adapter *qdev = netdev_priv(ndev);
u32 enable_bit = 0;
int status;
status = ql_sem_spinlock(qdev, SEM_MAC_ADDR_MASK);
if (status)
return;
if (ql_set_mac_addr_reg
(qdev, (u8 *) &enable_bit, MAC_ADDR_TYPE_VLAN, vid)) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to clear vlan address.\n");
}
ql_sem_unlock(qdev, SEM_MAC_ADDR_MASK);
}
static void qlge_restore_vlan(struct ql_adapter *qdev)
{
qlge_vlan_rx_register(qdev->ndev, qdev->vlgrp);
if (qdev->vlgrp) {
u16 vid;
for (vid = 0; vid < VLAN_N_VID; vid++) {
if (!vlan_group_get_device(qdev->vlgrp, vid))
continue;
qlge_vlan_rx_add_vid(qdev->ndev, vid);
}
}
}
/* MSI-X Multiple Vector Interrupt Handler for inbound completions. */
static irqreturn_t qlge_msix_rx_isr(int irq, void *dev_id)
{
struct rx_ring *rx_ring = dev_id;
napi_schedule(&rx_ring->napi);
return IRQ_HANDLED;
}
/* This handles a fatal error, MPI activity, and the default
* rx_ring in an MSI-X multiple vector environment.
* In MSI/Legacy environment it also process the rest of
* the rx_rings.
*/
static irqreturn_t qlge_isr(int irq, void *dev_id)
{
struct rx_ring *rx_ring = dev_id;
struct ql_adapter *qdev = rx_ring->qdev;
struct intr_context *intr_context = &qdev->intr_context[0];
u32 var;
int work_done = 0;
spin_lock(&qdev->hw_lock);
if (atomic_read(&qdev->intr_context[0].irq_cnt)) {
netif_printk(qdev, intr, KERN_DEBUG, qdev->ndev,
"Shared Interrupt, Not ours!\n");
spin_unlock(&qdev->hw_lock);
return IRQ_NONE;
}
spin_unlock(&qdev->hw_lock);
var = ql_disable_completion_interrupt(qdev, intr_context->intr);
/*
* Check for fatal error.
*/
if (var & STS_FE) {
ql_queue_asic_error(qdev);
netdev_err(qdev->ndev, "Got fatal error, STS = %x.\n", var);
var = ql_read32(qdev, ERR_STS);
netdev_err(qdev->ndev, "Resetting chip. "
"Error Status Register = 0x%x\n", var);
return IRQ_HANDLED;
}
/*
* Check MPI processor activity.
*/
if ((var & STS_PI) &&
(ql_read32(qdev, INTR_MASK) & INTR_MASK_PI)) {
/*
* We've got an async event or mailbox completion.
* Handle it and clear the source of the interrupt.
*/
netif_err(qdev, intr, qdev->ndev,
"Got MPI processor interrupt.\n");
ql_disable_completion_interrupt(qdev, intr_context->intr);
ql_write32(qdev, INTR_MASK, (INTR_MASK_PI << 16));
queue_delayed_work_on(smp_processor_id(),
qdev->workqueue, &qdev->mpi_work, 0);
work_done++;
}
/*
* Get the bit-mask that shows the active queues for this
* pass. Compare it to the queues that this irq services
* and call napi if there's a match.
*/
var = ql_read32(qdev, ISR1);
if (var & intr_context->irq_mask) {
netif_info(qdev, intr, qdev->ndev,
"Waking handler for rx_ring[0].\n");
ql_disable_completion_interrupt(qdev, intr_context->intr);
napi_schedule(&rx_ring->napi);
work_done++;
}
ql_enable_completion_interrupt(qdev, intr_context->intr);
return work_done ? IRQ_HANDLED : IRQ_NONE;
}
static int ql_tso(struct sk_buff *skb, struct ob_mac_tso_iocb_req *mac_iocb_ptr)
{
if (skb_is_gso(skb)) {
int err;
if (skb_header_cloned(skb)) {
err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (err)
return err;
}
mac_iocb_ptr->opcode = OPCODE_OB_MAC_TSO_IOCB;
mac_iocb_ptr->flags3 |= OB_MAC_TSO_IOCB_IC;
mac_iocb_ptr->frame_len = cpu_to_le32((u32) skb->len);
mac_iocb_ptr->total_hdrs_len =
cpu_to_le16(skb_transport_offset(skb) + tcp_hdrlen(skb));
mac_iocb_ptr->net_trans_offset =
cpu_to_le16(skb_network_offset(skb) |
skb_transport_offset(skb)
<< OB_MAC_TRANSPORT_HDR_SHIFT);
mac_iocb_ptr->mss = cpu_to_le16(skb_shinfo(skb)->gso_size);
mac_iocb_ptr->flags2 |= OB_MAC_TSO_IOCB_LSO;
if (likely(skb->protocol == htons(ETH_P_IP))) {
struct iphdr *iph = ip_hdr(skb);
iph->check = 0;
mac_iocb_ptr->flags1 |= OB_MAC_TSO_IOCB_IP4;
tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr,
iph->daddr, 0,
IPPROTO_TCP,
0);
} else if (skb->protocol == htons(ETH_P_IPV6)) {
mac_iocb_ptr->flags1 |= OB_MAC_TSO_IOCB_IP6;
tcp_hdr(skb)->check =
~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0);
}
return 1;
}
return 0;
}
static void ql_hw_csum_setup(struct sk_buff *skb,
struct ob_mac_tso_iocb_req *mac_iocb_ptr)
{
int len;
struct iphdr *iph = ip_hdr(skb);
__sum16 *check;
mac_iocb_ptr->opcode = OPCODE_OB_MAC_TSO_IOCB;
mac_iocb_ptr->frame_len = cpu_to_le32((u32) skb->len);
mac_iocb_ptr->net_trans_offset =
cpu_to_le16(skb_network_offset(skb) |
skb_transport_offset(skb) << OB_MAC_TRANSPORT_HDR_SHIFT);
mac_iocb_ptr->flags1 |= OB_MAC_TSO_IOCB_IP4;
len = (ntohs(iph->tot_len) - (iph->ihl << 2));
if (likely(iph->protocol == IPPROTO_TCP)) {
check = &(tcp_hdr(skb)->check);
mac_iocb_ptr->flags2 |= OB_MAC_TSO_IOCB_TC;
mac_iocb_ptr->total_hdrs_len =
cpu_to_le16(skb_transport_offset(skb) +
(tcp_hdr(skb)->doff << 2));
} else {
check = &(udp_hdr(skb)->check);
mac_iocb_ptr->flags2 |= OB_MAC_TSO_IOCB_UC;
mac_iocb_ptr->total_hdrs_len =
cpu_to_le16(skb_transport_offset(skb) +
sizeof(struct udphdr));
}
*check = ~csum_tcpudp_magic(iph->saddr,
iph->daddr, len, iph->protocol, 0);
}
static netdev_tx_t qlge_send(struct sk_buff *skb, struct net_device *ndev)
{
struct tx_ring_desc *tx_ring_desc;
struct ob_mac_iocb_req *mac_iocb_ptr;
struct ql_adapter *qdev = netdev_priv(ndev);
int tso;
struct tx_ring *tx_ring;
u32 tx_ring_idx = (u32) skb->queue_mapping;
tx_ring = &qdev->tx_ring[tx_ring_idx];
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
if (unlikely(atomic_read(&tx_ring->tx_count) < 2)) {
netif_info(qdev, tx_queued, qdev->ndev,
"%s: shutting down tx queue %d du to lack of resources.\n",
__func__, tx_ring_idx);
netif_stop_subqueue(ndev, tx_ring->wq_id);
atomic_inc(&tx_ring->queue_stopped);
tx_ring->tx_errors++;
return NETDEV_TX_BUSY;
}
tx_ring_desc = &tx_ring->q[tx_ring->prod_idx];
mac_iocb_ptr = tx_ring_desc->queue_entry;
memset((void *)mac_iocb_ptr, 0, sizeof(*mac_iocb_ptr));
mac_iocb_ptr->opcode = OPCODE_OB_MAC_IOCB;
mac_iocb_ptr->tid = tx_ring_desc->index;
/* We use the upper 32-bits to store the tx queue for this IO.
* When we get the completion we can use it to establish the context.
*/
mac_iocb_ptr->txq_idx = tx_ring_idx;
tx_ring_desc->skb = skb;
mac_iocb_ptr->frame_len = cpu_to_le16((u16) skb->len);
if (vlan_tx_tag_present(skb)) {
netif_printk(qdev, tx_queued, KERN_DEBUG, qdev->ndev,
"Adding a vlan tag %d.\n", vlan_tx_tag_get(skb));
mac_iocb_ptr->flags3 |= OB_MAC_IOCB_V;
mac_iocb_ptr->vlan_tci = cpu_to_le16(vlan_tx_tag_get(skb));
}
tso = ql_tso(skb, (struct ob_mac_tso_iocb_req *)mac_iocb_ptr);
if (tso < 0) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
} else if (unlikely(!tso) && (skb->ip_summed == CHECKSUM_PARTIAL)) {
ql_hw_csum_setup(skb,
(struct ob_mac_tso_iocb_req *)mac_iocb_ptr);
}
if (ql_map_send(qdev, mac_iocb_ptr, skb, tx_ring_desc) !=
NETDEV_TX_OK) {
netif_err(qdev, tx_queued, qdev->ndev,
"Could not map the segments.\n");
tx_ring->tx_errors++;
return NETDEV_TX_BUSY;
}
QL_DUMP_OB_MAC_IOCB(mac_iocb_ptr);
tx_ring->prod_idx++;
if (tx_ring->prod_idx == tx_ring->wq_len)
tx_ring->prod_idx = 0;
wmb();
ql_write_db_reg(tx_ring->prod_idx, tx_ring->prod_idx_db_reg);
netif_printk(qdev, tx_queued, KERN_DEBUG, qdev->ndev,
"tx queued, slot %d, len %d\n",
tx_ring->prod_idx, skb->len);
atomic_dec(&tx_ring->tx_count);
return NETDEV_TX_OK;
}
static void ql_free_shadow_space(struct ql_adapter *qdev)
{
if (qdev->rx_ring_shadow_reg_area) {
pci_free_consistent(qdev->pdev,
PAGE_SIZE,
qdev->rx_ring_shadow_reg_area,
qdev->rx_ring_shadow_reg_dma);
qdev->rx_ring_shadow_reg_area = NULL;
}
if (qdev->tx_ring_shadow_reg_area) {
pci_free_consistent(qdev->pdev,
PAGE_SIZE,
qdev->tx_ring_shadow_reg_area,
qdev->tx_ring_shadow_reg_dma);
qdev->tx_ring_shadow_reg_area = NULL;
}
}
static int ql_alloc_shadow_space(struct ql_adapter *qdev)
{
qdev->rx_ring_shadow_reg_area =
pci_alloc_consistent(qdev->pdev,
PAGE_SIZE, &qdev->rx_ring_shadow_reg_dma);
if (qdev->rx_ring_shadow_reg_area == NULL) {
netif_err(qdev, ifup, qdev->ndev,
"Allocation of RX shadow space failed.\n");
return -ENOMEM;
}
memset(qdev->rx_ring_shadow_reg_area, 0, PAGE_SIZE);
qdev->tx_ring_shadow_reg_area =
pci_alloc_consistent(qdev->pdev, PAGE_SIZE,
&qdev->tx_ring_shadow_reg_dma);
if (qdev->tx_ring_shadow_reg_area == NULL) {
netif_err(qdev, ifup, qdev->ndev,
"Allocation of TX shadow space failed.\n");
goto err_wqp_sh_area;
}
memset(qdev->tx_ring_shadow_reg_area, 0, PAGE_SIZE);
return 0;
err_wqp_sh_area:
pci_free_consistent(qdev->pdev,
PAGE_SIZE,
qdev->rx_ring_shadow_reg_area,
qdev->rx_ring_shadow_reg_dma);
return -ENOMEM;
}
static void ql_init_tx_ring(struct ql_adapter *qdev, struct tx_ring *tx_ring)
{
struct tx_ring_desc *tx_ring_desc;
int i;
struct ob_mac_iocb_req *mac_iocb_ptr;
mac_iocb_ptr = tx_ring->wq_base;
tx_ring_desc = tx_ring->q;
for (i = 0; i < tx_ring->wq_len; i++) {
tx_ring_desc->index = i;
tx_ring_desc->skb = NULL;
tx_ring_desc->queue_entry = mac_iocb_ptr;
mac_iocb_ptr++;
tx_ring_desc++;
}
atomic_set(&tx_ring->tx_count, tx_ring->wq_len);
atomic_set(&tx_ring->queue_stopped, 0);
}
static void ql_free_tx_resources(struct ql_adapter *qdev,
struct tx_ring *tx_ring)
{
if (tx_ring->wq_base) {
pci_free_consistent(qdev->pdev, tx_ring->wq_size,
tx_ring->wq_base, tx_ring->wq_base_dma);
tx_ring->wq_base = NULL;
}
kfree(tx_ring->q);
tx_ring->q = NULL;
}
static int ql_alloc_tx_resources(struct ql_adapter *qdev,
struct tx_ring *tx_ring)
{
tx_ring->wq_base =
pci_alloc_consistent(qdev->pdev, tx_ring->wq_size,
&tx_ring->wq_base_dma);
if ((tx_ring->wq_base == NULL) ||
tx_ring->wq_base_dma & WQ_ADDR_ALIGN) {
netif_err(qdev, ifup, qdev->ndev, "tx_ring alloc failed.\n");
return -ENOMEM;
}
tx_ring->q =
kmalloc(tx_ring->wq_len * sizeof(struct tx_ring_desc), GFP_KERNEL);
if (tx_ring->q == NULL)
goto err;
return 0;
err:
pci_free_consistent(qdev->pdev, tx_ring->wq_size,
tx_ring->wq_base, tx_ring->wq_base_dma);
return -ENOMEM;
}
static void ql_free_lbq_buffers(struct ql_adapter *qdev, struct rx_ring *rx_ring)
{
struct bq_desc *lbq_desc;
uint32_t curr_idx, clean_idx;
curr_idx = rx_ring->lbq_curr_idx;
clean_idx = rx_ring->lbq_clean_idx;
while (curr_idx != clean_idx) {
lbq_desc = &rx_ring->lbq[curr_idx];
if (lbq_desc->p.pg_chunk.last_flag) {
pci_unmap_page(qdev->pdev,
lbq_desc->p.pg_chunk.map,
ql_lbq_block_size(qdev),
PCI_DMA_FROMDEVICE);
lbq_desc->p.pg_chunk.last_flag = 0;
}
put_page(lbq_desc->p.pg_chunk.page);
lbq_desc->p.pg_chunk.page = NULL;
if (++curr_idx == rx_ring->lbq_len)
curr_idx = 0;
}
}
static void ql_free_sbq_buffers(struct ql_adapter *qdev, struct rx_ring *rx_ring)
{
int i;
struct bq_desc *sbq_desc;
for (i = 0; i < rx_ring->sbq_len; i++) {
sbq_desc = &rx_ring->sbq[i];
if (sbq_desc == NULL) {
netif_err(qdev, ifup, qdev->ndev,
"sbq_desc %d is NULL.\n", i);
return;
}
if (sbq_desc->p.skb) {
pci_unmap_single(qdev->pdev,
dma_unmap_addr(sbq_desc, mapaddr),
dma_unmap_len(sbq_desc, maplen),
PCI_DMA_FROMDEVICE);
dev_kfree_skb(sbq_desc->p.skb);
sbq_desc->p.skb = NULL;
}
}
}
/* Free all large and small rx buffers associated
* with the completion queues for this device.
*/
static void ql_free_rx_buffers(struct ql_adapter *qdev)
{
int i;
struct rx_ring *rx_ring;
for (i = 0; i < qdev->rx_ring_count; i++) {
rx_ring = &qdev->rx_ring[i];
if (rx_ring->lbq)
ql_free_lbq_buffers(qdev, rx_ring);
if (rx_ring->sbq)
ql_free_sbq_buffers(qdev, rx_ring);
}
}
static void ql_alloc_rx_buffers(struct ql_adapter *qdev)
{
struct rx_ring *rx_ring;
int i;
for (i = 0; i < qdev->rx_ring_count; i++) {
rx_ring = &qdev->rx_ring[i];
if (rx_ring->type != TX_Q)
ql_update_buffer_queues(qdev, rx_ring);
}
}
static void ql_init_lbq_ring(struct ql_adapter *qdev,
struct rx_ring *rx_ring)
{
int i;
struct bq_desc *lbq_desc;
__le64 *bq = rx_ring->lbq_base;
memset(rx_ring->lbq, 0, rx_ring->lbq_len * sizeof(struct bq_desc));
for (i = 0; i < rx_ring->lbq_len; i++) {
lbq_desc = &rx_ring->lbq[i];
memset(lbq_desc, 0, sizeof(*lbq_desc));
lbq_desc->index = i;
lbq_desc->addr = bq;
bq++;
}
}
static void ql_init_sbq_ring(struct ql_adapter *qdev,
struct rx_ring *rx_ring)
{
int i;
struct bq_desc *sbq_desc;
__le64 *bq = rx_ring->sbq_base;
memset(rx_ring->sbq, 0, rx_ring->sbq_len * sizeof(struct bq_desc));
for (i = 0; i < rx_ring->sbq_len; i++) {
sbq_desc = &rx_ring->sbq[i];
memset(sbq_desc, 0, sizeof(*sbq_desc));
sbq_desc->index = i;
sbq_desc->addr = bq;
bq++;
}
}
static void ql_free_rx_resources(struct ql_adapter *qdev,
struct rx_ring *rx_ring)
{
/* Free the small buffer queue. */
if (rx_ring->sbq_base) {
pci_free_consistent(qdev->pdev,
rx_ring->sbq_size,
rx_ring->sbq_base, rx_ring->sbq_base_dma);
rx_ring->sbq_base = NULL;
}
/* Free the small buffer queue control blocks. */
kfree(rx_ring->sbq);
rx_ring->sbq = NULL;
/* Free the large buffer queue. */
if (rx_ring->lbq_base) {
pci_free_consistent(qdev->pdev,
rx_ring->lbq_size,
rx_ring->lbq_base, rx_ring->lbq_base_dma);
rx_ring->lbq_base = NULL;
}
/* Free the large buffer queue control blocks. */
kfree(rx_ring->lbq);
rx_ring->lbq = NULL;
/* Free the rx queue. */
if (rx_ring->cq_base) {
pci_free_consistent(qdev->pdev,
rx_ring->cq_size,
rx_ring->cq_base, rx_ring->cq_base_dma);
rx_ring->cq_base = NULL;
}
}
/* Allocate queues and buffers for this completions queue based
* on the values in the parameter structure. */
static int ql_alloc_rx_resources(struct ql_adapter *qdev,
struct rx_ring *rx_ring)
{
/*
* Allocate the completion queue for this rx_ring.
*/
rx_ring->cq_base =
pci_alloc_consistent(qdev->pdev, rx_ring->cq_size,
&rx_ring->cq_base_dma);
if (rx_ring->cq_base == NULL) {
netif_err(qdev, ifup, qdev->ndev, "rx_ring alloc failed.\n");
return -ENOMEM;
}
if (rx_ring->sbq_len) {
/*
* Allocate small buffer queue.
*/
rx_ring->sbq_base =
pci_alloc_consistent(qdev->pdev, rx_ring->sbq_size,
&rx_ring->sbq_base_dma);
if (rx_ring->sbq_base == NULL) {
netif_err(qdev, ifup, qdev->ndev,
"Small buffer queue allocation failed.\n");
goto err_mem;
}
/*
* Allocate small buffer queue control blocks.
*/
rx_ring->sbq =
kmalloc(rx_ring->sbq_len * sizeof(struct bq_desc),
GFP_KERNEL);
if (rx_ring->sbq == NULL) {
netif_err(qdev, ifup, qdev->ndev,
"Small buffer queue control block allocation failed.\n");
goto err_mem;
}
ql_init_sbq_ring(qdev, rx_ring);
}
if (rx_ring->lbq_len) {
/*
* Allocate large buffer queue.
*/
rx_ring->lbq_base =
pci_alloc_consistent(qdev->pdev, rx_ring->lbq_size,
&rx_ring->lbq_base_dma);
if (rx_ring->lbq_base == NULL) {
netif_err(qdev, ifup, qdev->ndev,
"Large buffer queue allocation failed.\n");
goto err_mem;
}
/*
* Allocate large buffer queue control blocks.
*/
rx_ring->lbq =
kmalloc(rx_ring->lbq_len * sizeof(struct bq_desc),
GFP_KERNEL);
if (rx_ring->lbq == NULL) {
netif_err(qdev, ifup, qdev->ndev,
"Large buffer queue control block allocation failed.\n");
goto err_mem;
}
ql_init_lbq_ring(qdev, rx_ring);
}
return 0;
err_mem:
ql_free_rx_resources(qdev, rx_ring);
return -ENOMEM;
}
static void ql_tx_ring_clean(struct ql_adapter *qdev)
{
struct tx_ring *tx_ring;
struct tx_ring_desc *tx_ring_desc;
int i, j;
/*
* Loop through all queues and free
* any resources.
*/
for (j = 0; j < qdev->tx_ring_count; j++) {
tx_ring = &qdev->tx_ring[j];
for (i = 0; i < tx_ring->wq_len; i++) {
tx_ring_desc = &tx_ring->q[i];
if (tx_ring_desc && tx_ring_desc->skb) {
netif_err(qdev, ifdown, qdev->ndev,
"Freeing lost SKB %p, from queue %d, index %d.\n",
tx_ring_desc->skb, j,
tx_ring_desc->index);
ql_unmap_send(qdev, tx_ring_desc,
tx_ring_desc->map_cnt);
dev_kfree_skb(tx_ring_desc->skb);
tx_ring_desc->skb = NULL;
}
}
}
}
static void ql_free_mem_resources(struct ql_adapter *qdev)
{
int i;
for (i = 0; i < qdev->tx_ring_count; i++)
ql_free_tx_resources(qdev, &qdev->tx_ring[i]);
for (i = 0; i < qdev->rx_ring_count; i++)
ql_free_rx_resources(qdev, &qdev->rx_ring[i]);
ql_free_shadow_space(qdev);
}
static int ql_alloc_mem_resources(struct ql_adapter *qdev)
{
int i;
/* Allocate space for our shadow registers and such. */
if (ql_alloc_shadow_space(qdev))
return -ENOMEM;
for (i = 0; i < qdev->rx_ring_count; i++) {
if (ql_alloc_rx_resources(qdev, &qdev->rx_ring[i]) != 0) {
netif_err(qdev, ifup, qdev->ndev,
"RX resource allocation failed.\n");
goto err_mem;
}
}
/* Allocate tx queue resources */
for (i = 0; i < qdev->tx_ring_count; i++) {
if (ql_alloc_tx_resources(qdev, &qdev->tx_ring[i]) != 0) {
netif_err(qdev, ifup, qdev->ndev,
"TX resource allocation failed.\n");
goto err_mem;
}
}
return 0;
err_mem:
ql_free_mem_resources(qdev);
return -ENOMEM;
}
/* Set up the rx ring control block and pass it to the chip.
* The control block is defined as
* "Completion Queue Initialization Control Block", or cqicb.
*/
static int ql_start_rx_ring(struct ql_adapter *qdev, struct rx_ring *rx_ring)
{
struct cqicb *cqicb = &rx_ring->cqicb;
void *shadow_reg = qdev->rx_ring_shadow_reg_area +
(rx_ring->cq_id * RX_RING_SHADOW_SPACE);
u64 shadow_reg_dma = qdev->rx_ring_shadow_reg_dma +
(rx_ring->cq_id * RX_RING_SHADOW_SPACE);
void __iomem *doorbell_area =
qdev->doorbell_area + (DB_PAGE_SIZE * (128 + rx_ring->cq_id));
int err = 0;
u16 bq_len;
u64 tmp;
__le64 *base_indirect_ptr;
int page_entries;
/* Set up the shadow registers for this ring. */
rx_ring->prod_idx_sh_reg = shadow_reg;
rx_ring->prod_idx_sh_reg_dma = shadow_reg_dma;
*rx_ring->prod_idx_sh_reg = 0;
shadow_reg += sizeof(u64);
shadow_reg_dma += sizeof(u64);
rx_ring->lbq_base_indirect = shadow_reg;
rx_ring->lbq_base_indirect_dma = shadow_reg_dma;
shadow_reg += (sizeof(u64) * MAX_DB_PAGES_PER_BQ(rx_ring->lbq_len));
shadow_reg_dma += (sizeof(u64) * MAX_DB_PAGES_PER_BQ(rx_ring->lbq_len));
rx_ring->sbq_base_indirect = shadow_reg;
rx_ring->sbq_base_indirect_dma = shadow_reg_dma;
/* PCI doorbell mem area + 0x00 for consumer index register */
rx_ring->cnsmr_idx_db_reg = (u32 __iomem *) doorbell_area;
rx_ring->cnsmr_idx = 0;
rx_ring->curr_entry = rx_ring->cq_base;
/* PCI doorbell mem area + 0x04 for valid register */
rx_ring->valid_db_reg = doorbell_area + 0x04;
/* PCI doorbell mem area + 0x18 for large buffer consumer */
rx_ring->lbq_prod_idx_db_reg = (u32 __iomem *) (doorbell_area + 0x18);
/* PCI doorbell mem area + 0x1c */
rx_ring->sbq_prod_idx_db_reg = (u32 __iomem *) (doorbell_area + 0x1c);
memset((void *)cqicb, 0, sizeof(struct cqicb));
cqicb->msix_vect = rx_ring->irq;
bq_len = (rx_ring->cq_len == 65536) ? 0 : (u16) rx_ring->cq_len;
cqicb->len = cpu_to_le16(bq_len | LEN_V | LEN_CPP_CONT);
cqicb->addr = cpu_to_le64(rx_ring->cq_base_dma);
cqicb->prod_idx_addr = cpu_to_le64(rx_ring->prod_idx_sh_reg_dma);
/*
* Set up the control block load flags.
*/
cqicb->flags = FLAGS_LC | /* Load queue base address */
FLAGS_LV | /* Load MSI-X vector */
FLAGS_LI; /* Load irq delay values */
if (rx_ring->lbq_len) {
cqicb->flags |= FLAGS_LL; /* Load lbq values */
tmp = (u64)rx_ring->lbq_base_dma;
base_indirect_ptr = (__le64 *) rx_ring->lbq_base_indirect;
page_entries = 0;
do {
*base_indirect_ptr = cpu_to_le64(tmp);
tmp += DB_PAGE_SIZE;
base_indirect_ptr++;
page_entries++;
} while (page_entries < MAX_DB_PAGES_PER_BQ(rx_ring->lbq_len));
cqicb->lbq_addr =
cpu_to_le64(rx_ring->lbq_base_indirect_dma);
bq_len = (rx_ring->lbq_buf_size == 65536) ? 0 :
(u16) rx_ring->lbq_buf_size;
cqicb->lbq_buf_size = cpu_to_le16(bq_len);
bq_len = (rx_ring->lbq_len == 65536) ? 0 :
(u16) rx_ring->lbq_len;
cqicb->lbq_len = cpu_to_le16(bq_len);
rx_ring->lbq_prod_idx = 0;
rx_ring->lbq_curr_idx = 0;
rx_ring->lbq_clean_idx = 0;
rx_ring->lbq_free_cnt = rx_ring->lbq_len;
}
if (rx_ring->sbq_len) {
cqicb->flags |= FLAGS_LS; /* Load sbq values */
tmp = (u64)rx_ring->sbq_base_dma;
base_indirect_ptr = (__le64 *) rx_ring->sbq_base_indirect;
page_entries = 0;
do {
*base_indirect_ptr = cpu_to_le64(tmp);
tmp += DB_PAGE_SIZE;
base_indirect_ptr++;
page_entries++;
} while (page_entries < MAX_DB_PAGES_PER_BQ(rx_ring->sbq_len));
cqicb->sbq_addr =
cpu_to_le64(rx_ring->sbq_base_indirect_dma);
cqicb->sbq_buf_size =
cpu_to_le16((u16)(rx_ring->sbq_buf_size));
bq_len = (rx_ring->sbq_len == 65536) ? 0 :
(u16) rx_ring->sbq_len;
cqicb->sbq_len = cpu_to_le16(bq_len);
rx_ring->sbq_prod_idx = 0;
rx_ring->sbq_curr_idx = 0;
rx_ring->sbq_clean_idx = 0;
rx_ring->sbq_free_cnt = rx_ring->sbq_len;
}
switch (rx_ring->type) {
case TX_Q:
cqicb->irq_delay = cpu_to_le16(qdev->tx_coalesce_usecs);
cqicb->pkt_delay = cpu_to_le16(qdev->tx_max_coalesced_frames);
break;
case RX_Q:
/* Inbound completion handling rx_rings run in
* separate NAPI contexts.
*/
netif_napi_add(qdev->ndev, &rx_ring->napi, ql_napi_poll_msix,
64);
cqicb->irq_delay = cpu_to_le16(qdev->rx_coalesce_usecs);
cqicb->pkt_delay = cpu_to_le16(qdev->rx_max_coalesced_frames);
break;
default:
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Invalid rx_ring->type = %d.\n", rx_ring->type);
}
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Initializing rx work queue.\n");
err = ql_write_cfg(qdev, cqicb, sizeof(struct cqicb),
CFG_LCQ, rx_ring->cq_id);
if (err) {
netif_err(qdev, ifup, qdev->ndev, "Failed to load CQICB.\n");
return err;
}
return err;
}
static int ql_start_tx_ring(struct ql_adapter *qdev, struct tx_ring *tx_ring)
{
struct wqicb *wqicb = (struct wqicb *)tx_ring;
void __iomem *doorbell_area =
qdev->doorbell_area + (DB_PAGE_SIZE * tx_ring->wq_id);
void *shadow_reg = qdev->tx_ring_shadow_reg_area +
(tx_ring->wq_id * sizeof(u64));
u64 shadow_reg_dma = qdev->tx_ring_shadow_reg_dma +
(tx_ring->wq_id * sizeof(u64));
int err = 0;
/*
* Assign doorbell registers for this tx_ring.
*/
/* TX PCI doorbell mem area for tx producer index */
tx_ring->prod_idx_db_reg = (u32 __iomem *) doorbell_area;
tx_ring->prod_idx = 0;
/* TX PCI doorbell mem area + 0x04 */
tx_ring->valid_db_reg = doorbell_area + 0x04;
/*
* Assign shadow registers for this tx_ring.
*/
tx_ring->cnsmr_idx_sh_reg = shadow_reg;
tx_ring->cnsmr_idx_sh_reg_dma = shadow_reg_dma;
wqicb->len = cpu_to_le16(tx_ring->wq_len | Q_LEN_V | Q_LEN_CPP_CONT);
wqicb->flags = cpu_to_le16(Q_FLAGS_LC |
Q_FLAGS_LB | Q_FLAGS_LI | Q_FLAGS_LO);
wqicb->cq_id_rss = cpu_to_le16(tx_ring->cq_id);
wqicb->rid = 0;
wqicb->addr = cpu_to_le64(tx_ring->wq_base_dma);
wqicb->cnsmr_idx_addr = cpu_to_le64(tx_ring->cnsmr_idx_sh_reg_dma);
ql_init_tx_ring(qdev, tx_ring);
err = ql_write_cfg(qdev, wqicb, sizeof(*wqicb), CFG_LRQ,
(u16) tx_ring->wq_id);
if (err) {
netif_err(qdev, ifup, qdev->ndev, "Failed to load tx_ring.\n");
return err;
}
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Successfully loaded WQICB.\n");
return err;
}
static void ql_disable_msix(struct ql_adapter *qdev)
{
if (test_bit(QL_MSIX_ENABLED, &qdev->flags)) {
pci_disable_msix(qdev->pdev);
clear_bit(QL_MSIX_ENABLED, &qdev->flags);
kfree(qdev->msi_x_entry);
qdev->msi_x_entry = NULL;
} else if (test_bit(QL_MSI_ENABLED, &qdev->flags)) {
pci_disable_msi(qdev->pdev);
clear_bit(QL_MSI_ENABLED, &qdev->flags);
}
}
/* We start by trying to get the number of vectors
* stored in qdev->intr_count. If we don't get that
* many then we reduce the count and try again.
*/
static void ql_enable_msix(struct ql_adapter *qdev)
{
int i, err;
/* Get the MSIX vectors. */
if (qlge_irq_type == MSIX_IRQ) {
/* Try to alloc space for the msix struct,
* if it fails then go to MSI/legacy.
*/
qdev->msi_x_entry = kcalloc(qdev->intr_count,
sizeof(struct msix_entry),
GFP_KERNEL);
if (!qdev->msi_x_entry) {
qlge_irq_type = MSI_IRQ;
goto msi;
}
for (i = 0; i < qdev->intr_count; i++)
qdev->msi_x_entry[i].entry = i;
/* Loop to get our vectors. We start with
* what we want and settle for what we get.
*/
do {
err = pci_enable_msix(qdev->pdev,
qdev->msi_x_entry, qdev->intr_count);
if (err > 0)
qdev->intr_count = err;
} while (err > 0);
if (err < 0) {
kfree(qdev->msi_x_entry);
qdev->msi_x_entry = NULL;
netif_warn(qdev, ifup, qdev->ndev,
"MSI-X Enable failed, trying MSI.\n");
qdev->intr_count = 1;
qlge_irq_type = MSI_IRQ;
} else if (err == 0) {
set_bit(QL_MSIX_ENABLED, &qdev->flags);
netif_info(qdev, ifup, qdev->ndev,
"MSI-X Enabled, got %d vectors.\n",
qdev->intr_count);
return;
}
}
msi:
qdev->intr_count = 1;
if (qlge_irq_type == MSI_IRQ) {
if (!pci_enable_msi(qdev->pdev)) {
set_bit(QL_MSI_ENABLED, &qdev->flags);
netif_info(qdev, ifup, qdev->ndev,
"Running with MSI interrupts.\n");
return;
}
}
qlge_irq_type = LEG_IRQ;
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Running with legacy interrupts.\n");
}
/* Each vector services 1 RSS ring and and 1 or more
* TX completion rings. This function loops through
* the TX completion rings and assigns the vector that
* will service it. An example would be if there are
* 2 vectors (so 2 RSS rings) and 8 TX completion rings.
* This would mean that vector 0 would service RSS ring 0
* and TX completion rings 0,1,2 and 3. Vector 1 would
* service RSS ring 1 and TX completion rings 4,5,6 and 7.
*/
static void ql_set_tx_vect(struct ql_adapter *qdev)
{
int i, j, vect;
u32 tx_rings_per_vector = qdev->tx_ring_count / qdev->intr_count;
if (likely(test_bit(QL_MSIX_ENABLED, &qdev->flags))) {
/* Assign irq vectors to TX rx_rings.*/
for (vect = 0, j = 0, i = qdev->rss_ring_count;
i < qdev->rx_ring_count; i++) {
if (j == tx_rings_per_vector) {
vect++;
j = 0;
}
qdev->rx_ring[i].irq = vect;
j++;
}
} else {
/* For single vector all rings have an irq
* of zero.
*/
for (i = 0; i < qdev->rx_ring_count; i++)
qdev->rx_ring[i].irq = 0;
}
}
/* Set the interrupt mask for this vector. Each vector
* will service 1 RSS ring and 1 or more TX completion
* rings. This function sets up a bit mask per vector
* that indicates which rings it services.
*/
static void ql_set_irq_mask(struct ql_adapter *qdev, struct intr_context *ctx)
{
int j, vect = ctx->intr;
u32 tx_rings_per_vector = qdev->tx_ring_count / qdev->intr_count;
if (likely(test_bit(QL_MSIX_ENABLED, &qdev->flags))) {
/* Add the RSS ring serviced by this vector
* to the mask.
*/
ctx->irq_mask = (1 << qdev->rx_ring[vect].cq_id);
/* Add the TX ring(s) serviced by this vector
* to the mask. */
for (j = 0; j < tx_rings_per_vector; j++) {
ctx->irq_mask |=
(1 << qdev->rx_ring[qdev->rss_ring_count +
(vect * tx_rings_per_vector) + j].cq_id);
}
} else {
/* For single vector we just shift each queue's
* ID into the mask.
*/
for (j = 0; j < qdev->rx_ring_count; j++)
ctx->irq_mask |= (1 << qdev->rx_ring[j].cq_id);
}
}
/*
* Here we build the intr_context structures based on
* our rx_ring count and intr vector count.
* The intr_context structure is used to hook each vector
* to possibly different handlers.
*/
static void ql_resolve_queues_to_irqs(struct ql_adapter *qdev)
{
int i = 0;
struct intr_context *intr_context = &qdev->intr_context[0];
if (likely(test_bit(QL_MSIX_ENABLED, &qdev->flags))) {
/* Each rx_ring has it's
* own intr_context since we have separate
* vectors for each queue.
*/
for (i = 0; i < qdev->intr_count; i++, intr_context++) {
qdev->rx_ring[i].irq = i;
intr_context->intr = i;
intr_context->qdev = qdev;
/* Set up this vector's bit-mask that indicates
* which queues it services.
*/
ql_set_irq_mask(qdev, intr_context);
/*
* We set up each vectors enable/disable/read bits so
* there's no bit/mask calculations in the critical path.
*/
intr_context->intr_en_mask =
INTR_EN_TYPE_MASK | INTR_EN_INTR_MASK |
INTR_EN_TYPE_ENABLE | INTR_EN_IHD_MASK | INTR_EN_IHD
| i;
intr_context->intr_dis_mask =
INTR_EN_TYPE_MASK | INTR_EN_INTR_MASK |
INTR_EN_TYPE_DISABLE | INTR_EN_IHD_MASK |
INTR_EN_IHD | i;
intr_context->intr_read_mask =
INTR_EN_TYPE_MASK | INTR_EN_INTR_MASK |
INTR_EN_TYPE_READ | INTR_EN_IHD_MASK | INTR_EN_IHD |
i;
if (i == 0) {
/* The first vector/queue handles
* broadcast/multicast, fatal errors,
* and firmware events. This in addition
* to normal inbound NAPI processing.
*/
intr_context->handler = qlge_isr;
sprintf(intr_context->name, "%s-rx-%d",
qdev->ndev->name, i);
} else {
/*
* Inbound queues handle unicast frames only.
*/
intr_context->handler = qlge_msix_rx_isr;
sprintf(intr_context->name, "%s-rx-%d",
qdev->ndev->name, i);
}
}
} else {
/*
* All rx_rings use the same intr_context since
* there is only one vector.
*/
intr_context->intr = 0;
intr_context->qdev = qdev;
/*
* We set up each vectors enable/disable/read bits so
* there's no bit/mask calculations in the critical path.
*/
intr_context->intr_en_mask =
INTR_EN_TYPE_MASK | INTR_EN_INTR_MASK | INTR_EN_TYPE_ENABLE;
intr_context->intr_dis_mask =
INTR_EN_TYPE_MASK | INTR_EN_INTR_MASK |
INTR_EN_TYPE_DISABLE;
intr_context->intr_read_mask =
INTR_EN_TYPE_MASK | INTR_EN_INTR_MASK | INTR_EN_TYPE_READ;
/*
* Single interrupt means one handler for all rings.
*/
intr_context->handler = qlge_isr;
sprintf(intr_context->name, "%s-single_irq", qdev->ndev->name);
/* Set up this vector's bit-mask that indicates
* which queues it services. In this case there is
* a single vector so it will service all RSS and
* TX completion rings.
*/
ql_set_irq_mask(qdev, intr_context);
}
/* Tell the TX completion rings which MSIx vector
* they will be using.
*/
ql_set_tx_vect(qdev);
}
static void ql_free_irq(struct ql_adapter *qdev)
{
int i;
struct intr_context *intr_context = &qdev->intr_context[0];
for (i = 0; i < qdev->intr_count; i++, intr_context++) {
if (intr_context->hooked) {
if (test_bit(QL_MSIX_ENABLED, &qdev->flags)) {
free_irq(qdev->msi_x_entry[i].vector,
&qdev->rx_ring[i]);
netif_printk(qdev, ifdown, KERN_DEBUG, qdev->ndev,
"freeing msix interrupt %d.\n", i);
} else {
free_irq(qdev->pdev->irq, &qdev->rx_ring[0]);
netif_printk(qdev, ifdown, KERN_DEBUG, qdev->ndev,
"freeing msi interrupt %d.\n", i);
}
}
}
ql_disable_msix(qdev);
}
static int ql_request_irq(struct ql_adapter *qdev)
{
int i;
int status = 0;
struct pci_dev *pdev = qdev->pdev;
struct intr_context *intr_context = &qdev->intr_context[0];
ql_resolve_queues_to_irqs(qdev);
for (i = 0; i < qdev->intr_count; i++, intr_context++) {
atomic_set(&intr_context->irq_cnt, 0);
if (test_bit(QL_MSIX_ENABLED, &qdev->flags)) {
status = request_irq(qdev->msi_x_entry[i].vector,
intr_context->handler,
0,
intr_context->name,
&qdev->rx_ring[i]);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Failed request for MSIX interrupt %d.\n",
i);
goto err_irq;
} else {
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Hooked intr %d, queue type %s, with name %s.\n",
i,
qdev->rx_ring[i].type == DEFAULT_Q ?
"DEFAULT_Q" :
qdev->rx_ring[i].type == TX_Q ?
"TX_Q" :
qdev->rx_ring[i].type == RX_Q ?
"RX_Q" : "",
intr_context->name);
}
} else {
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"trying msi or legacy interrupts.\n");
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"%s: irq = %d.\n", __func__, pdev->irq);
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"%s: context->name = %s.\n", __func__,
intr_context->name);
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"%s: dev_id = 0x%p.\n", __func__,
&qdev->rx_ring[0]);
status =
request_irq(pdev->irq, qlge_isr,
test_bit(QL_MSI_ENABLED,
&qdev->
flags) ? 0 : IRQF_SHARED,
intr_context->name, &qdev->rx_ring[0]);
if (status)
goto err_irq;
netif_err(qdev, ifup, qdev->ndev,
"Hooked intr %d, queue type %s, with name %s.\n",
i,
qdev->rx_ring[0].type == DEFAULT_Q ?
"DEFAULT_Q" :
qdev->rx_ring[0].type == TX_Q ? "TX_Q" :
qdev->rx_ring[0].type == RX_Q ? "RX_Q" : "",
intr_context->name);
}
intr_context->hooked = 1;
}
return status;
err_irq:
netif_err(qdev, ifup, qdev->ndev, "Failed to get the interrupts!!!/n");
ql_free_irq(qdev);
return status;
}
static int ql_start_rss(struct ql_adapter *qdev)
{
static const u8 init_hash_seed[] = {
0x6d, 0x5a, 0x56, 0xda, 0x25, 0x5b, 0x0e, 0xc2,
0x41, 0x67, 0x25, 0x3d, 0x43, 0xa3, 0x8f, 0xb0,
0xd0, 0xca, 0x2b, 0xcb, 0xae, 0x7b, 0x30, 0xb4,
0x77, 0xcb, 0x2d, 0xa3, 0x80, 0x30, 0xf2, 0x0c,
0x6a, 0x42, 0xb7, 0x3b, 0xbe, 0xac, 0x01, 0xfa
};
struct ricb *ricb = &qdev->ricb;
int status = 0;
int i;
u8 *hash_id = (u8 *) ricb->hash_cq_id;
memset((void *)ricb, 0, sizeof(*ricb));
ricb->base_cq = RSS_L4K;
ricb->flags =
(RSS_L6K | RSS_LI | RSS_LB | RSS_LM | RSS_RT4 | RSS_RT6);
ricb->mask = cpu_to_le16((u16)(0x3ff));
/*
* Fill out the Indirection Table.
*/
for (i = 0; i < 1024; i++)
hash_id[i] = (i & (qdev->rss_ring_count - 1));
memcpy((void *)&ricb->ipv6_hash_key[0], init_hash_seed, 40);
memcpy((void *)&ricb->ipv4_hash_key[0], init_hash_seed, 16);
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev, "Initializing RSS.\n");
status = ql_write_cfg(qdev, ricb, sizeof(*ricb), CFG_LR, 0);
if (status) {
netif_err(qdev, ifup, qdev->ndev, "Failed to load RICB.\n");
return status;
}
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Successfully loaded RICB.\n");
return status;
}
static int ql_clear_routing_entries(struct ql_adapter *qdev)
{
int i, status = 0;
status = ql_sem_spinlock(qdev, SEM_RT_IDX_MASK);
if (status)
return status;
/* Clear all the entries in the routing table. */
for (i = 0; i < 16; i++) {
status = ql_set_routing_reg(qdev, i, 0, 0);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to init routing register for CAM packets.\n");
break;
}
}
ql_sem_unlock(qdev, SEM_RT_IDX_MASK);
return status;
}
/* Initialize the frame-to-queue routing. */
static int ql_route_initialize(struct ql_adapter *qdev)
{
int status = 0;
/* Clear all the entries in the routing table. */
status = ql_clear_routing_entries(qdev);
if (status)
return status;
status = ql_sem_spinlock(qdev, SEM_RT_IDX_MASK);
if (status)
return status;
status = ql_set_routing_reg(qdev, RT_IDX_IP_CSUM_ERR_SLOT,
RT_IDX_IP_CSUM_ERR, 1);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to init routing register "
"for IP CSUM error packets.\n");
goto exit;
}
status = ql_set_routing_reg(qdev, RT_IDX_TCP_UDP_CSUM_ERR_SLOT,
RT_IDX_TU_CSUM_ERR, 1);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to init routing register "
"for TCP/UDP CSUM error packets.\n");
goto exit;
}
status = ql_set_routing_reg(qdev, RT_IDX_BCAST_SLOT, RT_IDX_BCAST, 1);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to init routing register for broadcast packets.\n");
goto exit;
}
/* If we have more than one inbound queue, then turn on RSS in the
* routing block.
*/
if (qdev->rss_ring_count > 1) {
status = ql_set_routing_reg(qdev, RT_IDX_RSS_MATCH_SLOT,
RT_IDX_RSS_MATCH, 1);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to init routing register for MATCH RSS packets.\n");
goto exit;
}
}
status = ql_set_routing_reg(qdev, RT_IDX_CAM_HIT_SLOT,
RT_IDX_CAM_HIT, 1);
if (status)
netif_err(qdev, ifup, qdev->ndev,
"Failed to init routing register for CAM packets.\n");
exit:
ql_sem_unlock(qdev, SEM_RT_IDX_MASK);
return status;
}
int ql_cam_route_initialize(struct ql_adapter *qdev)
{
int status, set;
/* If check if the link is up and use to
* determine if we are setting or clearing
* the MAC address in the CAM.
*/
set = ql_read32(qdev, STS);
set &= qdev->port_link_up;
status = ql_set_mac_addr(qdev, set);
if (status) {
netif_err(qdev, ifup, qdev->ndev, "Failed to init mac address.\n");
return status;
}
status = ql_route_initialize(qdev);
if (status)
netif_err(qdev, ifup, qdev->ndev, "Failed to init routing table.\n");
return status;
}
static int ql_adapter_initialize(struct ql_adapter *qdev)
{
u32 value, mask;
int i;
int status = 0;
/*
* Set up the System register to halt on errors.
*/
value = SYS_EFE | SYS_FAE;
mask = value << 16;
ql_write32(qdev, SYS, mask | value);
/* Set the default queue, and VLAN behavior. */
value = NIC_RCV_CFG_DFQ | NIC_RCV_CFG_RV;
mask = NIC_RCV_CFG_DFQ_MASK | (NIC_RCV_CFG_RV << 16);
ql_write32(qdev, NIC_RCV_CFG, (mask | value));
/* Set the MPI interrupt to enabled. */
ql_write32(qdev, INTR_MASK, (INTR_MASK_PI << 16) | INTR_MASK_PI);
/* Enable the function, set pagesize, enable error checking. */
value = FSC_FE | FSC_EPC_INBOUND | FSC_EPC_OUTBOUND |
FSC_EC | FSC_VM_PAGE_4K;
value |= SPLT_SETTING;
/* Set/clear header splitting. */
mask = FSC_VM_PAGESIZE_MASK |
FSC_DBL_MASK | FSC_DBRST_MASK | (value << 16);
ql_write32(qdev, FSC, mask | value);
ql_write32(qdev, SPLT_HDR, SPLT_LEN);
/* Set RX packet routing to use port/pci function on which the
* packet arrived on in addition to usual frame routing.
* This is helpful on bonding where both interfaces can have
* the same MAC address.
*/
ql_write32(qdev, RST_FO, RST_FO_RR_MASK | RST_FO_RR_RCV_FUNC_CQ);
/* Reroute all packets to our Interface.
* They may have been routed to MPI firmware
* due to WOL.
*/
value = ql_read32(qdev, MGMT_RCV_CFG);
value &= ~MGMT_RCV_CFG_RM;
mask = 0xffff0000;
/* Sticky reg needs clearing due to WOL. */
ql_write32(qdev, MGMT_RCV_CFG, mask);
ql_write32(qdev, MGMT_RCV_CFG, mask | value);
/* Default WOL is enable on Mezz cards */
if (qdev->pdev->subsystem_device == 0x0068 ||
qdev->pdev->subsystem_device == 0x0180)
qdev->wol = WAKE_MAGIC;
/* Start up the rx queues. */
for (i = 0; i < qdev->rx_ring_count; i++) {
status = ql_start_rx_ring(qdev, &qdev->rx_ring[i]);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to start rx ring[%d].\n", i);
return status;
}
}
/* If there is more than one inbound completion queue
* then download a RICB to configure RSS.
*/
if (qdev->rss_ring_count > 1) {
status = ql_start_rss(qdev);
if (status) {
netif_err(qdev, ifup, qdev->ndev, "Failed to start RSS.\n");
return status;
}
}
/* Start up the tx queues. */
for (i = 0; i < qdev->tx_ring_count; i++) {
status = ql_start_tx_ring(qdev, &qdev->tx_ring[i]);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to start tx ring[%d].\n", i);
return status;
}
}
/* Initialize the port and set the max framesize. */
status = qdev->nic_ops->port_initialize(qdev);
if (status)
netif_err(qdev, ifup, qdev->ndev, "Failed to start port.\n");
/* Set up the MAC address and frame routing filter. */
status = ql_cam_route_initialize(qdev);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Failed to init CAM/Routing tables.\n");
return status;
}
/* Start NAPI for the RSS queues. */
for (i = 0; i < qdev->rss_ring_count; i++) {
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"Enabling NAPI for rx_ring[%d].\n", i);
napi_enable(&qdev->rx_ring[i].napi);
}
return status;
}
/* Issue soft reset to chip. */
static int ql_adapter_reset(struct ql_adapter *qdev)
{
u32 value;
int status = 0;
unsigned long end_jiffies;
/* Clear all the entries in the routing table. */
status = ql_clear_routing_entries(qdev);
if (status) {
netif_err(qdev, ifup, qdev->ndev, "Failed to clear routing bits.\n");
return status;
}
end_jiffies = jiffies +
max((unsigned long)1, usecs_to_jiffies(30));
/* Check if bit is set then skip the mailbox command and
* clear the bit, else we are in normal reset process.
*/
if (!test_bit(QL_ASIC_RECOVERY, &qdev->flags)) {
/* Stop management traffic. */
ql_mb_set_mgmnt_traffic_ctl(qdev, MB_SET_MPI_TFK_STOP);
/* Wait for the NIC and MGMNT FIFOs to empty. */
ql_wait_fifo_empty(qdev);
} else
clear_bit(QL_ASIC_RECOVERY, &qdev->flags);
ql_write32(qdev, RST_FO, (RST_FO_FR << 16) | RST_FO_FR);
do {
value = ql_read32(qdev, RST_FO);
if ((value & RST_FO_FR) == 0)
break;
cpu_relax();
} while (time_before(jiffies, end_jiffies));
if (value & RST_FO_FR) {
netif_err(qdev, ifdown, qdev->ndev,
"ETIMEDOUT!!! errored out of resetting the chip!\n");
status = -ETIMEDOUT;
}
/* Resume management traffic. */
ql_mb_set_mgmnt_traffic_ctl(qdev, MB_SET_MPI_TFK_RESUME);
return status;
}
static void ql_display_dev_info(struct net_device *ndev)
{
struct ql_adapter *qdev = netdev_priv(ndev);
netif_info(qdev, probe, qdev->ndev,
"Function #%d, Port %d, NIC Roll %d, NIC Rev = %d, "
"XG Roll = %d, XG Rev = %d.\n",
qdev->func,
qdev->port,
qdev->chip_rev_id & 0x0000000f,
qdev->chip_rev_id >> 4 & 0x0000000f,
qdev->chip_rev_id >> 8 & 0x0000000f,
qdev->chip_rev_id >> 12 & 0x0000000f);
netif_info(qdev, probe, qdev->ndev,
"MAC address %pM\n", ndev->dev_addr);
}
static int ql_wol(struct ql_adapter *qdev)
{
int status = 0;
u32 wol = MB_WOL_DISABLE;
/* The CAM is still intact after a reset, but if we
* are doing WOL, then we may need to program the
* routing regs. We would also need to issue the mailbox
* commands to instruct the MPI what to do per the ethtool
* settings.
*/
if (qdev->wol & (WAKE_ARP | WAKE_MAGICSECURE | WAKE_PHY | WAKE_UCAST |
WAKE_MCAST | WAKE_BCAST)) {
netif_err(qdev, ifdown, qdev->ndev,
"Unsupported WOL paramter. qdev->wol = 0x%x.\n",
qdev->wol);
return -EINVAL;
}
if (qdev->wol & WAKE_MAGIC) {
status = ql_mb_wol_set_magic(qdev, 1);
if (status) {
netif_err(qdev, ifdown, qdev->ndev,
"Failed to set magic packet on %s.\n",
qdev->ndev->name);
return status;
} else
netif_info(qdev, drv, qdev->ndev,
"Enabled magic packet successfully on %s.\n",
qdev->ndev->name);
wol |= MB_WOL_MAGIC_PKT;
}
if (qdev->wol) {
wol |= MB_WOL_MODE_ON;
status = ql_mb_wol_mode(qdev, wol);
netif_err(qdev, drv, qdev->ndev,
"WOL %s (wol code 0x%x) on %s\n",
(status == 0) ? "Successfully set" : "Failed",
wol, qdev->ndev->name);
}
return status;
}
static void ql_cancel_all_work_sync(struct ql_adapter *qdev)
{
/* Don't kill the reset worker thread if we
* are in the process of recovery.
*/
if (test_bit(QL_ADAPTER_UP, &qdev->flags))
cancel_delayed_work_sync(&qdev->asic_reset_work);
cancel_delayed_work_sync(&qdev->mpi_reset_work);
cancel_delayed_work_sync(&qdev->mpi_work);
cancel_delayed_work_sync(&qdev->mpi_idc_work);
cancel_delayed_work_sync(&qdev->mpi_core_to_log);
cancel_delayed_work_sync(&qdev->mpi_port_cfg_work);
}
static int ql_adapter_down(struct ql_adapter *qdev)
{
int i, status = 0;
ql_link_off(qdev);
ql_cancel_all_work_sync(qdev);
for (i = 0; i < qdev->rss_ring_count; i++)
napi_disable(&qdev->rx_ring[i].napi);
clear_bit(QL_ADAPTER_UP, &qdev->flags);
ql_disable_interrupts(qdev);
ql_tx_ring_clean(qdev);
/* Call netif_napi_del() from common point.
*/
for (i = 0; i < qdev->rss_ring_count; i++)
netif_napi_del(&qdev->rx_ring[i].napi);
status = ql_adapter_reset(qdev);
if (status)
netif_err(qdev, ifdown, qdev->ndev, "reset(func #%d) FAILED!\n",
qdev->func);
ql_free_rx_buffers(qdev);
return status;
}
static int ql_adapter_up(struct ql_adapter *qdev)
{
int err = 0;
err = ql_adapter_initialize(qdev);
if (err) {
netif_info(qdev, ifup, qdev->ndev, "Unable to initialize adapter.\n");
goto err_init;
}
set_bit(QL_ADAPTER_UP, &qdev->flags);
ql_alloc_rx_buffers(qdev);
/* If the port is initialized and the
* link is up the turn on the carrier.
*/
if ((ql_read32(qdev, STS) & qdev->port_init) &&
(ql_read32(qdev, STS) & qdev->port_link_up))
ql_link_on(qdev);
/* Restore rx mode. */
clear_bit(QL_ALLMULTI, &qdev->flags);
clear_bit(QL_PROMISCUOUS, &qdev->flags);
qlge_set_multicast_list(qdev->ndev);
/* Restore vlan setting. */
qlge_restore_vlan(qdev);
ql_enable_interrupts(qdev);
ql_enable_all_completion_interrupts(qdev);
netif_tx_start_all_queues(qdev->ndev);
return 0;
err_init:
ql_adapter_reset(qdev);
return err;
}
static void ql_release_adapter_resources(struct ql_adapter *qdev)
{
ql_free_mem_resources(qdev);
ql_free_irq(qdev);
}
static int ql_get_adapter_resources(struct ql_adapter *qdev)
{
int status = 0;
if (ql_alloc_mem_resources(qdev)) {
netif_err(qdev, ifup, qdev->ndev, "Unable to allocate memory.\n");
return -ENOMEM;
}
status = ql_request_irq(qdev);
return status;
}
static int qlge_close(struct net_device *ndev)
{
struct ql_adapter *qdev = netdev_priv(ndev);
/* If we hit pci_channel_io_perm_failure
* failure condition, then we already
* brought the adapter down.
*/
if (test_bit(QL_EEH_FATAL, &qdev->flags)) {
netif_err(qdev, drv, qdev->ndev, "EEH fatal did unload.\n");
clear_bit(QL_EEH_FATAL, &qdev->flags);
return 0;
}
/*
* Wait for device to recover from a reset.
* (Rarely happens, but possible.)
*/
while (!test_bit(QL_ADAPTER_UP, &qdev->flags))
msleep(1);
ql_adapter_down(qdev);
ql_release_adapter_resources(qdev);
return 0;
}
static int ql_configure_rings(struct ql_adapter *qdev)
{
int i;
struct rx_ring *rx_ring;
struct tx_ring *tx_ring;
int cpu_cnt = min(MAX_CPUS, (int)num_online_cpus());
unsigned int lbq_buf_len = (qdev->ndev->mtu > 1500) ?
LARGE_BUFFER_MAX_SIZE : LARGE_BUFFER_MIN_SIZE;
qdev->lbq_buf_order = get_order(lbq_buf_len);
/* In a perfect world we have one RSS ring for each CPU
* and each has it's own vector. To do that we ask for
* cpu_cnt vectors. ql_enable_msix() will adjust the
* vector count to what we actually get. We then
* allocate an RSS ring for each.
* Essentially, we are doing min(cpu_count, msix_vector_count).
*/
qdev->intr_count = cpu_cnt;
ql_enable_msix(qdev);
/* Adjust the RSS ring count to the actual vector count. */
qdev->rss_ring_count = qdev->intr_count;
qdev->tx_ring_count = cpu_cnt;
qdev->rx_ring_count = qdev->tx_ring_count + qdev->rss_ring_count;
for (i = 0; i < qdev->tx_ring_count; i++) {
tx_ring = &qdev->tx_ring[i];
memset((void *)tx_ring, 0, sizeof(*tx_ring));
tx_ring->qdev = qdev;
tx_ring->wq_id = i;
tx_ring->wq_len = qdev->tx_ring_size;
tx_ring->wq_size =
tx_ring->wq_len * sizeof(struct ob_mac_iocb_req);
/*
* The completion queue ID for the tx rings start
* immediately after the rss rings.
*/
tx_ring->cq_id = qdev->rss_ring_count + i;
}
for (i = 0; i < qdev->rx_ring_count; i++) {
rx_ring = &qdev->rx_ring[i];
memset((void *)rx_ring, 0, sizeof(*rx_ring));
rx_ring->qdev = qdev;
rx_ring->cq_id = i;
rx_ring->cpu = i % cpu_cnt; /* CPU to run handler on. */
if (i < qdev->rss_ring_count) {
/*
* Inbound (RSS) queues.
*/
rx_ring->cq_len = qdev->rx_ring_size;
rx_ring->cq_size =
rx_ring->cq_len * sizeof(struct ql_net_rsp_iocb);
rx_ring->lbq_len = NUM_LARGE_BUFFERS;
rx_ring->lbq_size =
rx_ring->lbq_len * sizeof(__le64);
rx_ring->lbq_buf_size = (u16)lbq_buf_len;
netif_printk(qdev, ifup, KERN_DEBUG, qdev->ndev,
"lbq_buf_size %d, order = %d\n",
rx_ring->lbq_buf_size,
qdev->lbq_buf_order);
rx_ring->sbq_len = NUM_SMALL_BUFFERS;
rx_ring->sbq_size =
rx_ring->sbq_len * sizeof(__le64);
rx_ring->sbq_buf_size = SMALL_BUF_MAP_SIZE;
rx_ring->type = RX_Q;
} else {
/*
* Outbound queue handles outbound completions only.
*/
/* outbound cq is same size as tx_ring it services. */
rx_ring->cq_len = qdev->tx_ring_size;
rx_ring->cq_size =
rx_ring->cq_len * sizeof(struct ql_net_rsp_iocb);
rx_ring->lbq_len = 0;
rx_ring->lbq_size = 0;
rx_ring->lbq_buf_size = 0;
rx_ring->sbq_len = 0;
rx_ring->sbq_size = 0;
rx_ring->sbq_buf_size = 0;
rx_ring->type = TX_Q;
}
}
return 0;
}
static int qlge_open(struct net_device *ndev)
{
int err = 0;
struct ql_adapter *qdev = netdev_priv(ndev);
err = ql_adapter_reset(qdev);
if (err)
return err;
err = ql_configure_rings(qdev);
if (err)
return err;
err = ql_get_adapter_resources(qdev);
if (err)
goto error_up;
err = ql_adapter_up(qdev);
if (err)
goto error_up;
return err;
error_up:
ql_release_adapter_resources(qdev);
return err;
}
static int ql_change_rx_buffers(struct ql_adapter *qdev)
{
struct rx_ring *rx_ring;
int i, status;
u32 lbq_buf_len;
/* Wait for an outstanding reset to complete. */
if (!test_bit(QL_ADAPTER_UP, &qdev->flags)) {
int i = 3;
while (i-- && !test_bit(QL_ADAPTER_UP, &qdev->flags)) {
netif_err(qdev, ifup, qdev->ndev,
"Waiting for adapter UP...\n");
ssleep(1);
}
if (!i) {
netif_err(qdev, ifup, qdev->ndev,
"Timed out waiting for adapter UP\n");
return -ETIMEDOUT;
}
}
status = ql_adapter_down(qdev);
if (status)
goto error;
/* Get the new rx buffer size. */
lbq_buf_len = (qdev->ndev->mtu > 1500) ?
LARGE_BUFFER_MAX_SIZE : LARGE_BUFFER_MIN_SIZE;
qdev->lbq_buf_order = get_order(lbq_buf_len);
for (i = 0; i < qdev->rss_ring_count; i++) {
rx_ring = &qdev->rx_ring[i];
/* Set the new size. */
rx_ring->lbq_buf_size = lbq_buf_len;
}
status = ql_adapter_up(qdev);
if (status)
goto error;
return status;
error:
netif_alert(qdev, ifup, qdev->ndev,
"Driver up/down cycle failed, closing device.\n");
set_bit(QL_ADAPTER_UP, &qdev->flags);
dev_close(qdev->ndev);
return status;
}
static int qlge_change_mtu(struct net_device *ndev, int new_mtu)
{
struct ql_adapter *qdev = netdev_priv(ndev);
int status;
if (ndev->mtu == 1500 && new_mtu == 9000) {
netif_err(qdev, ifup, qdev->ndev, "Changing to jumbo MTU.\n");
} else if (ndev->mtu == 9000 && new_mtu == 1500) {
netif_err(qdev, ifup, qdev->ndev, "Changing to normal MTU.\n");
} else
return -EINVAL;
queue_delayed_work(qdev->workqueue,
&qdev->mpi_port_cfg_work, 3*HZ);
ndev->mtu = new_mtu;
if (!netif_running(qdev->ndev)) {
return 0;
}
status = ql_change_rx_buffers(qdev);
if (status) {
netif_err(qdev, ifup, qdev->ndev,
"Changing MTU failed.\n");
}
return status;
}
static struct net_device_stats *qlge_get_stats(struct net_device
*ndev)
{
struct ql_adapter *qdev = netdev_priv(ndev);
struct rx_ring *rx_ring = &qdev->rx_ring[0];
struct tx_ring *tx_ring = &qdev->tx_ring[0];
unsigned long pkts, mcast, dropped, errors, bytes;
int i;
/* Get RX stats. */
pkts = mcast = dropped = errors = bytes = 0;
for (i = 0; i < qdev->rss_ring_count; i++, rx_ring++) {
pkts += rx_ring->rx_packets;
bytes += rx_ring->rx_bytes;
dropped += rx_ring->rx_dropped;
errors += rx_ring->rx_errors;
mcast += rx_ring->rx_multicast;
}
ndev->stats.rx_packets = pkts;
ndev->stats.rx_bytes = bytes;
ndev->stats.rx_dropped = dropped;
ndev->stats.rx_errors = errors;
ndev->stats.multicast = mcast;
/* Get TX stats. */
pkts = errors = bytes = 0;
for (i = 0; i < qdev->tx_ring_count; i++, tx_ring++) {
pkts += tx_ring->tx_packets;
bytes += tx_ring->tx_bytes;
errors += tx_ring->tx_errors;
}
ndev->stats.tx_packets = pkts;
ndev->stats.tx_bytes = bytes;
ndev->stats.tx_errors = errors;
return &ndev->stats;
}
static void qlge_set_multicast_list(struct net_device *ndev)
{
struct ql_adapter *qdev = netdev_priv(ndev);
struct netdev_hw_addr *ha;
int i, status;
status = ql_sem_spinlock(qdev, SEM_RT_IDX_MASK);
if (status)
return;
/*
* Set or clear promiscuous mode if a
* transition is taking place.
*/
if (ndev->flags & IFF_PROMISC) {
if (!test_bit(QL_PROMISCUOUS, &qdev->flags)) {
if (ql_set_routing_reg
(qdev, RT_IDX_PROMISCUOUS_SLOT, RT_IDX_VALID, 1)) {
netif_err(qdev, hw, qdev->ndev,
"Failed to set promiscuous mode.\n");
} else {
set_bit(QL_PROMISCUOUS, &qdev->flags);
}
}
} else {
if (test_bit(QL_PROMISCUOUS, &qdev->flags)) {
if (ql_set_routing_reg
(qdev, RT_IDX_PROMISCUOUS_SLOT, RT_IDX_VALID, 0)) {
netif_err(qdev, hw, qdev->ndev,
"Failed to clear promiscuous mode.\n");
} else {
clear_bit(QL_PROMISCUOUS, &qdev->flags);
}
}
}
/*
* Set or clear all multicast mode if a
* transition is taking place.
*/
if ((ndev->flags & IFF_ALLMULTI) ||
(netdev_mc_count(ndev) > MAX_MULTICAST_ENTRIES)) {
if (!test_bit(QL_ALLMULTI, &qdev->flags)) {
if (ql_set_routing_reg
(qdev, RT_IDX_ALLMULTI_SLOT, RT_IDX_MCAST, 1)) {
netif_err(qdev, hw, qdev->ndev,
"Failed to set all-multi mode.\n");
} else {
set_bit(QL_ALLMULTI, &qdev->flags);
}
}
} else {
if (test_bit(QL_ALLMULTI, &qdev->flags)) {
if (ql_set_routing_reg
(qdev, RT_IDX_ALLMULTI_SLOT, RT_IDX_MCAST, 0)) {
netif_err(qdev, hw, qdev->ndev,
"Failed to clear all-multi mode.\n");
} else {
clear_bit(QL_ALLMULTI, &qdev->flags);
}
}
}
if (!netdev_mc_empty(ndev)) {
status = ql_sem_spinlock(qdev, SEM_MAC_ADDR_MASK);
if (status)
goto exit;
i = 0;
netdev_for_each_mc_addr(ha, ndev) {
if (ql_set_mac_addr_reg(qdev, (u8 *) ha->addr,
MAC_ADDR_TYPE_MULTI_MAC, i)) {
netif_err(qdev, hw, qdev->ndev,
"Failed to loadmulticast address.\n");
ql_sem_unlock(qdev, SEM_MAC_ADDR_MASK);
goto exit;
}
i++;
}
ql_sem_unlock(qdev, SEM_MAC_ADDR_MASK);
if (ql_set_routing_reg
(qdev, RT_IDX_MCAST_MATCH_SLOT, RT_IDX_MCAST_MATCH, 1)) {
netif_err(qdev, hw, qdev->ndev,
"Failed to set multicast match mode.\n");
} else {
set_bit(QL_ALLMULTI, &qdev->flags);
}
}
exit:
ql_sem_unlock(qdev, SEM_RT_IDX_MASK);
}
static int qlge_set_mac_address(struct net_device *ndev, void *p)
{
struct ql_adapter *qdev = netdev_priv(ndev);
struct sockaddr *addr = p;
int status;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(ndev->dev_addr, addr->sa_data, ndev->addr_len);
/* Update local copy of current mac address. */
memcpy(qdev->current_mac_addr, ndev->dev_addr, ndev->addr_len);
status = ql_sem_spinlock(qdev, SEM_MAC_ADDR_MASK);
if (status)
return status;
status = ql_set_mac_addr_reg(qdev, (u8 *) ndev->dev_addr,
MAC_ADDR_TYPE_CAM_MAC, qdev->func * MAX_CQ);
if (status)
netif_err(qdev, hw, qdev->ndev, "Failed to load MAC address.\n");
ql_sem_unlock(qdev, SEM_MAC_ADDR_MASK);
return status;
}
static void qlge_tx_timeout(struct net_device *ndev)
{
struct ql_adapter *qdev = netdev_priv(ndev);
ql_queue_asic_error(qdev);
}
static void ql_asic_reset_work(struct work_struct *work)
{
struct ql_adapter *qdev =
container_of(work, struct ql_adapter, asic_reset_work.work);
int status;
rtnl_lock();
status = ql_adapter_down(qdev);
if (status)
goto error;
status = ql_adapter_up(qdev);
if (status)
goto error;
/* Restore rx mode. */
clear_bit(QL_ALLMULTI, &qdev->flags);
clear_bit(QL_PROMISCUOUS, &qdev->flags);
qlge_set_multicast_list(qdev->ndev);
rtnl_unlock();
return;
error:
netif_alert(qdev, ifup, qdev->ndev,
"Driver up/down cycle failed, closing device\n");
set_bit(QL_ADAPTER_UP, &qdev->flags);
dev_close(qdev->ndev);
rtnl_unlock();
}
static const struct nic_operations qla8012_nic_ops = {
.get_flash = ql_get_8012_flash_params,
.port_initialize = ql_8012_port_initialize,
};
static const struct nic_operations qla8000_nic_ops = {
.get_flash = ql_get_8000_flash_params,
.port_initialize = ql_8000_port_initialize,
};
/* Find the pcie function number for the other NIC
* on this chip. Since both NIC functions share a
* common firmware we have the lowest enabled function
* do any common work. Examples would be resetting
* after a fatal firmware error, or doing a firmware
* coredump.
*/
static int ql_get_alt_pcie_func(struct ql_adapter *qdev)
{
int status = 0;
u32 temp;
u32 nic_func1, nic_func2;
status = ql_read_mpi_reg(qdev, MPI_TEST_FUNC_PORT_CFG,
&temp);
if (status)
return status;
nic_func1 = ((temp >> MPI_TEST_NIC1_FUNC_SHIFT) &
MPI_TEST_NIC_FUNC_MASK);
nic_func2 = ((temp >> MPI_TEST_NIC2_FUNC_SHIFT) &
MPI_TEST_NIC_FUNC_MASK);
if (qdev->func == nic_func1)
qdev->alt_func = nic_func2;
else if (qdev->func == nic_func2)
qdev->alt_func = nic_func1;
else
status = -EIO;
return status;
}
static int ql_get_board_info(struct ql_adapter *qdev)
{
int status;
qdev->func =
(ql_read32(qdev, STS) & STS_FUNC_ID_MASK) >> STS_FUNC_ID_SHIFT;
if (qdev->func > 3)
return -EIO;
status = ql_get_alt_pcie_func(qdev);
if (status)
return status;
qdev->port = (qdev->func < qdev->alt_func) ? 0 : 1;
if (qdev->port) {
qdev->xg_sem_mask = SEM_XGMAC1_MASK;
qdev->port_link_up = STS_PL1;
qdev->port_init = STS_PI1;
qdev->mailbox_in = PROC_ADDR_MPI_RISC | PROC_ADDR_FUNC2_MBI;
qdev->mailbox_out = PROC_ADDR_MPI_RISC | PROC_ADDR_FUNC2_MBO;
} else {
qdev->xg_sem_mask = SEM_XGMAC0_MASK;
qdev->port_link_up = STS_PL0;
qdev->port_init = STS_PI0;
qdev->mailbox_in = PROC_ADDR_MPI_RISC | PROC_ADDR_FUNC0_MBI;
qdev->mailbox_out = PROC_ADDR_MPI_RISC | PROC_ADDR_FUNC0_MBO;
}
qdev->chip_rev_id = ql_read32(qdev, REV_ID);
qdev->device_id = qdev->pdev->device;
if (qdev->device_id == QLGE_DEVICE_ID_8012)
qdev->nic_ops = &qla8012_nic_ops;
else if (qdev->device_id == QLGE_DEVICE_ID_8000)
qdev->nic_ops = &qla8000_nic_ops;
return status;
}
static void ql_release_all(struct pci_dev *pdev)
{
struct net_device *ndev = pci_get_drvdata(pdev);
struct ql_adapter *qdev = netdev_priv(ndev);
if (qdev->workqueue) {
destroy_workqueue(qdev->workqueue);
qdev->workqueue = NULL;
}
if (qdev->reg_base)
iounmap(qdev->reg_base);
if (qdev->doorbell_area)
iounmap(qdev->doorbell_area);
vfree(qdev->mpi_coredump);
pci_release_regions(pdev);
pci_set_drvdata(pdev, NULL);
}
static int __devinit ql_init_device(struct pci_dev *pdev,
struct net_device *ndev, int cards_found)
{
struct ql_adapter *qdev = netdev_priv(ndev);
int err = 0;
memset((void *)qdev, 0, sizeof(*qdev));
err = pci_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "PCI device enable failed.\n");
return err;
}
qdev->ndev = ndev;
qdev->pdev = pdev;
pci_set_drvdata(pdev, ndev);
/* Set PCIe read request size */
err = pcie_set_readrq(pdev, 4096);
if (err) {
dev_err(&pdev->dev, "Set readrq failed.\n");
goto err_out1;
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
dev_err(&pdev->dev, "PCI region request failed.\n");
return err;
}
pci_set_master(pdev);
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
set_bit(QL_DMA64, &qdev->flags);
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
} else {
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (!err)
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
}
if (err) {
dev_err(&pdev->dev, "No usable DMA configuration.\n");
goto err_out2;
}
/* Set PCIe reset type for EEH to fundamental. */
pdev->needs_freset = 1;
pci_save_state(pdev);
qdev->reg_base =
ioremap_nocache(pci_resource_start(pdev, 1),
pci_resource_len(pdev, 1));
if (!qdev->reg_base) {
dev_err(&pdev->dev, "Register mapping failed.\n");
err = -ENOMEM;
goto err_out2;
}
qdev->doorbell_area_size = pci_resource_len(pdev, 3);
qdev->doorbell_area =
ioremap_nocache(pci_resource_start(pdev, 3),
pci_resource_len(pdev, 3));
if (!qdev->doorbell_area) {
dev_err(&pdev->dev, "Doorbell register mapping failed.\n");
err = -ENOMEM;
goto err_out2;
}
err = ql_get_board_info(qdev);
if (err) {
dev_err(&pdev->dev, "Register access failed.\n");
err = -EIO;
goto err_out2;
}
qdev->msg_enable = netif_msg_init(debug, default_msg);
spin_lock_init(&qdev->hw_lock);
spin_lock_init(&qdev->stats_lock);
if (qlge_mpi_coredump) {
qdev->mpi_coredump =
vmalloc(sizeof(struct ql_mpi_coredump));
if (qdev->mpi_coredump == NULL) {
dev_err(&pdev->dev, "Coredump alloc failed.\n");
err = -ENOMEM;
goto err_out2;
}
if (qlge_force_coredump)
set_bit(QL_FRC_COREDUMP, &qdev->flags);
}
/* make sure the EEPROM is good */
err = qdev->nic_ops->get_flash(qdev);
if (err) {
dev_err(&pdev->dev, "Invalid FLASH.\n");
goto err_out2;
}
memcpy(ndev->perm_addr, ndev->dev_addr, ndev->addr_len);
/* Keep local copy of current mac address. */
memcpy(qdev->current_mac_addr, ndev->dev_addr, ndev->addr_len);
/* Set up the default ring sizes. */
qdev->tx_ring_size = NUM_TX_RING_ENTRIES;
qdev->rx_ring_size = NUM_RX_RING_ENTRIES;
/* Set up the coalescing parameters. */
qdev->rx_coalesce_usecs = DFLT_COALESCE_WAIT;
qdev->tx_coalesce_usecs = DFLT_COALESCE_WAIT;
qdev->rx_max_coalesced_frames = DFLT_INTER_FRAME_WAIT;
qdev->tx_max_coalesced_frames = DFLT_INTER_FRAME_WAIT;
/*
* Set up the operating parameters.
*/
qdev->workqueue = create_singlethread_workqueue(ndev->name);
INIT_DELAYED_WORK(&qdev->asic_reset_work, ql_asic_reset_work);
INIT_DELAYED_WORK(&qdev->mpi_reset_work, ql_mpi_reset_work);
INIT_DELAYED_WORK(&qdev->mpi_work, ql_mpi_work);
INIT_DELAYED_WORK(&qdev->mpi_port_cfg_work, ql_mpi_port_cfg_work);
INIT_DELAYED_WORK(&qdev->mpi_idc_work, ql_mpi_idc_work);
INIT_DELAYED_WORK(&qdev->mpi_core_to_log, ql_mpi_core_to_log);
init_completion(&qdev->ide_completion);
mutex_init(&qdev->mpi_mutex);
if (!cards_found) {
dev_info(&pdev->dev, "%s\n", DRV_STRING);
dev_info(&pdev->dev, "Driver name: %s, Version: %s.\n",
DRV_NAME, DRV_VERSION);
}
return 0;
err_out2:
ql_release_all(pdev);
err_out1:
pci_disable_device(pdev);
return err;
}
static const struct net_device_ops qlge_netdev_ops = {
.ndo_open = qlge_open,
.ndo_stop = qlge_close,
.ndo_start_xmit = qlge_send,
.ndo_change_mtu = qlge_change_mtu,
.ndo_get_stats = qlge_get_stats,
.ndo_set_multicast_list = qlge_set_multicast_list,
.ndo_set_mac_address = qlge_set_mac_address,
.ndo_validate_addr = eth_validate_addr,
.ndo_tx_timeout = qlge_tx_timeout,
.ndo_vlan_rx_register = qlge_vlan_rx_register,
.ndo_vlan_rx_add_vid = qlge_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = qlge_vlan_rx_kill_vid,
};
static void ql_timer(unsigned long data)
{
struct ql_adapter *qdev = (struct ql_adapter *)data;
u32 var = 0;
var = ql_read32(qdev, STS);
if (pci_channel_offline(qdev->pdev)) {
netif_err(qdev, ifup, qdev->ndev, "EEH STS = 0x%.08x.\n", var);
return;
}
mod_timer(&qdev->timer, jiffies + (5*HZ));
}
static int __devinit qlge_probe(struct pci_dev *pdev,
const struct pci_device_id *pci_entry)
{
struct net_device *ndev = NULL;
struct ql_adapter *qdev = NULL;
static int cards_found = 0;
int err = 0;
ndev = alloc_etherdev_mq(sizeof(struct ql_adapter),
min(MAX_CPUS, (int)num_online_cpus()));
if (!ndev)
return -ENOMEM;
err = ql_init_device(pdev, ndev, cards_found);
if (err < 0) {
free_netdev(ndev);
return err;
}
qdev = netdev_priv(ndev);
SET_NETDEV_DEV(ndev, &pdev->dev);
ndev->hw_features = NETIF_F_SG | NETIF_F_IP_CSUM |
NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_TSO_ECN |
NETIF_F_HW_VLAN_TX | NETIF_F_RXCSUM;
ndev->features = ndev->hw_features |
NETIF_F_HW_VLAN_RX | NETIF_F_HW_VLAN_FILTER;
if (test_bit(QL_DMA64, &qdev->flags))
ndev->features |= NETIF_F_HIGHDMA;
/*
* Set up net_device structure.
*/
ndev->tx_queue_len = qdev->tx_ring_size;
ndev->irq = pdev->irq;
ndev->netdev_ops = &qlge_netdev_ops;
SET_ETHTOOL_OPS(ndev, &qlge_ethtool_ops);
ndev->watchdog_timeo = 10 * HZ;
err = register_netdev(ndev);
if (err) {
dev_err(&pdev->dev, "net device registration failed.\n");
ql_release_all(pdev);
pci_disable_device(pdev);
return err;
}
/* Start up the timer to trigger EEH if
* the bus goes dead
*/
init_timer_deferrable(&qdev->timer);
qdev->timer.data = (unsigned long)qdev;
qdev->timer.function = ql_timer;
qdev->timer.expires = jiffies + (5*HZ);
add_timer(&qdev->timer);
ql_link_off(qdev);
ql_display_dev_info(ndev);
atomic_set(&qdev->lb_count, 0);
cards_found++;
return 0;
}
netdev_tx_t ql_lb_send(struct sk_buff *skb, struct net_device *ndev)
{
return qlge_send(skb, ndev);
}
int ql_clean_lb_rx_ring(struct rx_ring *rx_ring, int budget)
{
return ql_clean_inbound_rx_ring(rx_ring, budget);
}
static void __devexit qlge_remove(struct pci_dev *pdev)
{
struct net_device *ndev = pci_get_drvdata(pdev);
struct ql_adapter *qdev = netdev_priv(ndev);
del_timer_sync(&qdev->timer);
ql_cancel_all_work_sync(qdev);
unregister_netdev(ndev);
ql_release_all(pdev);
pci_disable_device(pdev);
free_netdev(ndev);
}
/* Clean up resources without touching hardware. */
static void ql_eeh_close(struct net_device *ndev)
{
int i;
struct ql_adapter *qdev = netdev_priv(ndev);
if (netif_carrier_ok(ndev)) {
netif_carrier_off(ndev);
netif_stop_queue(ndev);
}
/* Disabling the timer */
del_timer_sync(&qdev->timer);
ql_cancel_all_work_sync(qdev);
for (i = 0; i < qdev->rss_ring_count; i++)
netif_napi_del(&qdev->rx_ring[i].napi);
clear_bit(QL_ADAPTER_UP, &qdev->flags);
ql_tx_ring_clean(qdev);
ql_free_rx_buffers(qdev);
ql_release_adapter_resources(qdev);
}
/*
* This callback is called by the PCI subsystem whenever
* a PCI bus error is detected.
*/
static pci_ers_result_t qlge_io_error_detected(struct pci_dev *pdev,
enum pci_channel_state state)
{
struct net_device *ndev = pci_get_drvdata(pdev);
struct ql_adapter *qdev = netdev_priv(ndev);
switch (state) {
case pci_channel_io_normal:
return PCI_ERS_RESULT_CAN_RECOVER;
case pci_channel_io_frozen:
netif_device_detach(ndev);
if (netif_running(ndev))
ql_eeh_close(ndev);
pci_disable_device(pdev);
return PCI_ERS_RESULT_NEED_RESET;
case pci_channel_io_perm_failure:
dev_err(&pdev->dev,
"%s: pci_channel_io_perm_failure.\n", __func__);
ql_eeh_close(ndev);
set_bit(QL_EEH_FATAL, &qdev->flags);
return PCI_ERS_RESULT_DISCONNECT;
}
/* Request a slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/*
* This callback is called after the PCI buss has been reset.
* Basically, this tries to restart the card from scratch.
* This is a shortened version of the device probe/discovery code,
* it resembles the first-half of the () routine.
*/
static pci_ers_result_t qlge_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *ndev = pci_get_drvdata(pdev);
struct ql_adapter *qdev = netdev_priv(ndev);
pdev->error_state = pci_channel_io_normal;
pci_restore_state(pdev);
if (pci_enable_device(pdev)) {
netif_err(qdev, ifup, qdev->ndev,
"Cannot re-enable PCI device after reset.\n");
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
if (ql_adapter_reset(qdev)) {
netif_err(qdev, drv, qdev->ndev, "reset FAILED!\n");
set_bit(QL_EEH_FATAL, &qdev->flags);
return PCI_ERS_RESULT_DISCONNECT;
}
return PCI_ERS_RESULT_RECOVERED;
}
static void qlge_io_resume(struct pci_dev *pdev)
{
struct net_device *ndev = pci_get_drvdata(pdev);
struct ql_adapter *qdev = netdev_priv(ndev);
int err = 0;
if (netif_running(ndev)) {
err = qlge_open(ndev);
if (err) {
netif_err(qdev, ifup, qdev->ndev,
"Device initialization failed after reset.\n");
return;
}
} else {
netif_err(qdev, ifup, qdev->ndev,
"Device was not running prior to EEH.\n");
}
mod_timer(&qdev->timer, jiffies + (5*HZ));
netif_device_attach(ndev);
}
static struct pci_error_handlers qlge_err_handler = {
.error_detected = qlge_io_error_detected,
.slot_reset = qlge_io_slot_reset,
.resume = qlge_io_resume,
};
static int qlge_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *ndev = pci_get_drvdata(pdev);
struct ql_adapter *qdev = netdev_priv(ndev);
int err;
netif_device_detach(ndev);
del_timer_sync(&qdev->timer);
if (netif_running(ndev)) {
err = ql_adapter_down(qdev);
if (!err)
return err;
}
ql_wol(qdev);
err = pci_save_state(pdev);
if (err)
return err;
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
#ifdef CONFIG_PM
static int qlge_resume(struct pci_dev *pdev)
{
struct net_device *ndev = pci_get_drvdata(pdev);
struct ql_adapter *qdev = netdev_priv(ndev);
int err;
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
err = pci_enable_device(pdev);
if (err) {
netif_err(qdev, ifup, qdev->ndev, "Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
if (netif_running(ndev)) {
err = ql_adapter_up(qdev);
if (err)
return err;
}
mod_timer(&qdev->timer, jiffies + (5*HZ));
netif_device_attach(ndev);
return 0;
}
#endif /* CONFIG_PM */
static void qlge_shutdown(struct pci_dev *pdev)
{
qlge_suspend(pdev, PMSG_SUSPEND);
}
static struct pci_driver qlge_driver = {
.name = DRV_NAME,
.id_table = qlge_pci_tbl,
.probe = qlge_probe,
.remove = __devexit_p(qlge_remove),
#ifdef CONFIG_PM
.suspend = qlge_suspend,
.resume = qlge_resume,
#endif
.shutdown = qlge_shutdown,
.err_handler = &qlge_err_handler
};
static int __init qlge_init_module(void)
{
return pci_register_driver(&qlge_driver);
}
static void __exit qlge_exit(void)
{
pci_unregister_driver(&qlge_driver);
}
module_init(qlge_init_module);
module_exit(qlge_exit);
| gpl-2.0 |
emwno/android_kernel_N7100 | .fr-M0hgqN/drivers/staging/mei/init.c | 2379 | 20367 | /*
*
* Intel Management Engine Interface (Intel MEI) Linux driver
* Copyright (c) 2003-2011, 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.
*
*/
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/wait.h>
#include <linux/delay.h>
#include "mei_dev.h"
#include "hw.h"
#include "interface.h"
#include "mei.h"
const uuid_le mei_amthi_guid = UUID_LE(0x12f80028, 0xb4b7, 0x4b2d, 0xac,
0xa8, 0x46, 0xe0, 0xff, 0x65,
0x81, 0x4c);
/**
* mei_initialize_list - Sets up a queue list.
*
* @list: An instance of our list structure
* @dev: the device structure
*/
void mei_initialize_list(struct mei_io_list *list, struct mei_device *dev)
{
/* initialize our queue list */
INIT_LIST_HEAD(&list->mei_cb.cb_list);
list->status = 0;
list->device_extension = dev;
}
/**
* mei_flush_queues - flushes queue lists belonging to cl.
*
* @dev: the device structure
* @cl: private data of the file object
*/
void mei_flush_queues(struct mei_device *dev, struct mei_cl *cl)
{
int i;
if (!dev || !cl)
return;
for (i = 0; i < MEI_IO_LISTS_NUMBER; i++) {
dev_dbg(&dev->pdev->dev, "remove list entry belonging to cl\n");
mei_flush_list(dev->io_list_array[i], cl);
}
}
/**
* mei_flush_list - removes list entry belonging to cl.
*
* @list: An instance of our list structure
* @cl: private data of the file object
*/
void mei_flush_list(struct mei_io_list *list, struct mei_cl *cl)
{
struct mei_cl *cl_tmp;
struct mei_cl_cb *cb_pos = NULL;
struct mei_cl_cb *cb_next = NULL;
if (!list || !cl)
return;
if (list->status != 0)
return;
if (list_empty(&list->mei_cb.cb_list))
return;
list_for_each_entry_safe(cb_pos, cb_next,
&list->mei_cb.cb_list, cb_list) {
if (cb_pos) {
cl_tmp = (struct mei_cl *)
cb_pos->file_private;
if (cl_tmp &&
mei_fe_same_id(cl, cl_tmp))
list_del(&cb_pos->cb_list);
}
}
}
/**
* mei_reset_iamthif_params - initializes mei device iamthif
*
* @dev: the device structure
*/
static void mei_reset_iamthif_params(struct mei_device *dev)
{
/* reset iamthif parameters. */
dev->iamthif_current_cb = NULL;
dev->iamthif_msg_buf_size = 0;
dev->iamthif_msg_buf_index = 0;
dev->iamthif_canceled = 0;
dev->iamthif_ioctl = 0;
dev->iamthif_state = MEI_IAMTHIF_IDLE;
dev->iamthif_timer = 0;
}
/**
* init_mei_device - allocates and initializes the mei device structure
*
* @pdev: The pci device structure
*
* returns The mei_device_device pointer on success, NULL on failure.
*/
struct mei_device *init_mei_device(struct pci_dev *pdev)
{
int i;
struct mei_device *dev;
dev = kzalloc(sizeof(struct mei_device), GFP_KERNEL);
if (!dev)
return NULL;
/* setup our list array */
dev->io_list_array[0] = &dev->read_list;
dev->io_list_array[1] = &dev->write_list;
dev->io_list_array[2] = &dev->write_waiting_list;
dev->io_list_array[3] = &dev->ctrl_wr_list;
dev->io_list_array[4] = &dev->ctrl_rd_list;
dev->io_list_array[5] = &dev->amthi_cmd_list;
dev->io_list_array[6] = &dev->amthi_read_complete_list;
INIT_LIST_HEAD(&dev->file_list);
INIT_LIST_HEAD(&dev->wd_cl.link);
INIT_LIST_HEAD(&dev->iamthif_cl.link);
mutex_init(&dev->device_lock);
init_waitqueue_head(&dev->wait_recvd_msg);
init_waitqueue_head(&dev->wait_stop_wd);
dev->mei_state = MEI_INITIALIZING;
dev->iamthif_state = MEI_IAMTHIF_IDLE;
for (i = 0; i < MEI_IO_LISTS_NUMBER; i++)
mei_initialize_list(dev->io_list_array[i], dev);
dev->pdev = pdev;
return dev;
}
/**
* mei_hw_init - initializes host and fw to start work.
*
* @dev: the device structure
*
* returns 0 on success, <0 on failure.
*/
int mei_hw_init(struct mei_device *dev)
{
int err = 0;
int ret;
mutex_lock(&dev->device_lock);
dev->host_hw_state = mei_hcsr_read(dev);
dev->me_hw_state = mei_mecsr_read(dev);
dev_dbg(&dev->pdev->dev, "host_hw_state = 0x%08x, mestate = 0x%08x.\n",
dev->host_hw_state, dev->me_hw_state);
/* acknowledge interrupt and stop interupts */
if ((dev->host_hw_state & H_IS) == H_IS)
mei_reg_write(dev, H_CSR, dev->host_hw_state);
dev->recvd_msg = 0;
dev_dbg(&dev->pdev->dev, "reset in start the mei device.\n");
mei_reset(dev, 1);
dev_dbg(&dev->pdev->dev, "host_hw_state = 0x%08x, me_hw_state = 0x%08x.\n",
dev->host_hw_state, dev->me_hw_state);
/* wait for ME to turn on ME_RDY */
if (!dev->recvd_msg) {
mutex_unlock(&dev->device_lock);
err = wait_event_interruptible_timeout(dev->wait_recvd_msg,
dev->recvd_msg, MEI_INTEROP_TIMEOUT);
mutex_lock(&dev->device_lock);
}
if (err <= 0 && !dev->recvd_msg) {
dev->mei_state = MEI_DISABLED;
dev_dbg(&dev->pdev->dev,
"wait_event_interruptible_timeout failed"
"on wait for ME to turn on ME_RDY.\n");
ret = -ENODEV;
goto out;
}
if (!(((dev->host_hw_state & H_RDY) == H_RDY) &&
((dev->me_hw_state & ME_RDY_HRA) == ME_RDY_HRA))) {
dev->mei_state = MEI_DISABLED;
dev_dbg(&dev->pdev->dev,
"host_hw_state = 0x%08x, me_hw_state = 0x%08x.\n",
dev->host_hw_state, dev->me_hw_state);
if (!(dev->host_hw_state & H_RDY))
dev_dbg(&dev->pdev->dev, "host turn off H_RDY.\n");
if (!(dev->me_hw_state & ME_RDY_HRA))
dev_dbg(&dev->pdev->dev, "ME turn off ME_RDY.\n");
printk(KERN_ERR "mei: link layer initialization failed.\n");
ret = -ENODEV;
goto out;
}
if (dev->version.major_version != HBM_MAJOR_VERSION ||
dev->version.minor_version != HBM_MINOR_VERSION) {
dev_dbg(&dev->pdev->dev, "MEI start failed.\n");
ret = -ENODEV;
goto out;
}
dev->recvd_msg = 0;
dev_dbg(&dev->pdev->dev, "host_hw_state = 0x%08x, me_hw_state = 0x%08x.\n",
dev->host_hw_state, dev->me_hw_state);
dev_dbg(&dev->pdev->dev, "ME turn on ME_RDY and host turn on H_RDY.\n");
dev_dbg(&dev->pdev->dev, "link layer has been established.\n");
dev_dbg(&dev->pdev->dev, "MEI start success.\n");
ret = 0;
out:
mutex_unlock(&dev->device_lock);
return ret;
}
/**
* mei_hw_reset - resets fw via mei csr register.
*
* @dev: the device structure
* @interrupts_enabled: if interrupt should be enabled after reset.
*/
static void mei_hw_reset(struct mei_device *dev, int interrupts_enabled)
{
dev->host_hw_state |= (H_RST | H_IG);
if (interrupts_enabled)
mei_enable_interrupts(dev);
else
mei_disable_interrupts(dev);
}
/**
* mei_reset - resets host and fw.
*
* @dev: the device structure
* @interrupts_enabled: if interrupt should be enabled after reset.
*/
void mei_reset(struct mei_device *dev, int interrupts_enabled)
{
struct mei_cl *cl_pos = NULL;
struct mei_cl *cl_next = NULL;
struct mei_cl_cb *cb_pos = NULL;
struct mei_cl_cb *cb_next = NULL;
bool unexpected;
if (dev->mei_state == MEI_RECOVERING_FROM_RESET) {
dev->need_reset = 1;
return;
}
unexpected = (dev->mei_state != MEI_INITIALIZING &&
dev->mei_state != MEI_DISABLED &&
dev->mei_state != MEI_POWER_DOWN &&
dev->mei_state != MEI_POWER_UP);
dev->host_hw_state = mei_hcsr_read(dev);
dev_dbg(&dev->pdev->dev, "before reset host_hw_state = 0x%08x.\n",
dev->host_hw_state);
mei_hw_reset(dev, interrupts_enabled);
dev->host_hw_state &= ~H_RST;
dev->host_hw_state |= H_IG;
mei_hcsr_set(dev);
dev_dbg(&dev->pdev->dev, "currently saved host_hw_state = 0x%08x.\n",
dev->host_hw_state);
dev->need_reset = 0;
if (dev->mei_state != MEI_INITIALIZING) {
if (dev->mei_state != MEI_DISABLED &&
dev->mei_state != MEI_POWER_DOWN)
dev->mei_state = MEI_RESETING;
list_for_each_entry_safe(cl_pos,
cl_next, &dev->file_list, link) {
cl_pos->state = MEI_FILE_DISCONNECTED;
cl_pos->mei_flow_ctrl_creds = 0;
cl_pos->read_cb = NULL;
cl_pos->timer_count = 0;
}
/* remove entry if already in list */
dev_dbg(&dev->pdev->dev, "list del iamthif and wd file list.\n");
mei_remove_client_from_file_list(dev,
dev->wd_cl.host_client_id);
mei_remove_client_from_file_list(dev,
dev->iamthif_cl.host_client_id);
mei_reset_iamthif_params(dev);
dev->wd_due_counter = 0;
dev->extra_write_index = 0;
}
dev->num_mei_me_clients = 0;
dev->rd_msg_hdr = 0;
dev->stop = 0;
dev->wd_pending = 0;
/* update the state of the registers after reset */
dev->host_hw_state = mei_hcsr_read(dev);
dev->me_hw_state = mei_mecsr_read(dev);
dev_dbg(&dev->pdev->dev, "after reset host_hw_state = 0x%08x, me_hw_state = 0x%08x.\n",
dev->host_hw_state, dev->me_hw_state);
if (unexpected)
dev_warn(&dev->pdev->dev, "unexpected reset.\n");
/* Wake up all readings so they can be interrupted */
list_for_each_entry_safe(cl_pos, cl_next, &dev->file_list, link) {
if (waitqueue_active(&cl_pos->rx_wait)) {
dev_dbg(&dev->pdev->dev, "Waking up client!\n");
wake_up_interruptible(&cl_pos->rx_wait);
}
}
/* remove all waiting requests */
if (dev->write_list.status == 0 &&
!list_empty(&dev->write_list.mei_cb.cb_list)) {
list_for_each_entry_safe(cb_pos, cb_next,
&dev->write_list.mei_cb.cb_list, cb_list) {
if (cb_pos) {
list_del(&cb_pos->cb_list);
mei_free_cb_private(cb_pos);
cb_pos = NULL;
}
}
}
}
/**
* host_start_message - mei host sends start message.
*
* @dev: the device structure
*
* returns none.
*/
void host_start_message(struct mei_device *dev)
{
struct mei_msg_hdr *mei_hdr;
struct hbm_host_version_request *host_start_req;
/* host start message */
mei_hdr = (struct mei_msg_hdr *) &dev->wr_msg_buf[0];
mei_hdr->host_addr = 0;
mei_hdr->me_addr = 0;
mei_hdr->length = sizeof(struct hbm_host_version_request);
mei_hdr->msg_complete = 1;
mei_hdr->reserved = 0;
host_start_req =
(struct hbm_host_version_request *) &dev->wr_msg_buf[1];
memset(host_start_req, 0, sizeof(struct hbm_host_version_request));
host_start_req->cmd.cmd = HOST_START_REQ_CMD;
host_start_req->host_version.major_version = HBM_MAJOR_VERSION;
host_start_req->host_version.minor_version = HBM_MINOR_VERSION;
dev->recvd_msg = 0;
if (!mei_write_message(dev, mei_hdr,
(unsigned char *) (host_start_req),
mei_hdr->length)) {
dev_dbg(&dev->pdev->dev, "write send version message to FW fail.\n");
dev->mei_state = MEI_RESETING;
mei_reset(dev, 1);
}
dev->init_clients_state = MEI_START_MESSAGE;
dev->init_clients_timer = INIT_CLIENTS_TIMEOUT;
return ;
}
/**
* host_enum_clients_message - host sends enumeration client request message.
*
* @dev: the device structure
*
* returns none.
*/
void host_enum_clients_message(struct mei_device *dev)
{
struct mei_msg_hdr *mei_hdr;
struct hbm_host_enum_request *host_enum_req;
mei_hdr = (struct mei_msg_hdr *) &dev->wr_msg_buf[0];
/* enumerate clients */
mei_hdr->host_addr = 0;
mei_hdr->me_addr = 0;
mei_hdr->length = sizeof(struct hbm_host_enum_request);
mei_hdr->msg_complete = 1;
mei_hdr->reserved = 0;
host_enum_req = (struct hbm_host_enum_request *) &dev->wr_msg_buf[1];
memset(host_enum_req, 0, sizeof(struct hbm_host_enum_request));
host_enum_req->cmd.cmd = HOST_ENUM_REQ_CMD;
if (!mei_write_message(dev, mei_hdr,
(unsigned char *) (host_enum_req),
mei_hdr->length)) {
dev->mei_state = MEI_RESETING;
dev_dbg(&dev->pdev->dev, "write send enumeration request message to FW fail.\n");
mei_reset(dev, 1);
}
dev->init_clients_state = MEI_ENUM_CLIENTS_MESSAGE;
dev->init_clients_timer = INIT_CLIENTS_TIMEOUT;
return ;
}
/**
* allocate_me_clients_storage - allocates storage for me clients
*
* @dev: the device structure
*
* returns none.
*/
void allocate_me_clients_storage(struct mei_device *dev)
{
struct mei_me_client *clients;
int b;
/* count how many ME clients we have */
for_each_set_bit(b, dev->me_clients_map, MEI_CLIENTS_MAX)
dev->num_mei_me_clients++;
if (dev->num_mei_me_clients <= 0)
return ;
if (dev->me_clients != NULL) {
kfree(dev->me_clients);
dev->me_clients = NULL;
}
dev_dbg(&dev->pdev->dev, "memory allocation for ME clients size=%zd.\n",
dev->num_mei_me_clients * sizeof(struct mei_me_client));
/* allocate storage for ME clients representation */
clients = kcalloc(dev->num_mei_me_clients,
sizeof(struct mei_me_client), GFP_KERNEL);
if (!clients) {
dev_dbg(&dev->pdev->dev, "memory allocation for ME clients failed.\n");
dev->mei_state = MEI_RESETING;
mei_reset(dev, 1);
return ;
}
dev->me_clients = clients;
return ;
}
/**
* host_client_properties - reads properties for client
*
* @dev: the device structure
*
* returns none.
*/
void host_client_properties(struct mei_device *dev)
{
struct mei_msg_hdr *mei_header;
struct hbm_props_request *host_cli_req;
int b;
u8 client_num = dev->me_client_presentation_num;
b = dev->me_client_index;
b = find_next_bit(dev->me_clients_map, MEI_CLIENTS_MAX, b);
if (b < MEI_CLIENTS_MAX) {
dev->me_clients[client_num].client_id = b;
dev->me_clients[client_num].mei_flow_ctrl_creds = 0;
mei_header = (struct mei_msg_hdr *)&dev->wr_msg_buf[0];
mei_header->host_addr = 0;
mei_header->me_addr = 0;
mei_header->length = sizeof(struct hbm_props_request);
mei_header->msg_complete = 1;
mei_header->reserved = 0;
host_cli_req = (struct hbm_props_request *)&dev->wr_msg_buf[1];
memset(host_cli_req, 0, sizeof(struct hbm_props_request));
host_cli_req->cmd.cmd = HOST_CLIENT_PROPERTIES_REQ_CMD;
host_cli_req->address = b;
if (!mei_write_message(dev, mei_header,
(unsigned char *)host_cli_req,
mei_header->length)) {
dev->mei_state = MEI_RESETING;
dev_dbg(&dev->pdev->dev, "write send enumeration request message to FW fail.\n");
mei_reset(dev, 1);
return;
}
dev->init_clients_timer = INIT_CLIENTS_TIMEOUT;
dev->me_client_index = b;
return;
}
/*
* Clear Map for indicating now ME clients
* with associated host client
*/
bitmap_zero(dev->host_clients_map, MEI_CLIENTS_MAX);
dev->write_hang = -1;
dev->open_handle_count = 0;
bitmap_set(dev->host_clients_map, 0, 3);
dev->mei_state = MEI_ENABLED;
mei_wd_host_init(dev);
return;
}
/**
* mei_init_file_private - initializes private file structure.
*
* @priv: private file structure to be initialized
* @file: the file structure
*/
void mei_init_file_private(struct mei_cl *priv, struct mei_device *dev)
{
memset(priv, 0, sizeof(struct mei_cl));
init_waitqueue_head(&priv->wait);
init_waitqueue_head(&priv->rx_wait);
init_waitqueue_head(&priv->tx_wait);
INIT_LIST_HEAD(&priv->link);
priv->reading_state = MEI_IDLE;
priv->writing_state = MEI_IDLE;
priv->dev = dev;
}
int mei_find_me_client_index(const struct mei_device *dev, uuid_le cuuid)
{
int i, res = -1;
for (i = 0; i < dev->num_mei_me_clients; ++i)
if (uuid_le_cmp(cuuid,
dev->me_clients[i].props.protocol_name) == 0) {
res = i;
break;
}
return res;
}
/**
* mei_find_me_client_update_filext - searches for ME client guid
* sets client_id in mei_file_private if found
* @dev: the device structure
* @priv: private file structure to set client_id in
* @cguid: searched guid of ME client
* @client_id: id of host client to be set in file private structure
*
* returns ME client index
*/
u8 mei_find_me_client_update_filext(struct mei_device *dev, struct mei_cl *priv,
const uuid_le *cguid, u8 client_id)
{
int i;
if (!dev || !priv || !cguid)
return 0;
/* check for valid client id */
i = mei_find_me_client_index(dev, *cguid);
if (i >= 0) {
priv->me_client_id = dev->me_clients[i].client_id;
priv->state = MEI_FILE_CONNECTING;
priv->host_client_id = client_id;
list_add_tail(&priv->link, &dev->file_list);
return (u8)i;
}
return 0;
}
/**
* host_init_iamthif - mei initialization iamthif client.
*
* @dev: the device structure
*
*/
void host_init_iamthif(struct mei_device *dev)
{
u8 i;
unsigned char *msg_buf;
mei_init_file_private(&dev->iamthif_cl, dev);
dev->iamthif_cl.state = MEI_FILE_DISCONNECTED;
/* find ME amthi client */
i = mei_find_me_client_update_filext(dev, &dev->iamthif_cl,
&mei_amthi_guid, MEI_IAMTHIF_HOST_CLIENT_ID);
if (dev->iamthif_cl.state != MEI_FILE_CONNECTING) {
dev_dbg(&dev->pdev->dev, "failed to find iamthif client.\n");
return;
}
/* Do not render the system unusable when iamthif_mtu is not equal to
the value received from ME.
Assign iamthif_mtu to the value received from ME in order to solve the
hardware macro incompatibility. */
dev_dbg(&dev->pdev->dev, "[DEFAULT] IAMTHIF = %d\n", dev->iamthif_mtu);
dev->iamthif_mtu = dev->me_clients[i].props.max_msg_length;
dev_dbg(&dev->pdev->dev,
"IAMTHIF = %d\n",
dev->me_clients[i].props.max_msg_length);
kfree(dev->iamthif_msg_buf);
dev->iamthif_msg_buf = NULL;
/* allocate storage for ME message buffer */
msg_buf = kcalloc(dev->iamthif_mtu,
sizeof(unsigned char), GFP_KERNEL);
if (!msg_buf) {
dev_dbg(&dev->pdev->dev, "memory allocation for ME message buffer failed.\n");
return;
}
dev->iamthif_msg_buf = msg_buf;
if (!mei_connect(dev, &dev->iamthif_cl)) {
dev_dbg(&dev->pdev->dev, "Failed to connect to AMTHI client\n");
dev->iamthif_cl.state = MEI_FILE_DISCONNECTED;
dev->iamthif_cl.host_client_id = 0;
} else {
dev->iamthif_cl.timer_count = CONNECT_TIMEOUT;
}
}
/**
* mei_alloc_file_private - allocates a private file structure and sets it up.
* @file: the file structure
*
* returns The allocated file or NULL on failure
*/
struct mei_cl *mei_alloc_file_private(struct mei_device *dev)
{
struct mei_cl *priv;
priv = kmalloc(sizeof(struct mei_cl), GFP_KERNEL);
if (!priv)
return NULL;
mei_init_file_private(priv, dev);
return priv;
}
/**
* mei_disconnect_host_client - sends disconnect message to fw from host client.
*
* @dev: the device structure
* @cl: private data of the file object
*
* Locking: called under "dev->device_lock" lock
*
* returns 0 on success, <0 on failure.
*/
int mei_disconnect_host_client(struct mei_device *dev, struct mei_cl *cl)
{
int rets, err;
long timeout = 15; /* 15 seconds */
struct mei_cl_cb *cb;
if (!dev || !cl)
return -ENODEV;
if (cl->state != MEI_FILE_DISCONNECTING)
return 0;
cb = kzalloc(sizeof(struct mei_cl_cb), GFP_KERNEL);
if (!cb)
return -ENOMEM;
INIT_LIST_HEAD(&cb->cb_list);
cb->file_private = cl;
cb->major_file_operations = MEI_CLOSE;
if (dev->mei_host_buffer_is_empty) {
dev->mei_host_buffer_is_empty = 0;
if (mei_disconnect(dev, cl)) {
mdelay(10); /* Wait for hardware disconnection ready */
list_add_tail(&cb->cb_list,
&dev->ctrl_rd_list.mei_cb.cb_list);
} else {
rets = -ENODEV;
dev_dbg(&dev->pdev->dev, "failed to call mei_disconnect.\n");
goto free;
}
} else {
dev_dbg(&dev->pdev->dev, "add disconnect cb to control write list\n");
list_add_tail(&cb->cb_list,
&dev->ctrl_wr_list.mei_cb.cb_list);
}
mutex_unlock(&dev->device_lock);
err = wait_event_timeout(dev->wait_recvd_msg,
(MEI_FILE_DISCONNECTED == cl->state),
timeout * HZ);
mutex_lock(&dev->device_lock);
if (MEI_FILE_DISCONNECTED == cl->state) {
rets = 0;
dev_dbg(&dev->pdev->dev, "successfully disconnected from FW client.\n");
} else {
rets = -ENODEV;
if (MEI_FILE_DISCONNECTED != cl->state)
dev_dbg(&dev->pdev->dev, "wrong status client disconnect.\n");
if (err)
dev_dbg(&dev->pdev->dev,
"wait failed disconnect err=%08x\n",
err);
dev_dbg(&dev->pdev->dev, "failed to disconnect from FW client.\n");
}
mei_flush_list(&dev->ctrl_rd_list, cl);
mei_flush_list(&dev->ctrl_wr_list, cl);
free:
mei_free_cb_private(cb);
return rets;
}
/**
* mei_remove_client_from_file_list -
* removes file private data from device file list
*
* @dev: the device structure
* @host_client_id: host client id to be removed
*/
void mei_remove_client_from_file_list(struct mei_device *dev,
u8 host_client_id)
{
struct mei_cl *cl_pos = NULL;
struct mei_cl *cl_next = NULL;
list_for_each_entry_safe(cl_pos, cl_next, &dev->file_list, link) {
if (host_client_id == cl_pos->host_client_id) {
dev_dbg(&dev->pdev->dev, "remove host client = %d, ME client = %d\n",
cl_pos->host_client_id,
cl_pos->me_client_id);
list_del_init(&cl_pos->link);
break;
}
}
}
| gpl-2.0 |
hsarkanen/linux-imx6 | tools/perf/util/dwarf-aux.c | 2379 | 22398 | /*
* dwarf-aux.c : libdw auxiliary interfaces
*
* 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 <stdbool.h>
#include "util.h"
#include "debug.h"
#include "dwarf-aux.h"
/**
* cu_find_realpath - Find the realpath of the target file
* @cu_die: A DIE(dwarf information entry) of CU(compilation Unit)
* @fname: The tail filename of the target file
*
* Find the real(long) path of @fname in @cu_die.
*/
const char *cu_find_realpath(Dwarf_Die *cu_die, const char *fname)
{
Dwarf_Files *files;
size_t nfiles, i;
const char *src = NULL;
int ret;
if (!fname)
return NULL;
ret = dwarf_getsrcfiles(cu_die, &files, &nfiles);
if (ret != 0)
return NULL;
for (i = 0; i < nfiles; i++) {
src = dwarf_filesrc(files, i, NULL, NULL);
if (strtailcmp(src, fname) == 0)
break;
}
if (i == nfiles)
return NULL;
return src;
}
/**
* cu_get_comp_dir - Get the path of compilation directory
* @cu_die: a CU DIE
*
* Get the path of compilation directory of given @cu_die.
* Since this depends on DW_AT_comp_dir, older gcc will not
* embedded it. In that case, this returns NULL.
*/
const char *cu_get_comp_dir(Dwarf_Die *cu_die)
{
Dwarf_Attribute attr;
if (dwarf_attr(cu_die, DW_AT_comp_dir, &attr) == NULL)
return NULL;
return dwarf_formstring(&attr);
}
/**
* cu_find_lineinfo - Get a line number and file name for given address
* @cu_die: a CU DIE
* @addr: An address
* @fname: a pointer which returns the file name string
* @lineno: a pointer which returns the line number
*
* Find a line number and file name for @addr in @cu_die.
*/
int cu_find_lineinfo(Dwarf_Die *cu_die, unsigned long addr,
const char **fname, int *lineno)
{
Dwarf_Line *line;
Dwarf_Addr laddr;
line = dwarf_getsrc_die(cu_die, (Dwarf_Addr)addr);
if (line && dwarf_lineaddr(line, &laddr) == 0 &&
addr == (unsigned long)laddr && dwarf_lineno(line, lineno) == 0) {
*fname = dwarf_linesrc(line, NULL, NULL);
if (!*fname)
/* line number is useless without filename */
*lineno = 0;
}
return *lineno ?: -ENOENT;
}
static int __die_find_inline_cb(Dwarf_Die *die_mem, void *data);
/**
* cu_walk_functions_at - Walk on function DIEs at given address
* @cu_die: A CU DIE
* @addr: An address
* @callback: A callback which called with found DIEs
* @data: A user data
*
* Walk on function DIEs at given @addr in @cu_die. Passed DIEs
* should be subprogram or inlined-subroutines.
*/
int cu_walk_functions_at(Dwarf_Die *cu_die, Dwarf_Addr addr,
int (*callback)(Dwarf_Die *, void *), void *data)
{
Dwarf_Die die_mem;
Dwarf_Die *sc_die;
int ret = -ENOENT;
/* Inlined function could be recursive. Trace it until fail */
for (sc_die = die_find_realfunc(cu_die, addr, &die_mem);
sc_die != NULL;
sc_die = die_find_child(sc_die, __die_find_inline_cb, &addr,
&die_mem)) {
ret = callback(sc_die, data);
if (ret)
break;
}
return ret;
}
/**
* die_compare_name - Compare diename and tname
* @dw_die: a DIE
* @tname: a string of target name
*
* Compare the name of @dw_die and @tname. Return false if @dw_die has no name.
*/
bool die_compare_name(Dwarf_Die *dw_die, const char *tname)
{
const char *name;
name = dwarf_diename(dw_die);
return name ? (strcmp(tname, name) == 0) : false;
}
/**
* die_get_call_lineno - Get callsite line number of inline-function instance
* @in_die: a DIE of an inlined function instance
*
* Get call-site line number of @in_die. This means from where the inline
* function is called.
*/
int die_get_call_lineno(Dwarf_Die *in_die)
{
Dwarf_Attribute attr;
Dwarf_Word ret;
if (!dwarf_attr(in_die, DW_AT_call_line, &attr))
return -ENOENT;
dwarf_formudata(&attr, &ret);
return (int)ret;
}
/**
* die_get_type - Get type DIE
* @vr_die: a DIE of a variable
* @die_mem: where to store a type DIE
*
* Get a DIE of the type of given variable (@vr_die), and store
* it to die_mem. Return NULL if fails to get a type DIE.
*/
Dwarf_Die *die_get_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
{
Dwarf_Attribute attr;
if (dwarf_attr_integrate(vr_die, DW_AT_type, &attr) &&
dwarf_formref_die(&attr, die_mem))
return die_mem;
else
return NULL;
}
/* Get a type die, but skip qualifiers */
static Dwarf_Die *__die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
{
int tag;
do {
vr_die = die_get_type(vr_die, die_mem);
if (!vr_die)
break;
tag = dwarf_tag(vr_die);
} while (tag == DW_TAG_const_type ||
tag == DW_TAG_restrict_type ||
tag == DW_TAG_volatile_type ||
tag == DW_TAG_shared_type);
return vr_die;
}
/**
* die_get_real_type - Get a type die, but skip qualifiers and typedef
* @vr_die: a DIE of a variable
* @die_mem: where to store a type DIE
*
* Get a DIE of the type of given variable (@vr_die), and store
* it to die_mem. Return NULL if fails to get a type DIE.
* If the type is qualifiers (e.g. const) or typedef, this skips it
* and tries to find real type (structure or basic types, e.g. int).
*/
Dwarf_Die *die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
{
do {
vr_die = __die_get_real_type(vr_die, die_mem);
} while (vr_die && dwarf_tag(vr_die) == DW_TAG_typedef);
return vr_die;
}
/* Get attribute and translate it as a udata */
static int die_get_attr_udata(Dwarf_Die *tp_die, unsigned int attr_name,
Dwarf_Word *result)
{
Dwarf_Attribute attr;
if (dwarf_attr(tp_die, attr_name, &attr) == NULL ||
dwarf_formudata(&attr, result) != 0)
return -ENOENT;
return 0;
}
/* Get attribute and translate it as a sdata */
static int die_get_attr_sdata(Dwarf_Die *tp_die, unsigned int attr_name,
Dwarf_Sword *result)
{
Dwarf_Attribute attr;
if (dwarf_attr(tp_die, attr_name, &attr) == NULL ||
dwarf_formsdata(&attr, result) != 0)
return -ENOENT;
return 0;
}
/**
* die_is_signed_type - Check whether a type DIE is signed or not
* @tp_die: a DIE of a type
*
* Get the encoding of @tp_die and return true if the encoding
* is signed.
*/
bool die_is_signed_type(Dwarf_Die *tp_die)
{
Dwarf_Word ret;
if (die_get_attr_udata(tp_die, DW_AT_encoding, &ret))
return false;
return (ret == DW_ATE_signed_char || ret == DW_ATE_signed ||
ret == DW_ATE_signed_fixed);
}
/**
* die_get_data_member_location - Get the data-member offset
* @mb_die: a DIE of a member of a data structure
* @offs: The offset of the member in the data structure
*
* Get the offset of @mb_die in the data structure including @mb_die, and
* stores result offset to @offs. If any error occurs this returns errno.
*/
int die_get_data_member_location(Dwarf_Die *mb_die, Dwarf_Word *offs)
{
Dwarf_Attribute attr;
Dwarf_Op *expr;
size_t nexpr;
int ret;
if (dwarf_attr(mb_die, DW_AT_data_member_location, &attr) == NULL)
return -ENOENT;
if (dwarf_formudata(&attr, offs) != 0) {
/* DW_AT_data_member_location should be DW_OP_plus_uconst */
ret = dwarf_getlocation(&attr, &expr, &nexpr);
if (ret < 0 || nexpr == 0)
return -ENOENT;
if (expr[0].atom != DW_OP_plus_uconst || nexpr != 1) {
pr_debug("Unable to get offset:Unexpected OP %x (%zd)\n",
expr[0].atom, nexpr);
return -ENOTSUP;
}
*offs = (Dwarf_Word)expr[0].number;
}
return 0;
}
/* Get the call file index number in CU DIE */
static int die_get_call_fileno(Dwarf_Die *in_die)
{
Dwarf_Sword idx;
if (die_get_attr_sdata(in_die, DW_AT_call_file, &idx) == 0)
return (int)idx;
else
return -ENOENT;
}
/* Get the declared file index number in CU DIE */
static int die_get_decl_fileno(Dwarf_Die *pdie)
{
Dwarf_Sword idx;
if (die_get_attr_sdata(pdie, DW_AT_decl_file, &idx) == 0)
return (int)idx;
else
return -ENOENT;
}
/**
* die_get_call_file - Get callsite file name of inlined function instance
* @in_die: a DIE of an inlined function instance
*
* Get call-site file name of @in_die. This means from which file the inline
* function is called.
*/
const char *die_get_call_file(Dwarf_Die *in_die)
{
Dwarf_Die cu_die;
Dwarf_Files *files;
int idx;
idx = die_get_call_fileno(in_die);
if (idx < 0 || !dwarf_diecu(in_die, &cu_die, NULL, NULL) ||
dwarf_getsrcfiles(&cu_die, &files, NULL) != 0)
return NULL;
return dwarf_filesrc(files, idx, NULL, NULL);
}
/**
* die_find_child - Generic DIE search function in DIE tree
* @rt_die: a root DIE
* @callback: a callback function
* @data: a user data passed to the callback function
* @die_mem: a buffer for result DIE
*
* Trace DIE tree from @rt_die and call @callback for each child DIE.
* If @callback returns DIE_FIND_CB_END, this stores the DIE into
* @die_mem and returns it. If @callback returns DIE_FIND_CB_CONTINUE,
* this continues to trace the tree. Optionally, @callback can return
* DIE_FIND_CB_CHILD and DIE_FIND_CB_SIBLING, those means trace only
* the children and trace only the siblings respectively.
* Returns NULL if @callback can't find any appropriate DIE.
*/
Dwarf_Die *die_find_child(Dwarf_Die *rt_die,
int (*callback)(Dwarf_Die *, void *),
void *data, Dwarf_Die *die_mem)
{
Dwarf_Die child_die;
int ret;
ret = dwarf_child(rt_die, die_mem);
if (ret != 0)
return NULL;
do {
ret = callback(die_mem, data);
if (ret == DIE_FIND_CB_END)
return die_mem;
if ((ret & DIE_FIND_CB_CHILD) &&
die_find_child(die_mem, callback, data, &child_die)) {
memcpy(die_mem, &child_die, sizeof(Dwarf_Die));
return die_mem;
}
} while ((ret & DIE_FIND_CB_SIBLING) &&
dwarf_siblingof(die_mem, die_mem) == 0);
return NULL;
}
struct __addr_die_search_param {
Dwarf_Addr addr;
Dwarf_Die *die_mem;
};
/* die_find callback for non-inlined function search */
static int __die_search_func_cb(Dwarf_Die *fn_die, void *data)
{
struct __addr_die_search_param *ad = data;
if (dwarf_tag(fn_die) == DW_TAG_subprogram &&
dwarf_haspc(fn_die, ad->addr)) {
memcpy(ad->die_mem, fn_die, sizeof(Dwarf_Die));
return DWARF_CB_ABORT;
}
return DWARF_CB_OK;
}
/**
* die_find_realfunc - Search a non-inlined function at given address
* @cu_die: a CU DIE which including @addr
* @addr: target address
* @die_mem: a buffer for result DIE
*
* Search a non-inlined function DIE which includes @addr. Stores the
* DIE to @die_mem and returns it if found. Returns NULl if failed.
*/
Dwarf_Die *die_find_realfunc(Dwarf_Die *cu_die, Dwarf_Addr addr,
Dwarf_Die *die_mem)
{
struct __addr_die_search_param ad;
ad.addr = addr;
ad.die_mem = die_mem;
/* dwarf_getscopes can't find subprogram. */
if (!dwarf_getfuncs(cu_die, __die_search_func_cb, &ad, 0))
return NULL;
else
return die_mem;
}
/* die_find callback for inline function search */
static int __die_find_inline_cb(Dwarf_Die *die_mem, void *data)
{
Dwarf_Addr *addr = data;
if (dwarf_tag(die_mem) == DW_TAG_inlined_subroutine &&
dwarf_haspc(die_mem, *addr))
return DIE_FIND_CB_END;
return DIE_FIND_CB_CONTINUE;
}
/**
* die_find_inlinefunc - Search an inlined function at given address
* @cu_die: a CU DIE which including @addr
* @addr: target address
* @die_mem: a buffer for result DIE
*
* Search an inlined function DIE which includes @addr. Stores the
* DIE to @die_mem and returns it if found. Returns NULl if failed.
* If several inlined functions are expanded recursively, this trace
* it and returns deepest one.
*/
Dwarf_Die *die_find_inlinefunc(Dwarf_Die *sp_die, Dwarf_Addr addr,
Dwarf_Die *die_mem)
{
Dwarf_Die tmp_die;
sp_die = die_find_child(sp_die, __die_find_inline_cb, &addr, &tmp_die);
if (!sp_die)
return NULL;
/* Inlined function could be recursive. Trace it until fail */
while (sp_die) {
memcpy(die_mem, sp_die, sizeof(Dwarf_Die));
sp_die = die_find_child(sp_die, __die_find_inline_cb, &addr,
&tmp_die);
}
return die_mem;
}
struct __instance_walk_param {
void *addr;
int (*callback)(Dwarf_Die *, void *);
void *data;
int retval;
};
static int __die_walk_instances_cb(Dwarf_Die *inst, void *data)
{
struct __instance_walk_param *iwp = data;
Dwarf_Attribute attr_mem;
Dwarf_Die origin_mem;
Dwarf_Attribute *attr;
Dwarf_Die *origin;
int tmp;
attr = dwarf_attr(inst, DW_AT_abstract_origin, &attr_mem);
if (attr == NULL)
return DIE_FIND_CB_CONTINUE;
origin = dwarf_formref_die(attr, &origin_mem);
if (origin == NULL || origin->addr != iwp->addr)
return DIE_FIND_CB_CONTINUE;
/* Ignore redundant instances */
if (dwarf_tag(inst) == DW_TAG_inlined_subroutine) {
dwarf_decl_line(origin, &tmp);
if (die_get_call_lineno(inst) == tmp) {
tmp = die_get_decl_fileno(origin);
if (die_get_call_fileno(inst) == tmp)
return DIE_FIND_CB_CONTINUE;
}
}
iwp->retval = iwp->callback(inst, iwp->data);
return (iwp->retval) ? DIE_FIND_CB_END : DIE_FIND_CB_CONTINUE;
}
/**
* die_walk_instances - Walk on instances of given DIE
* @or_die: an abstract original DIE
* @callback: a callback function which is called with instance DIE
* @data: user data
*
* Walk on the instances of give @in_die. @in_die must be an inlined function
* declartion. This returns the return value of @callback if it returns
* non-zero value, or -ENOENT if there is no instance.
*/
int die_walk_instances(Dwarf_Die *or_die, int (*callback)(Dwarf_Die *, void *),
void *data)
{
Dwarf_Die cu_die;
Dwarf_Die die_mem;
struct __instance_walk_param iwp = {
.addr = or_die->addr,
.callback = callback,
.data = data,
.retval = -ENOENT,
};
if (dwarf_diecu(or_die, &cu_die, NULL, NULL) == NULL)
return -ENOENT;
die_find_child(&cu_die, __die_walk_instances_cb, &iwp, &die_mem);
return iwp.retval;
}
/* Line walker internal parameters */
struct __line_walk_param {
bool recursive;
line_walk_callback_t callback;
void *data;
int retval;
};
static int __die_walk_funclines_cb(Dwarf_Die *in_die, void *data)
{
struct __line_walk_param *lw = data;
Dwarf_Addr addr = 0;
const char *fname;
int lineno;
if (dwarf_tag(in_die) == DW_TAG_inlined_subroutine) {
fname = die_get_call_file(in_die);
lineno = die_get_call_lineno(in_die);
if (fname && lineno > 0 && dwarf_entrypc(in_die, &addr) == 0) {
lw->retval = lw->callback(fname, lineno, addr, lw->data);
if (lw->retval != 0)
return DIE_FIND_CB_END;
}
}
if (!lw->recursive)
/* Don't need to search recursively */
return DIE_FIND_CB_SIBLING;
if (addr) {
fname = dwarf_decl_file(in_die);
if (fname && dwarf_decl_line(in_die, &lineno) == 0) {
lw->retval = lw->callback(fname, lineno, addr, lw->data);
if (lw->retval != 0)
return DIE_FIND_CB_END;
}
}
/* Continue to search nested inlined function call-sites */
return DIE_FIND_CB_CONTINUE;
}
/* Walk on lines of blocks included in given DIE */
static int __die_walk_funclines(Dwarf_Die *sp_die, bool recursive,
line_walk_callback_t callback, void *data)
{
struct __line_walk_param lw = {
.recursive = recursive,
.callback = callback,
.data = data,
.retval = 0,
};
Dwarf_Die die_mem;
Dwarf_Addr addr;
const char *fname;
int lineno;
/* Handle function declaration line */
fname = dwarf_decl_file(sp_die);
if (fname && dwarf_decl_line(sp_die, &lineno) == 0 &&
dwarf_entrypc(sp_die, &addr) == 0) {
lw.retval = callback(fname, lineno, addr, data);
if (lw.retval != 0)
goto done;
}
die_find_child(sp_die, __die_walk_funclines_cb, &lw, &die_mem);
done:
return lw.retval;
}
static int __die_walk_culines_cb(Dwarf_Die *sp_die, void *data)
{
struct __line_walk_param *lw = data;
lw->retval = __die_walk_funclines(sp_die, true, lw->callback, lw->data);
if (lw->retval != 0)
return DWARF_CB_ABORT;
return DWARF_CB_OK;
}
/**
* die_walk_lines - Walk on lines inside given DIE
* @rt_die: a root DIE (CU, subprogram or inlined_subroutine)
* @callback: callback routine
* @data: user data
*
* Walk on all lines inside given @rt_die and call @callback on each line.
* If the @rt_die is a function, walk only on the lines inside the function,
* otherwise @rt_die must be a CU DIE.
* Note that this walks not only dwarf line list, but also function entries
* and inline call-site.
*/
int die_walk_lines(Dwarf_Die *rt_die, line_walk_callback_t callback, void *data)
{
Dwarf_Lines *lines;
Dwarf_Line *line;
Dwarf_Addr addr;
const char *fname;
int lineno, ret = 0;
Dwarf_Die die_mem, *cu_die;
size_t nlines, i;
/* Get the CU die */
if (dwarf_tag(rt_die) != DW_TAG_compile_unit)
cu_die = dwarf_diecu(rt_die, &die_mem, NULL, NULL);
else
cu_die = rt_die;
if (!cu_die) {
pr_debug2("Failed to get CU from given DIE.\n");
return -EINVAL;
}
/* Get lines list in the CU */
if (dwarf_getsrclines(cu_die, &lines, &nlines) != 0) {
pr_debug2("Failed to get source lines on this CU.\n");
return -ENOENT;
}
pr_debug2("Get %zd lines from this CU\n", nlines);
/* Walk on the lines on lines list */
for (i = 0; i < nlines; i++) {
line = dwarf_onesrcline(lines, i);
if (line == NULL ||
dwarf_lineno(line, &lineno) != 0 ||
dwarf_lineaddr(line, &addr) != 0) {
pr_debug2("Failed to get line info. "
"Possible error in debuginfo.\n");
continue;
}
/* Filter lines based on address */
if (rt_die != cu_die)
/*
* Address filtering
* The line is included in given function, and
* no inline block includes it.
*/
if (!dwarf_haspc(rt_die, addr) ||
die_find_inlinefunc(rt_die, addr, &die_mem))
continue;
/* Get source line */
fname = dwarf_linesrc(line, NULL, NULL);
ret = callback(fname, lineno, addr, data);
if (ret != 0)
return ret;
}
/*
* Dwarf lines doesn't include function declarations and inlined
* subroutines. We have to check functions list or given function.
*/
if (rt_die != cu_die)
/*
* Don't need walk functions recursively, because nested
* inlined functions don't have lines of the specified DIE.
*/
ret = __die_walk_funclines(rt_die, false, callback, data);
else {
struct __line_walk_param param = {
.callback = callback,
.data = data,
.retval = 0,
};
dwarf_getfuncs(cu_die, __die_walk_culines_cb, ¶m, 0);
ret = param.retval;
}
return ret;
}
struct __find_variable_param {
const char *name;
Dwarf_Addr addr;
};
static int __die_find_variable_cb(Dwarf_Die *die_mem, void *data)
{
struct __find_variable_param *fvp = data;
int tag;
tag = dwarf_tag(die_mem);
if ((tag == DW_TAG_formal_parameter ||
tag == DW_TAG_variable) &&
die_compare_name(die_mem, fvp->name))
return DIE_FIND_CB_END;
if (dwarf_haspc(die_mem, fvp->addr))
return DIE_FIND_CB_CONTINUE;
else
return DIE_FIND_CB_SIBLING;
}
/**
* die_find_variable_at - Find a given name variable at given address
* @sp_die: a function DIE
* @name: variable name
* @addr: address
* @die_mem: a buffer for result DIE
*
* Find a variable DIE called @name at @addr in @sp_die.
*/
Dwarf_Die *die_find_variable_at(Dwarf_Die *sp_die, const char *name,
Dwarf_Addr addr, Dwarf_Die *die_mem)
{
struct __find_variable_param fvp = { .name = name, .addr = addr};
return die_find_child(sp_die, __die_find_variable_cb, (void *)&fvp,
die_mem);
}
static int __die_find_member_cb(Dwarf_Die *die_mem, void *data)
{
const char *name = data;
if ((dwarf_tag(die_mem) == DW_TAG_member) &&
die_compare_name(die_mem, name))
return DIE_FIND_CB_END;
return DIE_FIND_CB_SIBLING;
}
/**
* die_find_member - Find a given name member in a data structure
* @st_die: a data structure type DIE
* @name: member name
* @die_mem: a buffer for result DIE
*
* Find a member DIE called @name in @st_die.
*/
Dwarf_Die *die_find_member(Dwarf_Die *st_die, const char *name,
Dwarf_Die *die_mem)
{
return die_find_child(st_die, __die_find_member_cb, (void *)name,
die_mem);
}
/**
* die_get_typename - Get the name of given variable DIE
* @vr_die: a variable DIE
* @buf: a buffer for result type name
* @len: a max-length of @buf
*
* Get the name of @vr_die and stores it to @buf. Return the actual length
* of type name if succeeded. Return -E2BIG if @len is not enough long, and
* Return -ENOENT if failed to find type name.
* Note that the result will stores typedef name if possible, and stores
* "*(function_type)" if the type is a function pointer.
*/
int die_get_typename(Dwarf_Die *vr_die, char *buf, int len)
{
Dwarf_Die type;
int tag, ret, ret2;
const char *tmp = "";
if (__die_get_real_type(vr_die, &type) == NULL)
return -ENOENT;
tag = dwarf_tag(&type);
if (tag == DW_TAG_array_type || tag == DW_TAG_pointer_type)
tmp = "*";
else if (tag == DW_TAG_subroutine_type) {
/* Function pointer */
ret = snprintf(buf, len, "(function_type)");
return (ret >= len) ? -E2BIG : ret;
} else {
if (!dwarf_diename(&type))
return -ENOENT;
if (tag == DW_TAG_union_type)
tmp = "union ";
else if (tag == DW_TAG_structure_type)
tmp = "struct ";
else if (tag == DW_TAG_enumeration_type)
tmp = "enum ";
/* Write a base name */
ret = snprintf(buf, len, "%s%s", tmp, dwarf_diename(&type));
return (ret >= len) ? -E2BIG : ret;
}
ret = die_get_typename(&type, buf, len);
if (ret > 0) {
ret2 = snprintf(buf + ret, len - ret, "%s", tmp);
ret = (ret2 >= len - ret) ? -E2BIG : ret2 + ret;
}
return ret;
}
/**
* die_get_varname - Get the name and type of given variable DIE
* @vr_die: a variable DIE
* @buf: a buffer for type and variable name
* @len: the max-length of @buf
*
* Get the name and type of @vr_die and stores it in @buf as "type\tname".
*/
int die_get_varname(Dwarf_Die *vr_die, char *buf, int len)
{
int ret, ret2;
ret = die_get_typename(vr_die, buf, len);
if (ret < 0) {
pr_debug("Failed to get type, make it unknown.\n");
ret = snprintf(buf, len, "(unknown_type)");
}
if (ret > 0) {
ret2 = snprintf(buf + ret, len - ret, "\t%s",
dwarf_diename(vr_die));
ret = (ret2 >= len - ret) ? -E2BIG : ret2 + ret;
}
return ret;
}
| gpl-2.0 |
thesawolf/android_kernel_allwinner_a10 | drivers/ata/acard-ahci.c | 2379 | 13305 |
/*
* acard-ahci.c - ACard AHCI SATA support
*
* Maintained by: Jeff Garzik <jgarzik@pobox.com>
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2010 Red Hat, Inc.
*
*
* 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 this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* AHCI hardware documentation:
* http://www.intel.com/technology/serialata/pdf/rev1_0.pdf
* http://www.intel.com/technology/serialata/pdf/rev1_1.pdf
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/device.h>
#include <linux/dmi.h>
#include <linux/gfp.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
#include <linux/libata.h>
#include "ahci.h"
#define DRV_NAME "acard-ahci"
#define DRV_VERSION "1.0"
/*
Received FIS structure limited to 80h.
*/
#define ACARD_AHCI_RX_FIS_SZ 128
enum {
AHCI_PCI_BAR = 5,
};
enum board_ids {
board_acard_ahci,
};
struct acard_sg {
__le32 addr;
__le32 addr_hi;
__le32 reserved;
__le32 size; /* bit 31 (EOT) max==0x10000 (64k) */
};
static void acard_ahci_qc_prep(struct ata_queued_cmd *qc);
static bool acard_ahci_qc_fill_rtf(struct ata_queued_cmd *qc);
static int acard_ahci_port_start(struct ata_port *ap);
static int acard_ahci_init_one(struct pci_dev *pdev, const struct pci_device_id *ent);
#ifdef CONFIG_PM
static int acard_ahci_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg);
static int acard_ahci_pci_device_resume(struct pci_dev *pdev);
#endif
static struct scsi_host_template acard_ahci_sht = {
AHCI_SHT("acard-ahci"),
};
static struct ata_port_operations acard_ops = {
.inherits = &ahci_ops,
.qc_prep = acard_ahci_qc_prep,
.qc_fill_rtf = acard_ahci_qc_fill_rtf,
.port_start = acard_ahci_port_start,
};
#define AHCI_HFLAGS(flags) .private_data = (void *)(flags)
static const struct ata_port_info acard_ahci_port_info[] = {
[board_acard_ahci] =
{
AHCI_HFLAGS (AHCI_HFLAG_NO_NCQ),
.flags = AHCI_FLAG_COMMON,
.pio_mask = ATA_PIO4,
.udma_mask = ATA_UDMA6,
.port_ops = &acard_ops,
},
};
static const struct pci_device_id acard_ahci_pci_tbl[] = {
/* ACard */
{ PCI_VDEVICE(ARTOP, 0x000d), board_acard_ahci }, /* ATP8620 */
{ } /* terminate list */
};
static struct pci_driver acard_ahci_pci_driver = {
.name = DRV_NAME,
.id_table = acard_ahci_pci_tbl,
.probe = acard_ahci_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = acard_ahci_pci_device_suspend,
.resume = acard_ahci_pci_device_resume,
#endif
};
#ifdef CONFIG_PM
static int acard_ahci_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg)
{
struct ata_host *host = dev_get_drvdata(&pdev->dev);
struct ahci_host_priv *hpriv = host->private_data;
void __iomem *mmio = hpriv->mmio;
u32 ctl;
if (mesg.event & PM_EVENT_SUSPEND &&
hpriv->flags & AHCI_HFLAG_NO_SUSPEND) {
dev_printk(KERN_ERR, &pdev->dev,
"BIOS update required for suspend/resume\n");
return -EIO;
}
if (mesg.event & PM_EVENT_SLEEP) {
/* AHCI spec rev1.1 section 8.3.3:
* Software must disable interrupts prior to requesting a
* transition of the HBA to D3 state.
*/
ctl = readl(mmio + HOST_CTL);
ctl &= ~HOST_IRQ_EN;
writel(ctl, mmio + HOST_CTL);
readl(mmio + HOST_CTL); /* flush */
}
return ata_pci_device_suspend(pdev, mesg);
}
static int acard_ahci_pci_device_resume(struct pci_dev *pdev)
{
struct ata_host *host = dev_get_drvdata(&pdev->dev);
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
if (pdev->dev.power.power_state.event == PM_EVENT_SUSPEND) {
rc = ahci_reset_controller(host);
if (rc)
return rc;
ahci_init_controller(host);
}
ata_host_resume(host);
return 0;
}
#endif
static int acard_ahci_configure_dma_masks(struct pci_dev *pdev, int using_dac)
{
int rc;
if (using_dac &&
!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (rc) {
rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc) {
dev_printk(KERN_ERR, &pdev->dev,
"64-bit DMA enable failed\n");
return rc;
}
}
} else {
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc) {
dev_printk(KERN_ERR, &pdev->dev,
"32-bit DMA enable failed\n");
return rc;
}
rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc) {
dev_printk(KERN_ERR, &pdev->dev,
"32-bit consistent DMA enable failed\n");
return rc;
}
}
return 0;
}
static void acard_ahci_pci_print_info(struct ata_host *host)
{
struct pci_dev *pdev = to_pci_dev(host->dev);
u16 cc;
const char *scc_s;
pci_read_config_word(pdev, 0x0a, &cc);
if (cc == PCI_CLASS_STORAGE_IDE)
scc_s = "IDE";
else if (cc == PCI_CLASS_STORAGE_SATA)
scc_s = "SATA";
else if (cc == PCI_CLASS_STORAGE_RAID)
scc_s = "RAID";
else
scc_s = "unknown";
ahci_print_info(host, scc_s);
}
static unsigned int acard_ahci_fill_sg(struct ata_queued_cmd *qc, void *cmd_tbl)
{
struct scatterlist *sg;
struct acard_sg *acard_sg = cmd_tbl + AHCI_CMD_TBL_HDR_SZ;
unsigned int si, last_si = 0;
VPRINTK("ENTER\n");
/*
* Next, the S/G list.
*/
for_each_sg(qc->sg, sg, qc->n_elem, si) {
dma_addr_t addr = sg_dma_address(sg);
u32 sg_len = sg_dma_len(sg);
/*
* ACard note:
* We must set an end-of-table (EOT) bit,
* and the segment cannot exceed 64k (0x10000)
*/
acard_sg[si].addr = cpu_to_le32(addr & 0xffffffff);
acard_sg[si].addr_hi = cpu_to_le32((addr >> 16) >> 16);
acard_sg[si].size = cpu_to_le32(sg_len);
last_si = si;
}
acard_sg[last_si].size |= cpu_to_le32(1 << 31); /* set EOT */
return si;
}
static void acard_ahci_qc_prep(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ahci_port_priv *pp = ap->private_data;
int is_atapi = ata_is_atapi(qc->tf.protocol);
void *cmd_tbl;
u32 opts;
const u32 cmd_fis_len = 5; /* five dwords */
unsigned int n_elem;
/*
* Fill in command table information. First, the header,
* a SATA Register - Host to Device command FIS.
*/
cmd_tbl = pp->cmd_tbl + qc->tag * AHCI_CMD_TBL_SZ;
ata_tf_to_fis(&qc->tf, qc->dev->link->pmp, 1, cmd_tbl);
if (is_atapi) {
memset(cmd_tbl + AHCI_CMD_TBL_CDB, 0, 32);
memcpy(cmd_tbl + AHCI_CMD_TBL_CDB, qc->cdb, qc->dev->cdb_len);
}
n_elem = 0;
if (qc->flags & ATA_QCFLAG_DMAMAP)
n_elem = acard_ahci_fill_sg(qc, cmd_tbl);
/*
* Fill in command slot information.
*
* ACard note: prd table length not filled in
*/
opts = cmd_fis_len | (qc->dev->link->pmp << 12);
if (qc->tf.flags & ATA_TFLAG_WRITE)
opts |= AHCI_CMD_WRITE;
if (is_atapi)
opts |= AHCI_CMD_ATAPI | AHCI_CMD_PREFETCH;
ahci_fill_cmd_slot(pp, qc->tag, opts);
}
static bool acard_ahci_qc_fill_rtf(struct ata_queued_cmd *qc)
{
struct ahci_port_priv *pp = qc->ap->private_data;
u8 *rx_fis = pp->rx_fis;
if (pp->fbs_enabled)
rx_fis += qc->dev->link->pmp * ACARD_AHCI_RX_FIS_SZ;
/*
* After a successful execution of an ATA PIO data-in command,
* the device doesn't send D2H Reg FIS to update the TF and
* the host should take TF and E_Status from the preceding PIO
* Setup FIS.
*/
if (qc->tf.protocol == ATA_PROT_PIO && qc->dma_dir == DMA_FROM_DEVICE &&
!(qc->flags & ATA_QCFLAG_FAILED)) {
ata_tf_from_fis(rx_fis + RX_FIS_PIO_SETUP, &qc->result_tf);
qc->result_tf.command = (rx_fis + RX_FIS_PIO_SETUP)[15];
} else
ata_tf_from_fis(rx_fis + RX_FIS_D2H_REG, &qc->result_tf);
return true;
}
static int acard_ahci_port_start(struct ata_port *ap)
{
struct ahci_host_priv *hpriv = ap->host->private_data;
struct device *dev = ap->host->dev;
struct ahci_port_priv *pp;
void *mem;
dma_addr_t mem_dma;
size_t dma_sz, rx_fis_sz;
pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
if (!pp)
return -ENOMEM;
/* check FBS capability */
if ((hpriv->cap & HOST_CAP_FBS) && sata_pmp_supported(ap)) {
void __iomem *port_mmio = ahci_port_base(ap);
u32 cmd = readl(port_mmio + PORT_CMD);
if (cmd & PORT_CMD_FBSCP)
pp->fbs_supported = true;
else if (hpriv->flags & AHCI_HFLAG_YES_FBS) {
dev_printk(KERN_INFO, dev,
"port %d can do FBS, forcing FBSCP\n",
ap->port_no);
pp->fbs_supported = true;
} else
dev_printk(KERN_WARNING, dev,
"port %d is not capable of FBS\n",
ap->port_no);
}
if (pp->fbs_supported) {
dma_sz = AHCI_PORT_PRIV_FBS_DMA_SZ;
rx_fis_sz = ACARD_AHCI_RX_FIS_SZ * 16;
} else {
dma_sz = AHCI_PORT_PRIV_DMA_SZ;
rx_fis_sz = ACARD_AHCI_RX_FIS_SZ;
}
mem = dmam_alloc_coherent(dev, dma_sz, &mem_dma, GFP_KERNEL);
if (!mem)
return -ENOMEM;
memset(mem, 0, dma_sz);
/*
* First item in chunk of DMA memory: 32-slot command table,
* 32 bytes each in size
*/
pp->cmd_slot = mem;
pp->cmd_slot_dma = mem_dma;
mem += AHCI_CMD_SLOT_SZ;
mem_dma += AHCI_CMD_SLOT_SZ;
/*
* Second item: Received-FIS area
*/
pp->rx_fis = mem;
pp->rx_fis_dma = mem_dma;
mem += rx_fis_sz;
mem_dma += rx_fis_sz;
/*
* Third item: data area for storing a single command
* and its scatter-gather table
*/
pp->cmd_tbl = mem;
pp->cmd_tbl_dma = mem_dma;
/*
* Save off initial list of interrupts to be enabled.
* This could be changed later
*/
pp->intr_mask = DEF_PORT_IRQ;
ap->private_data = pp;
/* engage engines, captain */
return ahci_port_resume(ap);
}
static int acard_ahci_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
static int printed_version;
unsigned int board_id = ent->driver_data;
struct ata_port_info pi = acard_ahci_port_info[board_id];
const struct ata_port_info *ppi[] = { &pi, NULL };
struct device *dev = &pdev->dev;
struct ahci_host_priv *hpriv;
struct ata_host *host;
int n_ports, i, rc;
VPRINTK("ENTER\n");
WARN_ON((int)ATA_MAX_QUEUE > AHCI_MAX_CMDS);
if (!printed_version++)
dev_printk(KERN_DEBUG, &pdev->dev, "version " DRV_VERSION "\n");
/* acquire resources */
rc = pcim_enable_device(pdev);
if (rc)
return rc;
/* AHCI controllers often implement SFF compatible interface.
* Grab all PCI BARs just in case.
*/
rc = pcim_iomap_regions_request_all(pdev, 1 << AHCI_PCI_BAR, DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(pdev);
if (rc)
return rc;
hpriv = devm_kzalloc(dev, sizeof(*hpriv), GFP_KERNEL);
if (!hpriv)
return -ENOMEM;
hpriv->flags |= (unsigned long)pi.private_data;
if (!(hpriv->flags & AHCI_HFLAG_NO_MSI))
pci_enable_msi(pdev);
hpriv->mmio = pcim_iomap_table(pdev)[AHCI_PCI_BAR];
/* save initial config */
ahci_save_initial_config(&pdev->dev, hpriv, 0, 0);
/* prepare host */
if (hpriv->cap & HOST_CAP_NCQ)
pi.flags |= ATA_FLAG_NCQ;
if (hpriv->cap & HOST_CAP_PMP)
pi.flags |= ATA_FLAG_PMP;
ahci_set_em_messages(hpriv, &pi);
/* CAP.NP sometimes indicate the index of the last enabled
* port, at other times, that of the last possible port, so
* determining the maximum port number requires looking at
* both CAP.NP and port_map.
*/
n_ports = max(ahci_nr_ports(hpriv->cap), fls(hpriv->port_map));
host = ata_host_alloc_pinfo(&pdev->dev, ppi, n_ports);
if (!host)
return -ENOMEM;
host->private_data = hpriv;
if (!(hpriv->cap & HOST_CAP_SSS) || ahci_ignore_sss)
host->flags |= ATA_HOST_PARALLEL_SCAN;
else
printk(KERN_INFO "ahci: SSS flag set, parallel bus scan disabled\n");
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
ata_port_pbar_desc(ap, AHCI_PCI_BAR, -1, "abar");
ata_port_pbar_desc(ap, AHCI_PCI_BAR,
0x100 + ap->port_no * 0x80, "port");
/* set initial link pm policy */
/*
ap->pm_policy = NOT_AVAILABLE;
*/
/* disabled/not-implemented port */
if (!(hpriv->port_map & (1 << i)))
ap->ops = &ata_dummy_port_ops;
}
/* initialize adapter */
rc = acard_ahci_configure_dma_masks(pdev, hpriv->cap & HOST_CAP_64);
if (rc)
return rc;
rc = ahci_reset_controller(host);
if (rc)
return rc;
ahci_init_controller(host);
acard_ahci_pci_print_info(host);
pci_set_master(pdev);
return ata_host_activate(host, pdev->irq, ahci_interrupt, IRQF_SHARED,
&acard_ahci_sht);
}
static int __init acard_ahci_init(void)
{
return pci_register_driver(&acard_ahci_pci_driver);
}
static void __exit acard_ahci_exit(void)
{
pci_unregister_driver(&acard_ahci_pci_driver);
}
MODULE_AUTHOR("Jeff Garzik");
MODULE_DESCRIPTION("ACard AHCI SATA low-level driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, acard_ahci_pci_tbl);
MODULE_VERSION(DRV_VERSION);
module_init(acard_ahci_init);
module_exit(acard_ahci_exit);
| gpl-2.0 |
djvoleur/S6_UniKernel | arch/mips/mti-sead3/sead3-ehci.c | 3147 | 1096 | /*
* 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.
*
* Copyright (C) 2012 MIPS Technologies, Inc. All rights reserved.
*/
#include <linux/module.h>
#include <linux/irq.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
struct resource ehci_resources[] = {
{
.start = 0x1b200000,
.end = 0x1b200fff,
.flags = IORESOURCE_MEM
},
{
.start = MIPS_CPU_IRQ_BASE + 2,
.flags = IORESOURCE_IRQ
}
};
u64 sead3_usbdev_dma_mask = DMA_BIT_MASK(32);
static struct platform_device ehci_device = {
.name = "sead3-ehci",
.id = 0,
.dev = {
.dma_mask = &sead3_usbdev_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32)
},
.num_resources = ARRAY_SIZE(ehci_resources),
.resource = ehci_resources
};
static int __init ehci_init(void)
{
return platform_device_register(&ehci_device);
}
module_init(ehci_init);
MODULE_AUTHOR("Chris Dearman <chris@mips.com>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("EHCI probe driver for SEAD3");
| gpl-2.0 |
p2pjack/furnace_kernel_lge_mako | sound/drivers/dummy.c | 4939 | 31003 | /*
* Dummy soundcard
* 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/platform_device.h>
#include <linux/jiffies.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/hrtimer.h>
#include <linux/math64.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/tlv.h>
#include <sound/pcm.h>
#include <sound/rawmidi.h>
#include <sound/info.h>
#include <sound/initval.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_DESCRIPTION("Dummy soundcard (/dev/null)");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{ALSA,Dummy soundcard}}");
#define MAX_PCM_DEVICES 4
#define MAX_PCM_SUBSTREAMS 128
#define MAX_MIDI_DEVICES 2
/* defaults */
#define MAX_BUFFER_SIZE (64*1024)
#define MIN_PERIOD_SIZE 64
#define MAX_PERIOD_SIZE MAX_BUFFER_SIZE
#define USE_FORMATS (SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE)
#define USE_RATE SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000
#define USE_RATE_MIN 5500
#define USE_RATE_MAX 48000
#define USE_CHANNELS_MIN 1
#define USE_CHANNELS_MAX 2
#define USE_PERIODS_MIN 1
#define USE_PERIODS_MAX 1024
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = {1, [1 ... (SNDRV_CARDS - 1)] = 0};
static char *model[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = NULL};
static int pcm_devs[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
static int pcm_substreams[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 8};
//static int midi_devs[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 2};
#ifdef CONFIG_HIGH_RES_TIMERS
static bool hrtimer = 1;
#endif
static bool fake_buffer = 1;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for dummy soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for dummy soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable this dummy soundcard.");
module_param_array(model, charp, NULL, 0444);
MODULE_PARM_DESC(model, "Soundcard model.");
module_param_array(pcm_devs, int, NULL, 0444);
MODULE_PARM_DESC(pcm_devs, "PCM devices # (0-4) for dummy driver.");
module_param_array(pcm_substreams, int, NULL, 0444);
MODULE_PARM_DESC(pcm_substreams, "PCM substreams # (1-128) for dummy driver.");
//module_param_array(midi_devs, int, NULL, 0444);
//MODULE_PARM_DESC(midi_devs, "MIDI devices # (0-2) for dummy driver.");
module_param(fake_buffer, bool, 0444);
MODULE_PARM_DESC(fake_buffer, "Fake buffer allocations.");
#ifdef CONFIG_HIGH_RES_TIMERS
module_param(hrtimer, bool, 0644);
MODULE_PARM_DESC(hrtimer, "Use hrtimer as the timer source.");
#endif
static struct platform_device *devices[SNDRV_CARDS];
#define MIXER_ADDR_MASTER 0
#define MIXER_ADDR_LINE 1
#define MIXER_ADDR_MIC 2
#define MIXER_ADDR_SYNTH 3
#define MIXER_ADDR_CD 4
#define MIXER_ADDR_LAST 4
struct dummy_timer_ops {
int (*create)(struct snd_pcm_substream *);
void (*free)(struct snd_pcm_substream *);
int (*prepare)(struct snd_pcm_substream *);
int (*start)(struct snd_pcm_substream *);
int (*stop)(struct snd_pcm_substream *);
snd_pcm_uframes_t (*pointer)(struct snd_pcm_substream *);
};
struct dummy_model {
const char *name;
int (*playback_constraints)(struct snd_pcm_runtime *runtime);
int (*capture_constraints)(struct snd_pcm_runtime *runtime);
u64 formats;
size_t buffer_bytes_max;
size_t period_bytes_min;
size_t period_bytes_max;
unsigned int periods_min;
unsigned int periods_max;
unsigned int rates;
unsigned int rate_min;
unsigned int rate_max;
unsigned int channels_min;
unsigned int channels_max;
};
struct snd_dummy {
struct snd_card *card;
struct dummy_model *model;
struct snd_pcm *pcm;
struct snd_pcm_hardware pcm_hw;
spinlock_t mixer_lock;
int mixer_volume[MIXER_ADDR_LAST+1][2];
int capture_source[MIXER_ADDR_LAST+1][2];
const struct dummy_timer_ops *timer_ops;
};
/*
* card models
*/
static int emu10k1_playback_constraints(struct snd_pcm_runtime *runtime)
{
int err;
err = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0)
return err;
err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 256, UINT_MAX);
if (err < 0)
return err;
return 0;
}
struct dummy_model model_emu10k1 = {
.name = "emu10k1",
.playback_constraints = emu10k1_playback_constraints,
.buffer_bytes_max = 128 * 1024,
};
struct dummy_model model_rme9652 = {
.name = "rme9652",
.buffer_bytes_max = 26 * 64 * 1024,
.formats = SNDRV_PCM_FMTBIT_S32_LE,
.channels_min = 26,
.channels_max = 26,
.periods_min = 2,
.periods_max = 2,
};
struct dummy_model model_ice1712 = {
.name = "ice1712",
.buffer_bytes_max = 256 * 1024,
.formats = SNDRV_PCM_FMTBIT_S32_LE,
.channels_min = 10,
.channels_max = 10,
.periods_min = 1,
.periods_max = 1024,
};
struct dummy_model model_uda1341 = {
.name = "uda1341",
.buffer_bytes_max = 16380,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 2,
.channels_max = 2,
.periods_min = 2,
.periods_max = 255,
};
struct dummy_model model_ac97 = {
.name = "ac97",
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_48000,
.rate_min = 48000,
.rate_max = 48000,
};
struct dummy_model model_ca0106 = {
.name = "ca0106",
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.buffer_bytes_max = ((65536-64)*8),
.period_bytes_max = (65536-64),
.periods_min = 2,
.periods_max = 8,
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_48000|SNDRV_PCM_RATE_96000|SNDRV_PCM_RATE_192000,
.rate_min = 48000,
.rate_max = 192000,
};
struct dummy_model *dummy_models[] = {
&model_emu10k1,
&model_rme9652,
&model_ice1712,
&model_uda1341,
&model_ac97,
&model_ca0106,
NULL
};
/*
* system timer interface
*/
struct dummy_systimer_pcm {
spinlock_t lock;
struct timer_list timer;
unsigned long base_time;
unsigned int frac_pos; /* fractional sample position (based HZ) */
unsigned int frac_period_rest;
unsigned int frac_buffer_size; /* buffer_size * HZ */
unsigned int frac_period_size; /* period_size * HZ */
unsigned int rate;
int elapsed;
struct snd_pcm_substream *substream;
};
static void dummy_systimer_rearm(struct dummy_systimer_pcm *dpcm)
{
dpcm->timer.expires = jiffies +
(dpcm->frac_period_rest + dpcm->rate - 1) / dpcm->rate;
add_timer(&dpcm->timer);
}
static void dummy_systimer_update(struct dummy_systimer_pcm *dpcm)
{
unsigned long delta;
delta = jiffies - dpcm->base_time;
if (!delta)
return;
dpcm->base_time += delta;
delta *= dpcm->rate;
dpcm->frac_pos += delta;
while (dpcm->frac_pos >= dpcm->frac_buffer_size)
dpcm->frac_pos -= dpcm->frac_buffer_size;
while (dpcm->frac_period_rest <= delta) {
dpcm->elapsed++;
dpcm->frac_period_rest += dpcm->frac_period_size;
}
dpcm->frac_period_rest -= delta;
}
static int dummy_systimer_start(struct snd_pcm_substream *substream)
{
struct dummy_systimer_pcm *dpcm = substream->runtime->private_data;
spin_lock(&dpcm->lock);
dpcm->base_time = jiffies;
dummy_systimer_rearm(dpcm);
spin_unlock(&dpcm->lock);
return 0;
}
static int dummy_systimer_stop(struct snd_pcm_substream *substream)
{
struct dummy_systimer_pcm *dpcm = substream->runtime->private_data;
spin_lock(&dpcm->lock);
del_timer(&dpcm->timer);
spin_unlock(&dpcm->lock);
return 0;
}
static int dummy_systimer_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct dummy_systimer_pcm *dpcm = runtime->private_data;
dpcm->frac_pos = 0;
dpcm->rate = runtime->rate;
dpcm->frac_buffer_size = runtime->buffer_size * HZ;
dpcm->frac_period_size = runtime->period_size * HZ;
dpcm->frac_period_rest = dpcm->frac_period_size;
dpcm->elapsed = 0;
return 0;
}
static void dummy_systimer_callback(unsigned long data)
{
struct dummy_systimer_pcm *dpcm = (struct dummy_systimer_pcm *)data;
unsigned long flags;
int elapsed = 0;
spin_lock_irqsave(&dpcm->lock, flags);
dummy_systimer_update(dpcm);
dummy_systimer_rearm(dpcm);
elapsed = dpcm->elapsed;
dpcm->elapsed = 0;
spin_unlock_irqrestore(&dpcm->lock, flags);
if (elapsed)
snd_pcm_period_elapsed(dpcm->substream);
}
static snd_pcm_uframes_t
dummy_systimer_pointer(struct snd_pcm_substream *substream)
{
struct dummy_systimer_pcm *dpcm = substream->runtime->private_data;
snd_pcm_uframes_t pos;
spin_lock(&dpcm->lock);
dummy_systimer_update(dpcm);
pos = dpcm->frac_pos / HZ;
spin_unlock(&dpcm->lock);
return pos;
}
static int dummy_systimer_create(struct snd_pcm_substream *substream)
{
struct dummy_systimer_pcm *dpcm;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (!dpcm)
return -ENOMEM;
substream->runtime->private_data = dpcm;
init_timer(&dpcm->timer);
dpcm->timer.data = (unsigned long) dpcm;
dpcm->timer.function = dummy_systimer_callback;
spin_lock_init(&dpcm->lock);
dpcm->substream = substream;
return 0;
}
static void dummy_systimer_free(struct snd_pcm_substream *substream)
{
kfree(substream->runtime->private_data);
}
static struct dummy_timer_ops dummy_systimer_ops = {
.create = dummy_systimer_create,
.free = dummy_systimer_free,
.prepare = dummy_systimer_prepare,
.start = dummy_systimer_start,
.stop = dummy_systimer_stop,
.pointer = dummy_systimer_pointer,
};
#ifdef CONFIG_HIGH_RES_TIMERS
/*
* hrtimer interface
*/
struct dummy_hrtimer_pcm {
ktime_t base_time;
ktime_t period_time;
atomic_t running;
struct hrtimer timer;
struct tasklet_struct tasklet;
struct snd_pcm_substream *substream;
};
static void dummy_hrtimer_pcm_elapsed(unsigned long priv)
{
struct dummy_hrtimer_pcm *dpcm = (struct dummy_hrtimer_pcm *)priv;
if (atomic_read(&dpcm->running))
snd_pcm_period_elapsed(dpcm->substream);
}
static enum hrtimer_restart dummy_hrtimer_callback(struct hrtimer *timer)
{
struct dummy_hrtimer_pcm *dpcm;
dpcm = container_of(timer, struct dummy_hrtimer_pcm, timer);
if (!atomic_read(&dpcm->running))
return HRTIMER_NORESTART;
tasklet_schedule(&dpcm->tasklet);
hrtimer_forward_now(timer, dpcm->period_time);
return HRTIMER_RESTART;
}
static int dummy_hrtimer_start(struct snd_pcm_substream *substream)
{
struct dummy_hrtimer_pcm *dpcm = substream->runtime->private_data;
dpcm->base_time = hrtimer_cb_get_time(&dpcm->timer);
hrtimer_start(&dpcm->timer, dpcm->period_time, HRTIMER_MODE_REL);
atomic_set(&dpcm->running, 1);
return 0;
}
static int dummy_hrtimer_stop(struct snd_pcm_substream *substream)
{
struct dummy_hrtimer_pcm *dpcm = substream->runtime->private_data;
atomic_set(&dpcm->running, 0);
hrtimer_cancel(&dpcm->timer);
return 0;
}
static inline void dummy_hrtimer_sync(struct dummy_hrtimer_pcm *dpcm)
{
tasklet_kill(&dpcm->tasklet);
}
static snd_pcm_uframes_t
dummy_hrtimer_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct dummy_hrtimer_pcm *dpcm = runtime->private_data;
u64 delta;
u32 pos;
delta = ktime_us_delta(hrtimer_cb_get_time(&dpcm->timer),
dpcm->base_time);
delta = div_u64(delta * runtime->rate + 999999, 1000000);
div_u64_rem(delta, runtime->buffer_size, &pos);
return pos;
}
static int dummy_hrtimer_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct dummy_hrtimer_pcm *dpcm = runtime->private_data;
unsigned int period, rate;
long sec;
unsigned long nsecs;
dummy_hrtimer_sync(dpcm);
period = runtime->period_size;
rate = runtime->rate;
sec = period / rate;
period %= rate;
nsecs = div_u64((u64)period * 1000000000UL + rate - 1, rate);
dpcm->period_time = ktime_set(sec, nsecs);
return 0;
}
static int dummy_hrtimer_create(struct snd_pcm_substream *substream)
{
struct dummy_hrtimer_pcm *dpcm;
dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
if (!dpcm)
return -ENOMEM;
substream->runtime->private_data = dpcm;
hrtimer_init(&dpcm->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
dpcm->timer.function = dummy_hrtimer_callback;
dpcm->substream = substream;
atomic_set(&dpcm->running, 0);
tasklet_init(&dpcm->tasklet, dummy_hrtimer_pcm_elapsed,
(unsigned long)dpcm);
return 0;
}
static void dummy_hrtimer_free(struct snd_pcm_substream *substream)
{
struct dummy_hrtimer_pcm *dpcm = substream->runtime->private_data;
dummy_hrtimer_sync(dpcm);
kfree(dpcm);
}
static struct dummy_timer_ops dummy_hrtimer_ops = {
.create = dummy_hrtimer_create,
.free = dummy_hrtimer_free,
.prepare = dummy_hrtimer_prepare,
.start = dummy_hrtimer_start,
.stop = dummy_hrtimer_stop,
.pointer = dummy_hrtimer_pointer,
};
#endif /* CONFIG_HIGH_RES_TIMERS */
/*
* PCM interface
*/
static int dummy_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct snd_dummy *dummy = snd_pcm_substream_chip(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
return dummy->timer_ops->start(substream);
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
return dummy->timer_ops->stop(substream);
}
return -EINVAL;
}
static int dummy_pcm_prepare(struct snd_pcm_substream *substream)
{
struct snd_dummy *dummy = snd_pcm_substream_chip(substream);
return dummy->timer_ops->prepare(substream);
}
static snd_pcm_uframes_t dummy_pcm_pointer(struct snd_pcm_substream *substream)
{
struct snd_dummy *dummy = snd_pcm_substream_chip(substream);
return dummy->timer_ops->pointer(substream);
}
static struct snd_pcm_hardware dummy_pcm_hardware = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_RESUME |
SNDRV_PCM_INFO_MMAP_VALID),
.formats = USE_FORMATS,
.rates = USE_RATE,
.rate_min = USE_RATE_MIN,
.rate_max = USE_RATE_MAX,
.channels_min = USE_CHANNELS_MIN,
.channels_max = USE_CHANNELS_MAX,
.buffer_bytes_max = MAX_BUFFER_SIZE,
.period_bytes_min = MIN_PERIOD_SIZE,
.period_bytes_max = MAX_PERIOD_SIZE,
.periods_min = USE_PERIODS_MIN,
.periods_max = USE_PERIODS_MAX,
.fifo_size = 0,
};
static int dummy_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
if (fake_buffer) {
/* runtime->dma_bytes has to be set manually to allow mmap */
substream->runtime->dma_bytes = params_buffer_bytes(hw_params);
return 0;
}
return snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(hw_params));
}
static int dummy_pcm_hw_free(struct snd_pcm_substream *substream)
{
if (fake_buffer)
return 0;
return snd_pcm_lib_free_pages(substream);
}
static int dummy_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_dummy *dummy = snd_pcm_substream_chip(substream);
struct dummy_model *model = dummy->model;
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
dummy->timer_ops = &dummy_systimer_ops;
#ifdef CONFIG_HIGH_RES_TIMERS
if (hrtimer)
dummy->timer_ops = &dummy_hrtimer_ops;
#endif
err = dummy->timer_ops->create(substream);
if (err < 0)
return err;
runtime->hw = dummy->pcm_hw;
if (substream->pcm->device & 1) {
runtime->hw.info &= ~SNDRV_PCM_INFO_INTERLEAVED;
runtime->hw.info |= SNDRV_PCM_INFO_NONINTERLEAVED;
}
if (substream->pcm->device & 2)
runtime->hw.info &= ~(SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID);
if (model == NULL)
return 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
if (model->playback_constraints)
err = model->playback_constraints(substream->runtime);
} else {
if (model->capture_constraints)
err = model->capture_constraints(substream->runtime);
}
if (err < 0) {
dummy->timer_ops->free(substream);
return err;
}
return 0;
}
static int dummy_pcm_close(struct snd_pcm_substream *substream)
{
struct snd_dummy *dummy = snd_pcm_substream_chip(substream);
dummy->timer_ops->free(substream);
return 0;
}
/*
* dummy buffer handling
*/
static void *dummy_page[2];
static void free_fake_buffer(void)
{
if (fake_buffer) {
int i;
for (i = 0; i < 2; i++)
if (dummy_page[i]) {
free_page((unsigned long)dummy_page[i]);
dummy_page[i] = NULL;
}
}
}
static int alloc_fake_buffer(void)
{
int i;
if (!fake_buffer)
return 0;
for (i = 0; i < 2; i++) {
dummy_page[i] = (void *)get_zeroed_page(GFP_KERNEL);
if (!dummy_page[i]) {
free_fake_buffer();
return -ENOMEM;
}
}
return 0;
}
static int dummy_pcm_copy(struct snd_pcm_substream *substream,
int channel, snd_pcm_uframes_t pos,
void __user *dst, snd_pcm_uframes_t count)
{
return 0; /* do nothing */
}
static int dummy_pcm_silence(struct snd_pcm_substream *substream,
int channel, snd_pcm_uframes_t pos,
snd_pcm_uframes_t count)
{
return 0; /* do nothing */
}
static struct page *dummy_pcm_page(struct snd_pcm_substream *substream,
unsigned long offset)
{
return virt_to_page(dummy_page[substream->stream]); /* the same page */
}
static struct snd_pcm_ops dummy_pcm_ops = {
.open = dummy_pcm_open,
.close = dummy_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = dummy_pcm_hw_params,
.hw_free = dummy_pcm_hw_free,
.prepare = dummy_pcm_prepare,
.trigger = dummy_pcm_trigger,
.pointer = dummy_pcm_pointer,
};
static struct snd_pcm_ops dummy_pcm_ops_no_buf = {
.open = dummy_pcm_open,
.close = dummy_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = dummy_pcm_hw_params,
.hw_free = dummy_pcm_hw_free,
.prepare = dummy_pcm_prepare,
.trigger = dummy_pcm_trigger,
.pointer = dummy_pcm_pointer,
.copy = dummy_pcm_copy,
.silence = dummy_pcm_silence,
.page = dummy_pcm_page,
};
static int __devinit snd_card_dummy_pcm(struct snd_dummy *dummy, int device,
int substreams)
{
struct snd_pcm *pcm;
struct snd_pcm_ops *ops;
int err;
err = snd_pcm_new(dummy->card, "Dummy PCM", device,
substreams, substreams, &pcm);
if (err < 0)
return err;
dummy->pcm = pcm;
if (fake_buffer)
ops = &dummy_pcm_ops_no_buf;
else
ops = &dummy_pcm_ops;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, ops);
pcm->private_data = dummy;
pcm->info_flags = 0;
strcpy(pcm->name, "Dummy PCM");
if (!fake_buffer) {
snd_pcm_lib_preallocate_pages_for_all(pcm,
SNDRV_DMA_TYPE_CONTINUOUS,
snd_dma_continuous_data(GFP_KERNEL),
0, 64*1024);
}
return 0;
}
/*
* mixer interface
*/
#define DUMMY_VOLUME(xname, xindex, addr) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_TLV_READ, \
.name = xname, .index = xindex, \
.info = snd_dummy_volume_info, \
.get = snd_dummy_volume_get, .put = snd_dummy_volume_put, \
.private_value = addr, \
.tlv = { .p = db_scale_dummy } }
static int snd_dummy_volume_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = -50;
uinfo->value.integer.max = 100;
return 0;
}
static int snd_dummy_volume_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_dummy *dummy = snd_kcontrol_chip(kcontrol);
int addr = kcontrol->private_value;
spin_lock_irq(&dummy->mixer_lock);
ucontrol->value.integer.value[0] = dummy->mixer_volume[addr][0];
ucontrol->value.integer.value[1] = dummy->mixer_volume[addr][1];
spin_unlock_irq(&dummy->mixer_lock);
return 0;
}
static int snd_dummy_volume_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_dummy *dummy = snd_kcontrol_chip(kcontrol);
int change, addr = kcontrol->private_value;
int left, right;
left = ucontrol->value.integer.value[0];
if (left < -50)
left = -50;
if (left > 100)
left = 100;
right = ucontrol->value.integer.value[1];
if (right < -50)
right = -50;
if (right > 100)
right = 100;
spin_lock_irq(&dummy->mixer_lock);
change = dummy->mixer_volume[addr][0] != left ||
dummy->mixer_volume[addr][1] != right;
dummy->mixer_volume[addr][0] = left;
dummy->mixer_volume[addr][1] = right;
spin_unlock_irq(&dummy->mixer_lock);
return change;
}
static const DECLARE_TLV_DB_SCALE(db_scale_dummy, -4500, 30, 0);
#define DUMMY_CAPSRC(xname, xindex, addr) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_dummy_capsrc_info, \
.get = snd_dummy_capsrc_get, .put = snd_dummy_capsrc_put, \
.private_value = addr }
#define snd_dummy_capsrc_info snd_ctl_boolean_stereo_info
static int snd_dummy_capsrc_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_dummy *dummy = snd_kcontrol_chip(kcontrol);
int addr = kcontrol->private_value;
spin_lock_irq(&dummy->mixer_lock);
ucontrol->value.integer.value[0] = dummy->capture_source[addr][0];
ucontrol->value.integer.value[1] = dummy->capture_source[addr][1];
spin_unlock_irq(&dummy->mixer_lock);
return 0;
}
static int snd_dummy_capsrc_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_dummy *dummy = snd_kcontrol_chip(kcontrol);
int change, addr = kcontrol->private_value;
int left, right;
left = ucontrol->value.integer.value[0] & 1;
right = ucontrol->value.integer.value[1] & 1;
spin_lock_irq(&dummy->mixer_lock);
change = dummy->capture_source[addr][0] != left &&
dummy->capture_source[addr][1] != right;
dummy->capture_source[addr][0] = left;
dummy->capture_source[addr][1] = right;
spin_unlock_irq(&dummy->mixer_lock);
return change;
}
static struct snd_kcontrol_new snd_dummy_controls[] = {
DUMMY_VOLUME("Master Volume", 0, MIXER_ADDR_MASTER),
DUMMY_CAPSRC("Master Capture Switch", 0, MIXER_ADDR_MASTER),
DUMMY_VOLUME("Synth Volume", 0, MIXER_ADDR_SYNTH),
DUMMY_CAPSRC("Synth Capture Switch", 0, MIXER_ADDR_SYNTH),
DUMMY_VOLUME("Line Volume", 0, MIXER_ADDR_LINE),
DUMMY_CAPSRC("Line Capture Switch", 0, MIXER_ADDR_LINE),
DUMMY_VOLUME("Mic Volume", 0, MIXER_ADDR_MIC),
DUMMY_CAPSRC("Mic Capture Switch", 0, MIXER_ADDR_MIC),
DUMMY_VOLUME("CD Volume", 0, MIXER_ADDR_CD),
DUMMY_CAPSRC("CD Capture Switch", 0, MIXER_ADDR_CD)
};
static int __devinit snd_card_dummy_new_mixer(struct snd_dummy *dummy)
{
struct snd_card *card = dummy->card;
unsigned int idx;
int err;
spin_lock_init(&dummy->mixer_lock);
strcpy(card->mixername, "Dummy Mixer");
for (idx = 0; idx < ARRAY_SIZE(snd_dummy_controls); idx++) {
err = snd_ctl_add(card, snd_ctl_new1(&snd_dummy_controls[idx], dummy));
if (err < 0)
return err;
}
return 0;
}
#if defined(CONFIG_SND_DEBUG) && defined(CONFIG_PROC_FS)
/*
* proc interface
*/
static void print_formats(struct snd_dummy *dummy,
struct snd_info_buffer *buffer)
{
int i;
for (i = 0; i < SNDRV_PCM_FORMAT_LAST; i++) {
if (dummy->pcm_hw.formats & (1ULL << i))
snd_iprintf(buffer, " %s", snd_pcm_format_name(i));
}
}
static void print_rates(struct snd_dummy *dummy,
struct snd_info_buffer *buffer)
{
static int rates[] = {
5512, 8000, 11025, 16000, 22050, 32000, 44100, 48000,
64000, 88200, 96000, 176400, 192000,
};
int i;
if (dummy->pcm_hw.rates & SNDRV_PCM_RATE_CONTINUOUS)
snd_iprintf(buffer, " continuous");
if (dummy->pcm_hw.rates & SNDRV_PCM_RATE_KNOT)
snd_iprintf(buffer, " knot");
for (i = 0; i < ARRAY_SIZE(rates); i++)
if (dummy->pcm_hw.rates & (1 << i))
snd_iprintf(buffer, " %d", rates[i]);
}
#define get_dummy_int_ptr(dummy, ofs) \
(unsigned int *)((char *)&((dummy)->pcm_hw) + (ofs))
#define get_dummy_ll_ptr(dummy, ofs) \
(unsigned long long *)((char *)&((dummy)->pcm_hw) + (ofs))
struct dummy_hw_field {
const char *name;
const char *format;
unsigned int offset;
unsigned int size;
};
#define FIELD_ENTRY(item, fmt) { \
.name = #item, \
.format = fmt, \
.offset = offsetof(struct snd_pcm_hardware, item), \
.size = sizeof(dummy_pcm_hardware.item) }
static struct dummy_hw_field fields[] = {
FIELD_ENTRY(formats, "%#llx"),
FIELD_ENTRY(rates, "%#x"),
FIELD_ENTRY(rate_min, "%d"),
FIELD_ENTRY(rate_max, "%d"),
FIELD_ENTRY(channels_min, "%d"),
FIELD_ENTRY(channels_max, "%d"),
FIELD_ENTRY(buffer_bytes_max, "%ld"),
FIELD_ENTRY(period_bytes_min, "%ld"),
FIELD_ENTRY(period_bytes_max, "%ld"),
FIELD_ENTRY(periods_min, "%d"),
FIELD_ENTRY(periods_max, "%d"),
};
static void dummy_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_dummy *dummy = entry->private_data;
int i;
for (i = 0; i < ARRAY_SIZE(fields); i++) {
snd_iprintf(buffer, "%s ", fields[i].name);
if (fields[i].size == sizeof(int))
snd_iprintf(buffer, fields[i].format,
*get_dummy_int_ptr(dummy, fields[i].offset));
else
snd_iprintf(buffer, fields[i].format,
*get_dummy_ll_ptr(dummy, fields[i].offset));
if (!strcmp(fields[i].name, "formats"))
print_formats(dummy, buffer);
else if (!strcmp(fields[i].name, "rates"))
print_rates(dummy, buffer);
snd_iprintf(buffer, "\n");
}
}
static void dummy_proc_write(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_dummy *dummy = entry->private_data;
char line[64];
while (!snd_info_get_line(buffer, line, sizeof(line))) {
char item[20];
const char *ptr;
unsigned long long val;
int i;
ptr = snd_info_get_str(item, line, sizeof(item));
for (i = 0; i < ARRAY_SIZE(fields); i++) {
if (!strcmp(item, fields[i].name))
break;
}
if (i >= ARRAY_SIZE(fields))
continue;
snd_info_get_str(item, ptr, sizeof(item));
if (strict_strtoull(item, 0, &val))
continue;
if (fields[i].size == sizeof(int))
*get_dummy_int_ptr(dummy, fields[i].offset) = val;
else
*get_dummy_ll_ptr(dummy, fields[i].offset) = val;
}
}
static void __devinit dummy_proc_init(struct snd_dummy *chip)
{
struct snd_info_entry *entry;
if (!snd_card_proc_new(chip->card, "dummy_pcm", &entry)) {
snd_info_set_text_ops(entry, chip, dummy_proc_read);
entry->c.text.write = dummy_proc_write;
entry->mode |= S_IWUSR;
entry->private_data = chip;
}
}
#else
#define dummy_proc_init(x)
#endif /* CONFIG_SND_DEBUG && CONFIG_PROC_FS */
static int __devinit snd_dummy_probe(struct platform_device *devptr)
{
struct snd_card *card;
struct snd_dummy *dummy;
struct dummy_model *m = NULL, **mdl;
int idx, err;
int dev = devptr->id;
err = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_dummy), &card);
if (err < 0)
return err;
dummy = card->private_data;
dummy->card = card;
for (mdl = dummy_models; *mdl && model[dev]; mdl++) {
if (strcmp(model[dev], (*mdl)->name) == 0) {
printk(KERN_INFO
"snd-dummy: Using model '%s' for card %i\n",
(*mdl)->name, card->number);
m = dummy->model = *mdl;
break;
}
}
for (idx = 0; idx < MAX_PCM_DEVICES && idx < pcm_devs[dev]; idx++) {
if (pcm_substreams[dev] < 1)
pcm_substreams[dev] = 1;
if (pcm_substreams[dev] > MAX_PCM_SUBSTREAMS)
pcm_substreams[dev] = MAX_PCM_SUBSTREAMS;
err = snd_card_dummy_pcm(dummy, idx, pcm_substreams[dev]);
if (err < 0)
goto __nodev;
}
dummy->pcm_hw = dummy_pcm_hardware;
if (m) {
if (m->formats)
dummy->pcm_hw.formats = m->formats;
if (m->buffer_bytes_max)
dummy->pcm_hw.buffer_bytes_max = m->buffer_bytes_max;
if (m->period_bytes_min)
dummy->pcm_hw.period_bytes_min = m->period_bytes_min;
if (m->period_bytes_max)
dummy->pcm_hw.period_bytes_max = m->period_bytes_max;
if (m->periods_min)
dummy->pcm_hw.periods_min = m->periods_min;
if (m->periods_max)
dummy->pcm_hw.periods_max = m->periods_max;
if (m->rates)
dummy->pcm_hw.rates = m->rates;
if (m->rate_min)
dummy->pcm_hw.rate_min = m->rate_min;
if (m->rate_max)
dummy->pcm_hw.rate_max = m->rate_max;
if (m->channels_min)
dummy->pcm_hw.channels_min = m->channels_min;
if (m->channels_max)
dummy->pcm_hw.channels_max = m->channels_max;
}
err = snd_card_dummy_new_mixer(dummy);
if (err < 0)
goto __nodev;
strcpy(card->driver, "Dummy");
strcpy(card->shortname, "Dummy");
sprintf(card->longname, "Dummy %i", dev + 1);
dummy_proc_init(dummy);
snd_card_set_dev(card, &devptr->dev);
err = snd_card_register(card);
if (err == 0) {
platform_set_drvdata(devptr, card);
return 0;
}
__nodev:
snd_card_free(card);
return err;
}
static int __devexit snd_dummy_remove(struct platform_device *devptr)
{
snd_card_free(platform_get_drvdata(devptr));
platform_set_drvdata(devptr, NULL);
return 0;
}
#ifdef CONFIG_PM
static int snd_dummy_suspend(struct platform_device *pdev, pm_message_t state)
{
struct snd_card *card = platform_get_drvdata(pdev);
struct snd_dummy *dummy = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(dummy->pcm);
return 0;
}
static int snd_dummy_resume(struct platform_device *pdev)
{
struct snd_card *card = platform_get_drvdata(pdev);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif
#define SND_DUMMY_DRIVER "snd_dummy"
static struct platform_driver snd_dummy_driver = {
.probe = snd_dummy_probe,
.remove = __devexit_p(snd_dummy_remove),
#ifdef CONFIG_PM
.suspend = snd_dummy_suspend,
.resume = snd_dummy_resume,
#endif
.driver = {
.name = SND_DUMMY_DRIVER
},
};
static void snd_dummy_unregister_all(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(devices); ++i)
platform_device_unregister(devices[i]);
platform_driver_unregister(&snd_dummy_driver);
free_fake_buffer();
}
static int __init alsa_card_dummy_init(void)
{
int i, cards, err;
err = platform_driver_register(&snd_dummy_driver);
if (err < 0)
return err;
err = alloc_fake_buffer();
if (err < 0) {
platform_driver_unregister(&snd_dummy_driver);
return err;
}
cards = 0;
for (i = 0; i < SNDRV_CARDS; i++) {
struct platform_device *device;
if (! enable[i])
continue;
device = platform_device_register_simple(SND_DUMMY_DRIVER,
i, NULL, 0);
if (IS_ERR(device))
continue;
if (!platform_get_drvdata(device)) {
platform_device_unregister(device);
continue;
}
devices[i] = device;
cards++;
}
if (!cards) {
#ifdef MODULE
printk(KERN_ERR "Dummy soundcard not found or device busy\n");
#endif
snd_dummy_unregister_all();
return -ENODEV;
}
return 0;
}
static void __exit alsa_card_dummy_exit(void)
{
snd_dummy_unregister_all();
}
module_init(alsa_card_dummy_init)
module_exit(alsa_card_dummy_exit)
| gpl-2.0 |
ISTweak/android_kernel_sony_apq8064 | arch/score/kernel/module.c | 5195 | 4137 | /*
* arch/score/kernel/module.c
*
* Score Processor version.
*
* Copyright (C) 2009 Sunplus Core Technology Co., Ltd.
* Chen Liqin <liqin.chen@sunplusct.com>
* Lennox Wu <lennox.wu@sunplusct.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, see the file COPYING, or write
* to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/moduleloader.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
int apply_relocate(Elf_Shdr *sechdrs, const char *strtab,
unsigned int symindex, unsigned int relindex,
struct module *me)
{
Elf32_Shdr *symsec = sechdrs + symindex;
Elf32_Shdr *relsec = sechdrs + relindex;
Elf32_Shdr *dstsec = sechdrs + relsec->sh_info;
Elf32_Rel *rel = (void *)relsec->sh_addr;
unsigned int i;
for (i = 0; i < relsec->sh_size / sizeof(Elf32_Rel); i++, rel++) {
unsigned long loc;
Elf32_Sym *sym;
s32 r_offset;
r_offset = ELF32_R_SYM(rel->r_info);
if ((r_offset < 0) ||
(r_offset > (symsec->sh_size / sizeof(Elf32_Sym)))) {
printk(KERN_ERR "%s: bad relocation, section %d reloc %d\n",
me->name, relindex, i);
return -ENOEXEC;
}
sym = ((Elf32_Sym *)symsec->sh_addr) + r_offset;
if ((rel->r_offset < 0) ||
(rel->r_offset > dstsec->sh_size - sizeof(u32))) {
printk(KERN_ERR "%s: out of bounds relocation, "
"section %d reloc %d offset %d size %d\n",
me->name, relindex, i, rel->r_offset,
dstsec->sh_size);
return -ENOEXEC;
}
loc = dstsec->sh_addr + rel->r_offset;
switch (ELF32_R_TYPE(rel->r_info)) {
case R_SCORE_NONE:
break;
case R_SCORE_ABS32:
*(unsigned long *)loc += sym->st_value;
break;
case R_SCORE_HI16:
break;
case R_SCORE_LO16: {
unsigned long hi16_offset, offset;
unsigned long uvalue;
unsigned long temp, temp_hi;
temp_hi = *((unsigned long *)loc - 1);
temp = *(unsigned long *)loc;
hi16_offset = (((((temp_hi) >> 16) & 0x3) << 15) |
((temp_hi) & 0x7fff)) >> 1;
offset = ((temp >> 16 & 0x03) << 15) |
((temp & 0x7fff) >> 1);
offset = (hi16_offset << 16) | (offset & 0xffff);
uvalue = sym->st_value + offset;
hi16_offset = (uvalue >> 16) << 1;
temp_hi = ((temp_hi) & (~(0x37fff))) |
(hi16_offset & 0x7fff) |
((hi16_offset << 1) & 0x30000);
*((unsigned long *)loc - 1) = temp_hi;
offset = (uvalue & 0xffff) << 1;
temp = (temp & (~(0x37fff))) | (offset & 0x7fff) |
((offset << 1) & 0x30000);
*(unsigned long *)loc = temp;
break;
}
case R_SCORE_24: {
unsigned long hi16_offset, offset;
unsigned long uvalue;
unsigned long temp;
temp = *(unsigned long *)loc;
offset = (temp & 0x03FF7FFE);
hi16_offset = (offset & 0xFFFF0000);
offset = (hi16_offset | ((offset & 0xFFFF) << 1)) >> 2;
uvalue = (sym->st_value + offset) >> 1;
uvalue = uvalue & 0x00ffffff;
temp = (temp & 0xfc008001) |
((uvalue << 2) & 0x3ff0000) |
((uvalue & 0x3fff) << 1);
*(unsigned long *)loc = temp;
break;
}
default:
printk(KERN_ERR "%s: unknown relocation: %u\n",
me->name, ELF32_R_TYPE(rel->r_info));
return -ENOEXEC;
}
}
return 0;
}
int apply_relocate_add(Elf_Shdr *sechdrs, const char *strtab,
unsigned int symindex, unsigned int relsec,
struct module *me)
{
/* Non-standard return value... most other arch's return -ENOEXEC
* for an unsupported relocation variant
*/
return 0;
}
/* Given an address, look for it in the module exception tables. */
const struct exception_table_entry *search_module_dbetables(unsigned long addr)
{
return NULL;
}
| gpl-2.0 |
mythos234/SimplKernel-LL-N910G | drivers/media/i2c/saa7191.c | 7243 | 15802 | /*
* saa7191.c - Philips SAA7191 video decoder driver
*
* Copyright (C) 2003 Ladislav Michl <ladis@linux-mips.org>
* Copyright (C) 2004,2005 Mikael Nousiainen <tmnousia@cc.hut.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.
*/
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <linux/i2c.h>
#include <media/v4l2-device.h>
#include <media/v4l2-chip-ident.h>
#include "saa7191.h"
#define SAA7191_MODULE_VERSION "0.0.5"
MODULE_DESCRIPTION("Philips SAA7191 video decoder driver");
MODULE_VERSION(SAA7191_MODULE_VERSION);
MODULE_AUTHOR("Mikael Nousiainen <tmnousia@cc.hut.fi>");
MODULE_LICENSE("GPL");
// #define SAA7191_DEBUG
#ifdef SAA7191_DEBUG
#define dprintk(x...) printk("SAA7191: " x);
#else
#define dprintk(x...)
#endif
#define SAA7191_SYNC_COUNT 30
#define SAA7191_SYNC_DELAY 100 /* milliseconds */
struct saa7191 {
struct v4l2_subdev sd;
/* the register values are stored here as the actual
* I2C-registers are write-only */
u8 reg[25];
int input;
v4l2_std_id norm;
};
static inline struct saa7191 *to_saa7191(struct v4l2_subdev *sd)
{
return container_of(sd, struct saa7191, sd);
}
static const u8 initseq[] = {
0, /* Subaddress */
0x50, /* (0x50) SAA7191_REG_IDEL */
/* 50 Hz signal timing */
0x30, /* (0x30) SAA7191_REG_HSYB */
0x00, /* (0x00) SAA7191_REG_HSYS */
0xe8, /* (0xe8) SAA7191_REG_HCLB */
0xb6, /* (0xb6) SAA7191_REG_HCLS */
0xf4, /* (0xf4) SAA7191_REG_HPHI */
/* control */
SAA7191_LUMA_APER_1, /* (0x01) SAA7191_REG_LUMA - CVBS mode */
0x00, /* (0x00) SAA7191_REG_HUEC */
0xf8, /* (0xf8) SAA7191_REG_CKTQ */
0xf8, /* (0xf8) SAA7191_REG_CKTS */
0x90, /* (0x90) SAA7191_REG_PLSE */
0x90, /* (0x90) SAA7191_REG_SESE */
0x00, /* (0x00) SAA7191_REG_GAIN */
SAA7191_STDC_NFEN | SAA7191_STDC_HRMV, /* (0x0c) SAA7191_REG_STDC
* - not SECAM,
* slow time constant */
SAA7191_IOCK_OEDC | SAA7191_IOCK_OEHS | SAA7191_IOCK_OEVS
| SAA7191_IOCK_OEDY, /* (0x78) SAA7191_REG_IOCK
* - chroma from CVBS, GPSW1 & 2 off */
SAA7191_CTL3_AUFD | SAA7191_CTL3_SCEN | SAA7191_CTL3_OFTS
| SAA7191_CTL3_YDEL0, /* (0x99) SAA7191_REG_CTL3
* - automatic field detection */
0x00, /* (0x00) SAA7191_REG_CTL4 */
0x2c, /* (0x2c) SAA7191_REG_CHCV - PAL nominal value */
0x00, /* unused */
0x00, /* unused */
/* 60 Hz signal timing */
0x34, /* (0x34) SAA7191_REG_HS6B */
0x0a, /* (0x0a) SAA7191_REG_HS6S */
0xf4, /* (0xf4) SAA7191_REG_HC6B */
0xce, /* (0xce) SAA7191_REG_HC6S */
0xf4, /* (0xf4) SAA7191_REG_HP6I */
};
/* SAA7191 register handling */
static u8 saa7191_read_reg(struct v4l2_subdev *sd, u8 reg)
{
return to_saa7191(sd)->reg[reg];
}
static int saa7191_read_status(struct v4l2_subdev *sd, u8 *value)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
int ret;
ret = i2c_master_recv(client, value, 1);
if (ret < 0) {
printk(KERN_ERR "SAA7191: saa7191_read_status(): read failed\n");
return ret;
}
return 0;
}
static int saa7191_write_reg(struct v4l2_subdev *sd, u8 reg, u8 value)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
to_saa7191(sd)->reg[reg] = value;
return i2c_smbus_write_byte_data(client, reg, value);
}
/* the first byte of data must be the first subaddress number (register) */
static int saa7191_write_block(struct v4l2_subdev *sd,
u8 length, const u8 *data)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
struct saa7191 *decoder = to_saa7191(sd);
int i;
int ret;
for (i = 0; i < (length - 1); i++) {
decoder->reg[data[0] + i] = data[i + 1];
}
ret = i2c_master_send(client, data, length);
if (ret < 0) {
printk(KERN_ERR "SAA7191: saa7191_write_block(): "
"write failed\n");
return ret;
}
return 0;
}
/* Helper functions */
static int saa7191_s_routing(struct v4l2_subdev *sd,
u32 input, u32 output, u32 config)
{
struct saa7191 *decoder = to_saa7191(sd);
u8 luma = saa7191_read_reg(sd, SAA7191_REG_LUMA);
u8 iock = saa7191_read_reg(sd, SAA7191_REG_IOCK);
int err;
switch (input) {
case SAA7191_INPUT_COMPOSITE: /* Set Composite input */
iock &= ~(SAA7191_IOCK_CHRS | SAA7191_IOCK_GPSW1
| SAA7191_IOCK_GPSW2);
/* Chrominance trap active */
luma &= ~SAA7191_LUMA_BYPS;
break;
case SAA7191_INPUT_SVIDEO: /* Set S-Video input */
iock |= SAA7191_IOCK_CHRS | SAA7191_IOCK_GPSW2;
/* Chrominance trap bypassed */
luma |= SAA7191_LUMA_BYPS;
break;
default:
return -EINVAL;
}
err = saa7191_write_reg(sd, SAA7191_REG_LUMA, luma);
if (err)
return -EIO;
err = saa7191_write_reg(sd, SAA7191_REG_IOCK, iock);
if (err)
return -EIO;
decoder->input = input;
return 0;
}
static int saa7191_s_std(struct v4l2_subdev *sd, v4l2_std_id norm)
{
struct saa7191 *decoder = to_saa7191(sd);
u8 stdc = saa7191_read_reg(sd, SAA7191_REG_STDC);
u8 ctl3 = saa7191_read_reg(sd, SAA7191_REG_CTL3);
u8 chcv = saa7191_read_reg(sd, SAA7191_REG_CHCV);
int err;
if (norm & V4L2_STD_PAL) {
stdc &= ~SAA7191_STDC_SECS;
ctl3 &= ~(SAA7191_CTL3_AUFD | SAA7191_CTL3_FSEL);
chcv = SAA7191_CHCV_PAL;
} else if (norm & V4L2_STD_NTSC) {
stdc &= ~SAA7191_STDC_SECS;
ctl3 &= ~SAA7191_CTL3_AUFD;
ctl3 |= SAA7191_CTL3_FSEL;
chcv = SAA7191_CHCV_NTSC;
} else if (norm & V4L2_STD_SECAM) {
stdc |= SAA7191_STDC_SECS;
ctl3 &= ~(SAA7191_CTL3_AUFD | SAA7191_CTL3_FSEL);
chcv = SAA7191_CHCV_PAL;
} else {
return -EINVAL;
}
err = saa7191_write_reg(sd, SAA7191_REG_CTL3, ctl3);
if (err)
return -EIO;
err = saa7191_write_reg(sd, SAA7191_REG_STDC, stdc);
if (err)
return -EIO;
err = saa7191_write_reg(sd, SAA7191_REG_CHCV, chcv);
if (err)
return -EIO;
decoder->norm = norm;
dprintk("ctl3: %02x stdc: %02x chcv: %02x\n", ctl3,
stdc, chcv);
dprintk("norm: %llx\n", norm);
return 0;
}
static int saa7191_wait_for_signal(struct v4l2_subdev *sd, u8 *status)
{
int i = 0;
dprintk("Checking for signal...\n");
for (i = 0; i < SAA7191_SYNC_COUNT; i++) {
if (saa7191_read_status(sd, status))
return -EIO;
if (((*status) & SAA7191_STATUS_HLCK) == 0) {
dprintk("Signal found\n");
return 0;
}
msleep(SAA7191_SYNC_DELAY);
}
dprintk("No signal\n");
return -EBUSY;
}
static int saa7191_querystd(struct v4l2_subdev *sd, v4l2_std_id *norm)
{
struct saa7191 *decoder = to_saa7191(sd);
u8 stdc = saa7191_read_reg(sd, SAA7191_REG_STDC);
u8 ctl3 = saa7191_read_reg(sd, SAA7191_REG_CTL3);
u8 status;
v4l2_std_id old_norm = decoder->norm;
int err = 0;
dprintk("SAA7191 extended signal auto-detection...\n");
*norm = V4L2_STD_NTSC | V4L2_STD_PAL | V4L2_STD_SECAM;
stdc &= ~SAA7191_STDC_SECS;
ctl3 &= ~(SAA7191_CTL3_FSEL);
err = saa7191_write_reg(sd, SAA7191_REG_STDC, stdc);
if (err) {
err = -EIO;
goto out;
}
err = saa7191_write_reg(sd, SAA7191_REG_CTL3, ctl3);
if (err) {
err = -EIO;
goto out;
}
ctl3 |= SAA7191_CTL3_AUFD;
err = saa7191_write_reg(sd, SAA7191_REG_CTL3, ctl3);
if (err) {
err = -EIO;
goto out;
}
msleep(SAA7191_SYNC_DELAY);
err = saa7191_wait_for_signal(sd, &status);
if (err)
goto out;
if (status & SAA7191_STATUS_FIDT) {
/* 60Hz signal -> NTSC */
dprintk("60Hz signal: NTSC\n");
*norm = V4L2_STD_NTSC;
return 0;
}
/* 50Hz signal */
dprintk("50Hz signal: Trying PAL...\n");
/* try PAL first */
err = saa7191_s_std(sd, V4L2_STD_PAL);
if (err)
goto out;
msleep(SAA7191_SYNC_DELAY);
err = saa7191_wait_for_signal(sd, &status);
if (err)
goto out;
/* not 50Hz ? */
if (status & SAA7191_STATUS_FIDT) {
dprintk("No 50Hz signal\n");
saa7191_s_std(sd, old_norm);
return -EAGAIN;
}
if (status & SAA7191_STATUS_CODE) {
dprintk("PAL\n");
*norm = V4L2_STD_PAL;
return saa7191_s_std(sd, old_norm);
}
dprintk("No color detected with PAL - Trying SECAM...\n");
/* no color detected ? -> try SECAM */
err = saa7191_s_std(sd, V4L2_STD_SECAM);
if (err)
goto out;
msleep(SAA7191_SYNC_DELAY);
err = saa7191_wait_for_signal(sd, &status);
if (err)
goto out;
/* not 50Hz ? */
if (status & SAA7191_STATUS_FIDT) {
dprintk("No 50Hz signal\n");
err = -EAGAIN;
goto out;
}
if (status & SAA7191_STATUS_CODE) {
/* Color detected -> SECAM */
dprintk("SECAM\n");
*norm = V4L2_STD_SECAM;
return saa7191_s_std(sd, old_norm);
}
dprintk("No color detected with SECAM - Going back to PAL.\n");
out:
return saa7191_s_std(sd, old_norm);
}
static int saa7191_autodetect_norm(struct v4l2_subdev *sd)
{
u8 status;
dprintk("SAA7191 signal auto-detection...\n");
dprintk("Reading status...\n");
if (saa7191_read_status(sd, &status))
return -EIO;
dprintk("Checking for signal...\n");
/* no signal ? */
if (status & SAA7191_STATUS_HLCK) {
dprintk("No signal\n");
return -EBUSY;
}
dprintk("Signal found\n");
if (status & SAA7191_STATUS_FIDT) {
/* 60hz signal -> NTSC */
dprintk("NTSC\n");
return saa7191_s_std(sd, V4L2_STD_NTSC);
} else {
/* 50hz signal -> PAL */
dprintk("PAL\n");
return saa7191_s_std(sd, V4L2_STD_PAL);
}
}
static int saa7191_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
u8 reg;
int ret = 0;
switch (ctrl->id) {
case SAA7191_CONTROL_BANDPASS:
case SAA7191_CONTROL_BANDPASS_WEIGHT:
case SAA7191_CONTROL_CORING:
reg = saa7191_read_reg(sd, SAA7191_REG_LUMA);
switch (ctrl->id) {
case SAA7191_CONTROL_BANDPASS:
ctrl->value = ((s32)reg & SAA7191_LUMA_BPSS_MASK)
>> SAA7191_LUMA_BPSS_SHIFT;
break;
case SAA7191_CONTROL_BANDPASS_WEIGHT:
ctrl->value = ((s32)reg & SAA7191_LUMA_APER_MASK)
>> SAA7191_LUMA_APER_SHIFT;
break;
case SAA7191_CONTROL_CORING:
ctrl->value = ((s32)reg & SAA7191_LUMA_CORI_MASK)
>> SAA7191_LUMA_CORI_SHIFT;
break;
}
break;
case SAA7191_CONTROL_FORCE_COLOUR:
case SAA7191_CONTROL_CHROMA_GAIN:
reg = saa7191_read_reg(sd, SAA7191_REG_GAIN);
if (ctrl->id == SAA7191_CONTROL_FORCE_COLOUR)
ctrl->value = ((s32)reg & SAA7191_GAIN_COLO) ? 1 : 0;
else
ctrl->value = ((s32)reg & SAA7191_GAIN_LFIS_MASK)
>> SAA7191_GAIN_LFIS_SHIFT;
break;
case V4L2_CID_HUE:
reg = saa7191_read_reg(sd, SAA7191_REG_HUEC);
if (reg < 0x80)
reg += 0x80;
else
reg -= 0x80;
ctrl->value = (s32)reg;
break;
case SAA7191_CONTROL_VTRC:
reg = saa7191_read_reg(sd, SAA7191_REG_STDC);
ctrl->value = ((s32)reg & SAA7191_STDC_VTRC) ? 1 : 0;
break;
case SAA7191_CONTROL_LUMA_DELAY:
reg = saa7191_read_reg(sd, SAA7191_REG_CTL3);
ctrl->value = ((s32)reg & SAA7191_CTL3_YDEL_MASK)
>> SAA7191_CTL3_YDEL_SHIFT;
if (ctrl->value >= 4)
ctrl->value -= 8;
break;
case SAA7191_CONTROL_VNR:
reg = saa7191_read_reg(sd, SAA7191_REG_CTL4);
ctrl->value = ((s32)reg & SAA7191_CTL4_VNOI_MASK)
>> SAA7191_CTL4_VNOI_SHIFT;
break;
default:
ret = -EINVAL;
}
return ret;
}
static int saa7191_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
u8 reg;
int ret = 0;
switch (ctrl->id) {
case SAA7191_CONTROL_BANDPASS:
case SAA7191_CONTROL_BANDPASS_WEIGHT:
case SAA7191_CONTROL_CORING:
reg = saa7191_read_reg(sd, SAA7191_REG_LUMA);
switch (ctrl->id) {
case SAA7191_CONTROL_BANDPASS:
reg &= ~SAA7191_LUMA_BPSS_MASK;
reg |= (ctrl->value << SAA7191_LUMA_BPSS_SHIFT)
& SAA7191_LUMA_BPSS_MASK;
break;
case SAA7191_CONTROL_BANDPASS_WEIGHT:
reg &= ~SAA7191_LUMA_APER_MASK;
reg |= (ctrl->value << SAA7191_LUMA_APER_SHIFT)
& SAA7191_LUMA_APER_MASK;
break;
case SAA7191_CONTROL_CORING:
reg &= ~SAA7191_LUMA_CORI_MASK;
reg |= (ctrl->value << SAA7191_LUMA_CORI_SHIFT)
& SAA7191_LUMA_CORI_MASK;
break;
}
ret = saa7191_write_reg(sd, SAA7191_REG_LUMA, reg);
break;
case SAA7191_CONTROL_FORCE_COLOUR:
case SAA7191_CONTROL_CHROMA_GAIN:
reg = saa7191_read_reg(sd, SAA7191_REG_GAIN);
if (ctrl->id == SAA7191_CONTROL_FORCE_COLOUR) {
if (ctrl->value)
reg |= SAA7191_GAIN_COLO;
else
reg &= ~SAA7191_GAIN_COLO;
} else {
reg &= ~SAA7191_GAIN_LFIS_MASK;
reg |= (ctrl->value << SAA7191_GAIN_LFIS_SHIFT)
& SAA7191_GAIN_LFIS_MASK;
}
ret = saa7191_write_reg(sd, SAA7191_REG_GAIN, reg);
break;
case V4L2_CID_HUE:
reg = ctrl->value & 0xff;
if (reg < 0x80)
reg += 0x80;
else
reg -= 0x80;
ret = saa7191_write_reg(sd, SAA7191_REG_HUEC, reg);
break;
case SAA7191_CONTROL_VTRC:
reg = saa7191_read_reg(sd, SAA7191_REG_STDC);
if (ctrl->value)
reg |= SAA7191_STDC_VTRC;
else
reg &= ~SAA7191_STDC_VTRC;
ret = saa7191_write_reg(sd, SAA7191_REG_STDC, reg);
break;
case SAA7191_CONTROL_LUMA_DELAY: {
s32 value = ctrl->value;
if (value < 0)
value += 8;
reg = saa7191_read_reg(sd, SAA7191_REG_CTL3);
reg &= ~SAA7191_CTL3_YDEL_MASK;
reg |= (value << SAA7191_CTL3_YDEL_SHIFT)
& SAA7191_CTL3_YDEL_MASK;
ret = saa7191_write_reg(sd, SAA7191_REG_CTL3, reg);
break;
}
case SAA7191_CONTROL_VNR:
reg = saa7191_read_reg(sd, SAA7191_REG_CTL4);
reg &= ~SAA7191_CTL4_VNOI_MASK;
reg |= (ctrl->value << SAA7191_CTL4_VNOI_SHIFT)
& SAA7191_CTL4_VNOI_MASK;
ret = saa7191_write_reg(sd, SAA7191_REG_CTL4, reg);
break;
default:
ret = -EINVAL;
}
return ret;
}
/* I2C-interface */
static int saa7191_g_input_status(struct v4l2_subdev *sd, u32 *status)
{
u8 status_reg;
int res = V4L2_IN_ST_NO_SIGNAL;
if (saa7191_read_status(sd, &status_reg))
return -EIO;
if ((status_reg & SAA7191_STATUS_HLCK) == 0)
res = 0;
if (!(status_reg & SAA7191_STATUS_CODE))
res |= V4L2_IN_ST_NO_COLOR;
*status = res;
return 0;
}
static int saa7191_g_chip_ident(struct v4l2_subdev *sd,
struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_SAA7191, 0);
}
/* ----------------------------------------------------------------------- */
static const struct v4l2_subdev_core_ops saa7191_core_ops = {
.g_chip_ident = saa7191_g_chip_ident,
.g_ctrl = saa7191_g_ctrl,
.s_ctrl = saa7191_s_ctrl,
.s_std = saa7191_s_std,
};
static const struct v4l2_subdev_video_ops saa7191_video_ops = {
.s_routing = saa7191_s_routing,
.querystd = saa7191_querystd,
.g_input_status = saa7191_g_input_status,
};
static const struct v4l2_subdev_ops saa7191_ops = {
.core = &saa7191_core_ops,
.video = &saa7191_video_ops,
};
static int saa7191_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int err = 0;
struct saa7191 *decoder;
struct v4l2_subdev *sd;
v4l_info(client, "chip found @ 0x%x (%s)\n",
client->addr << 1, client->adapter->name);
decoder = kzalloc(sizeof(*decoder), GFP_KERNEL);
if (!decoder)
return -ENOMEM;
sd = &decoder->sd;
v4l2_i2c_subdev_init(sd, client, &saa7191_ops);
err = saa7191_write_block(sd, sizeof(initseq), initseq);
if (err) {
printk(KERN_ERR "SAA7191 initialization failed\n");
kfree(decoder);
return err;
}
printk(KERN_INFO "SAA7191 initialized\n");
decoder->input = SAA7191_INPUT_COMPOSITE;
decoder->norm = V4L2_STD_PAL;
err = saa7191_autodetect_norm(sd);
if (err && (err != -EBUSY))
printk(KERN_ERR "SAA7191: Signal auto-detection failed\n");
return 0;
}
static int saa7191_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
v4l2_device_unregister_subdev(sd);
kfree(to_saa7191(sd));
return 0;
}
static const struct i2c_device_id saa7191_id[] = {
{ "saa7191", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, saa7191_id);
static struct i2c_driver saa7191_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "saa7191",
},
.probe = saa7191_probe,
.remove = saa7191_remove,
.id_table = saa7191_id,
};
module_i2c_driver(saa7191_driver);
| gpl-2.0 |
deedwar/pure | tools/perf/util/ctype.c | 9291 | 1465 | /*
* Sane locale-independent, ASCII ctype.
*
* No surprises, and works with signed and unsigned chars.
*/
#include "util.h"
enum {
S = GIT_SPACE,
A = GIT_ALPHA,
D = GIT_DIGIT,
G = GIT_GLOB_SPECIAL, /* *, ?, [, \\ */
R = GIT_REGEX_SPECIAL, /* $, (, ), +, ., ^, {, | * */
P = GIT_PRINT_EXTRA, /* printable - alpha - digit - glob - regex */
PS = GIT_SPACE | GIT_PRINT_EXTRA,
};
unsigned char sane_ctype[256] = {
/* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
0, 0, 0, 0, 0, 0, 0, 0, 0, S, S, 0, 0, S, 0, 0, /* 0.. 15 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16.. 31 */
PS,P, P, P, R, P, P, P, R, R, G, R, P, P, R, P, /* 32.. 47 */
D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, G, /* 48.. 63 */
P, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, /* 64.. 79 */
A, A, A, A, A, A, A, A, A, A, A, G, G, P, R, P, /* 80.. 95 */
P, A, A, A, A, A, A, A, A, A, A, A, A, A, A, A, /* 96..111 */
A, A, A, A, A, A, A, A, A, A, A, R, R, P, P, 0, /* 112..127 */
/* Nothing in the 128.. range */
};
const char *graph_line =
"_____________________________________________________________________"
"_____________________________________________________________________";
const char *graph_dotted_line =
"---------------------------------------------------------------------"
"---------------------------------------------------------------------"
"---------------------------------------------------------------------";
| gpl-2.0 |
varunchitre15/thunderzap_tomato | drivers/video/svgalib.c | 10571 | 20381 | /*
* Common utility functions for VGA-based graphics cards.
*
* Copyright (c) 2006-2007 Ondrej Zajicek <santiago@crfreenet.org>
*
* 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.
*
* Some parts are based on David Boucher's viafb (http://davesdomain.org.uk/viafb/)
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/fb.h>
#include <linux/svga.h>
#include <asm/types.h>
#include <asm/io.h>
/* Write a CRT register value spread across multiple registers */
void svga_wcrt_multi(void __iomem *regbase, const struct vga_regset *regset, u32 value)
{
u8 regval, bitval, bitnum;
while (regset->regnum != VGA_REGSET_END_VAL) {
regval = vga_rcrt(regbase, regset->regnum);
bitnum = regset->lowbit;
while (bitnum <= regset->highbit) {
bitval = 1 << bitnum;
regval = regval & ~bitval;
if (value & 1) regval = regval | bitval;
bitnum ++;
value = value >> 1;
}
vga_wcrt(regbase, regset->regnum, regval);
regset ++;
}
}
/* Write a sequencer register value spread across multiple registers */
void svga_wseq_multi(void __iomem *regbase, const struct vga_regset *regset, u32 value)
{
u8 regval, bitval, bitnum;
while (regset->regnum != VGA_REGSET_END_VAL) {
regval = vga_rseq(regbase, regset->regnum);
bitnum = regset->lowbit;
while (bitnum <= regset->highbit) {
bitval = 1 << bitnum;
regval = regval & ~bitval;
if (value & 1) regval = regval | bitval;
bitnum ++;
value = value >> 1;
}
vga_wseq(regbase, regset->regnum, regval);
regset ++;
}
}
static unsigned int svga_regset_size(const struct vga_regset *regset)
{
u8 count = 0;
while (regset->regnum != VGA_REGSET_END_VAL) {
count += regset->highbit - regset->lowbit + 1;
regset ++;
}
return 1 << count;
}
/* ------------------------------------------------------------------------- */
/* Set graphics controller registers to sane values */
void svga_set_default_gfx_regs(void __iomem *regbase)
{
/* All standard GFX registers (GR00 - GR08) */
vga_wgfx(regbase, VGA_GFX_SR_VALUE, 0x00);
vga_wgfx(regbase, VGA_GFX_SR_ENABLE, 0x00);
vga_wgfx(regbase, VGA_GFX_COMPARE_VALUE, 0x00);
vga_wgfx(regbase, VGA_GFX_DATA_ROTATE, 0x00);
vga_wgfx(regbase, VGA_GFX_PLANE_READ, 0x00);
vga_wgfx(regbase, VGA_GFX_MODE, 0x00);
/* vga_wgfx(regbase, VGA_GFX_MODE, 0x20); */
/* vga_wgfx(regbase, VGA_GFX_MODE, 0x40); */
vga_wgfx(regbase, VGA_GFX_MISC, 0x05);
/* vga_wgfx(regbase, VGA_GFX_MISC, 0x01); */
vga_wgfx(regbase, VGA_GFX_COMPARE_MASK, 0x0F);
vga_wgfx(regbase, VGA_GFX_BIT_MASK, 0xFF);
}
/* Set attribute controller registers to sane values */
void svga_set_default_atc_regs(void __iomem *regbase)
{
u8 count;
vga_r(regbase, 0x3DA);
vga_w(regbase, VGA_ATT_W, 0x00);
/* All standard ATC registers (AR00 - AR14) */
for (count = 0; count <= 0xF; count ++)
svga_wattr(regbase, count, count);
svga_wattr(regbase, VGA_ATC_MODE, 0x01);
/* svga_wattr(regbase, VGA_ATC_MODE, 0x41); */
svga_wattr(regbase, VGA_ATC_OVERSCAN, 0x00);
svga_wattr(regbase, VGA_ATC_PLANE_ENABLE, 0x0F);
svga_wattr(regbase, VGA_ATC_PEL, 0x00);
svga_wattr(regbase, VGA_ATC_COLOR_PAGE, 0x00);
vga_r(regbase, 0x3DA);
vga_w(regbase, VGA_ATT_W, 0x20);
}
/* Set sequencer registers to sane values */
void svga_set_default_seq_regs(void __iomem *regbase)
{
/* Standard sequencer registers (SR01 - SR04), SR00 is not set */
vga_wseq(regbase, VGA_SEQ_CLOCK_MODE, VGA_SR01_CHAR_CLK_8DOTS);
vga_wseq(regbase, VGA_SEQ_PLANE_WRITE, VGA_SR02_ALL_PLANES);
vga_wseq(regbase, VGA_SEQ_CHARACTER_MAP, 0x00);
/* vga_wseq(regbase, VGA_SEQ_MEMORY_MODE, VGA_SR04_EXT_MEM | VGA_SR04_SEQ_MODE | VGA_SR04_CHN_4M); */
vga_wseq(regbase, VGA_SEQ_MEMORY_MODE, VGA_SR04_EXT_MEM | VGA_SR04_SEQ_MODE);
}
/* Set CRTC registers to sane values */
void svga_set_default_crt_regs(void __iomem *regbase)
{
/* Standard CRT registers CR03 CR08 CR09 CR14 CR17 */
svga_wcrt_mask(regbase, 0x03, 0x80, 0x80); /* Enable vertical retrace EVRA */
vga_wcrt(regbase, VGA_CRTC_PRESET_ROW, 0);
svga_wcrt_mask(regbase, VGA_CRTC_MAX_SCAN, 0, 0x1F);
vga_wcrt(regbase, VGA_CRTC_UNDERLINE, 0);
vga_wcrt(regbase, VGA_CRTC_MODE, 0xE3);
}
void svga_set_textmode_vga_regs(void __iomem *regbase)
{
/* svga_wseq_mask(regbase, 0x1, 0x00, 0x01); */ /* Switch 8/9 pixel per char */
vga_wseq(regbase, VGA_SEQ_MEMORY_MODE, VGA_SR04_EXT_MEM);
vga_wseq(regbase, VGA_SEQ_PLANE_WRITE, 0x03);
vga_wcrt(regbase, VGA_CRTC_MAX_SCAN, 0x0f); /* 0x4f */
vga_wcrt(regbase, VGA_CRTC_UNDERLINE, 0x1f);
svga_wcrt_mask(regbase, VGA_CRTC_MODE, 0x23, 0x7f);
vga_wcrt(regbase, VGA_CRTC_CURSOR_START, 0x0d);
vga_wcrt(regbase, VGA_CRTC_CURSOR_END, 0x0e);
vga_wcrt(regbase, VGA_CRTC_CURSOR_HI, 0x00);
vga_wcrt(regbase, VGA_CRTC_CURSOR_LO, 0x00);
vga_wgfx(regbase, VGA_GFX_MODE, 0x10); /* Odd/even memory mode */
vga_wgfx(regbase, VGA_GFX_MISC, 0x0E); /* Misc graphics register - text mode enable */
vga_wgfx(regbase, VGA_GFX_COMPARE_MASK, 0x00);
vga_r(regbase, 0x3DA);
vga_w(regbase, VGA_ATT_W, 0x00);
svga_wattr(regbase, 0x10, 0x0C); /* Attribute Mode Control Register - text mode, blinking and line graphics */
svga_wattr(regbase, 0x13, 0x08); /* Horizontal Pixel Panning Register */
vga_r(regbase, 0x3DA);
vga_w(regbase, VGA_ATT_W, 0x20);
}
#if 0
void svga_dump_var(struct fb_var_screeninfo *var, int node)
{
pr_debug("fb%d: var.vmode : 0x%X\n", node, var->vmode);
pr_debug("fb%d: var.xres : %d\n", node, var->xres);
pr_debug("fb%d: var.yres : %d\n", node, var->yres);
pr_debug("fb%d: var.bits_per_pixel: %d\n", node, var->bits_per_pixel);
pr_debug("fb%d: var.xres_virtual : %d\n", node, var->xres_virtual);
pr_debug("fb%d: var.yres_virtual : %d\n", node, var->yres_virtual);
pr_debug("fb%d: var.left_margin : %d\n", node, var->left_margin);
pr_debug("fb%d: var.right_margin : %d\n", node, var->right_margin);
pr_debug("fb%d: var.upper_margin : %d\n", node, var->upper_margin);
pr_debug("fb%d: var.lower_margin : %d\n", node, var->lower_margin);
pr_debug("fb%d: var.hsync_len : %d\n", node, var->hsync_len);
pr_debug("fb%d: var.vsync_len : %d\n", node, var->vsync_len);
pr_debug("fb%d: var.sync : 0x%X\n", node, var->sync);
pr_debug("fb%d: var.pixclock : %d\n\n", node, var->pixclock);
}
#endif /* 0 */
/* ------------------------------------------------------------------------- */
void svga_settile(struct fb_info *info, struct fb_tilemap *map)
{
const u8 *font = map->data;
u8 __iomem *fb = (u8 __iomem *)info->screen_base;
int i, c;
if ((map->width != 8) || (map->height != 16) ||
(map->depth != 1) || (map->length != 256)) {
printk(KERN_ERR "fb%d: unsupported font parameters: width %d, height %d, depth %d, length %d\n",
info->node, map->width, map->height, map->depth, map->length);
return;
}
fb += 2;
for (c = 0; c < map->length; c++) {
for (i = 0; i < map->height; i++) {
fb_writeb(font[i], fb + i * 4);
// fb[i * 4] = font[i];
}
fb += 128;
font += map->height;
}
}
/* Copy area in text (tileblit) mode */
void svga_tilecopy(struct fb_info *info, struct fb_tilearea *area)
{
int dx, dy;
/* colstride is halved in this function because u16 are used */
int colstride = 1 << (info->fix.type_aux & FB_AUX_TEXT_SVGA_MASK);
int rowstride = colstride * (info->var.xres_virtual / 8);
u16 __iomem *fb = (u16 __iomem *) info->screen_base;
u16 __iomem *src, *dst;
if ((area->sy > area->dy) ||
((area->sy == area->dy) && (area->sx > area->dx))) {
src = fb + area->sx * colstride + area->sy * rowstride;
dst = fb + area->dx * colstride + area->dy * rowstride;
} else {
src = fb + (area->sx + area->width - 1) * colstride
+ (area->sy + area->height - 1) * rowstride;
dst = fb + (area->dx + area->width - 1) * colstride
+ (area->dy + area->height - 1) * rowstride;
colstride = -colstride;
rowstride = -rowstride;
}
for (dy = 0; dy < area->height; dy++) {
u16 __iomem *src2 = src;
u16 __iomem *dst2 = dst;
for (dx = 0; dx < area->width; dx++) {
fb_writew(fb_readw(src2), dst2);
// *dst2 = *src2;
src2 += colstride;
dst2 += colstride;
}
src += rowstride;
dst += rowstride;
}
}
/* Fill area in text (tileblit) mode */
void svga_tilefill(struct fb_info *info, struct fb_tilerect *rect)
{
int dx, dy;
int colstride = 2 << (info->fix.type_aux & FB_AUX_TEXT_SVGA_MASK);
int rowstride = colstride * (info->var.xres_virtual / 8);
int attr = (0x0F & rect->bg) << 4 | (0x0F & rect->fg);
u8 __iomem *fb = (u8 __iomem *)info->screen_base;
fb += rect->sx * colstride + rect->sy * rowstride;
for (dy = 0; dy < rect->height; dy++) {
u8 __iomem *fb2 = fb;
for (dx = 0; dx < rect->width; dx++) {
fb_writeb(rect->index, fb2);
fb_writeb(attr, fb2 + 1);
fb2 += colstride;
}
fb += rowstride;
}
}
/* Write text in text (tileblit) mode */
void svga_tileblit(struct fb_info *info, struct fb_tileblit *blit)
{
int dx, dy, i;
int colstride = 2 << (info->fix.type_aux & FB_AUX_TEXT_SVGA_MASK);
int rowstride = colstride * (info->var.xres_virtual / 8);
int attr = (0x0F & blit->bg) << 4 | (0x0F & blit->fg);
u8 __iomem *fb = (u8 __iomem *)info->screen_base;
fb += blit->sx * colstride + blit->sy * rowstride;
i=0;
for (dy=0; dy < blit->height; dy ++) {
u8 __iomem *fb2 = fb;
for (dx = 0; dx < blit->width; dx ++) {
fb_writeb(blit->indices[i], fb2);
fb_writeb(attr, fb2 + 1);
fb2 += colstride;
i ++;
if (i == blit->length) return;
}
fb += rowstride;
}
}
/* Set cursor in text (tileblit) mode */
void svga_tilecursor(void __iomem *regbase, struct fb_info *info, struct fb_tilecursor *cursor)
{
u8 cs = 0x0d;
u8 ce = 0x0e;
u16 pos = cursor->sx + (info->var.xoffset / 8)
+ (cursor->sy + (info->var.yoffset / 16))
* (info->var.xres_virtual / 8);
if (! cursor -> mode)
return;
svga_wcrt_mask(regbase, 0x0A, 0x20, 0x20); /* disable cursor */
if (cursor -> shape == FB_TILE_CURSOR_NONE)
return;
switch (cursor -> shape) {
case FB_TILE_CURSOR_UNDERLINE:
cs = 0x0d;
break;
case FB_TILE_CURSOR_LOWER_THIRD:
cs = 0x09;
break;
case FB_TILE_CURSOR_LOWER_HALF:
cs = 0x07;
break;
case FB_TILE_CURSOR_TWO_THIRDS:
cs = 0x05;
break;
case FB_TILE_CURSOR_BLOCK:
cs = 0x01;
break;
}
/* set cursor position */
vga_wcrt(regbase, 0x0E, pos >> 8);
vga_wcrt(regbase, 0x0F, pos & 0xFF);
vga_wcrt(regbase, 0x0B, ce); /* set cursor end */
vga_wcrt(regbase, 0x0A, cs); /* set cursor start and enable it */
}
int svga_get_tilemax(struct fb_info *info)
{
return 256;
}
/* Get capabilities of accelerator based on the mode */
void svga_get_caps(struct fb_info *info, struct fb_blit_caps *caps,
struct fb_var_screeninfo *var)
{
if (var->bits_per_pixel == 0) {
/* can only support 256 8x16 bitmap */
caps->x = 1 << (8 - 1);
caps->y = 1 << (16 - 1);
caps->len = 256;
} else {
caps->x = (var->bits_per_pixel == 4) ? 1 << (8 - 1) : ~(u32)0;
caps->y = ~(u32)0;
caps->len = ~(u32)0;
}
}
EXPORT_SYMBOL(svga_get_caps);
/* ------------------------------------------------------------------------- */
/*
* Compute PLL settings (M, N, R)
* F_VCO = (F_BASE * M) / N
* F_OUT = F_VCO / (2^R)
*/
static inline u32 abs_diff(u32 a, u32 b)
{
return (a > b) ? (a - b) : (b - a);
}
int svga_compute_pll(const struct svga_pll *pll, u32 f_wanted, u16 *m, u16 *n, u16 *r, int node)
{
u16 am, an, ar;
u32 f_vco, f_current, delta_current, delta_best;
pr_debug("fb%d: ideal frequency: %d kHz\n", node, (unsigned int) f_wanted);
ar = pll->r_max;
f_vco = f_wanted << ar;
/* overflow check */
if ((f_vco >> ar) != f_wanted)
return -EINVAL;
/* It is usually better to have greater VCO clock
because of better frequency stability.
So first try r_max, then r smaller. */
while ((ar > pll->r_min) && (f_vco > pll->f_vco_max)) {
ar--;
f_vco = f_vco >> 1;
}
/* VCO bounds check */
if ((f_vco < pll->f_vco_min) || (f_vco > pll->f_vco_max))
return -EINVAL;
delta_best = 0xFFFFFFFF;
*m = 0;
*n = 0;
*r = ar;
am = pll->m_min;
an = pll->n_min;
while ((am <= pll->m_max) && (an <= pll->n_max)) {
f_current = (pll->f_base * am) / an;
delta_current = abs_diff (f_current, f_vco);
if (delta_current < delta_best) {
delta_best = delta_current;
*m = am;
*n = an;
}
if (f_current <= f_vco) {
am ++;
} else {
an ++;
}
}
f_current = (pll->f_base * *m) / *n;
pr_debug("fb%d: found frequency: %d kHz (VCO %d kHz)\n", node, (int) (f_current >> ar), (int) f_current);
pr_debug("fb%d: m = %d n = %d r = %d\n", node, (unsigned int) *m, (unsigned int) *n, (unsigned int) *r);
return 0;
}
/* ------------------------------------------------------------------------- */
/* Check CRT timing values */
int svga_check_timings(const struct svga_timing_regs *tm, struct fb_var_screeninfo *var, int node)
{
u32 value;
var->xres = (var->xres+7)&~7;
var->left_margin = (var->left_margin+7)&~7;
var->right_margin = (var->right_margin+7)&~7;
var->hsync_len = (var->hsync_len+7)&~7;
/* Check horizontal total */
value = var->xres + var->left_margin + var->right_margin + var->hsync_len;
if (((value / 8) - 5) >= svga_regset_size (tm->h_total_regs))
return -EINVAL;
/* Check horizontal display and blank start */
value = var->xres;
if (((value / 8) - 1) >= svga_regset_size (tm->h_display_regs))
return -EINVAL;
if (((value / 8) - 1) >= svga_regset_size (tm->h_blank_start_regs))
return -EINVAL;
/* Check horizontal sync start */
value = var->xres + var->right_margin;
if (((value / 8) - 1) >= svga_regset_size (tm->h_sync_start_regs))
return -EINVAL;
/* Check horizontal blank end (or length) */
value = var->left_margin + var->right_margin + var->hsync_len;
if ((value == 0) || ((value / 8) >= svga_regset_size (tm->h_blank_end_regs)))
return -EINVAL;
/* Check horizontal sync end (or length) */
value = var->hsync_len;
if ((value == 0) || ((value / 8) >= svga_regset_size (tm->h_sync_end_regs)))
return -EINVAL;
/* Check vertical total */
value = var->yres + var->upper_margin + var->lower_margin + var->vsync_len;
if ((value - 1) >= svga_regset_size(tm->v_total_regs))
return -EINVAL;
/* Check vertical display and blank start */
value = var->yres;
if ((value - 1) >= svga_regset_size(tm->v_display_regs))
return -EINVAL;
if ((value - 1) >= svga_regset_size(tm->v_blank_start_regs))
return -EINVAL;
/* Check vertical sync start */
value = var->yres + var->lower_margin;
if ((value - 1) >= svga_regset_size(tm->v_sync_start_regs))
return -EINVAL;
/* Check vertical blank end (or length) */
value = var->upper_margin + var->lower_margin + var->vsync_len;
if ((value == 0) || (value >= svga_regset_size (tm->v_blank_end_regs)))
return -EINVAL;
/* Check vertical sync end (or length) */
value = var->vsync_len;
if ((value == 0) || (value >= svga_regset_size (tm->v_sync_end_regs)))
return -EINVAL;
return 0;
}
/* Set CRT timing registers */
void svga_set_timings(void __iomem *regbase, const struct svga_timing_regs *tm,
struct fb_var_screeninfo *var,
u32 hmul, u32 hdiv, u32 vmul, u32 vdiv, u32 hborder, int node)
{
u8 regval;
u32 value;
value = var->xres + var->left_margin + var->right_margin + var->hsync_len;
value = (value * hmul) / hdiv;
pr_debug("fb%d: horizontal total : %d\n", node, value);
svga_wcrt_multi(regbase, tm->h_total_regs, (value / 8) - 5);
value = var->xres;
value = (value * hmul) / hdiv;
pr_debug("fb%d: horizontal display : %d\n", node, value);
svga_wcrt_multi(regbase, tm->h_display_regs, (value / 8) - 1);
value = var->xres;
value = (value * hmul) / hdiv;
pr_debug("fb%d: horizontal blank start: %d\n", node, value);
svga_wcrt_multi(regbase, tm->h_blank_start_regs, (value / 8) - 1 + hborder);
value = var->xres + var->left_margin + var->right_margin + var->hsync_len;
value = (value * hmul) / hdiv;
pr_debug("fb%d: horizontal blank end : %d\n", node, value);
svga_wcrt_multi(regbase, tm->h_blank_end_regs, (value / 8) - 1 - hborder);
value = var->xres + var->right_margin;
value = (value * hmul) / hdiv;
pr_debug("fb%d: horizontal sync start : %d\n", node, value);
svga_wcrt_multi(regbase, tm->h_sync_start_regs, (value / 8));
value = var->xres + var->right_margin + var->hsync_len;
value = (value * hmul) / hdiv;
pr_debug("fb%d: horizontal sync end : %d\n", node, value);
svga_wcrt_multi(regbase, tm->h_sync_end_regs, (value / 8));
value = var->yres + var->upper_margin + var->lower_margin + var->vsync_len;
value = (value * vmul) / vdiv;
pr_debug("fb%d: vertical total : %d\n", node, value);
svga_wcrt_multi(regbase, tm->v_total_regs, value - 2);
value = var->yres;
value = (value * vmul) / vdiv;
pr_debug("fb%d: vertical display : %d\n", node, value);
svga_wcrt_multi(regbase, tm->v_display_regs, value - 1);
value = var->yres;
value = (value * vmul) / vdiv;
pr_debug("fb%d: vertical blank start : %d\n", node, value);
svga_wcrt_multi(regbase, tm->v_blank_start_regs, value);
value = var->yres + var->upper_margin + var->lower_margin + var->vsync_len;
value = (value * vmul) / vdiv;
pr_debug("fb%d: vertical blank end : %d\n", node, value);
svga_wcrt_multi(regbase, tm->v_blank_end_regs, value - 2);
value = var->yres + var->lower_margin;
value = (value * vmul) / vdiv;
pr_debug("fb%d: vertical sync start : %d\n", node, value);
svga_wcrt_multi(regbase, tm->v_sync_start_regs, value);
value = var->yres + var->lower_margin + var->vsync_len;
value = (value * vmul) / vdiv;
pr_debug("fb%d: vertical sync end : %d\n", node, value);
svga_wcrt_multi(regbase, tm->v_sync_end_regs, value);
/* Set horizontal and vertical sync pulse polarity in misc register */
regval = vga_r(regbase, VGA_MIS_R);
if (var->sync & FB_SYNC_HOR_HIGH_ACT) {
pr_debug("fb%d: positive horizontal sync\n", node);
regval = regval & ~0x80;
} else {
pr_debug("fb%d: negative horizontal sync\n", node);
regval = regval | 0x80;
}
if (var->sync & FB_SYNC_VERT_HIGH_ACT) {
pr_debug("fb%d: positive vertical sync\n", node);
regval = regval & ~0x40;
} else {
pr_debug("fb%d: negative vertical sync\n\n", node);
regval = regval | 0x40;
}
vga_w(regbase, VGA_MIS_W, regval);
}
/* ------------------------------------------------------------------------- */
static inline int match_format(const struct svga_fb_format *frm,
struct fb_var_screeninfo *var)
{
int i = 0;
int stored = -EINVAL;
while (frm->bits_per_pixel != SVGA_FORMAT_END_VAL)
{
if ((var->bits_per_pixel == frm->bits_per_pixel) &&
(var->red.length <= frm->red.length) &&
(var->green.length <= frm->green.length) &&
(var->blue.length <= frm->blue.length) &&
(var->transp.length <= frm->transp.length) &&
(var->nonstd == frm->nonstd))
return i;
if (var->bits_per_pixel == frm->bits_per_pixel)
stored = i;
i++;
frm++;
}
return stored;
}
int svga_match_format(const struct svga_fb_format *frm,
struct fb_var_screeninfo *var,
struct fb_fix_screeninfo *fix)
{
int i = match_format(frm, var);
if (i >= 0) {
var->bits_per_pixel = frm[i].bits_per_pixel;
var->red = frm[i].red;
var->green = frm[i].green;
var->blue = frm[i].blue;
var->transp = frm[i].transp;
var->nonstd = frm[i].nonstd;
if (fix != NULL) {
fix->type = frm[i].type;
fix->type_aux = frm[i].type_aux;
fix->visual = frm[i].visual;
fix->xpanstep = frm[i].xpanstep;
}
}
return i;
}
EXPORT_SYMBOL(svga_wcrt_multi);
EXPORT_SYMBOL(svga_wseq_multi);
EXPORT_SYMBOL(svga_set_default_gfx_regs);
EXPORT_SYMBOL(svga_set_default_atc_regs);
EXPORT_SYMBOL(svga_set_default_seq_regs);
EXPORT_SYMBOL(svga_set_default_crt_regs);
EXPORT_SYMBOL(svga_set_textmode_vga_regs);
EXPORT_SYMBOL(svga_settile);
EXPORT_SYMBOL(svga_tilecopy);
EXPORT_SYMBOL(svga_tilefill);
EXPORT_SYMBOL(svga_tileblit);
EXPORT_SYMBOL(svga_tilecursor);
EXPORT_SYMBOL(svga_get_tilemax);
EXPORT_SYMBOL(svga_compute_pll);
EXPORT_SYMBOL(svga_check_timings);
EXPORT_SYMBOL(svga_set_timings);
EXPORT_SYMBOL(svga_match_format);
MODULE_AUTHOR("Ondrej Zajicek <santiago@crfreenet.org>");
MODULE_DESCRIPTION("Common utility functions for VGA-based graphics cards");
MODULE_LICENSE("GPL");
| gpl-2.0 |
TimofeyFox/GT-S7270_kernel | fs/cramfs/uncompress.c | 12363 | 1735 | /*
* uncompress.c
*
* (C) Copyright 1999 Linus Torvalds
*
* cramfs interfaces to the uncompression library. There's really just
* three entrypoints:
*
* - cramfs_uncompress_init() - called to initialize the thing.
* - cramfs_uncompress_exit() - tell me when you're done
* - cramfs_uncompress_block() - uncompress a block.
*
* NOTE NOTE NOTE! The uncompression is entirely single-threaded. We
* only have one stream, and we'll initialize it only once even if it
* then is used by multiple filesystems.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/vmalloc.h>
#include <linux/zlib.h>
#include <linux/cramfs_fs.h>
static z_stream stream;
static int initialized;
/* Returns length of decompressed data. */
int cramfs_uncompress_block(void *dst, int dstlen, void *src, int srclen)
{
int err;
stream.next_in = src;
stream.avail_in = srclen;
stream.next_out = dst;
stream.avail_out = dstlen;
err = zlib_inflateReset(&stream);
if (err != Z_OK) {
printk("zlib_inflateReset error %d\n", err);
zlib_inflateEnd(&stream);
zlib_inflateInit(&stream);
}
err = zlib_inflate(&stream, Z_FINISH);
if (err != Z_STREAM_END)
goto err;
return stream.total_out;
err:
printk("Error %d while decompressing!\n", err);
printk("%p(%d)->%p(%d)\n", src, srclen, dst, dstlen);
return -EIO;
}
int cramfs_uncompress_init(void)
{
if (!initialized++) {
stream.workspace = vmalloc(zlib_inflate_workspacesize());
if ( !stream.workspace ) {
initialized = 0;
return -ENOMEM;
}
stream.next_in = NULL;
stream.avail_in = 0;
zlib_inflateInit(&stream);
}
return 0;
}
void cramfs_uncompress_exit(void)
{
if (!--initialized) {
zlib_inflateEnd(&stream);
vfree(stream.workspace);
}
}
| gpl-2.0 |
NicholasFengTW/linux | arch/mips/pmcs-msp71xx/msp_elb.c | 14155 | 1857 | /*
* Sets up the proper Chip Select configuration registers. It is assumed that
* PMON sets up the ADDR and MASK registers properly.
*
* Copyright 2005-2006 PMC-Sierra, Inc.
* Author: Marc St-Jean, Marc_St-Jean@pmc-sierra.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 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 <msp_regs.h>
static int __init msp_elb_setup(void)
{
#if defined(CONFIG_PMC_MSP7120_GW) \
|| defined(CONFIG_PMC_MSP7120_EVAL)
/*
* Force all CNFG to be identical and equal to CS0,
* according to OPS doc
*/
*CS1_CNFG_REG = *CS2_CNFG_REG = *CS3_CNFG_REG = *CS0_CNFG_REG;
#endif
return 0;
}
subsys_initcall(msp_elb_setup);
| gpl-2.0 |
kevinleegithup/mysql-5.6.17 | extra/perror.c | 76 | 9587 | /*
Copyright (c) 2000, 2013, Oracle and/or its affiliates. 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 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 */
/* Return error-text for system error messages and handler messages */
#define PERROR_VERSION "2.11"
#include <my_global.h>
#include <my_sys.h>
#include <m_string.h>
#include <errno.h>
#include <my_getopt.h>
#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE
#include "../storage/ndb/src/ndbapi/ndberror.c"
#include "../storage/ndb/src/kernel/error/ndbd_exit_codes.c"
#include "../storage/ndb/include/mgmapi/mgmapi_error.h"
#endif
#include <welcome_copyright_notice.h> /* ORACLE_WELCOME_COPYRIGHT_NOTICE */
static my_bool verbose;
#include "../include/my_base.h"
#include "../mysys/my_handler_errors.h"
#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE
static my_bool ndb_code;
static char ndb_string[1024];
int mgmapi_error_string(int err_no, char *str, int size)
{
int i;
for (i= 0; i < ndb_mgm_noOfErrorMsgs; i++)
{
if ((int)ndb_mgm_error_msgs[i].code == err_no)
{
my_snprintf(str, size-1, "%s", ndb_mgm_error_msgs[i].msg);
str[size-1]= '\0';
return 0;
}
}
return -1;
}
#endif
static struct my_option my_long_options[] =
{
{"help", '?', "Displays this help and exits.", 0, 0, 0, GET_NO_ARG,
NO_ARG, 0, 0, 0, 0, 0, 0},
{"info", 'I', "Synonym for --help.", 0, 0, 0, GET_NO_ARG,
NO_ARG, 0, 0, 0, 0, 0, 0},
#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE
{"ndb", 257, "Ndbcluster storage engine specific error codes.", &ndb_code,
&ndb_code, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"silent", 's', "Only print the error message.", 0, 0, 0, GET_NO_ARG, NO_ARG,
0, 0, 0, 0, 0, 0},
{"verbose", 'v', "Print error code and message (default).", &verbose,
&verbose, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
{"version", 'V', "Displays version information and exits.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};
static void print_version(void)
{
printf("%s Ver %s, for %s (%s)\n",my_progname,PERROR_VERSION,
SYSTEM_TYPE,MACHINE_TYPE);
}
static void usage(void)
{
print_version();
puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2000"));
printf("Print a description for a system error code or a MySQL error code.\n");
printf("If you want to get the error for a negative error code, you should use\n-- before the first error code to tell perror that there was no more options.\n\n");
printf("Usage: %s [OPTIONS] [ERRORCODE [ERRORCODE...]]\n",my_progname);
my_print_help(my_long_options);
my_print_variables(my_long_options);
}
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
char *argument __attribute__((unused)))
{
switch (optid) {
case 's':
verbose=0;
break;
case 'V':
print_version();
exit(0);
break;
case 'I':
case '?':
usage();
exit(0);
break;
}
return 0;
}
static int get_options(int *argc,char ***argv)
{
int ho_error;
if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
exit(ho_error);
if (!*argc)
{
usage();
return 1;
}
return 0;
} /* get_options */
static const char *get_ha_error_msg(int code)
{
/*
If you got compilation error here about compile_time_assert array, check
that every HA_ERR_xxx constant has a corresponding error message in
handler_error_messages[] list (check mysys/my_handler_errors.h and
include/my_base.h).
*/
compile_time_assert(HA_ERR_FIRST + array_elements(handler_error_messages) ==
HA_ERR_LAST + 1);
if (code >= HA_ERR_FIRST && code <= HA_ERR_LAST)
return handler_error_messages[code - HA_ERR_FIRST];
return NullS;
}
typedef struct
{
const char *name;
uint code;
const char *text;
} st_error;
static st_error global_error_names[] =
{
#include <mysqld_ername.h>
{ 0, 0, 0 }
};
/**
Lookup an error by code in the global_error_names array.
@param code the code to lookup
@param [out] name_ptr the error name, when found
@param [out] msg_ptr the error text, when found
@return 1 when found, otherwise 0
*/
int get_ER_error_msg(uint code, const char **name_ptr, const char **msg_ptr)
{
st_error *tmp_error;
tmp_error= & global_error_names[0];
while (tmp_error->name != NULL)
{
if (tmp_error->code == code)
{
*name_ptr= tmp_error->name;
*msg_ptr= tmp_error->text;
return 1;
}
tmp_error++;
}
return 0;
}
#if defined(__WIN__)
static my_bool print_win_error_msg(DWORD error, my_bool verbose)
{
LPTSTR s;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, error, 0, (LPTSTR)&s, 0,
NULL))
{
if (verbose)
printf("Win32 error code %d: %s", error, s);
else
puts(s);
LocalFree(s);
return 0;
}
return 1;
}
#endif
/*
Register handler error messages for usage with my_error()
NOTES
This is safe to call multiple times as my_error_register()
will ignore calls to register already registered error numbers.
*/
static const char **get_handler_error_messages()
{
return handler_error_messages;
}
void my_handler_error_register(void)
{
/*
If you got compilation error here about compile_time_assert array, check
that every HA_ERR_xxx constant has a corresponding error message in
handler_error_messages[] list (check mysys/ma_handler_errors.h and
include/my_base.h).
*/
compile_time_assert(HA_ERR_FIRST + array_elements(handler_error_messages) ==
HA_ERR_LAST + 1);
my_error_register(get_handler_error_messages, HA_ERR_FIRST,
HA_ERR_FIRST+ array_elements(handler_error_messages)-1);
}
void my_handler_error_unregister(void)
{
my_error_unregister(HA_ERR_FIRST,
HA_ERR_FIRST+ array_elements(handler_error_messages)-1);
}
int main(int argc,char *argv[])
{
int error,code,found;
const char *msg;
const char *name;
char *unknown_error = 0;
#if defined(__WIN__)
my_bool skip_win_message= 0;
#endif
MY_INIT(argv[0]);
if (get_options(&argc,&argv))
exit(1);
my_handler_error_register();
error=0;
{
/*
On some system, like Linux, strerror(unknown_error) returns a
string 'Unknown Error'. To avoid printing it we try to find the
error string by asking for an impossible big error message.
On Solaris 2.8 it might return NULL
*/
if ((msg= strerror(10000)) == NULL)
msg= "Unknown Error";
/*
Allocate a buffer for unknown_error since strerror always returns
the same pointer on some platforms such as Windows
*/
unknown_error= malloc(strlen(msg)+1);
strmov(unknown_error, msg);
for ( ; argc-- > 0 ; argv++)
{
found=0;
code=atoi(*argv);
#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE
if (ndb_code)
{
if ((ndb_error_string(code, ndb_string, sizeof(ndb_string)) < 0) &&
(ndbd_exit_string(code, ndb_string, sizeof(ndb_string)) < 0) &&
(mgmapi_error_string(code, ndb_string, sizeof(ndb_string)) < 0))
{
msg= 0;
}
else
msg= ndb_string;
if (msg)
{
if (verbose)
printf("NDB error code %3d: %s\n",code,msg);
else
puts(msg);
}
else
{
fprintf(stderr,"Illegal ndb error code: %d\n",code);
error= 1;
}
found= 1;
msg= 0;
}
else
#endif
msg = strerror(code);
/*
We don't print the OS error message if it is the same as the
unknown_error message we retrieved above, or it starts with
'Unknown Error' (without regard to case).
*/
if (msg &&
my_strnncoll(&my_charset_latin1, (const uchar*) msg, 13,
(const uchar*) "Unknown Error", 13) &&
(!unknown_error || strcmp(msg, unknown_error)))
{
found= 1;
if (verbose)
printf("OS error code %3d: %s\n", code, msg);
else
puts(msg);
}
if ((msg= get_ha_error_msg(code)))
{
found= 1;
if (verbose)
printf("MySQL error code %3d: %s\n", code, msg);
else
puts(msg);
}
if (get_ER_error_msg(code, & name, & msg))
{
found= 1;
if (verbose)
printf("MySQL error code %3d (%s): %s\n", code, name, msg);
else
puts(msg);
}
if (!found)
{
#if defined(__WIN__)
if (!(skip_win_message= !print_win_error_msg((DWORD)code, verbose)))
{
#endif
fprintf(stderr,"Illegal error code: %d\n",code);
error=1;
#if defined(__WIN__)
}
#endif
}
#if defined(__WIN__)
if (!skip_win_message)
print_win_error_msg((DWORD)code, verbose);
#endif
}
}
/* if we allocated a buffer for unknown_error, free it now */
if (unknown_error)
free(unknown_error);
exit(error);
return error;
}
| gpl-2.0 |
finnq/android_kernel_asus_tf101 | drivers/video/tegra/host/nvhost_intr.c | 76 | 10719 | /*
* drivers/video/tegra/host/nvhost_intr.c
*
* Tegra Graphics Host Interrupt Management
*
* Copyright (c) 2010-2011, NVIDIA Corporation.
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "nvhost_intr.h"
#include "dev.h"
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <trace/events/nvhost.h>
/*** Wait list management ***/
struct nvhost_waitlist {
struct list_head list;
struct kref refcount;
u32 thresh;
enum nvhost_intr_action action;
atomic_t state;
void *data;
int count;
};
enum waitlist_state {
WLS_PENDING,
WLS_REMOVED,
WLS_CANCELLED,
WLS_HANDLED
};
static void waiter_release(struct kref *kref)
{
kfree(container_of(kref, struct nvhost_waitlist, refcount));
}
/**
* add a waiter to a waiter queue, sorted by threshold
* returns true if it was added at the head of the queue
*/
static bool add_waiter_to_queue(struct nvhost_waitlist *waiter,
struct list_head *queue)
{
struct nvhost_waitlist *pos;
u32 thresh = waiter->thresh;
list_for_each_entry_reverse(pos, queue, list)
if ((s32)(pos->thresh - thresh) <= 0) {
list_add(&waiter->list, &pos->list);
return false;
}
list_add(&waiter->list, queue);
return true;
}
/**
* run through a waiter queue for a single sync point ID
* and gather all completed waiters into lists by actions
*/
static void remove_completed_waiters(struct list_head *head, u32 sync,
struct list_head completed[NVHOST_INTR_ACTION_COUNT])
{
struct list_head *dest;
struct nvhost_waitlist *waiter, *next, *prev;
list_for_each_entry_safe(waiter, next, head, list) {
if ((s32)(waiter->thresh - sync) > 0)
break;
dest = completed + waiter->action;
/* consolidate submit cleanups */
if (waiter->action == NVHOST_INTR_ACTION_SUBMIT_COMPLETE
&& !list_empty(dest)) {
prev = list_entry(dest->prev,
struct nvhost_waitlist, list);
if (prev->data == waiter->data) {
prev->count++;
dest = NULL;
}
}
/* PENDING->REMOVED or CANCELLED->HANDLED */
if (atomic_inc_return(&waiter->state) == WLS_HANDLED || !dest) {
list_del(&waiter->list);
kref_put(&waiter->refcount, waiter_release);
} else {
list_move_tail(&waiter->list, dest);
}
}
}
void reset_threshold_interrupt(struct nvhost_intr *intr,
struct list_head *head,
unsigned int id)
{
u32 thresh = list_first_entry(head,
struct nvhost_waitlist, list)->thresh;
BUG_ON(!(intr_op(intr).set_syncpt_threshold &&
intr_op(intr).enable_syncpt_intr));
intr_op(intr).set_syncpt_threshold(intr, id, thresh);
intr_op(intr).enable_syncpt_intr(intr, id);
}
static void action_submit_complete(struct nvhost_waitlist *waiter)
{
struct nvhost_channel *channel = waiter->data;
int nr_completed = waiter->count;
/* Add nr_completed to trace */
trace_nvhost_channel_submit_complete(channel->desc->name,
nr_completed);
nvhost_cdma_update(&channel->cdma);
nvhost_module_idle_mult(&channel->mod, nr_completed);
}
static void action_ctxsave(struct nvhost_waitlist *waiter)
{
struct nvhost_hwctx *hwctx = waiter->data;
struct nvhost_channel *channel = hwctx->channel;
if (channel->ctxhandler.save_service)
channel->ctxhandler.save_service(hwctx);
channel->ctxhandler.put(hwctx);
}
static void action_ctxrestore(struct nvhost_waitlist *waiter)
{
struct nvhost_hwctx *hwctx = waiter->data;
struct nvhost_channel *channel = hwctx->channel;
channel->ctxhandler.put(hwctx);
}
static void action_wakeup(struct nvhost_waitlist *waiter)
{
wait_queue_head_t *wq = waiter->data;
wake_up(wq);
}
static void action_wakeup_interruptible(struct nvhost_waitlist *waiter)
{
wait_queue_head_t *wq = waiter->data;
wake_up_interruptible(wq);
}
typedef void (*action_handler)(struct nvhost_waitlist *waiter);
static action_handler action_handlers[NVHOST_INTR_ACTION_COUNT] = {
action_submit_complete,
action_ctxsave,
action_ctxrestore,
action_wakeup,
action_wakeup_interruptible,
};
static void run_handlers(struct list_head completed[NVHOST_INTR_ACTION_COUNT])
{
struct list_head *head = completed;
int i;
for (i = 0; i < NVHOST_INTR_ACTION_COUNT; ++i, ++head) {
action_handler handler = action_handlers[i];
struct nvhost_waitlist *waiter, *next;
list_for_each_entry_safe(waiter, next, head, list) {
list_del(&waiter->list);
handler(waiter);
WARN_ON(atomic_xchg(&waiter->state, WLS_HANDLED) != WLS_REMOVED);
kref_put(&waiter->refcount, waiter_release);
}
}
}
/**
* Remove & handle all waiters that have completed for the given syncpt
*/
static int process_wait_list(struct nvhost_intr *intr,
struct nvhost_intr_syncpt *syncpt,
u32 threshold)
{
struct list_head completed[NVHOST_INTR_ACTION_COUNT];
unsigned int i;
int empty;
for (i = 0; i < NVHOST_INTR_ACTION_COUNT; ++i)
INIT_LIST_HEAD(completed + i);
spin_lock(&syncpt->lock);
remove_completed_waiters(&syncpt->wait_head, threshold, completed);
empty = list_empty(&syncpt->wait_head);
if (!empty)
reset_threshold_interrupt(intr, &syncpt->wait_head,
syncpt->id);
spin_unlock(&syncpt->lock);
run_handlers(completed);
return empty;
}
/*** host syncpt interrupt service functions ***/
/**
* Sync point threshold interrupt service thread function
* Handles sync point threshold triggers, in thread context
*/
irqreturn_t nvhost_syncpt_thresh_fn(int irq, void *dev_id)
{
struct nvhost_intr_syncpt *syncpt = dev_id;
unsigned int id = syncpt->id;
struct nvhost_intr *intr = intr_syncpt_to_intr(syncpt);
struct nvhost_master *dev = intr_to_dev(intr);
(void)process_wait_list(intr, syncpt,
nvhost_syncpt_update_min(&dev->syncpt, id));
return IRQ_HANDLED;
}
/**
* free a syncpt's irq. syncpt interrupt should be disabled first.
*/
static void free_syncpt_irq(struct nvhost_intr_syncpt *syncpt)
{
if (syncpt->irq_requested) {
free_irq(syncpt->irq, syncpt);
syncpt->irq_requested = 0;
}
}
/*** host general interrupt service functions ***/
/*** Main API ***/
int nvhost_intr_add_action(struct nvhost_intr *intr, u32 id, u32 thresh,
enum nvhost_intr_action action, void *data,
void *_waiter,
void **ref)
{
struct nvhost_waitlist *waiter = _waiter;
struct nvhost_intr_syncpt *syncpt;
int queue_was_empty;
int err;
BUG_ON(waiter == NULL);
BUG_ON(!(intr_op(intr).set_syncpt_threshold &&
intr_op(intr).enable_syncpt_intr));
/* initialize a new waiter */
INIT_LIST_HEAD(&waiter->list);
kref_init(&waiter->refcount);
if (ref)
kref_get(&waiter->refcount);
waiter->thresh = thresh;
waiter->action = action;
atomic_set(&waiter->state, WLS_PENDING);
waiter->data = data;
waiter->count = 1;
BUG_ON(id >= intr_to_dev(intr)->syncpt.nb_pts);
syncpt = intr->syncpt + id;
spin_lock(&syncpt->lock);
/* lazily request irq for this sync point */
if (!syncpt->irq_requested) {
spin_unlock(&syncpt->lock);
mutex_lock(&intr->mutex);
BUG_ON(!(intr_op(intr).request_syncpt_irq));
err = intr_op(intr).request_syncpt_irq(syncpt);
mutex_unlock(&intr->mutex);
if (err) {
kfree(waiter);
return err;
}
spin_lock(&syncpt->lock);
}
queue_was_empty = list_empty(&syncpt->wait_head);
if (add_waiter_to_queue(waiter, &syncpt->wait_head)) {
/* added at head of list - new threshold value */
intr_op(intr).set_syncpt_threshold(intr, id, thresh);
/* added as first waiter - enable interrupt */
if (queue_was_empty)
intr_op(intr).enable_syncpt_intr(intr, id);
}
spin_unlock(&syncpt->lock);
if (ref)
*ref = waiter;
return 0;
}
void *nvhost_intr_alloc_waiter()
{
return kzalloc(sizeof(struct nvhost_waitlist),
GFP_KERNEL|__GFP_REPEAT);
}
void nvhost_intr_put_ref(struct nvhost_intr *intr, void *ref)
{
struct nvhost_waitlist *waiter = ref;
while (atomic_cmpxchg(&waiter->state,
WLS_PENDING, WLS_CANCELLED) == WLS_REMOVED)
schedule();
kref_put(&waiter->refcount, waiter_release);
}
/*** Init & shutdown ***/
int nvhost_intr_init(struct nvhost_intr *intr, u32 irq_gen, u32 irq_sync)
{
unsigned int id;
struct nvhost_intr_syncpt *syncpt;
struct nvhost_master *host =
container_of(intr, struct nvhost_master, intr);
u32 nb_pts = host->syncpt.nb_pts;
mutex_init(&intr->mutex);
intr->host_general_irq = irq_gen;
intr->host_general_irq_requested = false;
for (id = 0, syncpt = intr->syncpt;
id < nb_pts;
++id, ++syncpt) {
syncpt->intr = &host->intr;
syncpt->id = id;
syncpt->irq = irq_sync + id;
syncpt->irq_requested = 0;
spin_lock_init(&syncpt->lock);
INIT_LIST_HEAD(&syncpt->wait_head);
snprintf(syncpt->thresh_irq_name,
sizeof(syncpt->thresh_irq_name),
"host_sp_%02d", id);
}
return 0;
}
void nvhost_intr_deinit(struct nvhost_intr *intr)
{
nvhost_intr_stop(intr);
}
void nvhost_intr_start(struct nvhost_intr *intr, u32 hz)
{
BUG_ON(!(intr_op(intr).init_host_sync &&
intr_op(intr).set_host_clocks_per_usec &&
intr_op(intr).request_host_general_irq));
mutex_lock(&intr->mutex);
intr_op(intr).init_host_sync(intr);
intr_op(intr).set_host_clocks_per_usec(intr,
(hz + 1000000 - 1)/1000000);
intr_op(intr).request_host_general_irq(intr);
mutex_unlock(&intr->mutex);
}
void nvhost_intr_stop(struct nvhost_intr *intr)
{
unsigned int id;
struct nvhost_intr_syncpt *syncpt;
u32 nb_pts = intr_to_dev(intr)->syncpt.nb_pts;
BUG_ON(!(intr_op(intr).disable_all_syncpt_intrs &&
intr_op(intr).free_host_general_irq));
mutex_lock(&intr->mutex);
intr_op(intr).disable_all_syncpt_intrs(intr);
for (id = 0, syncpt = intr->syncpt;
id < nb_pts;
++id, ++syncpt) {
struct nvhost_waitlist *waiter, *next;
list_for_each_entry_safe(waiter, next, &syncpt->wait_head, list) {
if (atomic_cmpxchg(&waiter->state, WLS_CANCELLED, WLS_HANDLED)
== WLS_CANCELLED) {
list_del(&waiter->list);
kref_put(&waiter->refcount, waiter_release);
}
}
if (!list_empty(&syncpt->wait_head)) { /* output diagnostics */
printk(KERN_DEBUG "%s id=%d\n", __func__, id);
BUG_ON(1);
}
free_syncpt_irq(syncpt);
}
intr_op(intr).free_host_general_irq(intr);
mutex_unlock(&intr->mutex);
}
| gpl-2.0 |
ExPeacer/CAF_android-msm-2.6.32 | arch/arm/mach-msm/qdsp6v2/apr_tal_debug.c | 76 | 5062 | /* Copyright (c) 2010, 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.
*
* 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.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/uaccess.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/list.h>
#include <linux/sched.h>
#include <linux/wait.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/debugfs.h>
#include <linux/delay.h>
#include <mach/msm_smd.h>
#include "apr.h"
struct dentry *dentry;
struct apr_svc_ch_dev *handle;
struct apr_svc *apr_handle_q;
struct apr_svc *apr_handle_m;
struct apr_client_data clnt_data;
char l_buf[4096];
static int32_t aprv2_debug_fn_q(struct apr_client_data *data, void *priv)
{
pr_debug("Q6_Payload Length = %d\n", data->payload_size);
if (memcmp(data->payload, l_buf + 20, data->payload_size))
pr_info("FAIL: %d\n", data->payload_size);
else
pr_info("SUCCESS: %d\n", data->payload_size);
return 0;
}
static int32_t aprv2_debug_fn_m(struct apr_client_data *data, void *priv)
{
pr_info("M_Payload Length = %d\n", data->payload_size);
return 0;
}
static ssize_t apr_debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
pr_debug("apr debugfs opened\n");
return 0;
}
static ssize_t apr_debug_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int len;
static int t_len;
if (count < 0)
return 0;
len = count > 63 ? 63 : count;
if (copy_from_user(l_buf + 20 , buf, len)) {
pr_info("Unable to copy data from user space\n");
return -EFAULT;
}
l_buf[len + 20] = 0;
if (l_buf[len + 20 - 1] == '\n') {
l_buf[len + 20 - 1] = 0;
len--;
}
if (!strncmp(l_buf + 20, "open_q", 64)) {
apr_handle_q = apr_register("ADSP", "TEST", aprv2_debug_fn_q,
0xFFFFFFFF, NULL);
pr_info("Open_q %p\n", apr_handle_q);
} else if (!strncmp(l_buf + 20, "open_m", 64)) {
apr_handle_m = apr_register("MODEM", "TEST", aprv2_debug_fn_m,
0xFFFFFFFF, NULL);
pr_info("Open_m %p\n", apr_handle_m);
} else if (!strncmp(l_buf + 20, "write_q", 64)) {
struct apr_hdr *hdr;
t_len++;
t_len = t_len % 450;
if (!t_len % 99)
msleep(2000);
hdr = (struct apr_hdr *)l_buf;
hdr->hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_EVENT,
APR_HDR_LEN(20), APR_PKT_VER);
hdr->pkt_size = APR_PKT_SIZE(20, t_len);
hdr->src_port = 0;
hdr->dest_port = 0;
hdr->token = 0;
hdr->opcode = 0x12345678;
memset(l_buf + 20, 9, 4060);
apr_send_pkt(apr_handle_q, (uint32_t *)l_buf);
pr_debug("Write_q\n");
} else if (!strncmp(l_buf + 20, "write_m", 64)) {
struct apr_hdr *hdr;
hdr = (struct apr_hdr *)l_buf;
hdr->hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_EVENT,
APR_HDR_LEN(20), APR_PKT_VER);
hdr->pkt_size = APR_PKT_SIZE(20, 8);
hdr->src_port = 0;
hdr->dest_port = 0;
hdr->token = 0;
hdr->opcode = 0x12345678;
memset(l_buf + 30, 9, 4060);
apr_send_pkt(apr_handle_m, (uint32_t *)l_buf);
pr_info("Write_m\n");
} else if (!strncmp(l_buf + 20, "write_q4", 64)) {
struct apr_hdr *hdr;
hdr = (struct apr_hdr *)l_buf;
hdr->hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_EVENT,
APR_HDR_LEN(20), APR_PKT_VER);
hdr->pkt_size = APR_PKT_SIZE(20, 4076);
hdr->src_port = 0;
hdr->dest_port = 0;
hdr->token = 0;
hdr->opcode = 0x12345678;
memset(l_buf + 30, 9, 4060);
apr_send_pkt(apr_handle_q, (uint32_t *)l_buf);
pr_info("Write_q\n");
} else if (!strncmp(l_buf + 20, "write_m4", 64)) {
struct apr_hdr *hdr;
hdr = (struct apr_hdr *)l_buf;
hdr->hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_EVENT,
APR_HDR_LEN(20), APR_PKT_VER);
hdr->pkt_size = APR_PKT_SIZE(20, 4076);
hdr->src_port = 0;
hdr->dest_port = 0;
hdr->token = 0;
hdr->opcode = 0x12345678;
memset(l_buf + 30, 9, 4060);
apr_send_pkt(apr_handle_m, (uint32_t *)l_buf);
pr_info("Write_m\n");
} else if (!strncmp(l_buf + 20, "close", 64)) {
apr_deregister(apr_handle_q);
} else if (!strncmp(l_buf + 20, "loaded", 64)) {
change_q6_state(APR_Q6_LOADED);
} else
pr_info("Unknown Command\n");
return count;
}
static const struct file_operations apr_debug_fops = {
.write = apr_debug_write,
.open = apr_debug_open,
};
static int __init apr_init(void)
{
#ifdef CONFIG_DEBUG_FS
dentry = debugfs_create_file("apr", S_IFREG | S_IWUGO,
NULL, (void *) NULL, &apr_debug_fops);
#endif /* CONFIG_DEBUG_FS */
return 0;
}
device_initcall(apr_init);
| gpl-2.0 |
garrikus/o3_uboot | board/atum8548/ddr.c | 332 | 1766 | /*
* Copyright 2008 Freescale Semiconductor, 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.
*/
#include <common.h>
#include <i2c.h>
#include <asm/fsl_ddr_sdram.h>
#include <asm/fsl_ddr_dimm_params.h>
static void
get_spd(ddr2_spd_eeprom_t *spd, unsigned char i2c_address)
{
i2c_read(i2c_address, 0, 1, (uchar *)spd, sizeof(ddr2_spd_eeprom_t));
}
unsigned int fsl_ddr_get_mem_data_rate(void)
{
return get_ddr_freq(0);
}
void fsl_ddr_get_spd(ddr2_spd_eeprom_t *ctrl_dimms_spd,
unsigned int ctrl_num)
{
unsigned int i;
if (ctrl_num) {
printf("%s unexpected ctrl_num = %u\n", __FUNCTION__, ctrl_num);
return;
}
for (i = 0; i < CONFIG_DIMM_SLOTS_PER_CTLR; i++) {
get_spd(&(ctrl_dimms_spd[i]), SPD_EEPROM_ADDRESS);
}
}
void fsl_ddr_board_options(memctl_options_t *popts,
dimm_params_t *pdimm,
unsigned int ctrl_num)
{
/*
* Factors to consider for clock adjust:
* - number of chips on bus
* - position of slot
* - DDR1 vs. DDR2?
* - ???
*
* This needs to be determined on a board-by-board basis.
* 0110 3/4 cycle late
* 0111 7/8 cycle late
*/
popts->clk_adjust = 7;
/*
* Factors to consider for CPO:
* - frequency
* - ddr1 vs. ddr2
*/
popts->cpo_override = 10;
/*
* Factors to consider for write data delay:
* - number of DIMMs
*
* 1 = 1/4 clock delay
* 2 = 1/2 clock delay
* 3 = 3/4 clock delay
* 4 = 1 clock delay
* 5 = 5/4 clock delay
* 6 = 3/2 clock delay
*/
popts->write_data_delay = 3;
/*
* Factors to consider for half-strength driver enable:
* - number of DIMMs installed
*/
popts->half_strength_driver_enable = 0;
}
| gpl-2.0 |
Sharlion/android_kernel_lenovo_msm8992 | drivers/usb/serial/quatech2.c | 1868 | 25744 | /*
* usb-serial driver for Quatech USB 2 devices
*
* Copyright (C) 2012 Bill Pemberton (wfp5p@virginia.edu)
*
* 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.
*
*
* These devices all have only 1 bulk in and 1 bulk out that is shared
* for all serial ports.
*
*/
#include <asm/unaligned.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/serial.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include <linux/serial_reg.h>
#include <linux/uaccess.h>
/* default urb timeout for usb operations */
#define QT2_USB_TIMEOUT USB_CTRL_SET_TIMEOUT
#define QT_OPEN_CLOSE_CHANNEL 0xca
#define QT_SET_GET_DEVICE 0xc2
#define QT_SET_GET_REGISTER 0xc0
#define QT_GET_SET_PREBUF_TRIG_LVL 0xcc
#define QT_SET_ATF 0xcd
#define QT_TRANSFER_IN 0xc0
#define QT_HW_FLOW_CONTROL_MASK 0xc5
#define QT_SW_FLOW_CONTROL_MASK 0xc6
#define QT2_BREAK_CONTROL 0xc8
#define QT2_GET_SET_UART 0xc1
#define QT2_FLUSH_DEVICE 0xc4
#define QT2_GET_SET_QMCR 0xe1
#define QT2_QMCR_RS232 0x40
#define QT2_QMCR_RS422 0x10
#define SERIAL_CRTSCTS ((UART_MCR_RTS << 8) | UART_MSR_CTS)
#define SERIAL_EVEN_PARITY (UART_LCR_PARITY | UART_LCR_EPAR)
/* status bytes for the device */
#define QT2_CONTROL_BYTE 0x1b
#define QT2_LINE_STATUS 0x00 /* following 1 byte is line status */
#define QT2_MODEM_STATUS 0x01 /* following 1 byte is modem status */
#define QT2_XMIT_HOLD 0x02 /* following 2 bytes are ?? */
#define QT2_CHANGE_PORT 0x03 /* following 1 byte is port to change to */
#define QT2_REC_FLUSH 0x04 /* no following info */
#define QT2_XMIT_FLUSH 0x05 /* no following info */
#define QT2_CONTROL_ESCAPE 0xff /* pass through previous 2 control bytes */
#define MAX_BAUD_RATE 921600
#define DEFAULT_BAUD_RATE 9600
#define QT2_WRITE_BUFFER_SIZE 512 /* size of write buffer */
#define QT2_WRITE_CONTROL_SIZE 5 /* control bytes used for a write */
#define DRIVER_DESC "Quatech 2nd gen USB to Serial Driver"
#define USB_VENDOR_ID_QUATECH 0x061d
#define QUATECH_SSU2_100 0xC120 /* RS232 single port */
#define QUATECH_DSU2_100 0xC140 /* RS232 dual port */
#define QUATECH_DSU2_400 0xC150 /* RS232/422/485 dual port */
#define QUATECH_QSU2_100 0xC160 /* RS232 four port */
#define QUATECH_QSU2_400 0xC170 /* RS232/422/485 four port */
#define QUATECH_ESU2_100 0xC1A0 /* RS232 eight port */
#define QUATECH_ESU2_400 0xC180 /* RS232/422/485 eight port */
struct qt2_device_detail {
int product_id;
int num_ports;
};
#define QT_DETAILS(prod, ports) \
.product_id = (prod), \
.num_ports = (ports)
static const struct qt2_device_detail qt2_device_details[] = {
{QT_DETAILS(QUATECH_SSU2_100, 1)},
{QT_DETAILS(QUATECH_DSU2_400, 2)},
{QT_DETAILS(QUATECH_DSU2_100, 2)},
{QT_DETAILS(QUATECH_QSU2_400, 4)},
{QT_DETAILS(QUATECH_QSU2_100, 4)},
{QT_DETAILS(QUATECH_ESU2_400, 8)},
{QT_DETAILS(QUATECH_ESU2_100, 8)},
{QT_DETAILS(0, 0)} /* Terminating entry */
};
static const struct usb_device_id id_table[] = {
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_SSU2_100)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU2_100)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_DSU2_400)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU2_100)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_QSU2_400)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU2_100)},
{USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_ESU2_400)},
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table);
struct qt2_serial_private {
unsigned char current_port; /* current port for incoming data */
struct urb *read_urb; /* shared among all ports */
char read_buffer[512];
};
struct qt2_port_private {
u8 device_port;
spinlock_t urb_lock;
bool urb_in_use;
struct urb *write_urb;
char write_buffer[QT2_WRITE_BUFFER_SIZE];
spinlock_t lock;
u8 shadowLSR;
u8 shadowMSR;
struct usb_serial_port *port;
};
static void qt2_update_lsr(struct usb_serial_port *port, unsigned char *ch);
static void qt2_update_msr(struct usb_serial_port *port, unsigned char *ch);
static void qt2_write_bulk_callback(struct urb *urb);
static void qt2_read_bulk_callback(struct urb *urb);
static void qt2_release(struct usb_serial *serial)
{
struct qt2_serial_private *serial_priv;
serial_priv = usb_get_serial_data(serial);
usb_free_urb(serial_priv->read_urb);
kfree(serial_priv);
}
static inline int calc_baud_divisor(int baudrate)
{
int divisor, rem;
divisor = MAX_BAUD_RATE / baudrate;
rem = MAX_BAUD_RATE % baudrate;
/* Round to nearest divisor */
if (((rem * 2) >= baudrate) && (baudrate != 110))
divisor++;
return divisor;
}
static inline int qt2_set_port_config(struct usb_device *dev,
unsigned char port_number,
u16 baudrate, u16 lcr)
{
int divisor = calc_baud_divisor(baudrate);
u16 index = ((u16) (lcr << 8) | (u16) (port_number));
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
QT2_GET_SET_UART, 0x40,
divisor, index, NULL, 0, QT2_USB_TIMEOUT);
}
static inline int qt2_control_msg(struct usb_device *dev,
u8 request, u16 data, u16 index)
{
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
request, 0x40, data, index,
NULL, 0, QT2_USB_TIMEOUT);
}
static inline int qt2_setdevice(struct usb_device *dev, u8 *data)
{
u16 x = ((u16) (data[1] << 8) | (u16) (data[0]));
return qt2_control_msg(dev, QT_SET_GET_DEVICE, x, 0);
}
static inline int qt2_getdevice(struct usb_device *dev, u8 *data)
{
return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
QT_SET_GET_DEVICE, 0xc0, 0, 0,
data, 3, QT2_USB_TIMEOUT);
}
static inline int qt2_getregister(struct usb_device *dev,
u8 uart,
u8 reg,
u8 *data)
{
return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
QT_SET_GET_REGISTER, 0xc0, reg,
uart, data, sizeof(*data), QT2_USB_TIMEOUT);
}
static inline int qt2_setregister(struct usb_device *dev,
u8 uart, u8 reg, u16 data)
{
u16 value = (data << 8) | reg;
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
QT_SET_GET_REGISTER, 0x40, value, uart,
NULL, 0, QT2_USB_TIMEOUT);
}
static inline int update_mctrl(struct qt2_port_private *port_priv,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = port_priv->port;
struct usb_device *dev = port->serial->dev;
unsigned urb_value;
int status;
if (((set | clear) & (TIOCM_DTR | TIOCM_RTS)) == 0) {
dev_dbg(&port->dev,
"update_mctrl - DTR|RTS not being set|cleared\n");
return 0; /* no change */
}
clear &= ~set; /* 'set' takes precedence over 'clear' */
urb_value = 0;
if (set & TIOCM_DTR)
urb_value |= UART_MCR_DTR;
if (set & TIOCM_RTS)
urb_value |= UART_MCR_RTS;
status = qt2_setregister(dev, port_priv->device_port, UART_MCR,
urb_value);
if (status < 0)
dev_err(&port->dev,
"update_mctrl - Error from MODEM_CTRL urb: %i\n",
status);
return status;
}
static int qt2_calc_num_ports(struct usb_serial *serial)
{
struct qt2_device_detail d;
int i;
for (i = 0; d = qt2_device_details[i], d.product_id != 0; i++) {
if (d.product_id == le16_to_cpu(serial->dev->descriptor.idProduct))
return d.num_ports;
}
/* we didn't recognize the device */
dev_err(&serial->dev->dev,
"don't know the number of ports, assuming 1\n");
return 1;
}
static void qt2_set_termios(struct tty_struct *tty,
struct usb_serial_port *port,
struct ktermios *old_termios)
{
struct usb_device *dev = port->serial->dev;
struct qt2_port_private *port_priv;
struct ktermios *termios = &tty->termios;
u16 baud;
unsigned int cflag = termios->c_cflag;
u16 new_lcr = 0;
int status;
port_priv = usb_get_serial_port_data(port);
if (cflag & PARENB) {
if (cflag & PARODD)
new_lcr |= UART_LCR_PARITY;
else
new_lcr |= SERIAL_EVEN_PARITY;
}
switch (cflag & CSIZE) {
case CS5:
new_lcr |= UART_LCR_WLEN5;
break;
case CS6:
new_lcr |= UART_LCR_WLEN6;
break;
case CS7:
new_lcr |= UART_LCR_WLEN7;
break;
default:
case CS8:
new_lcr |= UART_LCR_WLEN8;
break;
}
baud = tty_get_baud_rate(tty);
if (!baud)
baud = 9600;
status = qt2_set_port_config(dev, port_priv->device_port, baud,
new_lcr);
if (status < 0)
dev_err(&port->dev, "%s - qt2_set_port_config failed: %i\n",
__func__, status);
if (cflag & CRTSCTS)
status = qt2_control_msg(dev, QT_HW_FLOW_CONTROL_MASK,
SERIAL_CRTSCTS,
port_priv->device_port);
else
status = qt2_control_msg(dev, QT_HW_FLOW_CONTROL_MASK,
0, port_priv->device_port);
if (status < 0)
dev_err(&port->dev, "%s - set HW flow control failed: %i\n",
__func__, status);
if (I_IXOFF(tty) || I_IXON(tty)) {
u16 x = ((u16) (START_CHAR(tty) << 8) | (u16) (STOP_CHAR(tty)));
status = qt2_control_msg(dev, QT_SW_FLOW_CONTROL_MASK,
x, port_priv->device_port);
} else
status = qt2_control_msg(dev, QT_SW_FLOW_CONTROL_MASK,
0, port_priv->device_port);
if (status < 0)
dev_err(&port->dev, "%s - set SW flow control failed: %i\n",
__func__, status);
}
static int qt2_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct usb_serial *serial;
struct qt2_port_private *port_priv;
u8 *data;
u16 device_port;
int status;
unsigned long flags;
device_port = (u16) (port->number - port->serial->minor);
serial = port->serial;
port_priv = usb_get_serial_port_data(port);
/* set the port to RS232 mode */
status = qt2_control_msg(serial->dev, QT2_GET_SET_QMCR,
QT2_QMCR_RS232, device_port);
if (status < 0) {
dev_err(&port->dev,
"%s failed to set RS232 mode for port %i error %i\n",
__func__, device_port, status);
return status;
}
data = kzalloc(2, GFP_KERNEL);
if (!data)
return -ENOMEM;
/* open the port */
status = usb_control_msg(serial->dev,
usb_rcvctrlpipe(serial->dev, 0),
QT_OPEN_CLOSE_CHANNEL,
0xc0, 0,
device_port, data, 2, QT2_USB_TIMEOUT);
if (status < 0) {
dev_err(&port->dev, "%s - open port failed %i", __func__,
status);
kfree(data);
return status;
}
spin_lock_irqsave(&port_priv->lock, flags);
port_priv->shadowLSR = data[0];
port_priv->shadowMSR = data[1];
spin_unlock_irqrestore(&port_priv->lock, flags);
kfree(data);
/* set to default speed and 8bit word size */
status = qt2_set_port_config(serial->dev, device_port,
DEFAULT_BAUD_RATE, UART_LCR_WLEN8);
if (status < 0) {
dev_err(&port->dev,
"%s - initial setup failed for port %i (%i)\n",
__func__, port->number, device_port);
return status;
}
port_priv->device_port = (u8) device_port;
if (tty)
qt2_set_termios(tty, port, &tty->termios);
return 0;
}
static void qt2_close(struct usb_serial_port *port)
{
struct usb_serial *serial;
struct qt2_port_private *port_priv;
unsigned long flags;
int i;
serial = port->serial;
port_priv = usb_get_serial_port_data(port);
spin_lock_irqsave(&port_priv->urb_lock, flags);
usb_kill_urb(port_priv->write_urb);
port_priv->urb_in_use = false;
spin_unlock_irqrestore(&port_priv->urb_lock, flags);
/* flush the port transmit buffer */
i = usb_control_msg(serial->dev,
usb_rcvctrlpipe(serial->dev, 0),
QT2_FLUSH_DEVICE, 0x40, 1,
port_priv->device_port, NULL, 0, QT2_USB_TIMEOUT);
if (i < 0)
dev_err(&port->dev, "%s - transmit buffer flush failed: %i\n",
__func__, i);
/* flush the port receive buffer */
i = usb_control_msg(serial->dev,
usb_rcvctrlpipe(serial->dev, 0),
QT2_FLUSH_DEVICE, 0x40, 0,
port_priv->device_port, NULL, 0, QT2_USB_TIMEOUT);
if (i < 0)
dev_err(&port->dev, "%s - receive buffer flush failed: %i\n",
__func__, i);
/* close the port */
i = usb_control_msg(serial->dev,
usb_sndctrlpipe(serial->dev, 0),
QT_OPEN_CLOSE_CHANNEL,
0x40, 0,
port_priv->device_port, NULL, 0, QT2_USB_TIMEOUT);
if (i < 0)
dev_err(&port->dev, "%s - close port failed %i\n",
__func__, i);
}
static void qt2_disconnect(struct usb_serial *serial)
{
struct qt2_serial_private *serial_priv = usb_get_serial_data(serial);
usb_kill_urb(serial_priv->read_urb);
}
static int get_serial_info(struct usb_serial_port *port,
struct serial_struct __user *retinfo)
{
struct serial_struct tmp;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.line = port->serial->minor;
tmp.port = 0;
tmp.irq = 0;
tmp.flags = ASYNC_SKIP_TEST | ASYNC_AUTO_IRQ;
tmp.xmit_fifo_size = port->bulk_out_size;
tmp.baud_base = 9600;
tmp.close_delay = 5*HZ;
tmp.closing_wait = 30*HZ;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
static int qt2_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct usb_serial_port *port = tty->driver_data;
switch (cmd) {
case TIOCGSERIAL:
return get_serial_info(port,
(struct serial_struct __user *)arg);
default:
break;
}
return -ENOIOCTLCMD;
}
static void qt2_process_status(struct usb_serial_port *port, unsigned char *ch)
{
switch (*ch) {
case QT2_LINE_STATUS:
qt2_update_lsr(port, ch + 1);
break;
case QT2_MODEM_STATUS:
qt2_update_msr(port, ch + 1);
break;
}
}
/* not needed, kept to document functionality */
static void qt2_process_xmit_empty(struct usb_serial_port *port,
unsigned char *ch)
{
int bytes_written;
bytes_written = (int)(*ch) + (int)(*(ch + 1) << 4);
}
/* not needed, kept to document functionality */
static void qt2_process_flush(struct usb_serial_port *port, unsigned char *ch)
{
return;
}
void qt2_process_read_urb(struct urb *urb)
{
struct usb_serial *serial;
struct qt2_serial_private *serial_priv;
struct usb_serial_port *port;
struct qt2_port_private *port_priv;
bool escapeflag;
unsigned char *ch;
int i;
unsigned char newport;
int len = urb->actual_length;
if (!len)
return;
ch = urb->transfer_buffer;
serial = urb->context;
serial_priv = usb_get_serial_data(serial);
port = serial->port[serial_priv->current_port];
port_priv = usb_get_serial_port_data(port);
for (i = 0; i < urb->actual_length; i++) {
ch = (unsigned char *)urb->transfer_buffer + i;
if ((i <= (len - 3)) &&
(*ch == QT2_CONTROL_BYTE) &&
(*(ch + 1) == QT2_CONTROL_BYTE)) {
escapeflag = false;
switch (*(ch + 2)) {
case QT2_LINE_STATUS:
case QT2_MODEM_STATUS:
if (i > (len - 4)) {
dev_warn(&port->dev,
"%s - status message too short\n",
__func__);
break;
}
qt2_process_status(port, ch + 2);
i += 3;
escapeflag = true;
break;
case QT2_XMIT_HOLD:
if (i > (len - 5)) {
dev_warn(&port->dev,
"%s - xmit_empty message too short\n",
__func__);
break;
}
qt2_process_xmit_empty(port, ch + 3);
i += 4;
escapeflag = true;
break;
case QT2_CHANGE_PORT:
if (i > (len - 4)) {
dev_warn(&port->dev,
"%s - change_port message too short\n",
__func__);
break;
}
tty_flip_buffer_push(&port->port);
newport = *(ch + 3);
if (newport > serial->num_ports) {
dev_err(&port->dev,
"%s - port change to invalid port: %i\n",
__func__, newport);
break;
}
serial_priv->current_port = newport;
port = serial->port[serial_priv->current_port];
port_priv = usb_get_serial_port_data(port);
i += 3;
escapeflag = true;
break;
case QT2_REC_FLUSH:
case QT2_XMIT_FLUSH:
qt2_process_flush(port, ch + 2);
i += 2;
escapeflag = true;
break;
case QT2_CONTROL_ESCAPE:
tty_buffer_request_room(&port->port, 2);
tty_insert_flip_string(&port->port, ch, 2);
i += 2;
escapeflag = true;
break;
default:
dev_warn(&port->dev,
"%s - unsupported command %i\n",
__func__, *(ch + 2));
break;
}
if (escapeflag)
continue;
}
tty_buffer_request_room(&port->port, 1);
tty_insert_flip_string(&port->port, ch, 1);
}
tty_flip_buffer_push(&port->port);
}
static void qt2_write_bulk_callback(struct urb *urb)
{
struct usb_serial_port *port;
struct qt2_port_private *port_priv;
port = urb->context;
port_priv = usb_get_serial_port_data(port);
spin_lock(&port_priv->urb_lock);
port_priv->urb_in_use = false;
usb_serial_port_softint(port);
spin_unlock(&port_priv->urb_lock);
}
static void qt2_read_bulk_callback(struct urb *urb)
{
struct usb_serial *serial = urb->context;
int status;
if (urb->status) {
dev_warn(&serial->dev->dev,
"%s - non-zero urb status: %i\n", __func__,
urb->status);
return;
}
qt2_process_read_urb(urb);
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status != 0)
dev_err(&serial->dev->dev,
"%s - resubmit read urb failed: %i\n",
__func__, status);
}
static int qt2_setup_urbs(struct usb_serial *serial)
{
struct usb_serial_port *port0;
struct qt2_serial_private *serial_priv;
int status;
port0 = serial->port[0];
serial_priv = usb_get_serial_data(serial);
serial_priv->read_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!serial_priv->read_urb) {
dev_err(&serial->dev->dev, "No free urbs available\n");
return -ENOMEM;
}
usb_fill_bulk_urb(serial_priv->read_urb, serial->dev,
usb_rcvbulkpipe(serial->dev,
port0->bulk_in_endpointAddress),
serial_priv->read_buffer,
sizeof(serial_priv->read_buffer),
qt2_read_bulk_callback, serial);
status = usb_submit_urb(serial_priv->read_urb, GFP_KERNEL);
if (status != 0) {
dev_err(&serial->dev->dev,
"%s - submit read urb failed %i\n", __func__, status);
usb_free_urb(serial_priv->read_urb);
return status;
}
return 0;
}
static int qt2_attach(struct usb_serial *serial)
{
struct qt2_serial_private *serial_priv;
int status;
/* power on unit */
status = usb_control_msg(serial->dev, usb_rcvctrlpipe(serial->dev, 0),
0xc2, 0x40, 0x8000, 0, NULL, 0,
QT2_USB_TIMEOUT);
if (status < 0) {
dev_err(&serial->dev->dev,
"%s - failed to power on unit: %i\n", __func__, status);
return status;
}
serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL);
if (!serial_priv) {
dev_err(&serial->dev->dev, "%s - Out of memory\n", __func__);
return -ENOMEM;
}
usb_set_serial_data(serial, serial_priv);
status = qt2_setup_urbs(serial);
if (status != 0)
goto attach_failed;
return 0;
attach_failed:
kfree(serial_priv);
return status;
}
static int qt2_port_probe(struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
struct qt2_port_private *port_priv;
u8 bEndpointAddress;
port_priv = kzalloc(sizeof(*port_priv), GFP_KERNEL);
if (!port_priv)
return -ENOMEM;
spin_lock_init(&port_priv->lock);
spin_lock_init(&port_priv->urb_lock);
port_priv->port = port;
port_priv->write_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!port_priv->write_urb) {
kfree(port_priv);
return -ENOMEM;
}
bEndpointAddress = serial->port[0]->bulk_out_endpointAddress;
usb_fill_bulk_urb(port_priv->write_urb, serial->dev,
usb_sndbulkpipe(serial->dev, bEndpointAddress),
port_priv->write_buffer,
sizeof(port_priv->write_buffer),
qt2_write_bulk_callback, port);
usb_set_serial_port_data(port, port_priv);
return 0;
}
static int qt2_port_remove(struct usb_serial_port *port)
{
struct qt2_port_private *port_priv;
port_priv = usb_get_serial_port_data(port);
usb_free_urb(port_priv->write_urb);
kfree(port_priv);
return 0;
}
static int qt2_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_device *dev = port->serial->dev;
struct qt2_port_private *port_priv = usb_get_serial_port_data(port);
u8 *d;
int r;
d = kzalloc(2, GFP_KERNEL);
if (!d)
return -ENOMEM;
r = qt2_getregister(dev, port_priv->device_port, UART_MCR, d);
if (r < 0)
goto mget_out;
r = qt2_getregister(dev, port_priv->device_port, UART_MSR, d + 1);
if (r < 0)
goto mget_out;
r = (d[0] & UART_MCR_DTR ? TIOCM_DTR : 0) |
(d[0] & UART_MCR_RTS ? TIOCM_RTS : 0) |
(d[1] & UART_MSR_CTS ? TIOCM_CTS : 0) |
(d[1] & UART_MSR_DCD ? TIOCM_CAR : 0) |
(d[1] & UART_MSR_RI ? TIOCM_RI : 0) |
(d[1] & UART_MSR_DSR ? TIOCM_DSR : 0);
mget_out:
kfree(d);
return r;
}
static int qt2_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct qt2_port_private *port_priv;
port_priv = usb_get_serial_port_data(tty->driver_data);
return update_mctrl(port_priv, set, clear);
}
static void qt2_break_ctl(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
struct qt2_port_private *port_priv;
int status;
u16 val;
port_priv = usb_get_serial_port_data(port);
val = (break_state == -1) ? 1 : 0;
status = qt2_control_msg(port->serial->dev, QT2_BREAK_CONTROL,
val, port_priv->device_port);
if (status < 0)
dev_warn(&port->dev,
"%s - failed to send control message: %i\n", __func__,
status);
}
static void qt2_dtr_rts(struct usb_serial_port *port, int on)
{
struct usb_device *dev = port->serial->dev;
struct qt2_port_private *port_priv = usb_get_serial_port_data(port);
/* Disable flow control */
if (!on) {
if (qt2_setregister(dev, port_priv->device_port,
UART_MCR, 0) < 0)
dev_warn(&port->dev, "error from flowcontrol urb\n");
}
/* drop RTS and DTR */
if (on)
update_mctrl(port_priv, TIOCM_DTR | TIOCM_RTS, 0);
else
update_mctrl(port_priv, 0, TIOCM_DTR | TIOCM_RTS);
}
static void qt2_update_msr(struct usb_serial_port *port, unsigned char *ch)
{
struct qt2_port_private *port_priv;
u8 newMSR = (u8) *ch;
unsigned long flags;
port_priv = usb_get_serial_port_data(port);
spin_lock_irqsave(&port_priv->lock, flags);
port_priv->shadowMSR = newMSR;
spin_unlock_irqrestore(&port_priv->lock, flags);
if (newMSR & UART_MSR_ANY_DELTA) {
/* update input line counters */
if (newMSR & UART_MSR_DCTS)
port->icount.cts++;
if (newMSR & UART_MSR_DDSR)
port->icount.dsr++;
if (newMSR & UART_MSR_DDCD)
port->icount.dcd++;
if (newMSR & UART_MSR_TERI)
port->icount.rng++;
wake_up_interruptible(&port->port.delta_msr_wait);
}
}
static void qt2_update_lsr(struct usb_serial_port *port, unsigned char *ch)
{
struct qt2_port_private *port_priv;
struct async_icount *icount;
unsigned long flags;
u8 newLSR = (u8) *ch;
port_priv = usb_get_serial_port_data(port);
if (newLSR & UART_LSR_BI)
newLSR &= (u8) (UART_LSR_OE | UART_LSR_BI);
spin_lock_irqsave(&port_priv->lock, flags);
port_priv->shadowLSR = newLSR;
spin_unlock_irqrestore(&port_priv->lock, flags);
icount = &port->icount;
if (newLSR & UART_LSR_BRK_ERROR_BITS) {
if (newLSR & UART_LSR_BI)
icount->brk++;
if (newLSR & UART_LSR_OE)
icount->overrun++;
if (newLSR & UART_LSR_PE)
icount->parity++;
if (newLSR & UART_LSR_FE)
icount->frame++;
}
}
static int qt2_write_room(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct qt2_port_private *port_priv;
unsigned long flags = 0;
int r;
port_priv = usb_get_serial_port_data(port);
spin_lock_irqsave(&port_priv->urb_lock, flags);
if (port_priv->urb_in_use)
r = 0;
else
r = QT2_WRITE_BUFFER_SIZE - QT2_WRITE_CONTROL_SIZE;
spin_unlock_irqrestore(&port_priv->urb_lock, flags);
return r;
}
static int qt2_write(struct tty_struct *tty,
struct usb_serial_port *port,
const unsigned char *buf, int count)
{
struct qt2_port_private *port_priv;
struct urb *write_urb;
unsigned char *data;
unsigned long flags;
int status;
int bytes_out = 0;
port_priv = usb_get_serial_port_data(port);
if (port_priv->write_urb == NULL) {
dev_err(&port->dev, "%s - no output urb\n", __func__);
return 0;
}
write_urb = port_priv->write_urb;
count = min(count, QT2_WRITE_BUFFER_SIZE - QT2_WRITE_CONTROL_SIZE);
data = write_urb->transfer_buffer;
spin_lock_irqsave(&port_priv->urb_lock, flags);
if (port_priv->urb_in_use == true) {
dev_err(&port->dev, "qt2_write - urb is in use\n");
goto write_out;
}
*data++ = QT2_CONTROL_BYTE;
*data++ = QT2_CONTROL_BYTE;
*data++ = port_priv->device_port;
put_unaligned_le16(count, data);
data += 2;
memcpy(data, buf, count);
write_urb->transfer_buffer_length = count + QT2_WRITE_CONTROL_SIZE;
status = usb_submit_urb(write_urb, GFP_ATOMIC);
if (status == 0) {
port_priv->urb_in_use = true;
bytes_out += count;
}
write_out:
spin_unlock_irqrestore(&port_priv->urb_lock, flags);
return bytes_out;
}
static struct usb_serial_driver qt2_device = {
.driver = {
.owner = THIS_MODULE,
.name = "quatech-serial",
},
.description = DRIVER_DESC,
.id_table = id_table,
.open = qt2_open,
.close = qt2_close,
.write = qt2_write,
.write_room = qt2_write_room,
.calc_num_ports = qt2_calc_num_ports,
.attach = qt2_attach,
.release = qt2_release,
.disconnect = qt2_disconnect,
.port_probe = qt2_port_probe,
.port_remove = qt2_port_remove,
.dtr_rts = qt2_dtr_rts,
.break_ctl = qt2_break_ctl,
.tiocmget = qt2_tiocmget,
.tiocmset = qt2_tiocmset,
.tiocmiwait = usb_serial_generic_tiocmiwait,
.get_icount = usb_serial_generic_get_icount,
.ioctl = qt2_ioctl,
.set_termios = qt2_set_termios,
};
static struct usb_serial_driver *const serial_drivers[] = {
&qt2_device, NULL
};
module_usb_serial_driver(serial_drivers, id_table);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
DroidThug/Trident | drivers/net/ethernet/stmicro/stmmac/ring_mode.c | 2124 | 3810 | /*******************************************************************************
Specialised functions for managing Ring mode
Copyright(C) 2011 STMicroelectronics Ltd
It defines all the functions used to handle the normal/enhanced
descriptors in case of the DMA is configured to work in chained or
in ring mode.
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".
Author: Giuseppe Cavallaro <peppe.cavallaro@st.com>
*******************************************************************************/
#include "stmmac.h"
static unsigned int stmmac_jumbo_frm(void *p, struct sk_buff *skb, int csum)
{
struct stmmac_priv *priv = (struct stmmac_priv *)p;
unsigned int txsize = priv->dma_tx_size;
unsigned int entry = priv->cur_tx % txsize;
struct dma_desc *desc = priv->dma_tx + entry;
unsigned int nopaged_len = skb_headlen(skb);
unsigned int bmax, len;
if (priv->plat->enh_desc)
bmax = BUF_SIZE_8KiB;
else
bmax = BUF_SIZE_2KiB;
len = nopaged_len - bmax;
if (nopaged_len > BUF_SIZE_8KiB) {
desc->des2 = dma_map_single(priv->device, skb->data,
bmax, DMA_TO_DEVICE);
priv->tx_skbuff_dma[entry] = desc->des2;
desc->des3 = desc->des2 + BUF_SIZE_4KiB;
priv->hw->desc->prepare_tx_desc(desc, 1, bmax, csum,
STMMAC_RING_MODE);
wmb();
entry = (++priv->cur_tx) % txsize;
desc = priv->dma_tx + entry;
desc->des2 = dma_map_single(priv->device, skb->data + bmax,
len, DMA_TO_DEVICE);
priv->tx_skbuff_dma[entry] = desc->des2;
desc->des3 = desc->des2 + BUF_SIZE_4KiB;
priv->hw->desc->prepare_tx_desc(desc, 0, len, csum,
STMMAC_RING_MODE);
wmb();
priv->hw->desc->set_tx_owner(desc);
priv->tx_skbuff[entry] = NULL;
} else {
desc->des2 = dma_map_single(priv->device, skb->data,
nopaged_len, DMA_TO_DEVICE);
priv->tx_skbuff_dma[entry] = desc->des2;
desc->des3 = desc->des2 + BUF_SIZE_4KiB;
priv->hw->desc->prepare_tx_desc(desc, 1, nopaged_len, csum,
STMMAC_RING_MODE);
}
return entry;
}
static unsigned int stmmac_is_jumbo_frm(int len, int enh_desc)
{
unsigned int ret = 0;
if (len >= BUF_SIZE_4KiB)
ret = 1;
return ret;
}
static void stmmac_refill_desc3(void *priv_ptr, struct dma_desc *p)
{
struct stmmac_priv *priv = (struct stmmac_priv *)priv_ptr;
if (unlikely(priv->plat->has_gmac))
/* Fill DES3 in case of RING mode */
if (priv->dma_buf_sz >= BUF_SIZE_8KiB)
p->des3 = p->des2 + BUF_SIZE_8KiB;
}
/* In ring mode we need to fill the desc3 because it is used as buffer */
static void stmmac_init_desc3(struct dma_desc *p)
{
p->des3 = p->des2 + BUF_SIZE_8KiB;
}
static void stmmac_clean_desc3(void *priv_ptr, struct dma_desc *p)
{
if (unlikely(p->des3))
p->des3 = 0;
}
static int stmmac_set_16kib_bfsize(int mtu)
{
int ret = 0;
if (unlikely(mtu >= BUF_SIZE_8KiB))
ret = BUF_SIZE_16KiB;
return ret;
}
const struct stmmac_ring_mode_ops ring_mode_ops = {
.is_jumbo_frm = stmmac_is_jumbo_frm,
.jumbo_frm = stmmac_jumbo_frm,
.refill_desc3 = stmmac_refill_desc3,
.init_desc3 = stmmac_init_desc3,
.clean_desc3 = stmmac_clean_desc3,
.set_16kib_bfsize = stmmac_set_16kib_bfsize,
};
| gpl-2.0 |
kirananto/REDMI2_RAZOR | drivers/tty/serial/netx-serial.c | 2124 | 17072 | /*
* Copyright (c) 2005 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix
*
* 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
*/
#if defined(CONFIG_SERIAL_NETX_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
#define SUPPORT_SYSRQ
#endif
#include <linux/device.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/sysrq.h>
#include <linux/platform_device.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial_core.h>
#include <linux/serial.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <mach/hardware.h>
#include <mach/netx-regs.h>
/* We've been assigned a range on the "Low-density serial ports" major */
#define SERIAL_NX_MAJOR 204
#define MINOR_START 170
enum uart_regs {
UART_DR = 0x00,
UART_SR = 0x04,
UART_LINE_CR = 0x08,
UART_BAUDDIV_MSB = 0x0c,
UART_BAUDDIV_LSB = 0x10,
UART_CR = 0x14,
UART_FR = 0x18,
UART_IIR = 0x1c,
UART_ILPR = 0x20,
UART_RTS_CR = 0x24,
UART_RTS_LEAD = 0x28,
UART_RTS_TRAIL = 0x2c,
UART_DRV_ENABLE = 0x30,
UART_BRM_CR = 0x34,
UART_RXFIFO_IRQLEVEL = 0x38,
UART_TXFIFO_IRQLEVEL = 0x3c,
};
#define SR_FE (1<<0)
#define SR_PE (1<<1)
#define SR_BE (1<<2)
#define SR_OE (1<<3)
#define LINE_CR_BRK (1<<0)
#define LINE_CR_PEN (1<<1)
#define LINE_CR_EPS (1<<2)
#define LINE_CR_STP2 (1<<3)
#define LINE_CR_FEN (1<<4)
#define LINE_CR_5BIT (0<<5)
#define LINE_CR_6BIT (1<<5)
#define LINE_CR_7BIT (2<<5)
#define LINE_CR_8BIT (3<<5)
#define LINE_CR_BITS_MASK (3<<5)
#define CR_UART_EN (1<<0)
#define CR_SIREN (1<<1)
#define CR_SIRLP (1<<2)
#define CR_MSIE (1<<3)
#define CR_RIE (1<<4)
#define CR_TIE (1<<5)
#define CR_RTIE (1<<6)
#define CR_LBE (1<<7)
#define FR_CTS (1<<0)
#define FR_DSR (1<<1)
#define FR_DCD (1<<2)
#define FR_BUSY (1<<3)
#define FR_RXFE (1<<4)
#define FR_TXFF (1<<5)
#define FR_RXFF (1<<6)
#define FR_TXFE (1<<7)
#define IIR_MIS (1<<0)
#define IIR_RIS (1<<1)
#define IIR_TIS (1<<2)
#define IIR_RTIS (1<<3)
#define IIR_MASK 0xf
#define RTS_CR_AUTO (1<<0)
#define RTS_CR_RTS (1<<1)
#define RTS_CR_COUNT (1<<2)
#define RTS_CR_MOD2 (1<<3)
#define RTS_CR_RTS_POL (1<<4)
#define RTS_CR_CTS_CTR (1<<5)
#define RTS_CR_CTS_POL (1<<6)
#define RTS_CR_STICK (1<<7)
#define UART_PORT_SIZE 0x40
#define DRIVER_NAME "netx-uart"
struct netx_port {
struct uart_port port;
};
static void netx_stop_tx(struct uart_port *port)
{
unsigned int val;
val = readl(port->membase + UART_CR);
writel(val & ~CR_TIE, port->membase + UART_CR);
}
static void netx_stop_rx(struct uart_port *port)
{
unsigned int val;
val = readl(port->membase + UART_CR);
writel(val & ~CR_RIE, port->membase + UART_CR);
}
static void netx_enable_ms(struct uart_port *port)
{
unsigned int val;
val = readl(port->membase + UART_CR);
writel(val | CR_MSIE, port->membase + UART_CR);
}
static inline void netx_transmit_buffer(struct uart_port *port)
{
struct circ_buf *xmit = &port->state->xmit;
if (port->x_char) {
writel(port->x_char, port->membase + UART_DR);
port->icount.tx++;
port->x_char = 0;
return;
}
if (uart_tx_stopped(port) || uart_circ_empty(xmit)) {
netx_stop_tx(port);
return;
}
do {
/* send xmit->buf[xmit->tail]
* out the port here */
writel(xmit->buf[xmit->tail], port->membase + UART_DR);
xmit->tail = (xmit->tail + 1) &
(UART_XMIT_SIZE - 1);
port->icount.tx++;
if (uart_circ_empty(xmit))
break;
} while (!(readl(port->membase + UART_FR) & FR_TXFF));
if (uart_circ_empty(xmit))
netx_stop_tx(port);
}
static void netx_start_tx(struct uart_port *port)
{
writel(
readl(port->membase + UART_CR) | CR_TIE, port->membase + UART_CR);
if (!(readl(port->membase + UART_FR) & FR_TXFF))
netx_transmit_buffer(port);
}
static unsigned int netx_tx_empty(struct uart_port *port)
{
return readl(port->membase + UART_FR) & FR_BUSY ? 0 : TIOCSER_TEMT;
}
static void netx_txint(struct uart_port *port)
{
struct circ_buf *xmit = &port->state->xmit;
if (uart_circ_empty(xmit) || uart_tx_stopped(port)) {
netx_stop_tx(port);
return;
}
netx_transmit_buffer(port);
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(port);
}
static void netx_rxint(struct uart_port *port)
{
unsigned char rx, flg, status;
while (!(readl(port->membase + UART_FR) & FR_RXFE)) {
rx = readl(port->membase + UART_DR);
flg = TTY_NORMAL;
port->icount.rx++;
status = readl(port->membase + UART_SR);
if (status & SR_BE) {
writel(0, port->membase + UART_SR);
if (uart_handle_break(port))
continue;
}
if (unlikely(status & (SR_FE | SR_PE | SR_OE))) {
if (status & SR_PE)
port->icount.parity++;
else if (status & SR_FE)
port->icount.frame++;
if (status & SR_OE)
port->icount.overrun++;
status &= port->read_status_mask;
if (status & SR_BE)
flg = TTY_BREAK;
else if (status & SR_PE)
flg = TTY_PARITY;
else if (status & SR_FE)
flg = TTY_FRAME;
}
if (uart_handle_sysrq_char(port, rx))
continue;
uart_insert_char(port, status, SR_OE, rx, flg);
}
tty_flip_buffer_push(&port->state->port);
}
static irqreturn_t netx_int(int irq, void *dev_id)
{
struct uart_port *port = dev_id;
unsigned long flags;
unsigned char status;
spin_lock_irqsave(&port->lock,flags);
status = readl(port->membase + UART_IIR) & IIR_MASK;
while (status) {
if (status & IIR_RIS)
netx_rxint(port);
if (status & IIR_TIS)
netx_txint(port);
if (status & IIR_MIS) {
if (readl(port->membase + UART_FR) & FR_CTS)
uart_handle_cts_change(port, 1);
else
uart_handle_cts_change(port, 0);
}
writel(0, port->membase + UART_IIR);
status = readl(port->membase + UART_IIR) & IIR_MASK;
}
spin_unlock_irqrestore(&port->lock,flags);
return IRQ_HANDLED;
}
static unsigned int netx_get_mctrl(struct uart_port *port)
{
unsigned int ret = TIOCM_DSR | TIOCM_CAR;
if (readl(port->membase + UART_FR) & FR_CTS)
ret |= TIOCM_CTS;
return ret;
}
static void netx_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
unsigned int val;
/* FIXME: Locking needed ? */
if (mctrl & TIOCM_RTS) {
val = readl(port->membase + UART_RTS_CR);
writel(val | RTS_CR_RTS, port->membase + UART_RTS_CR);
}
}
static void netx_break_ctl(struct uart_port *port, int break_state)
{
unsigned int line_cr;
spin_lock_irq(&port->lock);
line_cr = readl(port->membase + UART_LINE_CR);
if (break_state != 0)
line_cr |= LINE_CR_BRK;
else
line_cr &= ~LINE_CR_BRK;
writel(line_cr, port->membase + UART_LINE_CR);
spin_unlock_irq(&port->lock);
}
static int netx_startup(struct uart_port *port)
{
int ret;
ret = request_irq(port->irq, netx_int, 0,
DRIVER_NAME, port);
if (ret) {
dev_err(port->dev, "unable to grab irq%d\n",port->irq);
goto exit;
}
writel(readl(port->membase + UART_LINE_CR) | LINE_CR_FEN,
port->membase + UART_LINE_CR);
writel(CR_MSIE | CR_RIE | CR_TIE | CR_RTIE | CR_UART_EN,
port->membase + UART_CR);
exit:
return ret;
}
static void netx_shutdown(struct uart_port *port)
{
writel(0, port->membase + UART_CR) ;
free_irq(port->irq, port);
}
static void
netx_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
unsigned int baud, quot;
unsigned char old_cr;
unsigned char line_cr = LINE_CR_FEN;
unsigned char rts_cr = 0;
switch (termios->c_cflag & CSIZE) {
case CS5:
line_cr |= LINE_CR_5BIT;
break;
case CS6:
line_cr |= LINE_CR_6BIT;
break;
case CS7:
line_cr |= LINE_CR_7BIT;
break;
case CS8:
line_cr |= LINE_CR_8BIT;
break;
}
if (termios->c_cflag & CSTOPB)
line_cr |= LINE_CR_STP2;
if (termios->c_cflag & PARENB) {
line_cr |= LINE_CR_PEN;
if (!(termios->c_cflag & PARODD))
line_cr |= LINE_CR_EPS;
}
if (termios->c_cflag & CRTSCTS)
rts_cr = RTS_CR_AUTO | RTS_CR_CTS_CTR | RTS_CR_RTS_POL;
baud = uart_get_baud_rate(port, termios, old, 0, port->uartclk/16);
quot = baud * 4096;
quot /= 1000;
quot *= 256;
quot /= 100000;
spin_lock_irq(&port->lock);
uart_update_timeout(port, termios->c_cflag, baud);
old_cr = readl(port->membase + UART_CR);
/* disable interrupts */
writel(old_cr & ~(CR_MSIE | CR_RIE | CR_TIE | CR_RTIE),
port->membase + UART_CR);
/* drain transmitter */
while (readl(port->membase + UART_FR) & FR_BUSY);
/* disable UART */
writel(old_cr & ~CR_UART_EN, port->membase + UART_CR);
/* modem status interrupts */
old_cr &= ~CR_MSIE;
if (UART_ENABLE_MS(port, termios->c_cflag))
old_cr |= CR_MSIE;
writel((quot>>8) & 0xff, port->membase + UART_BAUDDIV_MSB);
writel(quot & 0xff, port->membase + UART_BAUDDIV_LSB);
writel(line_cr, port->membase + UART_LINE_CR);
writel(rts_cr, port->membase + UART_RTS_CR);
/*
* Characters to ignore
*/
port->ignore_status_mask = 0;
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= SR_PE;
if (termios->c_iflag & IGNBRK) {
port->ignore_status_mask |= SR_BE;
/*
* If we're ignoring parity and break indicators,
* ignore overruns too (for real raw support).
*/
if (termios->c_iflag & IGNPAR)
port->ignore_status_mask |= SR_PE;
}
port->read_status_mask = 0;
if (termios->c_iflag & (BRKINT | PARMRK))
port->read_status_mask |= SR_BE;
if (termios->c_iflag & INPCK)
port->read_status_mask |= SR_PE | SR_FE;
writel(old_cr, port->membase + UART_CR);
spin_unlock_irq(&port->lock);
}
static const char *netx_type(struct uart_port *port)
{
return port->type == PORT_NETX ? "NETX" : NULL;
}
static void netx_release_port(struct uart_port *port)
{
release_mem_region(port->mapbase, UART_PORT_SIZE);
}
static int netx_request_port(struct uart_port *port)
{
return request_mem_region(port->mapbase, UART_PORT_SIZE,
DRIVER_NAME) != NULL ? 0 : -EBUSY;
}
static void netx_config_port(struct uart_port *port, int flags)
{
if (flags & UART_CONFIG_TYPE && netx_request_port(port) == 0)
port->type = PORT_NETX;
}
static int
netx_verify_port(struct uart_port *port, struct serial_struct *ser)
{
int ret = 0;
if (ser->type != PORT_UNKNOWN && ser->type != PORT_NETX)
ret = -EINVAL;
return ret;
}
static struct uart_ops netx_pops = {
.tx_empty = netx_tx_empty,
.set_mctrl = netx_set_mctrl,
.get_mctrl = netx_get_mctrl,
.stop_tx = netx_stop_tx,
.start_tx = netx_start_tx,
.stop_rx = netx_stop_rx,
.enable_ms = netx_enable_ms,
.break_ctl = netx_break_ctl,
.startup = netx_startup,
.shutdown = netx_shutdown,
.set_termios = netx_set_termios,
.type = netx_type,
.release_port = netx_release_port,
.request_port = netx_request_port,
.config_port = netx_config_port,
.verify_port = netx_verify_port,
};
static struct netx_port netx_ports[] = {
{
.port = {
.type = PORT_NETX,
.iotype = UPIO_MEM,
.membase = (char __iomem *)io_p2v(NETX_PA_UART0),
.mapbase = NETX_PA_UART0,
.irq = NETX_IRQ_UART0,
.uartclk = 100000000,
.fifosize = 16,
.flags = UPF_BOOT_AUTOCONF,
.ops = &netx_pops,
.line = 0,
},
}, {
.port = {
.type = PORT_NETX,
.iotype = UPIO_MEM,
.membase = (char __iomem *)io_p2v(NETX_PA_UART1),
.mapbase = NETX_PA_UART1,
.irq = NETX_IRQ_UART1,
.uartclk = 100000000,
.fifosize = 16,
.flags = UPF_BOOT_AUTOCONF,
.ops = &netx_pops,
.line = 1,
},
}, {
.port = {
.type = PORT_NETX,
.iotype = UPIO_MEM,
.membase = (char __iomem *)io_p2v(NETX_PA_UART2),
.mapbase = NETX_PA_UART2,
.irq = NETX_IRQ_UART2,
.uartclk = 100000000,
.fifosize = 16,
.flags = UPF_BOOT_AUTOCONF,
.ops = &netx_pops,
.line = 2,
},
}
};
#ifdef CONFIG_SERIAL_NETX_CONSOLE
static void netx_console_putchar(struct uart_port *port, int ch)
{
while (readl(port->membase + UART_FR) & FR_BUSY);
writel(ch, port->membase + UART_DR);
}
static void
netx_console_write(struct console *co, const char *s, unsigned int count)
{
struct uart_port *port = &netx_ports[co->index].port;
unsigned char cr_save;
cr_save = readl(port->membase + UART_CR);
writel(cr_save | CR_UART_EN, port->membase + UART_CR);
uart_console_write(port, s, count, netx_console_putchar);
while (readl(port->membase + UART_FR) & FR_BUSY);
writel(cr_save, port->membase + UART_CR);
}
static void __init
netx_console_get_options(struct uart_port *port, int *baud,
int *parity, int *bits, int *flow)
{
unsigned char line_cr;
*baud = (readl(port->membase + UART_BAUDDIV_MSB) << 8) |
readl(port->membase + UART_BAUDDIV_LSB);
*baud *= 1000;
*baud /= 4096;
*baud *= 1000;
*baud /= 256;
*baud *= 100;
line_cr = readl(port->membase + UART_LINE_CR);
*parity = 'n';
if (line_cr & LINE_CR_PEN) {
if (line_cr & LINE_CR_EPS)
*parity = 'e';
else
*parity = 'o';
}
switch (line_cr & LINE_CR_BITS_MASK) {
case LINE_CR_8BIT:
*bits = 8;
break;
case LINE_CR_7BIT:
*bits = 7;
break;
case LINE_CR_6BIT:
*bits = 6;
break;
case LINE_CR_5BIT:
*bits = 5;
break;
}
if (readl(port->membase + UART_RTS_CR) & RTS_CR_AUTO)
*flow = 'r';
}
static int __init
netx_console_setup(struct console *co, char *options)
{
struct netx_port *sport;
int baud = 9600;
int bits = 8;
int parity = 'n';
int flow = 'n';
/*
* Check whether an invalid uart number has been specified, and
* if so, search for the first available port that does have
* console support.
*/
if (co->index == -1 || co->index >= ARRAY_SIZE(netx_ports))
co->index = 0;
sport = &netx_ports[co->index];
if (options) {
uart_parse_options(options, &baud, &parity, &bits, &flow);
} else {
/* if the UART is enabled, assume it has been correctly setup
* by the bootloader and get the options
*/
if (readl(sport->port.membase + UART_CR) & CR_UART_EN) {
netx_console_get_options(&sport->port, &baud,
&parity, &bits, &flow);
}
}
return uart_set_options(&sport->port, co, baud, parity, bits, flow);
}
static struct uart_driver netx_reg;
static struct console netx_console = {
.name = "ttyNX",
.write = netx_console_write,
.device = uart_console_device,
.setup = netx_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &netx_reg,
};
static int __init netx_console_init(void)
{
register_console(&netx_console);
return 0;
}
console_initcall(netx_console_init);
#define NETX_CONSOLE &netx_console
#else
#define NETX_CONSOLE NULL
#endif
static struct uart_driver netx_reg = {
.owner = THIS_MODULE,
.driver_name = DRIVER_NAME,
.dev_name = "ttyNX",
.major = SERIAL_NX_MAJOR,
.minor = MINOR_START,
.nr = ARRAY_SIZE(netx_ports),
.cons = NETX_CONSOLE,
};
static int serial_netx_suspend(struct platform_device *pdev, pm_message_t state)
{
struct netx_port *sport = platform_get_drvdata(pdev);
if (sport)
uart_suspend_port(&netx_reg, &sport->port);
return 0;
}
static int serial_netx_resume(struct platform_device *pdev)
{
struct netx_port *sport = platform_get_drvdata(pdev);
if (sport)
uart_resume_port(&netx_reg, &sport->port);
return 0;
}
static int serial_netx_probe(struct platform_device *pdev)
{
struct uart_port *port = &netx_ports[pdev->id].port;
dev_info(&pdev->dev, "initialising\n");
port->dev = &pdev->dev;
writel(1, port->membase + UART_RXFIFO_IRQLEVEL);
uart_add_one_port(&netx_reg, &netx_ports[pdev->id].port);
platform_set_drvdata(pdev, &netx_ports[pdev->id]);
return 0;
}
static int serial_netx_remove(struct platform_device *pdev)
{
struct netx_port *sport = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
if (sport)
uart_remove_one_port(&netx_reg, &sport->port);
return 0;
}
static struct platform_driver serial_netx_driver = {
.probe = serial_netx_probe,
.remove = serial_netx_remove,
.suspend = serial_netx_suspend,
.resume = serial_netx_resume,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
};
static int __init netx_serial_init(void)
{
int ret;
printk(KERN_INFO "Serial: NetX driver\n");
ret = uart_register_driver(&netx_reg);
if (ret)
return ret;
ret = platform_driver_register(&serial_netx_driver);
if (ret != 0)
uart_unregister_driver(&netx_reg);
return 0;
}
static void __exit netx_serial_exit(void)
{
platform_driver_unregister(&serial_netx_driver);
uart_unregister_driver(&netx_reg);
}
module_init(netx_serial_init);
module_exit(netx_serial_exit);
MODULE_AUTHOR("Sascha Hauer");
MODULE_DESCRIPTION("NetX serial port driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRIVER_NAME);
| gpl-2.0 |
mythos234/NB_ET_Kernel | fs/jfs/xattr.c | 2124 | 27956 | /*
* Copyright (C) International Business Machines Corp., 2000-2004
* Copyright (C) Christoph Hellwig, 2002
*
* 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/capability.h>
#include <linux/fs.h>
#include <linux/xattr.h>
#include <linux/posix_acl_xattr.h>
#include <linux/slab.h>
#include <linux/quotaops.h>
#include <linux/security.h>
#include "jfs_incore.h"
#include "jfs_superblock.h"
#include "jfs_dmap.h"
#include "jfs_debug.h"
#include "jfs_dinode.h"
#include "jfs_extent.h"
#include "jfs_metapage.h"
#include "jfs_xattr.h"
#include "jfs_acl.h"
/*
* jfs_xattr.c: extended attribute service
*
* Overall design --
*
* Format:
*
* Extended attribute lists (jfs_ea_list) consist of an overall size (32 bit
* value) and a variable (0 or more) number of extended attribute
* entries. Each extended attribute entry (jfs_ea) is a <name,value> double
* where <name> is constructed from a null-terminated ascii string
* (1 ... 255 bytes in the name) and <value> is arbitrary 8 bit data
* (1 ... 65535 bytes). The in-memory format is
*
* 0 1 2 4 4 + namelen + 1
* +-------+--------+--------+----------------+-------------------+
* | Flags | Name | Value | Name String \0 | Data . . . . |
* | | Length | Length | | |
* +-------+--------+--------+----------------+-------------------+
*
* A jfs_ea_list then is structured as
*
* 0 4 4 + EA_SIZE(ea1)
* +------------+-------------------+--------------------+-----
* | Overall EA | First FEA Element | Second FEA Element | .....
* | List Size | | |
* +------------+-------------------+--------------------+-----
*
* On-disk:
*
* FEALISTs are stored on disk using blocks allocated by dbAlloc() and
* written directly. An EA list may be in-lined in the inode if there is
* sufficient room available.
*/
struct ea_buffer {
int flag; /* Indicates what storage xattr points to */
int max_size; /* largest xattr that fits in current buffer */
dxd_t new_ea; /* dxd to replace ea when modifying xattr */
struct metapage *mp; /* metapage containing ea list */
struct jfs_ea_list *xattr; /* buffer containing ea list */
};
/*
* ea_buffer.flag values
*/
#define EA_INLINE 0x0001
#define EA_EXTENT 0x0002
#define EA_NEW 0x0004
#define EA_MALLOC 0x0008
static int is_known_namespace(const char *name)
{
if (strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN) &&
strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN) &&
strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN))
return false;
return true;
}
/*
* These three routines are used to recognize on-disk extended attributes
* that are in a recognized namespace. If the attribute is not recognized,
* "os2." is prepended to the name
*/
static int is_os2_xattr(struct jfs_ea *ea)
{
return !is_known_namespace(ea->name);
}
static inline int name_size(struct jfs_ea *ea)
{
if (is_os2_xattr(ea))
return ea->namelen + XATTR_OS2_PREFIX_LEN;
else
return ea->namelen;
}
static inline int copy_name(char *buffer, struct jfs_ea *ea)
{
int len = ea->namelen;
if (is_os2_xattr(ea)) {
memcpy(buffer, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN);
buffer += XATTR_OS2_PREFIX_LEN;
len += XATTR_OS2_PREFIX_LEN;
}
memcpy(buffer, ea->name, ea->namelen);
buffer[ea->namelen] = 0;
return len;
}
/* Forward references */
static void ea_release(struct inode *inode, struct ea_buffer *ea_buf);
/*
* NAME: ea_write_inline
*
* FUNCTION: Attempt to write an EA inline if area is available
*
* PRE CONDITIONS:
* Already verified that the specified EA is small enough to fit inline
*
* PARAMETERS:
* ip - Inode pointer
* ealist - EA list pointer
* size - size of ealist in bytes
* ea - dxd_t structure to be filled in with necessary EA information
* if we successfully copy the EA inline
*
* NOTES:
* Checks if the inode's inline area is available. If so, copies EA inline
* and sets <ea> fields appropriately. Otherwise, returns failure, EA will
* have to be put into an extent.
*
* RETURNS: 0 for successful copy to inline area; -1 if area not available
*/
static int ea_write_inline(struct inode *ip, struct jfs_ea_list *ealist,
int size, dxd_t * ea)
{
struct jfs_inode_info *ji = JFS_IP(ip);
/*
* Make sure we have an EA -- the NULL EA list is valid, but you
* can't copy it!
*/
if (ealist && size > sizeof (struct jfs_ea_list)) {
assert(size <= sizeof (ji->i_inline_ea));
/*
* See if the space is available or if it is already being
* used for an inline EA.
*/
if (!(ji->mode2 & INLINEEA) && !(ji->ea.flag & DXD_INLINE))
return -EPERM;
DXDsize(ea, size);
DXDlength(ea, 0);
DXDaddress(ea, 0);
memcpy(ji->i_inline_ea, ealist, size);
ea->flag = DXD_INLINE;
ji->mode2 &= ~INLINEEA;
} else {
ea->flag = 0;
DXDsize(ea, 0);
DXDlength(ea, 0);
DXDaddress(ea, 0);
/* Free up INLINE area */
if (ji->ea.flag & DXD_INLINE)
ji->mode2 |= INLINEEA;
}
return 0;
}
/*
* NAME: ea_write
*
* FUNCTION: Write an EA for an inode
*
* PRE CONDITIONS: EA has been verified
*
* PARAMETERS:
* ip - Inode pointer
* ealist - EA list pointer
* size - size of ealist in bytes
* ea - dxd_t structure to be filled in appropriately with where the
* EA was copied
*
* NOTES: Will write EA inline if able to, otherwise allocates blocks for an
* extent and synchronously writes it to those blocks.
*
* RETURNS: 0 for success; Anything else indicates failure
*/
static int ea_write(struct inode *ip, struct jfs_ea_list *ealist, int size,
dxd_t * ea)
{
struct super_block *sb = ip->i_sb;
struct jfs_inode_info *ji = JFS_IP(ip);
struct jfs_sb_info *sbi = JFS_SBI(sb);
int nblocks;
s64 blkno;
int rc = 0, i;
char *cp;
s32 nbytes, nb;
s32 bytes_to_write;
struct metapage *mp;
/*
* Quick check to see if this is an in-linable EA. Short EAs
* and empty EAs are all in-linable, provided the space exists.
*/
if (!ealist || size <= sizeof (ji->i_inline_ea)) {
if (!ea_write_inline(ip, ealist, size, ea))
return 0;
}
/* figure out how many blocks we need */
nblocks = (size + (sb->s_blocksize - 1)) >> sb->s_blocksize_bits;
/* Allocate new blocks to quota. */
rc = dquot_alloc_block(ip, nblocks);
if (rc)
return rc;
rc = dbAlloc(ip, INOHINT(ip), nblocks, &blkno);
if (rc) {
/*Rollback quota allocation. */
dquot_free_block(ip, nblocks);
return rc;
}
/*
* Now have nblocks worth of storage to stuff into the FEALIST.
* loop over the FEALIST copying data into the buffer one page at
* a time.
*/
cp = (char *) ealist;
nbytes = size;
for (i = 0; i < nblocks; i += sbi->nbperpage) {
/*
* Determine how many bytes for this request, and round up to
* the nearest aggregate block size
*/
nb = min(PSIZE, nbytes);
bytes_to_write =
((((nb + sb->s_blocksize - 1)) >> sb->s_blocksize_bits))
<< sb->s_blocksize_bits;
if (!(mp = get_metapage(ip, blkno + i, bytes_to_write, 1))) {
rc = -EIO;
goto failed;
}
memcpy(mp->data, cp, nb);
/*
* We really need a way to propagate errors for
* forced writes like this one. --hch
*
* (__write_metapage => release_metapage => flush_metapage)
*/
#ifdef _JFS_FIXME
if ((rc = flush_metapage(mp))) {
/*
* the write failed -- this means that the buffer
* is still assigned and the blocks are not being
* used. this seems like the best error recovery
* we can get ...
*/
goto failed;
}
#else
flush_metapage(mp);
#endif
cp += PSIZE;
nbytes -= nb;
}
ea->flag = DXD_EXTENT;
DXDsize(ea, le32_to_cpu(ealist->size));
DXDlength(ea, nblocks);
DXDaddress(ea, blkno);
/* Free up INLINE area */
if (ji->ea.flag & DXD_INLINE)
ji->mode2 |= INLINEEA;
return 0;
failed:
/* Rollback quota allocation. */
dquot_free_block(ip, nblocks);
dbFree(ip, blkno, nblocks);
return rc;
}
/*
* NAME: ea_read_inline
*
* FUNCTION: Read an inlined EA into user's buffer
*
* PARAMETERS:
* ip - Inode pointer
* ealist - Pointer to buffer to fill in with EA
*
* RETURNS: 0
*/
static int ea_read_inline(struct inode *ip, struct jfs_ea_list *ealist)
{
struct jfs_inode_info *ji = JFS_IP(ip);
int ea_size = sizeDXD(&ji->ea);
if (ea_size == 0) {
ealist->size = 0;
return 0;
}
/* Sanity Check */
if ((sizeDXD(&ji->ea) > sizeof (ji->i_inline_ea)))
return -EIO;
if (le32_to_cpu(((struct jfs_ea_list *) &ji->i_inline_ea)->size)
!= ea_size)
return -EIO;
memcpy(ealist, ji->i_inline_ea, ea_size);
return 0;
}
/*
* NAME: ea_read
*
* FUNCTION: copy EA data into user's buffer
*
* PARAMETERS:
* ip - Inode pointer
* ealist - Pointer to buffer to fill in with EA
*
* NOTES: If EA is inline calls ea_read_inline() to copy EA.
*
* RETURNS: 0 for success; other indicates failure
*/
static int ea_read(struct inode *ip, struct jfs_ea_list *ealist)
{
struct super_block *sb = ip->i_sb;
struct jfs_inode_info *ji = JFS_IP(ip);
struct jfs_sb_info *sbi = JFS_SBI(sb);
int nblocks;
s64 blkno;
char *cp = (char *) ealist;
int i;
int nbytes, nb;
s32 bytes_to_read;
struct metapage *mp;
/* quick check for in-line EA */
if (ji->ea.flag & DXD_INLINE)
return ea_read_inline(ip, ealist);
nbytes = sizeDXD(&ji->ea);
if (!nbytes) {
jfs_error(sb, "ea_read: nbytes is 0");
return -EIO;
}
/*
* Figure out how many blocks were allocated when this EA list was
* originally written to disk.
*/
nblocks = lengthDXD(&ji->ea) << sbi->l2nbperpage;
blkno = addressDXD(&ji->ea) << sbi->l2nbperpage;
/*
* I have found the disk blocks which were originally used to store
* the FEALIST. now i loop over each contiguous block copying the
* data into the buffer.
*/
for (i = 0; i < nblocks; i += sbi->nbperpage) {
/*
* Determine how many bytes for this request, and round up to
* the nearest aggregate block size
*/
nb = min(PSIZE, nbytes);
bytes_to_read =
((((nb + sb->s_blocksize - 1)) >> sb->s_blocksize_bits))
<< sb->s_blocksize_bits;
if (!(mp = read_metapage(ip, blkno + i, bytes_to_read, 1)))
return -EIO;
memcpy(cp, mp->data, nb);
release_metapage(mp);
cp += PSIZE;
nbytes -= nb;
}
return 0;
}
/*
* NAME: ea_get
*
* FUNCTION: Returns buffer containing existing extended attributes.
* The size of the buffer will be the larger of the existing
* attributes size, or min_size.
*
* The buffer, which may be inlined in the inode or in the
* page cache must be release by calling ea_release or ea_put
*
* PARAMETERS:
* inode - Inode pointer
* ea_buf - Structure to be populated with ealist and its metadata
* min_size- minimum size of buffer to be returned
*
* RETURNS: 0 for success; Other indicates failure
*/
static int ea_get(struct inode *inode, struct ea_buffer *ea_buf, int min_size)
{
struct jfs_inode_info *ji = JFS_IP(inode);
struct super_block *sb = inode->i_sb;
int size;
int ea_size = sizeDXD(&ji->ea);
int blocks_needed, current_blocks;
s64 blkno;
int rc;
int quota_allocation = 0;
/* When fsck.jfs clears a bad ea, it doesn't clear the size */
if (ji->ea.flag == 0)
ea_size = 0;
if (ea_size == 0) {
if (min_size == 0) {
ea_buf->flag = 0;
ea_buf->max_size = 0;
ea_buf->xattr = NULL;
return 0;
}
if ((min_size <= sizeof (ji->i_inline_ea)) &&
(ji->mode2 & INLINEEA)) {
ea_buf->flag = EA_INLINE | EA_NEW;
ea_buf->max_size = sizeof (ji->i_inline_ea);
ea_buf->xattr = (struct jfs_ea_list *) ji->i_inline_ea;
DXDlength(&ea_buf->new_ea, 0);
DXDaddress(&ea_buf->new_ea, 0);
ea_buf->new_ea.flag = DXD_INLINE;
DXDsize(&ea_buf->new_ea, min_size);
return 0;
}
current_blocks = 0;
} else if (ji->ea.flag & DXD_INLINE) {
if (min_size <= sizeof (ji->i_inline_ea)) {
ea_buf->flag = EA_INLINE;
ea_buf->max_size = sizeof (ji->i_inline_ea);
ea_buf->xattr = (struct jfs_ea_list *) ji->i_inline_ea;
goto size_check;
}
current_blocks = 0;
} else {
if (!(ji->ea.flag & DXD_EXTENT)) {
jfs_error(sb, "ea_get: invalid ea.flag)");
return -EIO;
}
current_blocks = (ea_size + sb->s_blocksize - 1) >>
sb->s_blocksize_bits;
}
size = max(min_size, ea_size);
if (size > PSIZE) {
/*
* To keep the rest of the code simple. Allocate a
* contiguous buffer to work with
*/
ea_buf->xattr = kmalloc(size, GFP_KERNEL);
if (ea_buf->xattr == NULL)
return -ENOMEM;
ea_buf->flag = EA_MALLOC;
ea_buf->max_size = (size + sb->s_blocksize - 1) &
~(sb->s_blocksize - 1);
if (ea_size == 0)
return 0;
if ((rc = ea_read(inode, ea_buf->xattr))) {
kfree(ea_buf->xattr);
ea_buf->xattr = NULL;
return rc;
}
goto size_check;
}
blocks_needed = (min_size + sb->s_blocksize - 1) >>
sb->s_blocksize_bits;
if (blocks_needed > current_blocks) {
/* Allocate new blocks to quota. */
rc = dquot_alloc_block(inode, blocks_needed);
if (rc)
return -EDQUOT;
quota_allocation = blocks_needed;
rc = dbAlloc(inode, INOHINT(inode), (s64) blocks_needed,
&blkno);
if (rc)
goto clean_up;
DXDlength(&ea_buf->new_ea, blocks_needed);
DXDaddress(&ea_buf->new_ea, blkno);
ea_buf->new_ea.flag = DXD_EXTENT;
DXDsize(&ea_buf->new_ea, min_size);
ea_buf->flag = EA_EXTENT | EA_NEW;
ea_buf->mp = get_metapage(inode, blkno,
blocks_needed << sb->s_blocksize_bits,
1);
if (ea_buf->mp == NULL) {
dbFree(inode, blkno, (s64) blocks_needed);
rc = -EIO;
goto clean_up;
}
ea_buf->xattr = ea_buf->mp->data;
ea_buf->max_size = (min_size + sb->s_blocksize - 1) &
~(sb->s_blocksize - 1);
if (ea_size == 0)
return 0;
if ((rc = ea_read(inode, ea_buf->xattr))) {
discard_metapage(ea_buf->mp);
dbFree(inode, blkno, (s64) blocks_needed);
goto clean_up;
}
goto size_check;
}
ea_buf->flag = EA_EXTENT;
ea_buf->mp = read_metapage(inode, addressDXD(&ji->ea),
lengthDXD(&ji->ea) << sb->s_blocksize_bits,
1);
if (ea_buf->mp == NULL) {
rc = -EIO;
goto clean_up;
}
ea_buf->xattr = ea_buf->mp->data;
ea_buf->max_size = (ea_size + sb->s_blocksize - 1) &
~(sb->s_blocksize - 1);
size_check:
if (EALIST_SIZE(ea_buf->xattr) != ea_size) {
printk(KERN_ERR "ea_get: invalid extended attribute\n");
print_hex_dump(KERN_ERR, "", DUMP_PREFIX_ADDRESS, 16, 1,
ea_buf->xattr, ea_size, 1);
ea_release(inode, ea_buf);
rc = -EIO;
goto clean_up;
}
return ea_size;
clean_up:
/* Rollback quota allocation */
if (quota_allocation)
dquot_free_block(inode, quota_allocation);
return (rc);
}
static void ea_release(struct inode *inode, struct ea_buffer *ea_buf)
{
if (ea_buf->flag & EA_MALLOC)
kfree(ea_buf->xattr);
else if (ea_buf->flag & EA_EXTENT) {
assert(ea_buf->mp);
release_metapage(ea_buf->mp);
if (ea_buf->flag & EA_NEW)
dbFree(inode, addressDXD(&ea_buf->new_ea),
lengthDXD(&ea_buf->new_ea));
}
}
static int ea_put(tid_t tid, struct inode *inode, struct ea_buffer *ea_buf,
int new_size)
{
struct jfs_inode_info *ji = JFS_IP(inode);
unsigned long old_blocks, new_blocks;
int rc = 0;
if (new_size == 0) {
ea_release(inode, ea_buf);
ea_buf = NULL;
} else if (ea_buf->flag & EA_INLINE) {
assert(new_size <= sizeof (ji->i_inline_ea));
ji->mode2 &= ~INLINEEA;
ea_buf->new_ea.flag = DXD_INLINE;
DXDsize(&ea_buf->new_ea, new_size);
DXDaddress(&ea_buf->new_ea, 0);
DXDlength(&ea_buf->new_ea, 0);
} else if (ea_buf->flag & EA_MALLOC) {
rc = ea_write(inode, ea_buf->xattr, new_size, &ea_buf->new_ea);
kfree(ea_buf->xattr);
} else if (ea_buf->flag & EA_NEW) {
/* We have already allocated a new dxd */
flush_metapage(ea_buf->mp);
} else {
/* ->xattr must point to original ea's metapage */
rc = ea_write(inode, ea_buf->xattr, new_size, &ea_buf->new_ea);
discard_metapage(ea_buf->mp);
}
if (rc)
return rc;
old_blocks = new_blocks = 0;
if (ji->ea.flag & DXD_EXTENT) {
invalidate_dxd_metapages(inode, ji->ea);
old_blocks = lengthDXD(&ji->ea);
}
if (ea_buf) {
txEA(tid, inode, &ji->ea, &ea_buf->new_ea);
if (ea_buf->new_ea.flag & DXD_EXTENT) {
new_blocks = lengthDXD(&ea_buf->new_ea);
if (ji->ea.flag & DXD_INLINE)
ji->mode2 |= INLINEEA;
}
ji->ea = ea_buf->new_ea;
} else {
txEA(tid, inode, &ji->ea, NULL);
if (ji->ea.flag & DXD_INLINE)
ji->mode2 |= INLINEEA;
ji->ea.flag = 0;
ji->ea.size = 0;
}
/* If old blocks exist, they must be removed from quota allocation. */
if (old_blocks)
dquot_free_block(inode, old_blocks);
inode->i_ctime = CURRENT_TIME;
return 0;
}
/*
* can_set_system_xattr
*
* This code is specific to the system.* namespace. It contains policy
* which doesn't belong in the main xattr codepath.
*/
static int can_set_system_xattr(struct inode *inode, const char *name,
const void *value, size_t value_len)
{
#ifdef CONFIG_JFS_POSIX_ACL
struct posix_acl *acl;
int rc;
if (!inode_owner_or_capable(inode))
return -EPERM;
/*
* POSIX_ACL_XATTR_ACCESS is tied to i_mode
*/
if (strcmp(name, POSIX_ACL_XATTR_ACCESS) == 0) {
acl = posix_acl_from_xattr(&init_user_ns, value, value_len);
if (IS_ERR(acl)) {
rc = PTR_ERR(acl);
printk(KERN_ERR "posix_acl_from_xattr returned %d\n",
rc);
return rc;
}
if (acl) {
rc = posix_acl_equiv_mode(acl, &inode->i_mode);
posix_acl_release(acl);
if (rc < 0) {
printk(KERN_ERR
"posix_acl_equiv_mode returned %d\n",
rc);
return rc;
}
mark_inode_dirty(inode);
}
/*
* We're changing the ACL. Get rid of the cached one
*/
forget_cached_acl(inode, ACL_TYPE_ACCESS);
return 0;
} else if (strcmp(name, POSIX_ACL_XATTR_DEFAULT) == 0) {
acl = posix_acl_from_xattr(&init_user_ns, value, value_len);
if (IS_ERR(acl)) {
rc = PTR_ERR(acl);
printk(KERN_ERR "posix_acl_from_xattr returned %d\n",
rc);
return rc;
}
posix_acl_release(acl);
/*
* We're changing the default ACL. Get rid of the cached one
*/
forget_cached_acl(inode, ACL_TYPE_DEFAULT);
return 0;
}
#endif /* CONFIG_JFS_POSIX_ACL */
return -EOPNOTSUPP;
}
/*
* Most of the permission checking is done by xattr_permission in the vfs.
* The local file system is responsible for handling the system.* namespace.
* We also need to verify that this is a namespace that we recognize.
*/
static int can_set_xattr(struct inode *inode, const char *name,
const void *value, size_t value_len)
{
if (!strncmp(name, XATTR_SYSTEM_PREFIX, XATTR_SYSTEM_PREFIX_LEN))
return can_set_system_xattr(inode, name, value, value_len);
if (!strncmp(name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN)) {
/*
* This makes sure that we aren't trying to set an
* attribute in a different namespace by prefixing it
* with "os2."
*/
if (is_known_namespace(name + XATTR_OS2_PREFIX_LEN))
return -EOPNOTSUPP;
return 0;
}
/*
* Don't allow setting an attribute in an unknown namespace.
*/
if (strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) &&
strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN) &&
strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
return -EOPNOTSUPP;
return 0;
}
int __jfs_setxattr(tid_t tid, struct inode *inode, const char *name,
const void *value, size_t value_len, int flags)
{
struct jfs_ea_list *ealist;
struct jfs_ea *ea, *old_ea = NULL, *next_ea = NULL;
struct ea_buffer ea_buf;
int old_ea_size = 0;
int xattr_size;
int new_size;
int namelen = strlen(name);
char *os2name = NULL;
int found = 0;
int rc;
int length;
if (strncmp(name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN) == 0) {
os2name = kmalloc(namelen - XATTR_OS2_PREFIX_LEN + 1,
GFP_KERNEL);
if (!os2name)
return -ENOMEM;
strcpy(os2name, name + XATTR_OS2_PREFIX_LEN);
name = os2name;
namelen -= XATTR_OS2_PREFIX_LEN;
}
down_write(&JFS_IP(inode)->xattr_sem);
xattr_size = ea_get(inode, &ea_buf, 0);
if (xattr_size < 0) {
rc = xattr_size;
goto out;
}
again:
ealist = (struct jfs_ea_list *) ea_buf.xattr;
new_size = sizeof (struct jfs_ea_list);
if (xattr_size) {
for (ea = FIRST_EA(ealist); ea < END_EALIST(ealist);
ea = NEXT_EA(ea)) {
if ((namelen == ea->namelen) &&
(memcmp(name, ea->name, namelen) == 0)) {
found = 1;
if (flags & XATTR_CREATE) {
rc = -EEXIST;
goto release;
}
old_ea = ea;
old_ea_size = EA_SIZE(ea);
next_ea = NEXT_EA(ea);
} else
new_size += EA_SIZE(ea);
}
}
if (!found) {
if (flags & XATTR_REPLACE) {
rc = -ENODATA;
goto release;
}
if (value == NULL) {
rc = 0;
goto release;
}
}
if (value)
new_size += sizeof (struct jfs_ea) + namelen + 1 + value_len;
if (new_size > ea_buf.max_size) {
/*
* We need to allocate more space for merged ea list.
* We should only have loop to again: once.
*/
ea_release(inode, &ea_buf);
xattr_size = ea_get(inode, &ea_buf, new_size);
if (xattr_size < 0) {
rc = xattr_size;
goto out;
}
goto again;
}
/* Remove old ea of the same name */
if (found) {
/* number of bytes following target EA */
length = (char *) END_EALIST(ealist) - (char *) next_ea;
if (length > 0)
memmove(old_ea, next_ea, length);
xattr_size -= old_ea_size;
}
/* Add new entry to the end */
if (value) {
if (xattr_size == 0)
/* Completely new ea list */
xattr_size = sizeof (struct jfs_ea_list);
ea = (struct jfs_ea *) ((char *) ealist + xattr_size);
ea->flag = 0;
ea->namelen = namelen;
ea->valuelen = (cpu_to_le16(value_len));
memcpy(ea->name, name, namelen);
ea->name[namelen] = 0;
if (value_len)
memcpy(&ea->name[namelen + 1], value, value_len);
xattr_size += EA_SIZE(ea);
}
/* DEBUG - If we did this right, these number match */
if (xattr_size != new_size) {
printk(KERN_ERR
"jfs_xsetattr: xattr_size = %d, new_size = %d\n",
xattr_size, new_size);
rc = -EINVAL;
goto release;
}
/*
* If we're left with an empty list, there's no ea
*/
if (new_size == sizeof (struct jfs_ea_list))
new_size = 0;
ealist->size = cpu_to_le32(new_size);
rc = ea_put(tid, inode, &ea_buf, new_size);
goto out;
release:
ea_release(inode, &ea_buf);
out:
up_write(&JFS_IP(inode)->xattr_sem);
kfree(os2name);
return rc;
}
int jfs_setxattr(struct dentry *dentry, const char *name, const void *value,
size_t value_len, int flags)
{
struct inode *inode = dentry->d_inode;
struct jfs_inode_info *ji = JFS_IP(inode);
int rc;
tid_t tid;
if ((rc = can_set_xattr(inode, name, value, value_len)))
return rc;
if (value == NULL) { /* empty EA, do not remove */
value = "";
value_len = 0;
}
tid = txBegin(inode->i_sb, 0);
mutex_lock(&ji->commit_mutex);
rc = __jfs_setxattr(tid, dentry->d_inode, name, value, value_len,
flags);
if (!rc)
rc = txCommit(tid, 1, &inode, 0);
txEnd(tid);
mutex_unlock(&ji->commit_mutex);
return rc;
}
ssize_t __jfs_getxattr(struct inode *inode, const char *name, void *data,
size_t buf_size)
{
struct jfs_ea_list *ealist;
struct jfs_ea *ea;
struct ea_buffer ea_buf;
int xattr_size;
ssize_t size;
int namelen = strlen(name);
char *value;
down_read(&JFS_IP(inode)->xattr_sem);
xattr_size = ea_get(inode, &ea_buf, 0);
if (xattr_size < 0) {
size = xattr_size;
goto out;
}
if (xattr_size == 0)
goto not_found;
ealist = (struct jfs_ea_list *) ea_buf.xattr;
/* Find the named attribute */
for (ea = FIRST_EA(ealist); ea < END_EALIST(ealist); ea = NEXT_EA(ea))
if ((namelen == ea->namelen) &&
memcmp(name, ea->name, namelen) == 0) {
/* Found it */
size = le16_to_cpu(ea->valuelen);
if (!data)
goto release;
else if (size > buf_size) {
size = -ERANGE;
goto release;
}
value = ((char *) &ea->name) + ea->namelen + 1;
memcpy(data, value, size);
goto release;
}
not_found:
size = -ENODATA;
release:
ea_release(inode, &ea_buf);
out:
up_read(&JFS_IP(inode)->xattr_sem);
return size;
}
ssize_t jfs_getxattr(struct dentry *dentry, const char *name, void *data,
size_t buf_size)
{
int err;
if (strncmp(name, XATTR_OS2_PREFIX, XATTR_OS2_PREFIX_LEN) == 0) {
/*
* skip past "os2." prefix
*/
name += XATTR_OS2_PREFIX_LEN;
/*
* Don't allow retrieving properly prefixed attributes
* by prepending them with "os2."
*/
if (is_known_namespace(name))
return -EOPNOTSUPP;
}
err = __jfs_getxattr(dentry->d_inode, name, data, buf_size);
return err;
}
/*
* No special permissions are needed to list attributes except for trusted.*
*/
static inline int can_list(struct jfs_ea *ea)
{
return (strncmp(ea->name, XATTR_TRUSTED_PREFIX,
XATTR_TRUSTED_PREFIX_LEN) ||
capable(CAP_SYS_ADMIN));
}
ssize_t jfs_listxattr(struct dentry * dentry, char *data, size_t buf_size)
{
struct inode *inode = dentry->d_inode;
char *buffer;
ssize_t size = 0;
int xattr_size;
struct jfs_ea_list *ealist;
struct jfs_ea *ea;
struct ea_buffer ea_buf;
down_read(&JFS_IP(inode)->xattr_sem);
xattr_size = ea_get(inode, &ea_buf, 0);
if (xattr_size < 0) {
size = xattr_size;
goto out;
}
if (xattr_size == 0)
goto release;
ealist = (struct jfs_ea_list *) ea_buf.xattr;
/* compute required size of list */
for (ea = FIRST_EA(ealist); ea < END_EALIST(ealist); ea = NEXT_EA(ea)) {
if (can_list(ea))
size += name_size(ea) + 1;
}
if (!data)
goto release;
if (size > buf_size) {
size = -ERANGE;
goto release;
}
/* Copy attribute names to buffer */
buffer = data;
for (ea = FIRST_EA(ealist); ea < END_EALIST(ealist); ea = NEXT_EA(ea)) {
if (can_list(ea)) {
int namelen = copy_name(buffer, ea);
buffer += namelen + 1;
}
}
release:
ea_release(inode, &ea_buf);
out:
up_read(&JFS_IP(inode)->xattr_sem);
return size;
}
int jfs_removexattr(struct dentry *dentry, const char *name)
{
struct inode *inode = dentry->d_inode;
struct jfs_inode_info *ji = JFS_IP(inode);
int rc;
tid_t tid;
if ((rc = can_set_xattr(inode, name, NULL, 0)))
return rc;
tid = txBegin(inode->i_sb, 0);
mutex_lock(&ji->commit_mutex);
rc = __jfs_setxattr(tid, dentry->d_inode, name, NULL, 0, XATTR_REPLACE);
if (!rc)
rc = txCommit(tid, 1, &inode, 0);
txEnd(tid);
mutex_unlock(&ji->commit_mutex);
return rc;
}
#ifdef CONFIG_JFS_SECURITY
int jfs_initxattrs(struct inode *inode, const struct xattr *xattr_array,
void *fs_info)
{
const struct xattr *xattr;
tid_t *tid = fs_info;
char *name;
int err = 0;
for (xattr = xattr_array; xattr->name != NULL; xattr++) {
name = kmalloc(XATTR_SECURITY_PREFIX_LEN +
strlen(xattr->name) + 1, GFP_NOFS);
if (!name) {
err = -ENOMEM;
break;
}
strcpy(name, XATTR_SECURITY_PREFIX);
strcpy(name + XATTR_SECURITY_PREFIX_LEN, xattr->name);
err = __jfs_setxattr(*tid, inode, name,
xattr->value, xattr->value_len, 0);
kfree(name);
if (err < 0)
break;
}
return err;
}
int jfs_init_security(tid_t tid, struct inode *inode, struct inode *dir,
const struct qstr *qstr)
{
return security_inode_init_security(inode, dir, qstr,
&jfs_initxattrs, &tid);
}
#endif
| gpl-2.0 |
AOKP-SGS2/android_kernel_samsung_espresso | drivers/media/video/s5p-fimc/fimc-reg.c | 2380 | 17930 | /*
* Register interface file for Samsung Camera Interface (FIMC) driver
*
* Copyright (c) 2010 Samsung Electronics
*
* Sylwester Nawrocki, s.nawrocki@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/io.h>
#include <linux/delay.h>
#include <mach/map.h>
#include <media/s5p_fimc.h>
#include "fimc-core.h"
void fimc_hw_reset(struct fimc_dev *dev)
{
u32 cfg;
cfg = readl(dev->regs + S5P_CISRCFMT);
cfg |= S5P_CISRCFMT_ITU601_8BIT;
writel(cfg, dev->regs + S5P_CISRCFMT);
/* Software reset. */
cfg = readl(dev->regs + S5P_CIGCTRL);
cfg |= (S5P_CIGCTRL_SWRST | S5P_CIGCTRL_IRQ_LEVEL);
writel(cfg, dev->regs + S5P_CIGCTRL);
udelay(1000);
cfg = readl(dev->regs + S5P_CIGCTRL);
cfg &= ~S5P_CIGCTRL_SWRST;
writel(cfg, dev->regs + S5P_CIGCTRL);
}
static u32 fimc_hw_get_in_flip(struct fimc_ctx *ctx)
{
u32 flip = S5P_MSCTRL_FLIP_NORMAL;
switch (ctx->flip) {
case FLIP_X_AXIS:
flip = S5P_MSCTRL_FLIP_X_MIRROR;
break;
case FLIP_Y_AXIS:
flip = S5P_MSCTRL_FLIP_Y_MIRROR;
break;
case FLIP_XY_AXIS:
flip = S5P_MSCTRL_FLIP_180;
break;
default:
break;
}
if (ctx->rotation <= 90)
return flip;
return (flip ^ S5P_MSCTRL_FLIP_180) & S5P_MSCTRL_FLIP_180;
}
static u32 fimc_hw_get_target_flip(struct fimc_ctx *ctx)
{
u32 flip = S5P_CITRGFMT_FLIP_NORMAL;
switch (ctx->flip) {
case FLIP_X_AXIS:
flip = S5P_CITRGFMT_FLIP_X_MIRROR;
break;
case FLIP_Y_AXIS:
flip = S5P_CITRGFMT_FLIP_Y_MIRROR;
break;
case FLIP_XY_AXIS:
flip = S5P_CITRGFMT_FLIP_180;
break;
default:
break;
}
if (ctx->rotation <= 90)
return flip;
return (flip ^ S5P_CITRGFMT_FLIP_180) & S5P_CITRGFMT_FLIP_180;
}
void fimc_hw_set_rotation(struct fimc_ctx *ctx)
{
u32 cfg, flip;
struct fimc_dev *dev = ctx->fimc_dev;
cfg = readl(dev->regs + S5P_CITRGFMT);
cfg &= ~(S5P_CITRGFMT_INROT90 | S5P_CITRGFMT_OUTROT90 |
S5P_CITRGFMT_FLIP_180);
/*
* The input and output rotator cannot work simultaneously.
* Use the output rotator in output DMA mode or the input rotator
* in direct fifo output mode.
*/
if (ctx->rotation == 90 || ctx->rotation == 270) {
if (ctx->out_path == FIMC_LCDFIFO)
cfg |= S5P_CITRGFMT_INROT90;
else
cfg |= S5P_CITRGFMT_OUTROT90;
}
if (ctx->out_path == FIMC_DMA) {
cfg |= fimc_hw_get_target_flip(ctx);
writel(cfg, dev->regs + S5P_CITRGFMT);
} else {
/* LCD FIFO path */
flip = readl(dev->regs + S5P_MSCTRL);
flip &= ~S5P_MSCTRL_FLIP_MASK;
flip |= fimc_hw_get_in_flip(ctx);
writel(flip, dev->regs + S5P_MSCTRL);
}
}
void fimc_hw_set_target_format(struct fimc_ctx *ctx)
{
u32 cfg;
struct fimc_dev *dev = ctx->fimc_dev;
struct fimc_frame *frame = &ctx->d_frame;
dbg("w= %d, h= %d color: %d", frame->width,
frame->height, frame->fmt->color);
cfg = readl(dev->regs + S5P_CITRGFMT);
cfg &= ~(S5P_CITRGFMT_FMT_MASK | S5P_CITRGFMT_HSIZE_MASK |
S5P_CITRGFMT_VSIZE_MASK);
switch (frame->fmt->color) {
case S5P_FIMC_RGB565...S5P_FIMC_RGB888:
cfg |= S5P_CITRGFMT_RGB;
break;
case S5P_FIMC_YCBCR420:
cfg |= S5P_CITRGFMT_YCBCR420;
break;
case S5P_FIMC_YCBYCR422...S5P_FIMC_CRYCBY422:
if (frame->fmt->colplanes == 1)
cfg |= S5P_CITRGFMT_YCBCR422_1P;
else
cfg |= S5P_CITRGFMT_YCBCR422;
break;
default:
break;
}
if (ctx->rotation == 90 || ctx->rotation == 270) {
cfg |= S5P_CITRGFMT_HSIZE(frame->height);
cfg |= S5P_CITRGFMT_VSIZE(frame->width);
} else {
cfg |= S5P_CITRGFMT_HSIZE(frame->width);
cfg |= S5P_CITRGFMT_VSIZE(frame->height);
}
writel(cfg, dev->regs + S5P_CITRGFMT);
cfg = readl(dev->regs + S5P_CITAREA) & ~S5P_CITAREA_MASK;
cfg |= (frame->width * frame->height);
writel(cfg, dev->regs + S5P_CITAREA);
}
static void fimc_hw_set_out_dma_size(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
struct fimc_frame *frame = &ctx->d_frame;
u32 cfg;
cfg = S5P_ORIG_SIZE_HOR(frame->f_width);
cfg |= S5P_ORIG_SIZE_VER(frame->f_height);
writel(cfg, dev->regs + S5P_ORGOSIZE);
/* Select color space conversion equation (HD/SD size).*/
cfg = readl(dev->regs + S5P_CIGCTRL);
if (frame->f_width >= 1280) /* HD */
cfg |= S5P_CIGCTRL_CSC_ITU601_709;
else /* SD */
cfg &= ~S5P_CIGCTRL_CSC_ITU601_709;
writel(cfg, dev->regs + S5P_CIGCTRL);
}
void fimc_hw_set_out_dma(struct fimc_ctx *ctx)
{
u32 cfg;
struct fimc_dev *dev = ctx->fimc_dev;
struct fimc_frame *frame = &ctx->d_frame;
struct fimc_dma_offset *offset = &frame->dma_offset;
/* Set the input dma offsets. */
cfg = 0;
cfg |= S5P_CIO_OFFS_HOR(offset->y_h);
cfg |= S5P_CIO_OFFS_VER(offset->y_v);
writel(cfg, dev->regs + S5P_CIOYOFF);
cfg = 0;
cfg |= S5P_CIO_OFFS_HOR(offset->cb_h);
cfg |= S5P_CIO_OFFS_VER(offset->cb_v);
writel(cfg, dev->regs + S5P_CIOCBOFF);
cfg = 0;
cfg |= S5P_CIO_OFFS_HOR(offset->cr_h);
cfg |= S5P_CIO_OFFS_VER(offset->cr_v);
writel(cfg, dev->regs + S5P_CIOCROFF);
fimc_hw_set_out_dma_size(ctx);
/* Configure chroma components order. */
cfg = readl(dev->regs + S5P_CIOCTRL);
cfg &= ~(S5P_CIOCTRL_ORDER2P_MASK | S5P_CIOCTRL_ORDER422_MASK |
S5P_CIOCTRL_YCBCR_PLANE_MASK);
if (frame->fmt->colplanes == 1)
cfg |= ctx->out_order_1p;
else if (frame->fmt->colplanes == 2)
cfg |= ctx->out_order_2p | S5P_CIOCTRL_YCBCR_2PLANE;
else if (frame->fmt->colplanes == 3)
cfg |= S5P_CIOCTRL_YCBCR_3PLANE;
writel(cfg, dev->regs + S5P_CIOCTRL);
}
static void fimc_hw_en_autoload(struct fimc_dev *dev, int enable)
{
u32 cfg = readl(dev->regs + S5P_ORGISIZE);
if (enable)
cfg |= S5P_CIREAL_ISIZE_AUTOLOAD_EN;
else
cfg &= ~S5P_CIREAL_ISIZE_AUTOLOAD_EN;
writel(cfg, dev->regs + S5P_ORGISIZE);
}
void fimc_hw_en_lastirq(struct fimc_dev *dev, int enable)
{
u32 cfg = readl(dev->regs + S5P_CIOCTRL);
if (enable)
cfg |= S5P_CIOCTRL_LASTIRQ_ENABLE;
else
cfg &= ~S5P_CIOCTRL_LASTIRQ_ENABLE;
writel(cfg, dev->regs + S5P_CIOCTRL);
}
void fimc_hw_set_prescaler(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
struct fimc_scaler *sc = &ctx->scaler;
u32 cfg, shfactor;
shfactor = 10 - (sc->hfactor + sc->vfactor);
cfg = S5P_CISCPRERATIO_SHFACTOR(shfactor);
cfg |= S5P_CISCPRERATIO_HOR(sc->pre_hratio);
cfg |= S5P_CISCPRERATIO_VER(sc->pre_vratio);
writel(cfg, dev->regs + S5P_CISCPRERATIO);
cfg = S5P_CISCPREDST_WIDTH(sc->pre_dst_width);
cfg |= S5P_CISCPREDST_HEIGHT(sc->pre_dst_height);
writel(cfg, dev->regs + S5P_CISCPREDST);
}
static void fimc_hw_set_scaler(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
struct fimc_scaler *sc = &ctx->scaler;
struct fimc_frame *src_frame = &ctx->s_frame;
struct fimc_frame *dst_frame = &ctx->d_frame;
u32 cfg = 0;
if (!(ctx->flags & FIMC_COLOR_RANGE_NARROW))
cfg |= (S5P_CISCCTRL_CSCR2Y_WIDE | S5P_CISCCTRL_CSCY2R_WIDE);
if (!sc->enabled)
cfg |= S5P_CISCCTRL_SCALERBYPASS;
if (sc->scaleup_h)
cfg |= S5P_CISCCTRL_SCALEUP_H;
if (sc->scaleup_v)
cfg |= S5P_CISCCTRL_SCALEUP_V;
if (sc->copy_mode)
cfg |= S5P_CISCCTRL_ONE2ONE;
if (ctx->in_path == FIMC_DMA) {
if (src_frame->fmt->color == S5P_FIMC_RGB565)
cfg |= S5P_CISCCTRL_INRGB_FMT_RGB565;
else if (src_frame->fmt->color == S5P_FIMC_RGB666)
cfg |= S5P_CISCCTRL_INRGB_FMT_RGB666;
else if (src_frame->fmt->color == S5P_FIMC_RGB888)
cfg |= S5P_CISCCTRL_INRGB_FMT_RGB888;
}
if (ctx->out_path == FIMC_DMA) {
if (dst_frame->fmt->color == S5P_FIMC_RGB565)
cfg |= S5P_CISCCTRL_OUTRGB_FMT_RGB565;
else if (dst_frame->fmt->color == S5P_FIMC_RGB666)
cfg |= S5P_CISCCTRL_OUTRGB_FMT_RGB666;
else if (dst_frame->fmt->color == S5P_FIMC_RGB888)
cfg |= S5P_CISCCTRL_OUTRGB_FMT_RGB888;
} else {
cfg |= S5P_CISCCTRL_OUTRGB_FMT_RGB888;
if (ctx->flags & FIMC_SCAN_MODE_INTERLACED)
cfg |= S5P_CISCCTRL_INTERLACE;
}
writel(cfg, dev->regs + S5P_CISCCTRL);
}
void fimc_hw_set_mainscaler(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
struct samsung_fimc_variant *variant = dev->variant;
struct fimc_scaler *sc = &ctx->scaler;
u32 cfg;
dbg("main_hratio= 0x%X main_vratio= 0x%X",
sc->main_hratio, sc->main_vratio);
fimc_hw_set_scaler(ctx);
cfg = readl(dev->regs + S5P_CISCCTRL);
if (variant->has_mainscaler_ext) {
cfg &= ~(S5P_CISCCTRL_MHRATIO_MASK | S5P_CISCCTRL_MVRATIO_MASK);
cfg |= S5P_CISCCTRL_MHRATIO_EXT(sc->main_hratio);
cfg |= S5P_CISCCTRL_MVRATIO_EXT(sc->main_vratio);
writel(cfg, dev->regs + S5P_CISCCTRL);
cfg = readl(dev->regs + S5P_CIEXTEN);
cfg &= ~(S5P_CIEXTEN_MVRATIO_EXT_MASK |
S5P_CIEXTEN_MHRATIO_EXT_MASK);
cfg |= S5P_CIEXTEN_MHRATIO_EXT(sc->main_hratio);
cfg |= S5P_CIEXTEN_MVRATIO_EXT(sc->main_vratio);
writel(cfg, dev->regs + S5P_CIEXTEN);
} else {
cfg &= ~(S5P_CISCCTRL_MHRATIO_MASK | S5P_CISCCTRL_MVRATIO_MASK);
cfg |= S5P_CISCCTRL_MHRATIO(sc->main_hratio);
cfg |= S5P_CISCCTRL_MVRATIO(sc->main_vratio);
writel(cfg, dev->regs + S5P_CISCCTRL);
}
}
void fimc_hw_en_capture(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
u32 cfg = readl(dev->regs + S5P_CIIMGCPT);
if (ctx->out_path == FIMC_DMA) {
/* one shot mode */
cfg |= S5P_CIIMGCPT_CPT_FREN_ENABLE | S5P_CIIMGCPT_IMGCPTEN;
} else {
/* Continuous frame capture mode (freerun). */
cfg &= ~(S5P_CIIMGCPT_CPT_FREN_ENABLE |
S5P_CIIMGCPT_CPT_FRMOD_CNT);
cfg |= S5P_CIIMGCPT_IMGCPTEN;
}
if (ctx->scaler.enabled)
cfg |= S5P_CIIMGCPT_IMGCPTEN_SC;
writel(cfg | S5P_CIIMGCPT_IMGCPTEN, dev->regs + S5P_CIIMGCPT);
}
void fimc_hw_set_effect(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
struct fimc_effect *effect = &ctx->effect;
u32 cfg = (S5P_CIIMGEFF_IE_ENABLE | S5P_CIIMGEFF_IE_SC_AFTER);
cfg |= effect->type;
if (effect->type == S5P_FIMC_EFFECT_ARBITRARY) {
cfg |= S5P_CIIMGEFF_PAT_CB(effect->pat_cb);
cfg |= S5P_CIIMGEFF_PAT_CR(effect->pat_cr);
}
writel(cfg, dev->regs + S5P_CIIMGEFF);
}
static void fimc_hw_set_in_dma_size(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
struct fimc_frame *frame = &ctx->s_frame;
u32 cfg_o = 0;
u32 cfg_r = 0;
if (FIMC_LCDFIFO == ctx->out_path)
cfg_r |= S5P_CIREAL_ISIZE_AUTOLOAD_EN;
cfg_o |= S5P_ORIG_SIZE_HOR(frame->f_width);
cfg_o |= S5P_ORIG_SIZE_VER(frame->f_height);
cfg_r |= S5P_CIREAL_ISIZE_WIDTH(frame->width);
cfg_r |= S5P_CIREAL_ISIZE_HEIGHT(frame->height);
writel(cfg_o, dev->regs + S5P_ORGISIZE);
writel(cfg_r, dev->regs + S5P_CIREAL_ISIZE);
}
void fimc_hw_set_in_dma(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
struct fimc_frame *frame = &ctx->s_frame;
struct fimc_dma_offset *offset = &frame->dma_offset;
u32 cfg;
/* Set the pixel offsets. */
cfg = S5P_CIO_OFFS_HOR(offset->y_h);
cfg |= S5P_CIO_OFFS_VER(offset->y_v);
writel(cfg, dev->regs + S5P_CIIYOFF);
cfg = S5P_CIO_OFFS_HOR(offset->cb_h);
cfg |= S5P_CIO_OFFS_VER(offset->cb_v);
writel(cfg, dev->regs + S5P_CIICBOFF);
cfg = S5P_CIO_OFFS_HOR(offset->cr_h);
cfg |= S5P_CIO_OFFS_VER(offset->cr_v);
writel(cfg, dev->regs + S5P_CIICROFF);
/* Input original and real size. */
fimc_hw_set_in_dma_size(ctx);
/* Use DMA autoload only in FIFO mode. */
fimc_hw_en_autoload(dev, ctx->out_path == FIMC_LCDFIFO);
/* Set the input DMA to process single frame only. */
cfg = readl(dev->regs + S5P_MSCTRL);
cfg &= ~(S5P_MSCTRL_INFORMAT_MASK
| S5P_MSCTRL_IN_BURST_COUNT_MASK
| S5P_MSCTRL_INPUT_MASK
| S5P_MSCTRL_C_INT_IN_MASK
| S5P_MSCTRL_2P_IN_ORDER_MASK);
cfg |= (S5P_MSCTRL_IN_BURST_COUNT(4)
| S5P_MSCTRL_INPUT_MEMORY
| S5P_MSCTRL_FIFO_CTRL_FULL);
switch (frame->fmt->color) {
case S5P_FIMC_RGB565...S5P_FIMC_RGB888:
cfg |= S5P_MSCTRL_INFORMAT_RGB;
break;
case S5P_FIMC_YCBCR420:
cfg |= S5P_MSCTRL_INFORMAT_YCBCR420;
if (frame->fmt->colplanes == 2)
cfg |= ctx->in_order_2p | S5P_MSCTRL_C_INT_IN_2PLANE;
else
cfg |= S5P_MSCTRL_C_INT_IN_3PLANE;
break;
case S5P_FIMC_YCBYCR422...S5P_FIMC_CRYCBY422:
if (frame->fmt->colplanes == 1) {
cfg |= ctx->in_order_1p
| S5P_MSCTRL_INFORMAT_YCBCR422_1P;
} else {
cfg |= S5P_MSCTRL_INFORMAT_YCBCR422;
if (frame->fmt->colplanes == 2)
cfg |= ctx->in_order_2p
| S5P_MSCTRL_C_INT_IN_2PLANE;
else
cfg |= S5P_MSCTRL_C_INT_IN_3PLANE;
}
break;
default:
break;
}
writel(cfg, dev->regs + S5P_MSCTRL);
/* Input/output DMA linear/tiled mode. */
cfg = readl(dev->regs + S5P_CIDMAPARAM);
cfg &= ~S5P_CIDMAPARAM_TILE_MASK;
if (tiled_fmt(ctx->s_frame.fmt))
cfg |= S5P_CIDMAPARAM_R_64X32;
if (tiled_fmt(ctx->d_frame.fmt))
cfg |= S5P_CIDMAPARAM_W_64X32;
writel(cfg, dev->regs + S5P_CIDMAPARAM);
}
void fimc_hw_set_input_path(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
u32 cfg = readl(dev->regs + S5P_MSCTRL);
cfg &= ~S5P_MSCTRL_INPUT_MASK;
if (ctx->in_path == FIMC_DMA)
cfg |= S5P_MSCTRL_INPUT_MEMORY;
else
cfg |= S5P_MSCTRL_INPUT_EXTCAM;
writel(cfg, dev->regs + S5P_MSCTRL);
}
void fimc_hw_set_output_path(struct fimc_ctx *ctx)
{
struct fimc_dev *dev = ctx->fimc_dev;
u32 cfg = readl(dev->regs + S5P_CISCCTRL);
cfg &= ~S5P_CISCCTRL_LCDPATHEN_FIFO;
if (ctx->out_path == FIMC_LCDFIFO)
cfg |= S5P_CISCCTRL_LCDPATHEN_FIFO;
writel(cfg, dev->regs + S5P_CISCCTRL);
}
void fimc_hw_set_input_addr(struct fimc_dev *dev, struct fimc_addr *paddr)
{
u32 cfg = readl(dev->regs + S5P_CIREAL_ISIZE);
cfg |= S5P_CIREAL_ISIZE_ADDR_CH_DIS;
writel(cfg, dev->regs + S5P_CIREAL_ISIZE);
writel(paddr->y, dev->regs + S5P_CIIYSA(0));
writel(paddr->cb, dev->regs + S5P_CIICBSA(0));
writel(paddr->cr, dev->regs + S5P_CIICRSA(0));
cfg &= ~S5P_CIREAL_ISIZE_ADDR_CH_DIS;
writel(cfg, dev->regs + S5P_CIREAL_ISIZE);
}
void fimc_hw_set_output_addr(struct fimc_dev *dev,
struct fimc_addr *paddr, int index)
{
int i = (index == -1) ? 0 : index;
do {
writel(paddr->y, dev->regs + S5P_CIOYSA(i));
writel(paddr->cb, dev->regs + S5P_CIOCBSA(i));
writel(paddr->cr, dev->regs + S5P_CIOCRSA(i));
dbg("dst_buf[%d]: 0x%X, cb: 0x%X, cr: 0x%X",
i, paddr->y, paddr->cb, paddr->cr);
} while (index == -1 && ++i < FIMC_MAX_OUT_BUFS);
}
int fimc_hw_set_camera_polarity(struct fimc_dev *fimc,
struct s5p_fimc_isp_info *cam)
{
u32 cfg = readl(fimc->regs + S5P_CIGCTRL);
cfg &= ~(S5P_CIGCTRL_INVPOLPCLK | S5P_CIGCTRL_INVPOLVSYNC |
S5P_CIGCTRL_INVPOLHREF | S5P_CIGCTRL_INVPOLHSYNC);
if (cam->flags & FIMC_CLK_INV_PCLK)
cfg |= S5P_CIGCTRL_INVPOLPCLK;
if (cam->flags & FIMC_CLK_INV_VSYNC)
cfg |= S5P_CIGCTRL_INVPOLVSYNC;
if (cam->flags & FIMC_CLK_INV_HREF)
cfg |= S5P_CIGCTRL_INVPOLHREF;
if (cam->flags & FIMC_CLK_INV_HSYNC)
cfg |= S5P_CIGCTRL_INVPOLHSYNC;
writel(cfg, fimc->regs + S5P_CIGCTRL);
return 0;
}
int fimc_hw_set_camera_source(struct fimc_dev *fimc,
struct s5p_fimc_isp_info *cam)
{
struct fimc_frame *f = &fimc->vid_cap.ctx->s_frame;
u32 cfg = 0;
u32 bus_width;
int i;
static const struct {
u32 pixelcode;
u32 cisrcfmt;
u16 bus_width;
} pix_desc[] = {
{ V4L2_MBUS_FMT_YUYV8_2X8, S5P_CISRCFMT_ORDER422_YCBYCR, 8 },
{ V4L2_MBUS_FMT_YVYU8_2X8, S5P_CISRCFMT_ORDER422_YCRYCB, 8 },
{ V4L2_MBUS_FMT_VYUY8_2X8, S5P_CISRCFMT_ORDER422_CRYCBY, 8 },
{ V4L2_MBUS_FMT_UYVY8_2X8, S5P_CISRCFMT_ORDER422_CBYCRY, 8 },
/* TODO: Add pixel codes for 16-bit bus width */
};
if (cam->bus_type == FIMC_ITU_601 || cam->bus_type == FIMC_ITU_656) {
for (i = 0; i < ARRAY_SIZE(pix_desc); i++) {
if (fimc->vid_cap.fmt.code == pix_desc[i].pixelcode) {
cfg = pix_desc[i].cisrcfmt;
bus_width = pix_desc[i].bus_width;
break;
}
}
if (i == ARRAY_SIZE(pix_desc)) {
v4l2_err(&fimc->vid_cap.v4l2_dev,
"Camera color format not supported: %d\n",
fimc->vid_cap.fmt.code);
return -EINVAL;
}
if (cam->bus_type == FIMC_ITU_601) {
if (bus_width == 8)
cfg |= S5P_CISRCFMT_ITU601_8BIT;
else if (bus_width == 16)
cfg |= S5P_CISRCFMT_ITU601_16BIT;
} /* else defaults to ITU-R BT.656 8-bit */
}
cfg |= S5P_CISRCFMT_HSIZE(f->o_width) | S5P_CISRCFMT_VSIZE(f->o_height);
writel(cfg, fimc->regs + S5P_CISRCFMT);
return 0;
}
int fimc_hw_set_camera_offset(struct fimc_dev *fimc, struct fimc_frame *f)
{
u32 hoff2, voff2;
u32 cfg = readl(fimc->regs + S5P_CIWDOFST);
cfg &= ~(S5P_CIWDOFST_HOROFF_MASK | S5P_CIWDOFST_VEROFF_MASK);
cfg |= S5P_CIWDOFST_OFF_EN |
S5P_CIWDOFST_HOROFF(f->offs_h) |
S5P_CIWDOFST_VEROFF(f->offs_v);
writel(cfg, fimc->regs + S5P_CIWDOFST);
/* See CIWDOFSTn register description in the datasheet for details. */
hoff2 = f->o_width - f->width - f->offs_h;
voff2 = f->o_height - f->height - f->offs_v;
cfg = S5P_CIWDOFST2_HOROFF(hoff2) | S5P_CIWDOFST2_VEROFF(voff2);
writel(cfg, fimc->regs + S5P_CIWDOFST2);
return 0;
}
int fimc_hw_set_camera_type(struct fimc_dev *fimc,
struct s5p_fimc_isp_info *cam)
{
u32 cfg, tmp;
struct fimc_vid_cap *vid_cap = &fimc->vid_cap;
cfg = readl(fimc->regs + S5P_CIGCTRL);
/* Select ITU B interface, disable Writeback path and test pattern. */
cfg &= ~(S5P_CIGCTRL_TESTPAT_MASK | S5P_CIGCTRL_SELCAM_ITU_A |
S5P_CIGCTRL_SELCAM_MIPI | S5P_CIGCTRL_CAMIF_SELWB |
S5P_CIGCTRL_SELCAM_MIPI_A);
if (cam->bus_type == FIMC_MIPI_CSI2) {
cfg |= S5P_CIGCTRL_SELCAM_MIPI;
if (cam->mux_id == 0)
cfg |= S5P_CIGCTRL_SELCAM_MIPI_A;
/* TODO: add remaining supported formats. */
if (vid_cap->fmt.code == V4L2_MBUS_FMT_VYUY8_2X8) {
tmp = S5P_CSIIMGFMT_YCBCR422_8BIT;
} else {
err("camera image format not supported: %d",
vid_cap->fmt.code);
return -EINVAL;
}
tmp |= (cam->csi_data_align == 32) << 8;
writel(tmp, fimc->regs + S5P_CSIIMGFMT);
} else if (cam->bus_type == FIMC_ITU_601 ||
cam->bus_type == FIMC_ITU_656) {
if (cam->mux_id == 0) /* ITU-A, ITU-B: 0, 1 */
cfg |= S5P_CIGCTRL_SELCAM_ITU_A;
} else if (cam->bus_type == FIMC_LCD_WB) {
cfg |= S5P_CIGCTRL_CAMIF_SELWB;
} else {
err("invalid camera bus type selected\n");
return -EINVAL;
}
writel(cfg, fimc->regs + S5P_CIGCTRL);
return 0;
}
| gpl-2.0 |
reddv1/lucid-nexus-ics | drivers/staging/usbip/userspace/src/usbip.c | 2380 | 13684 | /*
*
* Copyright (C) 2005-2007 Takahiro Hirofuchi
*/
#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif
#include "usbip.h"
#include "usbip_network.h"
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <glib.h>
static const char version[] = PACKAGE_STRING;
/* /sys/devices/platform/vhci_hcd/usb6/6-1/6-1:1.1 -> 1 */
static int get_interface_number(char *path)
{
char *c;
c = strstr(path, vhci_driver->hc_device->bus_id);
if (!c)
return -1; /* hc exist? */
c++;
/* -> usb6/6-1/6-1:1.1 */
c = strchr(c, '/');
if (!c)
return -1; /* hc exist? */
c++;
/* -> 6-1/6-1:1.1 */
c = strchr(c, '/');
if (!c)
return -1; /* no interface path */
c++;
/* -> 6-1:1.1 */
c = strchr(c, ':');
if (!c)
return -1; /* no configuration? */
c++;
/* -> 1.1 */
c = strchr(c, '.');
if (!c)
return -1; /* no interface? */
c++;
/* -> 1 */
return atoi(c);
}
static struct sysfs_device *open_usb_interface(struct usb_device *udev, int i)
{
struct sysfs_device *suinf;
char busid[SYSFS_BUS_ID_SIZE];
snprintf(busid, SYSFS_BUS_ID_SIZE, "%s:%d.%d",
udev->busid, udev->bConfigurationValue, i);
suinf = sysfs_open_device("usb", busid);
if (!suinf)
err("sysfs_open_device %s", busid);
return suinf;
}
#define MAX_BUFF 100
static int record_connection(char *host, char *port, char *busid, int rhport)
{
int fd;
char path[PATH_MAX+1];
char buff[MAX_BUFF+1];
int ret;
mkdir(VHCI_STATE_PATH, 0700);
snprintf(path, PATH_MAX, VHCI_STATE_PATH"/port%d", rhport);
fd = open(path, O_WRONLY|O_CREAT|O_TRUNC, S_IRWXU);
if (fd < 0)
return -1;
snprintf(buff, MAX_BUFF, "%s %s %s\n",
host, port, busid);
ret = write(fd, buff, strlen(buff));
if (ret != (ssize_t) strlen(buff)) {
close(fd);
return -1;
}
close(fd);
return 0;
}
static int read_record(int rhport, char *host, char *port, char *busid)
{
FILE *file;
char path[PATH_MAX+1];
snprintf(path, PATH_MAX, VHCI_STATE_PATH"/port%d", rhport);
file = fopen(path, "r");
if (!file) {
err("fopen");
return -1;
}
if (fscanf(file, "%s %s %s\n", host, port, busid) != 3) {
err("fscanf");
fclose(file);
return -1;
}
fclose(file);
return 0;
}
int usbip_vhci_imported_device_dump(struct usbip_imported_device *idev)
{
char product_name[100];
char host[NI_MAXHOST] = "unknown host";
char serv[NI_MAXSERV] = "unknown port";
char remote_busid[SYSFS_BUS_ID_SIZE];
int ret;
if (idev->status == VDEV_ST_NULL || idev->status == VDEV_ST_NOTASSIGNED) {
info("Port %02d: <%s>", idev->port, usbip_status_string(idev->status));
return 0;
}
ret = read_record(idev->port, host, serv, remote_busid);
if (ret) {
err("read_record");
return -1;
}
info("Port %02d: <%s> at %s", idev->port,
usbip_status_string(idev->status), usbip_speed_string(idev->udev.speed));
usbip_names_get_product(product_name, sizeof(product_name),
idev->udev.idVendor, idev->udev.idProduct);
info(" %s", product_name);
info("%10s -> usbip://%s:%s/%s (remote devid %08x (bus/dev %03d/%03d))",
idev->udev.busid, host, serv, remote_busid,
idev->devid,
idev->busnum, idev->devnum);
for (int i=0; i < idev->udev.bNumInterfaces; i++) {
/* show interface information */
struct sysfs_device *suinf;
suinf = open_usb_interface(&idev->udev, i);
if (!suinf)
continue;
info(" %6s used by %-17s", suinf->bus_id, suinf->driver_name);
sysfs_close_device(suinf);
/* show class device information */
struct class_device *cdev;
dlist_for_each_data(idev->cdev_list, cdev, struct class_device) {
int ifnum = get_interface_number(cdev->devpath);
if (ifnum == i) {
info(" %s", cdev->clspath);
}
}
}
return 0;
}
static int query_exported_devices(int sockfd)
{
int ret;
struct op_devlist_reply rep;
uint16_t code = OP_REP_DEVLIST;
bzero(&rep, sizeof(rep));
ret = usbip_send_op_common(sockfd, OP_REQ_DEVLIST, 0);
if (ret < 0) {
err("send op_common");
return -1;
}
ret = usbip_recv_op_common(sockfd, &code);
if (ret < 0) {
err("recv op_common");
return -1;
}
ret = usbip_recv(sockfd, (void *) &rep, sizeof(rep));
if (ret < 0) {
err("recv op_devlist");
return -1;
}
PACK_OP_DEVLIST_REPLY(0, &rep);
dbg("exportable %d devices", rep.ndev);
for (unsigned int i=0; i < rep.ndev; i++) {
char product_name[100];
char class_name[100];
struct usb_device udev;
bzero(&udev, sizeof(udev));
ret = usbip_recv(sockfd, (void *) &udev, sizeof(udev));
if (ret < 0) {
err("recv usb_device[%d]", i);
return -1;
}
pack_usb_device(0, &udev);
usbip_names_get_product(product_name, sizeof(product_name),
udev.idVendor, udev.idProduct);
usbip_names_get_class(class_name, sizeof(class_name), udev.bDeviceClass,
udev.bDeviceSubClass, udev.bDeviceProtocol);
info("%8s: %s", udev.busid, product_name);
info("%8s: %s", " ", udev.path);
info("%8s: %s", " ", class_name);
for (int j=0; j < udev.bNumInterfaces; j++) {
struct usb_interface uinf;
ret = usbip_recv(sockfd, (void *) &uinf, sizeof(uinf));
if (ret < 0) {
err("recv usb_interface[%d]", j);
return -1;
}
pack_usb_interface(0, &uinf);
usbip_names_get_class(class_name, sizeof(class_name), uinf.bInterfaceClass,
uinf.bInterfaceSubClass, uinf.bInterfaceProtocol);
info("%8s: %2d - %s", " ", j, class_name);
}
info(" ");
}
return rep.ndev;
}
static int import_device(int sockfd, struct usb_device *udev)
{
int ret;
int port;
ret = usbip_vhci_driver_open();
if (ret < 0) {
err("open vhci_driver");
return -1;
}
port = usbip_vhci_get_free_port();
if (port < 0) {
err("no free port");
usbip_vhci_driver_close();
return -1;
}
ret = usbip_vhci_attach_device(port, sockfd, udev->busnum,
udev->devnum, udev->speed);
if (ret < 0) {
err("import device");
usbip_vhci_driver_close();
return -1;
}
usbip_vhci_driver_close();
return port;
}
static int query_import_device(int sockfd, char *busid)
{
int ret;
struct op_import_request request;
struct op_import_reply reply;
uint16_t code = OP_REP_IMPORT;
bzero(&request, sizeof(request));
bzero(&reply, sizeof(reply));
/* send a request */
ret = usbip_send_op_common(sockfd, OP_REQ_IMPORT, 0);
if (ret < 0) {
err("send op_common");
return -1;
}
strncpy(request.busid, busid, SYSFS_BUS_ID_SIZE-1);
PACK_OP_IMPORT_REQUEST(0, &request);
ret = usbip_send(sockfd, (void *) &request, sizeof(request));
if (ret < 0) {
err("send op_import_request");
return -1;
}
/* recieve a reply */
ret = usbip_recv_op_common(sockfd, &code);
if (ret < 0) {
err("recv op_common");
return -1;
}
ret = usbip_recv(sockfd, (void *) &reply, sizeof(reply));
if (ret < 0) {
err("recv op_import_reply");
return -1;
}
PACK_OP_IMPORT_REPLY(0, &reply);
/* check the reply */
if (strncmp(reply.udev.busid, busid, SYSFS_BUS_ID_SIZE)) {
err("recv different busid %s", reply.udev.busid);
return -1;
}
/* import a device */
return import_device(sockfd, &reply.udev);
}
static int attach_device(char *host, char *busid)
{
int sockfd;
int ret;
int rhport;
sockfd = tcp_connect(host, USBIP_PORT_STRING);
if (sockfd < 0) {
err("tcp connect");
return -1;
}
rhport = query_import_device(sockfd, busid);
if (rhport < 0) {
err("query");
return -1;
}
close(sockfd);
ret = record_connection(host, USBIP_PORT_STRING,
busid, rhport);
if (ret < 0) {
err("record connection");
return -1;
}
return 0;
}
static int detach_port(char *port)
{
int ret;
uint8_t portnum;
for (unsigned int i=0; i < strlen(port); i++)
if (!isdigit(port[i])) {
err("invalid port %s", port);
return -1;
}
/* check max port */
portnum = atoi(port);
ret = usbip_vhci_driver_open();
if (ret < 0) {
err("open vhci_driver");
return -1;
}
ret = usbip_vhci_detach_device(portnum);
if (ret < 0)
return -1;
usbip_vhci_driver_close();
return ret;
}
static int show_exported_devices(char *host)
{
int ret;
int sockfd;
sockfd = tcp_connect(host, USBIP_PORT_STRING);
if (sockfd < 0) {
err("- %s failed", host);
return -1;
}
info("- %s", host);
ret = query_exported_devices(sockfd);
if (ret < 0) {
err("query");
return -1;
}
close(sockfd);
return 0;
}
static int attach_exported_devices(char *host, int sockfd)
{
int ret;
struct op_devlist_reply rep;
uint16_t code = OP_REP_DEVLIST;
bzero(&rep, sizeof(rep));
ret = usbip_send_op_common(sockfd, OP_REQ_DEVLIST, 0);
if(ret < 0) {
err("send op_common");
return -1;
}
ret = usbip_recv_op_common(sockfd, &code);
if(ret < 0) {
err("recv op_common");
return -1;
}
ret = usbip_recv(sockfd, (void *) &rep, sizeof(rep));
if(ret < 0) {
err("recv op_devlist");
return -1;
}
PACK_OP_DEVLIST_REPLY(0, &rep);
dbg("exportable %d devices", rep.ndev);
for(unsigned int i=0; i < rep.ndev; i++) {
char product_name[100];
char class_name[100];
struct usb_device udev;
bzero(&udev, sizeof(udev));
ret = usbip_recv(sockfd, (void *) &udev, sizeof(udev));
if(ret < 0) {
err("recv usb_device[%d]", i);
return -1;
}
pack_usb_device(0, &udev);
usbip_names_get_product(product_name, sizeof(product_name),
udev.idVendor, udev.idProduct);
usbip_names_get_class(class_name, sizeof(class_name), udev.bDeviceClass,
udev.bDeviceSubClass, udev.bDeviceProtocol);
dbg("Attaching usb port %s from host %s on usbip, with deviceid: %s", udev.busid, host, product_name);
for (int j=0; j < udev.bNumInterfaces; j++) {
struct usb_interface uinf;
ret = usbip_recv(sockfd, (void *) &uinf, sizeof(uinf));
if (ret < 0) {
err("recv usb_interface[%d]", j);
return -1;
}
pack_usb_interface(0, &uinf);
usbip_names_get_class(class_name, sizeof(class_name), uinf.bInterfaceClass,
uinf.bInterfaceSubClass, uinf.bInterfaceProtocol);
dbg("interface %2d - %s", j, class_name);
}
attach_device(host, udev.busid);
}
return rep.ndev;
}
static int attach_devices_all(char *host)
{
int ret;
int sockfd;
sockfd = tcp_connect(host, USBIP_PORT_STRING);
if(sockfd < 0) {
err("- %s failed", host);
return -1;
}
info("- %s", host);
ret = attach_exported_devices(host, sockfd);
if(ret < 0) {
err("query");
return -1;
}
close(sockfd);
return 0;
}
const char help_message[] = "\
Usage: usbip [options] \n\
-a, --attach [host] [bus_id] \n\
Attach a remote USB device. \n\
\n\
-x, --attachall [host] \n\
Attach all remote USB devices on the specific host. \n\
\n\
-d, --detach [ports] \n\
Detach an imported USB device. \n\
\n\
-l, --list [hosts] \n\
List exported USB devices. \n\
\n\
-p, --port \n\
List virtual USB port status. \n\
\n\
-D, --debug \n\
Print debugging information. \n\
\n\
-v, --version \n\
Show version. \n\
\n\
-h, --help \n\
Print this help. \n";
static void show_help(void)
{
printf("%s", help_message);
}
static int show_port_status(void)
{
int ret;
struct usbip_imported_device *idev;
ret = usbip_vhci_driver_open();
if (ret < 0)
return ret;
for (int i = 0; i < vhci_driver->nports; i++) {
idev = &vhci_driver->idev[i];
if (usbip_vhci_imported_device_dump(idev) < 0)
ret = -1;
}
usbip_vhci_driver_close();
return ret;
}
#define _GNU_SOURCE
#include <getopt.h>
static const struct option longopts[] = {
{"attach", no_argument, NULL, 'a'},
{"attachall", no_argument, NULL, 'x'},
{"detach", no_argument, NULL, 'd'},
{"port", no_argument, NULL, 'p'},
{"list", no_argument, NULL, 'l'},
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{"debug", no_argument, NULL, 'D'},
{"syslog", no_argument, NULL, 'S'},
{NULL, 0, NULL, 0}
};
int main(int argc, char *argv[])
{
int ret;
enum {
cmd_attach = 1,
cmd_attachall,
cmd_detach,
cmd_port,
cmd_list,
cmd_help,
cmd_version
} cmd = 0;
usbip_use_stderr = 1;
if (geteuid() != 0)
g_warning("running non-root?");
ret = usbip_names_init(USBIDS_FILE);
if (ret)
notice("failed to open %s", USBIDS_FILE);
for (;;) {
int c;
int index = 0;
c = getopt_long(argc, argv, "adplvhDSx", longopts, &index);
if (c == -1)
break;
switch(c) {
case 'a':
if (!cmd)
cmd = cmd_attach;
else
cmd = cmd_help;
break;
case 'd':
if (!cmd)
cmd = cmd_detach;
else
cmd = cmd_help;
break;
case 'p':
if (!cmd)
cmd = cmd_port;
else cmd = cmd_help;
break;
case 'l':
if (!cmd)
cmd = cmd_list;
else
cmd = cmd_help;
break;
case 'v':
if (!cmd)
cmd = cmd_version;
else
cmd = cmd_help;
break;
case 'x':
if(!cmd)
cmd = cmd_attachall;
else
cmd = cmd_help;
break;
case 'h':
cmd = cmd_help;
break;
case 'D':
usbip_use_debug = 1;
break;
case 'S':
usbip_use_syslog = 1;
break;
case '?':
break;
default:
err("getopt");
}
}
ret = 0;
switch(cmd) {
case cmd_attach:
if (optind == argc - 2)
ret = attach_device(argv[optind], argv[optind+1]);
else
show_help();
break;
case cmd_detach:
while (optind < argc)
ret = detach_port(argv[optind++]);
break;
case cmd_port:
ret = show_port_status();
break;
case cmd_list:
while (optind < argc)
ret = show_exported_devices(argv[optind++]);
break;
case cmd_attachall:
while(optind < argc)
ret = attach_devices_all(argv[optind++]);
break;
case cmd_version:
printf("%s\n", version);
break;
case cmd_help:
show_help();
break;
default:
show_help();
}
usbip_names_free();
exit((ret == 0) ? EXIT_SUCCESS : EXIT_FAILURE);
}
| gpl-2.0 |
youfoh/TizenProject | arch/arm/mach-at91/board-kafa.c | 2636 | 2844 | /*
* linux/arch/arm/mach-at91/board-kafa.c
*
* Copyright (C) 2006 Sperry-Sun
*
* 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/types.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <mach/hardware.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/cpu.h>
#include "at91_aic.h"
#include "board.h"
#include "generic.h"
static void __init kafa_init_early(void)
{
/* Set cpu type: PQFP */
at91rm9200_set_type(ARCH_REVISON_9200_PQFP);
/* Initialize processor: 18.432 MHz crystal */
at91_initialize(18432000);
}
static struct macb_platform_data __initdata kafa_eth_data = {
.phy_irq_pin = AT91_PIN_PC4,
.is_rmii = 0,
};
static struct at91_usbh_data __initdata kafa_usbh_data = {
.ports = 1,
.vbus_pin = {-EINVAL, -EINVAL},
.overcurrent_pin= {-EINVAL, -EINVAL},
};
static struct at91_udc_data __initdata kafa_udc_data = {
.vbus_pin = AT91_PIN_PB6,
.pullup_pin = AT91_PIN_PB7,
};
/*
* LEDs
*/
static struct gpio_led kafa_leds[] = {
{ /* D1 */
.name = "led1",
.gpio = AT91_PIN_PB4,
.active_low = 1,
.default_trigger = "heartbeat",
},
};
static void __init kafa_board_init(void)
{
/* Serial */
/* DBGU on ttyS0. (Rx & Tx only) */
at91_register_uart(0, 0, 0);
/* USART0 on ttyS1 (Rx, Tx, CTS, RTS) */
at91_register_uart(AT91RM9200_ID_US0, 1, ATMEL_UART_CTS | ATMEL_UART_RTS);
at91_add_device_serial();
/* Ethernet */
at91_add_device_eth(&kafa_eth_data);
/* USB Host */
at91_add_device_usbh(&kafa_usbh_data);
/* USB Device */
at91_add_device_udc(&kafa_udc_data);
/* I2C */
at91_add_device_i2c(NULL, 0);
/* SPI */
at91_add_device_spi(NULL, 0);
/* LEDs */
at91_gpio_leds(kafa_leds, ARRAY_SIZE(kafa_leds));
}
MACHINE_START(KAFA, "Sperry-Sun KAFA")
/* Maintainer: Sergei Sharonov */
.init_time = at91rm9200_timer_init,
.map_io = at91_map_io,
.handle_irq = at91_aic_handle_irq,
.init_early = kafa_init_early,
.init_irq = at91_init_irq_default,
.init_machine = kafa_board_init,
MACHINE_END
| gpl-2.0 |
JTdevAndroid/XKernel | drivers/hid/hid-monterey.c | 3148 | 1936 | /*
* HID driver for some monterey "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
*/
/*
* 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/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
static __u8 *mr_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 31 && rdesc[29] == 0x05 && rdesc[30] == 0x09) {
hid_info(hdev, "fixing up button/consumer in HID report descriptor\n");
rdesc[30] = 0x0c;
}
return rdesc;
}
#define mr_map_key_clear(c) hid_map_usage_clear(hi, usage, bit, max, \
EV_KEY, (c))
static int mr_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_CONSUMER)
return 0;
switch (usage->hid & HID_USAGE) {
case 0x156: mr_map_key_clear(KEY_WORDPROCESSOR); break;
case 0x157: mr_map_key_clear(KEY_SPREADSHEET); break;
case 0x158: mr_map_key_clear(KEY_PRESENTATION); break;
case 0x15c: mr_map_key_clear(KEY_STOP); break;
default:
return 0;
}
return 1;
}
static const struct hid_device_id mr_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_MONTEREY, USB_DEVICE_ID_GENIUS_KB29E) },
{ }
};
MODULE_DEVICE_TABLE(hid, mr_devices);
static struct hid_driver mr_driver = {
.name = "monterey",
.id_table = mr_devices,
.report_fixup = mr_report_fixup,
.input_mapping = mr_input_mapping,
};
module_hid_driver(mr_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
AuxXxi/caf_kernel | drivers/mfd/timpani-codec.c | 3404 | 98294 | /* Copyright (c) 2010-2012, 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/module.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/platform_device.h>
#include <linux/mfd/msm-adie-codec.h>
#include <linux/mfd/marimba.h>
#include <linux/mfd/timpani-audio.h>
#include <linux/debugfs.h>
#include <linux/uaccess.h>
#include <linux/string.h>
/* Timpani codec driver is activated through Marimba core driver */
#define MAX_MDELAY_US 20000
#define TIMPANI_PATH_MASK(x) (1 << (x))
#define TIMPANI_CODEC_AUXPGA_GAIN_RANGE (0x0F)
#define TIMPANI_RX1_ST_MASK (TIMPANI_CDC_RX1_CTL_SIDETONE_EN1_L_M |\
TIMPANI_CDC_RX1_CTL_SIDETONE_EN1_R_M)
#define TIMPANI_RX1_ST_ENABLE ((1 << TIMPANI_CDC_RX1_CTL_SIDETONE_EN1_L_S) |\
(1 << TIMPANI_CDC_RX1_CTL_SIDETONE_EN1_R_S))
#define TIMPANI_CDC_ST_MIXING_TX1_MASK (TIMPANI_CDC_ST_MIXING_TX1_L_M |\
TIMPANI_CDC_ST_MIXING_TX1_R_M)
#define TIMPANI_CDC_ST_MIXING_TX1_ENABLE ((1 << TIMPANI_CDC_ST_MIXING_TX1_L_S)\
| (1 << TIMPANI_CDC_ST_MIXING_TX1_R_S))
#define TIMPANI_CDC_ST_MIXING_TX2_MASK (TIMPANI_CDC_ST_MIXING_TX2_L_M |\
TIMPANI_CDC_ST_MIXING_TX2_R_M)
#define TIMPANI_CDC_ST_MIXING_TX2_ENABLE ((1 << TIMPANI_CDC_ST_MIXING_TX2_L_S)\
| (1 << TIMPANI_CDC_ST_MIXING_TX2_R_S))
enum refcnt {
DEC = 0,
INC = 1,
IGNORE = 2,
};
#define TIMPANI_ARRAY_SIZE (TIMPANI_A_CDC_COMP_HALT + 1)
#define MAX_SHADOW_RIGISTERS TIMPANI_A_CDC_COMP_HALT
static u8 timpani_shadow[TIMPANI_ARRAY_SIZE];
struct adie_codec_path {
struct adie_codec_dev_profile *profile;
struct adie_codec_register_image img;
u32 hwsetting_idx;
u32 stage_idx;
u32 curr_stage;
u32 reg_owner;
};
enum /* regaccess blk id */
{
RA_BLOCK_RX1 = 0,
RA_BLOCK_RX2,
RA_BLOCK_TX1,
RA_BLOCK_TX2,
RA_BLOCK_LB,
RA_BLOCK_SHARED_RX_LB,
RA_BLOCK_SHARED_TX,
RA_BLOCK_TXFE1,
RA_BLOCK_TXFE2,
RA_BLOCK_PA_COMMON,
RA_BLOCK_PA_EAR,
RA_BLOCK_PA_HPH,
RA_BLOCK_PA_LINE,
RA_BLOCK_PA_AUX,
RA_BLOCK_ADC,
RA_BLOCK_DMIC,
RA_BLOCK_TX_I2S,
RA_BLOCK_DRV,
RA_BLOCK_TEST,
RA_BLOCK_RESERVED,
RA_BLOCK_NUM,
};
enum /* regaccess onwer ID */
{
RA_OWNER_NONE = 0,
RA_OWNER_PATH_RX1,
RA_OWNER_PATH_RX2,
RA_OWNER_PATH_TX1,
RA_OWNER_PATH_TX2,
RA_OWNER_PATH_LB,
RA_OWNER_DRV,
RA_OWNER_NUM,
};
struct reg_acc_blk_cfg {
u8 valid_owners[RA_OWNER_NUM];
};
struct reg_ref_cnt {
u8 mask;
u8 path_mask;
};
#define TIMPANI_MAX_FIELDS 5
struct timpani_regaccess {
u8 reg_addr;
u8 blk_mask[RA_BLOCK_NUM];
u8 reg_mask;
u8 reg_default;
struct reg_ref_cnt fld_ref_cnt[TIMPANI_MAX_FIELDS];
};
struct timpani_regaccess timpani_regset[] = {
{
TIMPANI_A_MREF,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFC, 0x0, 0x3},
TIMPANI_MREF_M,
TIMPANI_MREF_POR,
{
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDAC_IDAC_REF_CUR,
{0xFC, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDAC_IDAC_REF_CUR_M,
TIMPANI_CDAC_IDAC_REF_CUR_POR,
{
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXADC12_REF_CURR,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF},
TIMPANI_TXADC12_REF_CURR_M,
TIMPANI_TXADC12_REF_CURR_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXADC3_EN,
{ 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFE, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1},
TIMPANI_TXADC3_EN_M,
TIMPANI_TXADC3_EN_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXADC4_EN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFE, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1},
TIMPANI_TXADC4_EN_M,
TIMPANI_TXADC4_EN_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CODEC_TXADC_STATUS_REGISTER_1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x30, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF},
TIMPANI_CODEC_TXADC_STATUS_REGISTER_1_M,
TIMPANI_CODEC_TXADC_STATUS_REGISTER_1_POR,
{
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x30, .path_mask = 0},
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXFE1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_TXFE1_M,
TIMPANI_TXFE1_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXFE2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_TXFE2_M,
TIMPANI_TXFE2_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXFE12_ATEST,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_TXFE12_ATEST_M,
TIMPANI_TXFE12_ATEST_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXFE_CLT,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF8, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7},
TIMPANI_TXFE_CLT_M,
TIMPANI_TXFE_CLT_POR,
{
{ .mask = 0xF8, .path_mask = 0},
{ .mask = 0x07, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXADC1_EN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFE, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1},
TIMPANI_TXADC1_EN_M,
TIMPANI_TXADC1_EN_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXADC2_EN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFE, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1},
TIMPANI_TXADC2_EN_M,
TIMPANI_TXADC2_EN_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXADC_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_TXADC_CTL_M,
TIMPANI_TXADC_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXADC_CTL2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_TXADC_CTL2_M,
TIMPANI_TXADC_CTL2_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXADC_CTL3,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xFE, 0x0, 0x0, 0x0, 0x0, 0x1},
TIMPANI_TXADC_CTL3_M,
TIMPANI_TXADC_CTL3_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXADC_CHOP_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0xFC, 0x0, 0x0, 0x0, 0x0, 0x3},
TIMPANI_TXADC_CHOP_CTL_M,
TIMPANI_TXADC_CHOP_CTL_POR,
{
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXFE3,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE2, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1D},
TIMPANI_TXFE3_M,
TIMPANI_TXFE3_POR,
{
{ .mask = 0xE2, .path_mask = 0},
{ .mask = 0x1D, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXFE4,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE2, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1D},
TIMPANI_TXFE4_M,
TIMPANI_TXFE4_POR,
{
{ .mask = 0xE2, .path_mask = 0},
{ .mask = 0x1D, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXFE3_ATEST,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_TXFE3_ATEST_M,
TIMPANI_TXFE3_ATEST_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_TXFE_DIFF_SE,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0xC, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF0},
TIMPANI_TXFE_DIFF_SE_M,
TIMPANI_TXFE_DIFF_SE_POR,
{
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x0C, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDAC_RX_CLK_CTL,
{0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDAC_RX_CLK_CTL_M,
TIMPANI_CDAC_RX_CLK_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDAC_BUFF_CTL,
{0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDAC_BUFF_CTL_M,
TIMPANI_CDAC_BUFF_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDAC_REF_CTL1,
{0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDAC_REF_CTL1_M,
TIMPANI_CDAC_REF_CTL1_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_IDAC_DWA_FIR_CTL,
{0xF8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7},
TIMPANI_IDAC_DWA_FIR_CTL_M,
TIMPANI_IDAC_DWA_FIR_CTL_POR,
{
{ .mask = 0xF8, .path_mask = 0},
{ .mask = 0x07, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDAC_REF_CTL2,
{0x6F, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x90},
TIMPANI_CDAC_REF_CTL2_M,
TIMPANI_CDAC_REF_CTL2_POR,
{
{ .mask = 0x6F, .path_mask = 0},
{ .mask = 0x90, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDAC_CTL1,
{0x7F, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80},
TIMPANI_CDAC_CTL1_M,
TIMPANI_CDAC_CTL1_POR,
{
{ .mask = 0x7F, .path_mask = 0},
{ .mask = 0x80, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDAC_CTL2,
{0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDAC_CTL2_M,
TIMPANI_CDAC_CTL2_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_IDAC_L_CTL,
{0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_IDAC_L_CTL_M,
TIMPANI_IDAC_L_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_IDAC_R_CTL,
{0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_IDAC_R_CTL_M,
TIMPANI_IDAC_R_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_MASTER_BIAS,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1F,
0xE0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_MASTER_BIAS_M,
TIMPANI_PA_MASTER_BIAS_POR,
{
{ .mask = 0x1F, .path_mask = 0},
{ .mask = 0xE0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_BIAS,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_CLASSD_BIAS_M,
TIMPANI_PA_CLASSD_BIAS_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_AUXPGA_CUR,
{0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_AUXPGA_CUR_M,
TIMPANI_AUXPGA_CUR_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_AUXPGA_CM,
{0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_AUXPGA_CM_M,
TIMPANI_AUXPGA_CM_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_EARPA_MSTB_EN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x2, 0xFC,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_HPH_EARPA_MSTB_EN_M,
TIMPANI_PA_HPH_EARPA_MSTB_EN_POR,
{
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x02, .path_mask = 0},
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_LINE_AUXO_EN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xF8, 0x7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_LINE_AUXO_EN_M,
TIMPANI_PA_LINE_AUXO_EN_POR,
{
{ .mask = 0xF8, .path_mask = 0},
{ .mask = 0x07, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_AUXPGA_EN,
{0x0, 0x0, 0x0, 0x0, 0x30, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_PA_CLASSD_AUXPGA_EN_M,
TIMPANI_PA_CLASSD_AUXPGA_EN_POR,
{
{ .mask = 0x30, .path_mask = 0},
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_LINE_L_GAIN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFC, 0x0, 0x3},
TIMPANI_PA_LINE_L_GAIN_M,
TIMPANI_PA_LINE_L_GAIN_POR,
{
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_LINE_R_GAIN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFC, 0x0, 0x3},
TIMPANI_PA_LINE_R_GAIN_M,
TIMPANI_PA_LINE_R_GAIN_POR,
{
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_L_GAIN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFE, 0x0, 0x1},
TIMPANI_PA_HPH_L_GAIN_M,
TIMPANI_PA_HPH_L_GAIN_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_R_GAIN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFE, 0x0, 0x1},
TIMPANI_PA_HPH_R_GAIN_M,
TIMPANI_PA_HPH_R_GAIN_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_AUXPGA_LR_GAIN,
{0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_AUXPGA_LR_GAIN_M,
TIMPANI_AUXPGA_LR_GAIN_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_AUXO_EARPA_CONN,
{0x21, 0x42, 0x0, 0x0, 0x84, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x18},
TIMPANI_PA_AUXO_EARPA_CONN_M,
TIMPANI_PA_AUXO_EARPA_CONN_POR,
{
{ .mask = 0x21, .path_mask = 0},
{ .mask = 0x42, .path_mask = 0},
{ .mask = 0x84, .path_mask = 0},
{ .mask = 0x18, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_LINE_ST_CONN,
{0x24, 0x48, 0x0, 0x0, 0x93, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_LINE_ST_CONN_M,
TIMPANI_PA_LINE_ST_CONN_POR,
{
{ .mask = 0x24, .path_mask = 0},
{ .mask = 0x48, .path_mask = 0},
{ .mask = 0x93, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_LINE_MONO_CONN,
{0x24, 0x48, 0x0, 0x0, 0x93, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_LINE_MONO_CONN_M,
TIMPANI_PA_LINE_MONO_CONN_POR,
{
{ .mask = 0x24, .path_mask = 0},
{ .mask = 0x48, .path_mask = 0},
{ .mask = 0x93, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_ST_CONN,
{0x24, 0x48, 0x0, 0x0, 0x90, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_HPH_ST_CONN_M,
TIMPANI_PA_HPH_ST_CONN_POR,
{
{ .mask = 0x24, .path_mask = 0},
{ .mask = 0x48, .path_mask = 0},
{ .mask = 0x90, .path_mask = 0},
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_MONO_CONN,
{0x24, 0x48, 0x0, 0x0, 0x90, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3},
TIMPANI_PA_HPH_MONO_CONN_M,
TIMPANI_PA_HPH_MONO_CONN_POR,
{
{ .mask = 0x24, .path_mask = 0},
{ .mask = 0x48, .path_mask = 0},
{ .mask = 0x90, .path_mask = 0},
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_CONN,
{0x80, 0x40, 0x0, 0x0, 0x20, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF},
TIMPANI_PA_CLASSD_CONN_M,
TIMPANI_PA_CLASSD_CONN_POR,
{
{ .mask = 0x80, .path_mask = 0},
{ .mask = 0x40, .path_mask = 0},
{ .mask = 0x20, .path_mask = 0},
{ .mask = 0x10, .path_mask = 0},
{ .mask = 0x0F, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CNP_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xCF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x30},
TIMPANI_PA_CNP_CTL_M,
TIMPANI_PA_CNP_CTL_POR,
{
{ .mask = 0xCF, .path_mask = 0},
{ .mask = 0x30, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_L_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3F,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_PA_CLASSD_L_CTL_M,
TIMPANI_PA_CLASSD_L_CTL_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_R_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3F,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_PA_CLASSD_R_CTL_M,
TIMPANI_PA_CLASSD_R_CTL_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_INT2_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_CLASSD_INT2_CTL_M,
TIMPANI_PA_CLASSD_INT2_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_L_OCP_CLK_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_HPH_L_OCP_CLK_CTL_M,
TIMPANI_PA_HPH_L_OCP_CLK_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_L_SW_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF7,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8},
TIMPANI_PA_CLASSD_L_SW_CTL_M,
TIMPANI_PA_CLASSD_L_SW_CTL_POR,
{
{ .mask = 0xF7, .path_mask = 0},
{ .mask = 0x08, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_L_OCP1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_CLASSD_L_OCP1_M,
TIMPANI_PA_CLASSD_L_OCP1_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_L_OCP2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_CLASSD_L_OCP2_M,
TIMPANI_PA_CLASSD_L_OCP2_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_R_OCP_CLK_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_HPH_R_OCP_CLK_CTL_M,
TIMPANI_PA_HPH_R_OCP_CLK_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_R_SW_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF7,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8},
TIMPANI_PA_CLASSD_R_SW_CTL_M,
TIMPANI_PA_CLASSD_R_SW_CTL_POR,
{
{ .mask = 0xF7, .path_mask = 0},
{ .mask = 0x08, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_R_OCP1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_CLASSD_R_OCP1_M,
TIMPANI_PA_CLASSD_R_OCP1_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_R_OCP2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_CLASSD_R_OCP2_M,
TIMPANI_PA_CLASSD_R_OCP2_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_CTL1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF},
TIMPANI_PA_HPH_CTL1_M,
TIMPANI_PA_HPH_CTL1_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_CTL2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFE,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1},
TIMPANI_PA_HPH_CTL2_M,
TIMPANI_PA_HPH_CTL2_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_LINE_AUXO_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0xC3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x3C, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_LINE_AUXO_CTL_M,
TIMPANI_PA_LINE_AUXO_CTL_POR,
{
{ .mask = 0xC3, .path_mask = 0},
{ .mask = 0x3C, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_AUXO_EARPA_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0x0,
0x0, 0x38, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_PA_AUXO_EARPA_CTL_M,
TIMPANI_PA_AUXO_EARPA_CTL_POR,
{
{ .mask = 0x07, .path_mask = 0},
{ .mask = 0x38, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_EARO_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_PA_EARO_CTL_M,
TIMPANI_PA_EARO_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_MASTER_BIAS_CUR,
{0x0, 0x0, 0x0, 0x0, 0x60, 0x0, 0x0, 0x0, 0x0, 0x80, 0x0, 0x18,
0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1},
TIMPANI_PA_MASTER_BIAS_CUR_M,
TIMPANI_PA_MASTER_BIAS_CUR_POR,
{
{ .mask = 0x60, .path_mask = 0},
{ .mask = 0x80, .path_mask = 0},
{ .mask = 0x18, .path_mask = 0},
{ .mask = 0x06, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
}
},
{
TIMPANI_A_PA_CLASSD_SC_STATUS,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xCC,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x33},
TIMPANI_PA_CLASSD_SC_STATUS_M,
TIMPANI_PA_CLASSD_SC_STATUS_POR,
{
{ .mask = 0xCC, .path_mask = 0},
{ .mask = 0x33, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_PA_HPH_SC_STATUS,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x88,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x77},
TIMPANI_PA_HPH_SC_STATUS_M,
TIMPANI_PA_HPH_SC_STATUS_POR,
{
{ .mask = 0x88, .path_mask = 0},
{ .mask = 0x77, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_EN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80, 0x7F},
TIMPANI_ATEST_EN_M,
TIMPANI_ATEST_EN_POR,
{
{ .mask = 0x80, .path_mask = 0},
{ .mask = 0x7F, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_TSHKADC,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0xF0},
TIMPANI_ATEST_TSHKADC_M,
TIMPANI_ATEST_TSHKADC_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_TXADC13,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7F, 0x80},
TIMPANI_ATEST_TXADC13_M,
TIMPANI_ATEST_TXADC13_POR,
{
{ .mask = 0x7F, .path_mask = 0},
{ .mask = 0x80, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_TXADC24,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7F, 0x80},
TIMPANI_ATEST_TXADC24_M,
TIMPANI_ATEST_TXADC24_POR,
{
{ .mask = 0x7F, .path_mask = 0},
{ .mask = 0x80, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_AUXPGA,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF8, 0x7},
TIMPANI_ATEST_AUXPGA_M,
TIMPANI_ATEST_AUXPGA_POR,
{
{ .mask = 0xF8, .path_mask = 0},
{ .mask = 0x07, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_CDAC,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0},
TIMPANI_ATEST_CDAC_M,
TIMPANI_ATEST_CDAC_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_IDAC,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0},
TIMPANI_ATEST_IDAC_M,
TIMPANI_ATEST_IDAC_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_PA1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0},
TIMPANI_ATEST_PA1_M,
TIMPANI_ATEST_PA1_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_CLASSD,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0},
TIMPANI_ATEST_CLASSD_M,
TIMPANI_ATEST_CLASSD_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_ATEST_LINEO_AUXO,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0},
TIMPANI_ATEST_LINEO_AUXO_M,
TIMPANI_ATEST_LINEO_AUXO_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RESET_CTL,
{0x2, 0x8, 0x5, 0x30, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_CDC_RESET_CTL_M,
TIMPANI_CDC_RESET_CTL_POR,
{
{ .mask = 0x02, .path_mask = 0},
{ .mask = 0x08, .path_mask = 0},
{ .mask = 0x05, .path_mask = 0},
{ .mask = 0x30, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX1_CTL,
{0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX1_CTL_M,
TIMPANI_CDC_RX1_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX_I2S_CTL,
{0x0, 0x0, 0x10, 0x20, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0x0, 0xC0},
TIMPANI_CDC_TX_I2S_CTL_M,
TIMPANI_CDC_TX_I2S_CTL_POR,
{
{ .mask = 0x10, .path_mask = 0},
{ .mask = 0x20, .path_mask = 0},
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_CH_CTL,
{0x3, 0x30, 0xC, 0xC0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_CH_CTL_M,
TIMPANI_CDC_CH_CTL_POR,
{
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x30, .path_mask = 0},
{ .mask = 0x0C, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX1LG,
{0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX1LG_M,
TIMPANI_CDC_RX1LG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX1RG,
{0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX1RG_M,
TIMPANI_CDC_RX1RG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX1LG,
{0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_TX1LG_M,
TIMPANI_CDC_TX1LG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX1RG,
{0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_TX1RG_M,
TIMPANI_CDC_TX1RG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX_PGA_TIMER,
{0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX_PGA_TIMER_M,
TIMPANI_CDC_RX_PGA_TIMER_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX_PGA_TIMER,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_TX_PGA_TIMER_M,
TIMPANI_CDC_TX_PGA_TIMER_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_GCTL1,
{0xF, 0x0, 0xF0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_GCTL1_M,
TIMPANI_CDC_GCTL1_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX1L_STG,
{0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_TX1L_STG_M,
TIMPANI_CDC_TX1L_STG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ST_CTL,
{0x0, 0xF, 0x0, 0xF0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_ST_CTL_M,
TIMPANI_CDC_ST_CTL_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX1L_DCOFFSET,
{0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX1L_DCOFFSET_M,
TIMPANI_CDC_RX1L_DCOFFSET_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX1R_DCOFFSET,
{0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX1R_DCOFFSET_M,
TIMPANI_CDC_RX1R_DCOFFSET_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_BYPASS_CTL1,
{0xF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF0},
TIMPANI_CDC_BYPASS_CTL1_M,
TIMPANI_CDC_BYPASS_CTL1_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_PDM_CONFIG,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0xF0},
TIMPANI_CDC_PDM_CONFIG_M,
TIMPANI_CDC_PDM_CONFIG_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TESTMODE1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3F, 0xC0},
TIMPANI_CDC_TESTMODE1_M,
TIMPANI_CDC_TESTMODE1_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_DMIC_CLK_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x3F, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_CDC_DMIC_CLK_CTL_M,
TIMPANI_CDC_DMIC_CLK_CTL_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ADC12_CLK_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_ADC12_CLK_CTL_M,
TIMPANI_CDC_ADC12_CLK_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX1_CTL,
{0x0, 0x0, 0x3F, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_CDC_TX1_CTL_M,
TIMPANI_CDC_TX1_CTL_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ADC34_CLK_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_ADC34_CLK_CTL_M,
TIMPANI_CDC_ADC34_CLK_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX2_CTL,
{0x0, 0x0, 0x0, 0x3F, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_CDC_TX2_CTL_M,
TIMPANI_CDC_TX2_CTL_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX1_CLK_CTL,
{0x1F, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE0},
TIMPANI_CDC_RX1_CLK_CTL_M,
TIMPANI_CDC_RX1_CLK_CTL_POR,
{
{ .mask = 0x1F, .path_mask = 0},
{ .mask = 0xE0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX2_CLK_CTL,
{0x1F, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xE0},
TIMPANI_CDC_RX2_CLK_CTL_M,
TIMPANI_CDC_RX2_CLK_CTL_POR,
{
{ .mask = 0x1F, .path_mask = 0},
{ .mask = 0xE0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_DEC_ADC_SEL,
{0x0, 0x0, 0xF, 0xF0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_DEC_ADC_SEL_M,
TIMPANI_CDC_DEC_ADC_SEL_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC_INPUT_MUX,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x3F, 0x0, 0xC0},
TIMPANI_CDC_ANC_INPUT_MUX_M,
TIMPANI_CDC_ANC_INPUT_MUX_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC_RX_CLK_NS_SEL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0xFE},
TIMPANI_CDC_ANC_RX_CLK_NS_SEL_M,
TIMPANI_CDC_ANC_RX_CLK_NS_SEL_POR,
{
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC_FB_TUNE_SEL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF},
TIMPANI_CDC_ANC_FB_TUNE_SEL_M,
TIMPANI_CDC_ANC_FB_TUNE_SEL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CLK_DIV_SYNC_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0xFC},
TIMPANI_CLK_DIV_SYNC_CTL_M,
TIMPANI_CLK_DIV_SYNC_CTL_POR,
{
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ADC_CLK_EN,
{0x0, 0x0, 0x3, 0xC, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF0},
TIMPANI_CDC_ADC_CLK_EN_M,
TIMPANI_CDC_ADC_CLK_EN_POR,
{
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x0C, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ST_MIXING,
{0x0, 0x0, 0x3, 0xC, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF0},
TIMPANI_CDC_ST_MIXING_M,
TIMPANI_CDC_ST_MIXING_POR,
{
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x0C, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX2_CTL,
{0x0, 0x7F, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80},
TIMPANI_CDC_RX2_CTL_M,
TIMPANI_CDC_RX2_CTL_POR,
{
{ .mask = 0x7F, .path_mask = 0},
{ .mask = 0x80, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ARB_CLK_EN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF},
TIMPANI_CDC_ARB_CLK_EN_M,
TIMPANI_CDC_ARB_CLK_EN_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_I2S_CTL2,
{0x2, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x39, 0x0, 0x0, 0xC0},
TIMPANI_CDC_I2S_CTL2_M,
TIMPANI_CDC_I2S_CTL2_POR,
{
{ .mask = 0x02, .path_mask = 0},
{ .mask = 0x04, .path_mask = 0},
{ .mask = 0x39, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX2LG,
{0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX2LG_M,
TIMPANI_CDC_RX2LG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX2RG,
{0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX2RG_M,
TIMPANI_CDC_RX2RG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX2LG,
{0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_TX2LG_M,
TIMPANI_CDC_TX2LG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX2RG,
{0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_TX2RG_M,
TIMPANI_CDC_TX2RG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_DMIC_MUX,
{0x0, 0x0, 0xF, 0xF0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_DMIC_MUX_M,
TIMPANI_CDC_DMIC_MUX_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ARB_CLK_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0xFC},
TIMPANI_CDC_ARB_CLK_CTL_M,
TIMPANI_CDC_ARB_CLK_CTL_POR,
{
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_GCTL2,
{0x0, 0xF, 0x0, 0xF0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_GCTL2_M,
TIMPANI_CDC_GCTL2_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_BYPASS_CTL2,
{0x0, 0x0, 0x3F, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_CDC_BYPASS_CTL2_M,
TIMPANI_CDC_BYPASS_CTL2_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_BYPASS_CTL3,
{0x0, 0x0, 0x0, 0x3F, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0},
TIMPANI_CDC_BYPASS_CTL3_M,
TIMPANI_CDC_BYPASS_CTL3_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_BYPASS_CTL4,
{0x0, 0xF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF0},
TIMPANI_CDC_BYPASS_CTL4_M,
TIMPANI_CDC_BYPASS_CTL4_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX2L_DCOFFSET,
{0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX2L_DCOFFSET_M,
TIMPANI_CDC_RX2L_DCOFFSET_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX2R_DCOFFSET,
{0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_RX2R_DCOFFSET_M,
TIMPANI_CDC_RX2R_DCOFFSET_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_RX_MIX_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0xFC},
TIMPANI_CDC_RX_MIX_CTL_M,
TIMPANI_CDC_RX_MIX_CTL_POR,
{
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_SPARE_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0xFE},
TIMPANI_CDC_SPARE_CTL_M,
TIMPANI_CDC_SPARE_CTL_POR,
{
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TESTMODE2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1F, 0xE0},
TIMPANI_CDC_TESTMODE2_M,
TIMPANI_CDC_TESTMODE2_POR,
{
{ .mask = 0x1F, .path_mask = 0},
{ .mask = 0xE0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_PDM_OE,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0},
TIMPANI_CDC_PDM_OE_M,
TIMPANI_CDC_PDM_OE_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX1R_STG,
{0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_TX1R_STG_M,
TIMPANI_CDC_TX1R_STG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX2L_STG,
{0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_TX2L_STG_M,
TIMPANI_CDC_TX2L_STG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_TX2R_STG,
{0x0, 0x0, 0x0, 0xFF, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
TIMPANI_CDC_TX2R_STG_M,
TIMPANI_CDC_TX2R_STG_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ARB_BYPASS_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF},
TIMPANI_CDC_ARB_BYPASS_CTL_M,
TIMPANI_CDC_ARB_BYPASS_CTL_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_CTL1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1F, 0x0, 0xE0},
TIMPANI_CDC_ANC1_CTL1_M,
TIMPANI_CDC_ANC1_CTL1_POR,
{
{ .mask = 0x1F, .path_mask = 0},
{ .mask = 0xE0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_CTL2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x3F, 0x0, 0xC0},
TIMPANI_CDC_ANC1_CTL2_M,
TIMPANI_CDC_ANC1_CTL2_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_FF_FB_SHIFT,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC1_FF_FB_SHIFT_M,
TIMPANI_CDC_ANC1_FF_FB_SHIFT_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_RX_NS,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0x0, 0xF8},
TIMPANI_CDC_ANC1_RX_NS_M,
TIMPANI_CDC_ANC1_RX_NS_POR,
{
{ .mask = 0x07, .path_mask = 0},
{ .mask = 0xF8, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_SPARE,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC1_SPARE_M,
TIMPANI_CDC_ANC1_SPARE_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_IIR_COEFF_PTR,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1F, 0x0, 0xE0},
TIMPANI_CDC_ANC1_IIR_COEFF_PTR_M,
TIMPANI_CDC_ANC1_IIR_COEFF_PTR_POR,
{
{ .mask = 0x1F, .path_mask = 0},
{ .mask = 0xE0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_IIR_COEFF_MSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0xFE},
TIMPANI_CDC_ANC1_IIR_COEFF_MSB_M,
TIMPANI_CDC_ANC1_IIR_COEFF_MSB_POR,
{
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_IIR_COEFF_LSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC1_IIR_COEFF_LSB_M,
TIMPANI_CDC_ANC1_IIR_COEFF_LSB_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_IIR_COEFF_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0xFC},
TIMPANI_CDC_ANC1_IIR_COEFF_CTL_M,
TIMPANI_CDC_ANC1_IIR_COEFF_CTL_POR,
{
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_LPF_COEFF_PTR,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_ANC1_LPF_COEFF_PTR_M,
TIMPANI_CDC_ANC1_LPF_COEFF_PTR_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_LPF_COEFF_MSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_ANC1_LPF_COEFF_MSB_M,
TIMPANI_CDC_ANC1_LPF_COEFF_MSB_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_LPF_COEFF_LSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC1_LPF_COEFF_LSB_M,
TIMPANI_CDC_ANC1_LPF_COEFF_LSB_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_SCALE_PTR,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC1_SCALE_PTR_M,
TIMPANI_CDC_ANC1_SCALE_PTR_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_SCALE,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC1_SCALE_M,
TIMPANI_CDC_ANC1_SCALE_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC1_DEBUG,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_ANC1_DEBUG_M,
TIMPANI_CDC_ANC1_DEBUG_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_CTL1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1F, 0x0, 0xE0},
TIMPANI_CDC_ANC2_CTL1_M,
TIMPANI_CDC_ANC2_CTL1_POR,
{
{ .mask = 0x1F, .path_mask = 0},
{ .mask = 0xE0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_CTL2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x3F, 0x0, 0xC0},
TIMPANI_CDC_ANC2_CTL2_M,
TIMPANI_CDC_ANC2_CTL2_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_FF_FB_SHIFT,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC2_FF_FB_SHIFT_M,
TIMPANI_CDC_ANC2_FF_FB_SHIFT_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_RX_NS,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0x0, 0xF8},
TIMPANI_CDC_ANC2_RX_NS_M,
TIMPANI_CDC_ANC2_RX_NS_POR,
{
{ .mask = 0x07, .path_mask = 0},
{ .mask = 0xF8, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_SPARE,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC2_SPARE_M,
TIMPANI_CDC_ANC2_SPARE_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_IIR_COEFF_PTR,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_ANC2_IIR_COEFF_PTR_M,
TIMPANI_CDC_ANC2_IIR_COEFF_PTR_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_IIR_COEFF_MSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0xFE},
TIMPANI_CDC_ANC2_IIR_COEFF_MSB_M,
TIMPANI_CDC_ANC2_IIR_COEFF_MSB_POR,
{
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_IIR_COEFF_LSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC2_IIR_COEFF_LSB_M,
TIMPANI_CDC_ANC2_IIR_COEFF_LSB_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_IIR_COEFF_CTL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0xFC},
TIMPANI_CDC_ANC2_IIR_COEFF_CTL_M,
TIMPANI_CDC_ANC2_IIR_COEFF_CTL_POR,
{
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_LPF_COEFF_PTR,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_ANC2_LPF_COEFF_PTR_M,
TIMPANI_CDC_ANC2_LPF_COEFF_PTR_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_LPF_COEFF_MSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_ANC2_LPF_COEFF_MSB_M,
TIMPANI_CDC_ANC2_LPF_COEFF_MSB_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_LPF_COEFF_LSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC2_LPF_COEFF_LSB_M,
TIMPANI_CDC_ANC2_LPF_COEFF_LSB_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_SCALE_PTR,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC2_SCALE_PTR_M,
TIMPANI_CDC_ANC2_SCALE_PTR_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_SCALE,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_ANC2_SCALE_M,
TIMPANI_CDC_ANC2_SCALE_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_ANC2_DEBUG,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_ANC2_DEBUG_M,
TIMPANI_CDC_ANC2_DEBUG_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_LINE_L_AVOL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xFC, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3},
TIMPANI_CDC_LINE_L_AVOL_M,
TIMPANI_CDC_LINE_L_AVOL_POR,
{
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_LINE_R_AVOL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xFC, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3},
TIMPANI_CDC_LINE_R_AVOL_M,
TIMPANI_CDC_LINE_R_AVOL_POR,
{
{ .mask = 0xFC, .path_mask = 0},
{ .mask = 0x03, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_HPH_L_AVOL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFE,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1},
TIMPANI_CDC_HPH_L_AVOL_M,
TIMPANI_CDC_HPH_L_AVOL_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_HPH_R_AVOL,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFE,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1},
TIMPANI_CDC_HPH_R_AVOL_M,
TIMPANI_CDC_HPH_R_AVOL_POR,
{
{ .mask = 0xFE, .path_mask = 0},
{ .mask = 0x01, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_CTL1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x3F, 0x0, 0xC0},
TIMPANI_CDC_COMP_CTL1_M,
TIMPANI_CDC_COMP_CTL1_POR,
{
{ .mask = 0x3F, .path_mask = 0},
{ .mask = 0xC0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_CTL2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_COMP_CTL2_M,
TIMPANI_CDC_COMP_CTL2_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_PEAK_METER,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_COMP_PEAK_METER_M,
TIMPANI_CDC_COMP_PEAK_METER_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_LEVEL_METER_CTL1,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xF, 0x0, 0xF0},
TIMPANI_CDC_COMP_LEVEL_METER_CTL1_M,
TIMPANI_CDC_COMP_LEVEL_METER_CTL1_POR,
{
{ .mask = 0x0F, .path_mask = 0},
{ .mask = 0xF0, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_LEVEL_METER_CTL2,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_COMP_LEVEL_METER_CTL2_M,
TIMPANI_CDC_COMP_LEVEL_METER_CTL2_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_ZONE_SELECT,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x7F, 0x0, 0x80},
TIMPANI_CDC_COMP_ZONE_SELECT_M,
TIMPANI_CDC_COMP_ZONE_SELECT_POR,
{
{ .mask = 0x7F, .path_mask = 0},
{ .mask = 0x80, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_ZC_MSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_COMP_ZC_MSB_M,
TIMPANI_CDC_COMP_ZC_MSB_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_ZC_LSB,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x0, 0x0},
TIMPANI_CDC_COMP_ZC_LSB_M,
TIMPANI_CDC_COMP_ZC_LSB_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_SHUT_DOWN,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF},
TIMPANI_CDC_COMP_SHUT_DOWN_M,
TIMPANI_CDC_COMP_SHUT_DOWN_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_SHUT_DOWN_STATUS,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF},
TIMPANI_CDC_COMP_SHUT_DOWN_STATUS_M,
TIMPANI_CDC_COMP_SHUT_DOWN_STATUS_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
},
{
TIMPANI_A_CDC_COMP_HALT,
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF},
TIMPANI_CDC_COMP_HALT_M,
TIMPANI_CDC_COMP_HALT_POR,
{
{ .mask = 0xFF, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
{ .mask = 0x00, .path_mask = 0},
}
}
};
struct reg_acc_blk_cfg timpani_blkcfg[RA_BLOCK_NUM] = {
{
.valid_owners = {RA_OWNER_NONE, RA_OWNER_PATH_RX1,
0, 0, 0, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_RX1 */
{
.valid_owners = {RA_OWNER_NONE, 0, RA_OWNER_PATH_RX2,
0, 0, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_RX2 */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, RA_OWNER_PATH_TX1,
0, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_TX1 */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, 0, RA_OWNER_PATH_TX2,
0, RA_OWNER_DRV}
},
/* RA_BLOCK_TX2 */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, 0, 0,
RA_OWNER_PATH_LB, RA_OWNER_DRV}
},
/* RA_BLOCK_LB */
{
.valid_owners = {RA_OWNER_NONE, RA_OWNER_PATH_RX1,
RA_OWNER_PATH_RX2, 0, 0, RA_OWNER_PATH_LB, RA_OWNER_DRV}
},
/* RA_BLOCK_SHARED_RX_LB */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, RA_OWNER_PATH_TX1,
RA_OWNER_PATH_TX2, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_SHARED_TX */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, RA_OWNER_PATH_TX1,
RA_OWNER_PATH_TX2, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_TXFE1 */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, RA_OWNER_PATH_TX1,
RA_OWNER_PATH_TX2, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_TXFE2 */
{
.valid_owners = {RA_OWNER_NONE, RA_OWNER_PATH_RX1,
RA_OWNER_PATH_RX2, 0, 0, RA_OWNER_PATH_LB, RA_OWNER_DRV}
},
/* RA_BLOCK_PA_COMMON */
{
.valid_owners = {RA_OWNER_NONE, RA_OWNER_PATH_RX1,
RA_OWNER_PATH_RX2, 0, 0, RA_OWNER_PATH_LB, RA_OWNER_DRV}
},
/* RA_BLOCK_PA_EAR */
{
.valid_owners = {RA_OWNER_NONE, RA_OWNER_PATH_RX1,
RA_OWNER_PATH_RX2, 0, 0, RA_OWNER_PATH_LB, RA_OWNER_DRV}
},
/* RA_BLOCK_PA_HPH */
{
.valid_owners = {RA_OWNER_NONE, RA_OWNER_PATH_RX1,
RA_OWNER_PATH_RX2, 0, 0, RA_OWNER_PATH_LB, RA_OWNER_DRV}
},
/* RA_BLOCK_PA_LINE */
{
.valid_owners = {RA_OWNER_NONE, RA_OWNER_PATH_RX1,
RA_OWNER_PATH_RX2, 0, 0, RA_OWNER_PATH_LB, RA_OWNER_DRV}
},
/* RA_BLOCK_PA_AUX */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, RA_OWNER_PATH_TX1,
RA_OWNER_PATH_TX2, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_ADC */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, RA_OWNER_PATH_TX1,
RA_OWNER_PATH_TX2, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_DMIC */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, RA_OWNER_PATH_TX1,
RA_OWNER_PATH_TX2, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_TX_I2S */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, 0, 0, 0, RA_OWNER_DRV}
},
/*RA_BLOCK_DRV */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, 0, 0, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_TEST */
{
.valid_owners = {RA_OWNER_NONE, 0, 0, 0, 0, 0, RA_OWNER_DRV}
},
/* RA_BLOCK_RESERVED */
};
struct adie_codec_state {
struct adie_codec_path path[ADIE_CODEC_MAX];
u32 ref_cnt;
struct marimba *pdrv_ptr;
struct marimba_codec_platform_data *codec_pdata;
struct mutex lock;
};
static struct adie_codec_state adie_codec;
/* A cacheable register is one that if the register's current value is being
* written to it again, then it is permissable to skip that register write
* because it does not actually change the value of the hardware register.
*
* Some registers are uncacheable, meaning that even they are being written
* again with their current value, the write has another purpose and must go
* through.
*
* Knowing the codec's uncacheable registers allows the driver to avoid
* unnecessary codec register writes while making sure important register writes
* are not skipped.
*/
static bool timpani_register_is_cacheable(u8 reg)
{
switch (reg) {
case TIMPANI_A_PA_LINE_L_GAIN:
case TIMPANI_A_PA_LINE_R_GAIN:
case TIMPANI_A_PA_HPH_L_GAIN:
case TIMPANI_A_PA_HPH_R_GAIN:
case TIMPANI_A_CDC_GCTL1:
case TIMPANI_A_CDC_ST_CTL:
case TIMPANI_A_CDC_GCTL2:
case TIMPANI_A_CDC_ARB_BYPASS_CTL:
case TIMPANI_A_CDC_CH_CTL:
case TIMPANI_A_CDC_ANC1_IIR_COEFF_PTR:
case TIMPANI_A_CDC_ANC1_IIR_COEFF_MSB:
case TIMPANI_A_CDC_ANC1_IIR_COEFF_LSB:
case TIMPANI_A_CDC_ANC1_LPF_COEFF_PTR:
case TIMPANI_A_CDC_ANC1_LPF_COEFF_MSB:
case TIMPANI_A_CDC_ANC1_LPF_COEFF_LSB:
case TIMPANI_A_CDC_ANC1_SCALE_PTR:
case TIMPANI_A_CDC_ANC1_SCALE:
case TIMPANI_A_CDC_ANC2_IIR_COEFF_PTR:
case TIMPANI_A_CDC_ANC2_IIR_COEFF_MSB:
case TIMPANI_A_CDC_ANC2_IIR_COEFF_LSB:
case TIMPANI_A_CDC_ANC2_LPF_COEFF_PTR:
case TIMPANI_A_CDC_ANC2_LPF_COEFF_MSB:
case TIMPANI_A_CDC_ANC2_LPF_COEFF_LSB:
case TIMPANI_A_CDC_ANC2_SCALE_PTR:
case TIMPANI_A_CDC_ANC2_SCALE:
case TIMPANI_A_CDC_ANC1_CTL1:
case TIMPANI_A_CDC_ANC1_CTL2:
case TIMPANI_A_CDC_ANC1_FF_FB_SHIFT:
case TIMPANI_A_CDC_ANC2_CTL1:
case TIMPANI_A_CDC_ANC2_CTL2:
case TIMPANI_A_CDC_ANC2_FF_FB_SHIFT:
case TIMPANI_A_AUXPGA_LR_GAIN:
case TIMPANI_A_CDC_ANC_INPUT_MUX:
return false;
default:
return true;
}
}
static int adie_codec_write(u8 reg, u8 mask, u8 val)
{
int rc = 0;
u8 new_val;
if (reg > MAX_SHADOW_RIGISTERS) {
pr_debug("register number is out of bound for shadow"
" registers reg = %d\n", reg);
new_val = (val & mask);
rc = marimba_write_bit_mask(adie_codec.pdrv_ptr, reg, &new_val,
1, 0xFF);
if (IS_ERR_VALUE(rc)) {
pr_err("%s: fail to write reg %x\n", __func__, reg);
rc = -EIO;
goto error;
}
return rc;
}
new_val = (val & mask) | (timpani_shadow[reg] & ~mask);
if (!(timpani_register_is_cacheable(reg) &&
(new_val == timpani_shadow[reg]))) {
rc = marimba_write_bit_mask(adie_codec.pdrv_ptr, reg, &new_val,
1, 0xFF);
if (IS_ERR_VALUE(rc)) {
pr_err("%s: fail to write reg %x\n", __func__, reg);
rc = -EIO;
goto error;
}
timpani_shadow[reg] = new_val;
pr_debug("%s: write reg %x val %x new value %x\n", __func__,
reg, val, new_val);
}
error:
return rc;
}
static int reg_in_use(u8 reg_ref, u8 path_type)
{
if ((reg_ref & ~path_type) == 0)
return 0;
else
return 1;
}
static int adie_codec_refcnt_write(u8 reg, u8 mask, u8 val, enum refcnt cnt,
u8 path_type)
{
u8 i;
int j;
u8 fld_mask;
u8 path_mask;
u8 reg_mask = 0;
int rc = 0;
for (i = 0; i < ARRAY_SIZE(timpani_regset); i++) {
if (timpani_regset[i].reg_addr == reg) {
for (j = 0; j < TIMPANI_MAX_FIELDS; j++) {
fld_mask = timpani_regset[i].fld_ref_cnt[j].mask
& mask;
path_mask = timpani_regset[i].fld_ref_cnt[j]
.path_mask;
if (fld_mask) {
if (!reg_in_use(path_mask, path_type))
reg_mask |= fld_mask;
if (cnt == INC)
timpani_regset[i].fld_ref_cnt[j]
.path_mask |= path_type;
else if (cnt == DEC)
timpani_regset[i].fld_ref_cnt[j]
.path_mask &=
~path_type;
}
}
if (reg_mask)
rc = adie_codec_write(reg, reg_mask, val);
reg_mask = 0;
break;
}
}
return rc;
}
static int adie_codec_read(u8 reg, u8 *val)
{
return marimba_read(adie_codec.pdrv_ptr, reg, val, 1);
}
static int timpani_adie_codec_setpath(struct adie_codec_path *path_ptr,
u32 freq_plan, u32 osr)
{
int rc = 0;
u32 i, freq_idx = 0, freq = 0;
if (path_ptr == NULL)
return -EINVAL;
if (path_ptr->curr_stage != ADIE_CODEC_DIGITAL_OFF) {
rc = -EBUSY;
goto error;
}
for (i = 0; i < path_ptr->profile->setting_sz; i++) {
if (path_ptr->profile->settings[i].osr == osr) {
if (path_ptr->profile->settings[i].freq_plan >=
freq_plan) {
if (freq == 0) {
freq = path_ptr->profile->settings[i].
freq_plan;
freq_idx = i;
} else if (path_ptr->profile->settings[i].
freq_plan < freq) {
freq = path_ptr->profile->settings[i].
freq_plan;
freq_idx = i;
}
}
}
}
if (freq_idx >= path_ptr->profile->setting_sz)
rc = -ENODEV;
else {
path_ptr->hwsetting_idx = freq_idx;
path_ptr->stage_idx = 0;
}
error:
return rc;
}
static u32 timpani_adie_codec_freq_supported(
struct adie_codec_dev_profile *profile,
u32 requested_freq)
{
u32 i, rc = -EINVAL;
for (i = 0; i < profile->setting_sz; i++) {
if (profile->settings[i].freq_plan >= requested_freq) {
rc = 0;
break;
}
}
return rc;
}
int timpani_adie_codec_enable_sidetone(struct adie_codec_path *rx_path_ptr,
u32 enable)
{
int rc = 0;
pr_debug("%s()\n", __func__);
mutex_lock(&adie_codec.lock);
if (!rx_path_ptr || &adie_codec.path[ADIE_CODEC_RX] != rx_path_ptr) {
pr_err("%s: invalid path pointer\n", __func__);
rc = -EINVAL;
goto error;
} else if (rx_path_ptr->curr_stage !=
ADIE_CODEC_DIGITAL_ANALOG_READY) {
pr_err("%s: bad state\n", __func__);
rc = -EPERM;
goto error;
}
if (enable) {
rc = adie_codec_write(TIMPANI_A_CDC_RX1_CTL,
TIMPANI_RX1_ST_MASK, TIMPANI_RX1_ST_ENABLE);
if (rx_path_ptr->reg_owner == RA_OWNER_PATH_RX1)
adie_codec_write(TIMPANI_A_CDC_ST_MIXING,
TIMPANI_CDC_ST_MIXING_TX1_MASK,
TIMPANI_CDC_ST_MIXING_TX1_ENABLE);
else if (rx_path_ptr->reg_owner == RA_OWNER_PATH_RX2)
adie_codec_write(TIMPANI_A_CDC_ST_MIXING,
TIMPANI_CDC_ST_MIXING_TX2_MASK,
TIMPANI_CDC_ST_MIXING_TX2_ENABLE);
} else {
rc = adie_codec_write(TIMPANI_A_CDC_RX1_CTL,
TIMPANI_RX1_ST_MASK, 0);
if (rx_path_ptr->reg_owner == RA_OWNER_PATH_RX1)
adie_codec_write(TIMPANI_A_CDC_ST_MIXING,
TIMPANI_CDC_ST_MIXING_TX1_MASK, 0);
else if (rx_path_ptr->reg_owner == RA_OWNER_PATH_RX2)
adie_codec_write(TIMPANI_A_CDC_ST_MIXING,
TIMPANI_CDC_ST_MIXING_TX2_MASK, 0);
}
error:
mutex_unlock(&adie_codec.lock);
return rc;
}
static int timpani_adie_codec_enable_anc(struct adie_codec_path *rx_path_ptr,
u32 enable, struct adie_codec_anc_data *calibration_writes)
{
int index = 0;
int rc = 0;
u8 reg, mask, val;
pr_debug("%s: enable = %d\n", __func__, enable);
mutex_lock(&adie_codec.lock);
if (!rx_path_ptr || &adie_codec.path[ADIE_CODEC_RX] != rx_path_ptr) {
pr_err("%s: invalid path pointer\n", __func__);
rc = -EINVAL;
goto error;
} else if (rx_path_ptr->curr_stage !=
ADIE_CODEC_DIGITAL_ANALOG_READY) {
pr_err("%s: bad state\n", __func__);
rc = -EPERM;
goto error;
}
if (enable) {
if (!calibration_writes || !calibration_writes->writes) {
pr_err("%s: No ANC calibration data\n", __func__);
rc = -EPERM;
goto error;
}
while (index < calibration_writes->size) {
ADIE_CODEC_UNPACK_ENTRY(calibration_writes->
writes[index], reg, mask, val);
adie_codec_write(reg, mask, val);
index++;
}
} else {
adie_codec_write(TIMPANI_A_CDC_ANC1_CTL1,
TIMPANI_CDC_ANC1_CTL1_ANC1_EN_M,
TIMPANI_CDC_ANC1_CTL1_ANC1_EN_ANC_DIS <<
TIMPANI_CDC_ANC1_CTL1_ANC1_EN_S);
adie_codec_write(TIMPANI_A_CDC_ANC2_CTL1,
TIMPANI_CDC_ANC2_CTL1_ANC2_EN_M,
TIMPANI_CDC_ANC2_CTL1_ANC2_EN_ANC_DIS <<
TIMPANI_CDC_ANC2_CTL1_ANC2_EN_S);
}
error:
mutex_unlock(&adie_codec.lock);
return rc;
}
static void adie_codec_restore_regdefault(u8 path_mask, u32 blk)
{
u32 ireg;
u32 regset_sz =
(sizeof(timpani_regset)/sizeof(struct timpani_regaccess));
for (ireg = 0; ireg < regset_sz; ireg++) {
if (timpani_regset[ireg].blk_mask[blk]) {
/* only process register belong to the block */
u8 reg = timpani_regset[ireg].reg_addr;
u8 mask = timpani_regset[ireg].blk_mask[blk];
u8 val = timpani_regset[ireg].reg_default;
adie_codec_refcnt_write(reg, mask, val, IGNORE,
path_mask);
}
}
}
static void adie_codec_reach_stage_action(struct adie_codec_path *path_ptr,
u32 stage)
{
u32 iblk, iowner; /* iterators */
u8 path_mask;
if (path_ptr == NULL)
return;
path_mask = TIMPANI_PATH_MASK(path_ptr->reg_owner);
if (stage != ADIE_CODEC_DIGITAL_OFF)
return;
for (iblk = 0 ; iblk <= RA_BLOCK_RESERVED ; iblk++) {
for (iowner = 0; iowner < RA_OWNER_NUM; iowner++) {
if (timpani_blkcfg[iblk].valid_owners[iowner] ==
path_ptr->reg_owner) {
adie_codec_restore_regdefault(path_mask, iblk);
break; /* This path owns this block */
}
}
}
}
static int timpani_adie_codec_proceed_stage(struct adie_codec_path *path_ptr,
u32 state)
{
int rc = 0, loop_exit = 0;
struct adie_codec_action_unit *curr_action;
struct adie_codec_hwsetting_entry *setting;
u8 reg, mask, val;
u8 path_mask;
if (path_ptr == NULL)
return -EINVAL;
path_mask = TIMPANI_PATH_MASK(path_ptr->reg_owner);
mutex_lock(&adie_codec.lock);
setting = &path_ptr->profile->settings[path_ptr->hwsetting_idx];
while (!loop_exit) {
curr_action = &setting->actions[path_ptr->stage_idx];
switch (curr_action->type) {
case ADIE_CODEC_ACTION_ENTRY:
ADIE_CODEC_UNPACK_ENTRY(curr_action->action,
reg, mask, val);
if (state == ADIE_CODEC_DIGITAL_OFF)
adie_codec_refcnt_write(reg, mask, val, DEC,
path_mask);
else
adie_codec_refcnt_write(reg, mask, val, INC,
path_mask);
break;
case ADIE_CODEC_ACTION_DELAY_WAIT:
if (curr_action->action > MAX_MDELAY_US)
msleep(curr_action->action/1000);
else
usleep_range(curr_action->action,
curr_action->action);
break;
case ADIE_CODEC_ACTION_STAGE_REACHED:
adie_codec_reach_stage_action(path_ptr,
curr_action->action);
if (curr_action->action == state) {
path_ptr->curr_stage = state;
loop_exit = 1;
}
break;
default:
BUG();
}
path_ptr->stage_idx++;
if (path_ptr->stage_idx == setting->action_sz)
path_ptr->stage_idx = 0;
}
mutex_unlock(&adie_codec.lock);
return rc;
}
static void timpani_codec_bring_up(void)
{
/* Codec power up sequence */
adie_codec_write(0xFF, 0xFF, 0x08);
adie_codec_write(0xFF, 0xFF, 0x0A);
adie_codec_write(0xFF, 0xFF, 0x0E);
adie_codec_write(0xFF, 0xFF, 0x07);
adie_codec_write(0xFF, 0xFF, 0x17);
adie_codec_write(TIMPANI_A_MREF, 0xFF, 0xF2);
msleep(15);
adie_codec_write(TIMPANI_A_MREF, 0xFF, 0x22);
/* Bypass TX HPFs to prevent pops */
adie_codec_write(TIMPANI_A_CDC_BYPASS_CTL2, TIMPANI_CDC_BYPASS_CTL2_M,
TIMPANI_CDC_BYPASS_CTL2_POR);
adie_codec_write(TIMPANI_A_CDC_BYPASS_CTL3, TIMPANI_CDC_BYPASS_CTL3_M,
TIMPANI_CDC_BYPASS_CTL3_POR);
}
static void timpani_codec_bring_down(void)
{
adie_codec_write(TIMPANI_A_MREF, 0xFF, TIMPANI_MREF_POR);
adie_codec_write(0xFF, 0xFF, 0x07);
adie_codec_write(0xFF, 0xFF, 0x06);
adie_codec_write(0xFF, 0xFF, 0x0E);
adie_codec_write(0xFF, 0xFF, 0x08);
}
static int timpani_adie_codec_open(struct adie_codec_dev_profile *profile,
struct adie_codec_path **path_pptr)
{
int rc = 0;
mutex_lock(&adie_codec.lock);
if (!profile || !path_pptr) {
rc = -EINVAL;
goto error;
}
if (adie_codec.path[profile->path_type].profile) {
rc = -EBUSY;
goto error;
}
if (!adie_codec.ref_cnt) {
if (adie_codec.codec_pdata &&
adie_codec.codec_pdata->marimba_codec_power) {
rc = adie_codec.codec_pdata->marimba_codec_power(1);
if (rc) {
pr_err("%s: could not power up timpani "
"codec\n", __func__);
goto error;
}
timpani_codec_bring_up();
} else {
pr_err("%s: couldn't detect timpani codec\n", __func__);
rc = -ENODEV;
goto error;
}
}
adie_codec.path[profile->path_type].profile = profile;
*path_pptr = (void *) &adie_codec.path[profile->path_type];
adie_codec.ref_cnt++;
adie_codec.path[profile->path_type].hwsetting_idx = 0;
adie_codec.path[profile->path_type].curr_stage = ADIE_CODEC_DIGITAL_OFF;
adie_codec.path[profile->path_type].stage_idx = 0;
error:
mutex_unlock(&adie_codec.lock);
return rc;
}
static int timpani_adie_codec_close(struct adie_codec_path *path_ptr)
{
int rc = 0;
mutex_lock(&adie_codec.lock);
if (!path_ptr) {
rc = -EINVAL;
goto error;
}
if (path_ptr->curr_stage != ADIE_CODEC_DIGITAL_OFF)
adie_codec_proceed_stage(path_ptr, ADIE_CODEC_DIGITAL_OFF);
BUG_ON(!adie_codec.ref_cnt);
path_ptr->profile = NULL;
adie_codec.ref_cnt--;
if (!adie_codec.ref_cnt) {
/* Timpani CDC power down sequence */
timpani_codec_bring_down();
if (adie_codec.codec_pdata &&
adie_codec.codec_pdata->marimba_codec_power) {
rc = adie_codec.codec_pdata->marimba_codec_power(0);
if (rc) {
pr_err("%s: could not power down timpani "
"codec\n", __func__);
goto error;
}
}
}
error:
mutex_unlock(&adie_codec.lock);
return rc;
}
static int timpani_adie_codec_set_master_mode(struct adie_codec_path *path_ptr,
u8 master)
{
u8 val = master ? 1 : 0;
if (!path_ptr)
return -EINVAL;
if (path_ptr->reg_owner == RA_OWNER_PATH_RX1)
adie_codec_write(TIMPANI_A_CDC_RX1_CTL, 0x01, val);
else if (path_ptr->reg_owner == RA_OWNER_PATH_TX1)
adie_codec_write(TIMPANI_A_CDC_TX_I2S_CTL, 0x01, val);
else
return -EINVAL;
return 0;
}
int timpani_adie_codec_set_device_analog_volume(
struct adie_codec_path *path_ptr,
u32 num_channels, u32 volume)
{
u8 val;
u8 curr_val;
u8 i;
adie_codec_read(TIMPANI_A_AUXPGA_LR_GAIN, &curr_val);
/* Volume is expressed as a percentage. */
/* The upper nibble is the left channel, lower right channel. */
val = (u8)((volume * TIMPANI_CODEC_AUXPGA_GAIN_RANGE) / 100);
val |= val << 4;
if ((curr_val & 0x0F) < (val & 0x0F)) {
for (i = curr_val; i < val; i += 0x11)
adie_codec_write(TIMPANI_A_AUXPGA_LR_GAIN, 0xFF, i);
} else if ((curr_val & 0x0F) > (val & 0x0F)) {
for (i = curr_val; i > val; i -= 0x11)
adie_codec_write(TIMPANI_A_AUXPGA_LR_GAIN, 0xFF, i);
}
return 0;
}
enum adie_vol_type {
ADIE_CODEC_RX_DIG_VOL,
ADIE_CODEC_TX_DIG_VOL,
ADIE_CODEC_VOL_TYPE_MAX
};
#define CDC_RX1LG 0x84
#define CDC_RX1RG 0x85
#define CDC_TX1LG 0x86
#define CDC_TX1RG 0x87
#define DIG_VOL_MASK 0xFF
#define CDC_GCTL1 0x8A
#define RX1_PGA_UPDATE_L 0x04
#define RX1_PGA_UPDATE_R 0x08
#define TX1_PGA_UPDATE_L 0x40
#define TX1_PGA_UPDATE_R 0x80
#define CDC_GCTL1_RX_MASK 0x0F
#define CDC_GCTL1_TX_MASK 0xF0
enum {
TIMPANI_MIN_DIG_VOL = -84, /* in DB*/
TIMPANI_MAX_DIG_VOL = 16, /* in DB*/
TIMPANI_DIG_VOL_STEP = 3 /* in DB*/
};
static int timpani_adie_codec_set_dig_vol(enum adie_vol_type vol_type,
u32 num_chan, u32 vol_per)
{
u8 reg_left, reg_right;
u8 gain_reg_val, gain_reg_mask;
s8 new_reg_val, cur_reg_val;
s8 step_size;
adie_codec_read(CDC_GCTL1, &gain_reg_val);
if (vol_type == ADIE_CODEC_RX_DIG_VOL) {
pr_debug("%s : RX DIG VOL. num_chan = %u\n", __func__,
num_chan);
reg_left = CDC_RX1LG;
reg_right = CDC_RX1RG;
if (num_chan == 1)
gain_reg_val |= RX1_PGA_UPDATE_L;
else
gain_reg_val |= (RX1_PGA_UPDATE_L | RX1_PGA_UPDATE_R);
gain_reg_mask = CDC_GCTL1_RX_MASK;
} else {
pr_debug("%s : TX DIG VOL. num_chan = %u\n", __func__,
num_chan);
reg_left = CDC_TX1LG;
reg_right = CDC_TX1RG;
if (num_chan == 1)
gain_reg_val |= TX1_PGA_UPDATE_L;
else
gain_reg_val |= (TX1_PGA_UPDATE_L | TX1_PGA_UPDATE_R);
gain_reg_mask = CDC_GCTL1_TX_MASK;
}
adie_codec_read(reg_left, &cur_reg_val);
pr_debug("%s: vol_per = %d cur_reg_val = %d 0x%x\n", __func__, vol_per,
cur_reg_val, cur_reg_val);
new_reg_val = TIMPANI_MIN_DIG_VOL +
(((TIMPANI_MAX_DIG_VOL - TIMPANI_MIN_DIG_VOL) * vol_per) / 100);
pr_debug("new_reg_val = %d 0x%x\n", new_reg_val, new_reg_val);
if (new_reg_val > cur_reg_val) {
step_size = TIMPANI_DIG_VOL_STEP;
} else if (new_reg_val < cur_reg_val) {
step_size = -TIMPANI_DIG_VOL_STEP;
} else {
pr_debug("new_reg_val and cur_reg_val are same 0x%x\n",
new_reg_val);
return 0;
}
while (cur_reg_val != new_reg_val) {
if (((new_reg_val > cur_reg_val) &&
((new_reg_val - cur_reg_val) < TIMPANI_DIG_VOL_STEP)) ||
((cur_reg_val > new_reg_val) &&
((cur_reg_val - new_reg_val)
< TIMPANI_DIG_VOL_STEP))) {
cur_reg_val = new_reg_val;
pr_debug("diff less than step. write new_reg_val = %d"
" 0x%x\n", new_reg_val, new_reg_val);
} else {
cur_reg_val = cur_reg_val + step_size;
pr_debug("cur_reg_val = %d 0x%x\n",
cur_reg_val, cur_reg_val);
}
adie_codec_write(reg_left, DIG_VOL_MASK, cur_reg_val);
if (num_chan == 2)
adie_codec_write(reg_right, DIG_VOL_MASK, cur_reg_val);
adie_codec_write(CDC_GCTL1, gain_reg_mask, gain_reg_val);
}
return 0;
}
static int timpani_adie_codec_set_device_digital_volume(
struct adie_codec_path *path_ptr,
u32 num_channels, u32 vol_percentage /* in percentage */)
{
enum adie_vol_type vol_type;
if (!path_ptr || (path_ptr->curr_stage !=
ADIE_CODEC_DIGITAL_ANALOG_READY)) {
pr_info("%s: timpani codec not ready for volume control\n",
__func__);
return -EPERM;
}
if (num_channels > 2) {
pr_err("%s: timpani odec only supports max two channels\n",
__func__);
return -EINVAL;
}
if (path_ptr->profile->path_type == ADIE_CODEC_RX) {
vol_type = ADIE_CODEC_RX_DIG_VOL;
} else if (path_ptr->profile->path_type == ADIE_CODEC_TX) {
vol_type = ADIE_CODEC_TX_DIG_VOL;
} else {
pr_err("%s: invalid device data neither RX nor TX\n",
__func__);
return -EINVAL;
}
timpani_adie_codec_set_dig_vol(vol_type, num_channels, vol_percentage);
return 0;
}
static const struct adie_codec_operations timpani_adie_ops = {
.codec_id = TIMPANI_ID,
.codec_open = timpani_adie_codec_open,
.codec_close = timpani_adie_codec_close,
.codec_setpath = timpani_adie_codec_setpath,
.codec_proceed_stage = timpani_adie_codec_proceed_stage,
.codec_freq_supported = timpani_adie_codec_freq_supported,
.codec_enable_sidetone = timpani_adie_codec_enable_sidetone,
.codec_set_master_mode = timpani_adie_codec_set_master_mode,
.codec_enable_anc = timpani_adie_codec_enable_anc,
.codec_set_device_analog_volume =
timpani_adie_codec_set_device_analog_volume,
.codec_set_device_digital_volume =
timpani_adie_codec_set_device_digital_volume,
};
static void timpani_codec_populate_shadow_registers(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(timpani_regset); i++) {
if (timpani_regset[i].reg_addr < TIMPANI_ARRAY_SIZE) {
timpani_shadow[timpani_regset[i].reg_addr] =
timpani_regset[i].reg_default;
}
}
}
#ifdef CONFIG_DEBUG_FS
static struct dentry *debugfs_timpani_dent;
static struct dentry *debugfs_peek;
static struct dentry *debugfs_poke;
static struct dentry *debugfs_power;
static struct dentry *debugfs_dump;
static unsigned char read_data;
static int codec_debug_open(struct inode *inode, struct file *file)
{
file->private_data = inode->i_private;
return 0;
}
static int get_parameters(char *buf, long int *param1, int num_of_par)
{
char *token;
int base, cnt;
token = strsep(&buf, " ");
for (cnt = 0; cnt < num_of_par; cnt++) {
if (token != NULL) {
if ((token[1] == 'x') || (token[1] == 'X'))
base = 16;
else
base = 10;
if (strict_strtoul(token, base, ¶m1[cnt]) != 0)
return -EINVAL;
token = strsep(&buf, " ");
}
else
return -EINVAL;
}
return 0;
}
static ssize_t codec_debug_read(struct file *file, char __user *ubuf,
size_t count, loff_t *ppos)
{
char lbuf[8];
snprintf(lbuf, sizeof(lbuf), "0x%x\n", read_data);
return simple_read_from_buffer(ubuf, count, ppos, lbuf, strlen(lbuf));
}
static ssize_t codec_debug_write(struct file *filp,
const char __user *ubuf, size_t cnt, loff_t *ppos)
{
char *access_str = filp->private_data;
char lbuf[32];
int rc;
int i;
int read_result;
u8 reg_val;
long int param[5];
if (cnt > sizeof(lbuf) - 1)
return -EINVAL;
rc = copy_from_user(lbuf, ubuf, cnt);
if (rc)
return -EFAULT;
lbuf[cnt] = '\0';
if (!strcmp(access_str, "power")) {
if (get_parameters(lbuf, param, 1) == 0) {
switch (param[0]) {
case 1:
adie_codec.codec_pdata->marimba_codec_power(1);
timpani_codec_bring_up();
break;
case 0:
timpani_codec_bring_down();
adie_codec.codec_pdata->marimba_codec_power(0);
break;
default:
rc = -EINVAL;
break;
}
} else
rc = -EINVAL;
} else if (!strcmp(access_str, "poke")) {
/* write */
rc = get_parameters(lbuf, param, 2);
if ((param[0] <= 0xFF) && (param[1] <= 0xFF) &&
(rc == 0))
adie_codec_write(param[0], 0xFF, param[1]);
else
rc = -EINVAL;
} else if (!strcmp(access_str, "peek")) {
/* read */
rc = get_parameters(lbuf, param, 1);
if ((param[0] <= 0xFF) && (rc == 0))
adie_codec_read(param[0], &read_data);
else
rc = -EINVAL;
} else if (!strcmp(access_str, "dump")) {
pr_info("************** timpani regs *************\n");
for (i = 0; i < 0xFF; i++) {
read_result = adie_codec_read(i, ®_val);
if (read_result < 0) {
pr_info("failed to read codec register\n");
break;
} else
pr_info("reg 0x%02X val 0x%02X\n", i, reg_val);
}
pr_info("*****************************************\n");
}
if (rc == 0)
rc = cnt;
else
pr_err("%s: rc = %d\n", __func__, rc);
return rc;
}
static const struct file_operations codec_debug_ops = {
.open = codec_debug_open,
.write = codec_debug_write,
.read = codec_debug_read
};
#endif
static int timpani_codec_probe(struct platform_device *pdev)
{
int rc;
adie_codec.pdrv_ptr = platform_get_drvdata(pdev);
adie_codec.codec_pdata = pdev->dev.platform_data;
if (adie_codec.codec_pdata->snddev_profile_init)
adie_codec.codec_pdata->snddev_profile_init();
timpani_codec_populate_shadow_registers();
/* Register the timpani ADIE operations */
rc = adie_codec_register_codec_operations(&timpani_adie_ops);
#ifdef CONFIG_DEBUG_FS
debugfs_timpani_dent = debugfs_create_dir("msm_adie_codec", 0);
if (!IS_ERR(debugfs_timpani_dent)) {
debugfs_peek = debugfs_create_file("peek",
S_IFREG | S_IRUGO, debugfs_timpani_dent,
(void *) "peek", &codec_debug_ops);
debugfs_poke = debugfs_create_file("poke",
S_IFREG | S_IRUGO, debugfs_timpani_dent,
(void *) "poke", &codec_debug_ops);
debugfs_power = debugfs_create_file("power",
S_IFREG | S_IRUGO, debugfs_timpani_dent,
(void *) "power", &codec_debug_ops);
debugfs_dump = debugfs_create_file("dump",
S_IFREG | S_IRUGO, debugfs_timpani_dent,
(void *) "dump", &codec_debug_ops);
}
#endif
return rc;
}
static struct platform_driver timpani_codec_driver = {
.probe = timpani_codec_probe,
.driver = {
.name = "timpani_codec",
.owner = THIS_MODULE,
},
};
static int __init timpani_codec_init(void)
{
s32 rc;
rc = platform_driver_register(&timpani_codec_driver);
if (IS_ERR_VALUE(rc))
goto error;
adie_codec.path[ADIE_CODEC_TX].reg_owner = RA_OWNER_PATH_TX1;
adie_codec.path[ADIE_CODEC_RX].reg_owner = RA_OWNER_PATH_RX1;
adie_codec.path[ADIE_CODEC_LB].reg_owner = RA_OWNER_PATH_LB;
mutex_init(&adie_codec.lock);
error:
return rc;
}
static void __exit timpani_codec_exit(void)
{
#ifdef CONFIG_DEBUG_FS
debugfs_remove(debugfs_peek);
debugfs_remove(debugfs_poke);
debugfs_remove(debugfs_power);
debugfs_remove(debugfs_dump);
debugfs_remove(debugfs_timpani_dent);
#endif
platform_driver_unregister(&timpani_codec_driver);
}
module_init(timpani_codec_init);
module_exit(timpani_codec_exit);
MODULE_DESCRIPTION("Timpani codec driver");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
omega-roms/I9300_Stock_Kernel_JB_4.3 | drivers/ssb/sdio.c | 4172 | 16198 | /*
* Sonics Silicon Backplane
* SDIO-Hostbus related functions
*
* Copyright 2009 Albert Herranz <albert_herranz@yahoo.es>
*
* Based on drivers/ssb/pcmcia.c
* Copyright 2006 Johannes Berg <johannes@sipsolutions.net>
* Copyright 2007-2008 Michael Buesch <mb@bu3sch.de>
*
* Licensed under the GNU/GPL. See COPYING for details.
*
*/
#include <linux/ssb/ssb.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/etherdevice.h>
#include <linux/mmc/sdio_func.h>
#include "ssb_private.h"
/* Define the following to 1 to enable a printk on each coreswitch. */
#define SSB_VERBOSE_SDIOCORESWITCH_DEBUG 0
/* Hardware invariants CIS tuples */
#define SSB_SDIO_CIS 0x80
#define SSB_SDIO_CIS_SROMREV 0x00
#define SSB_SDIO_CIS_ID 0x01
#define SSB_SDIO_CIS_BOARDREV 0x02
#define SSB_SDIO_CIS_PA 0x03
#define SSB_SDIO_CIS_PA_PA0B0_LO 0
#define SSB_SDIO_CIS_PA_PA0B0_HI 1
#define SSB_SDIO_CIS_PA_PA0B1_LO 2
#define SSB_SDIO_CIS_PA_PA0B1_HI 3
#define SSB_SDIO_CIS_PA_PA0B2_LO 4
#define SSB_SDIO_CIS_PA_PA0B2_HI 5
#define SSB_SDIO_CIS_PA_ITSSI 6
#define SSB_SDIO_CIS_PA_MAXPOW 7
#define SSB_SDIO_CIS_OEMNAME 0x04
#define SSB_SDIO_CIS_CCODE 0x05
#define SSB_SDIO_CIS_ANTENNA 0x06
#define SSB_SDIO_CIS_ANTGAIN 0x07
#define SSB_SDIO_CIS_BFLAGS 0x08
#define SSB_SDIO_CIS_LEDS 0x09
#define CISTPL_FUNCE_LAN_NODE_ID 0x04 /* same as in PCMCIA */
/*
* Function 1 miscellaneous registers.
*
* Definitions match src/include/sbsdio.h from the
* Android Open Source Project
* http://android.git.kernel.org/?p=platform/system/wlan/broadcom.git
*
*/
#define SBSDIO_FUNC1_SBADDRLOW 0x1000a /* SB Address window Low (b15) */
#define SBSDIO_FUNC1_SBADDRMID 0x1000b /* SB Address window Mid (b23-b16) */
#define SBSDIO_FUNC1_SBADDRHIGH 0x1000c /* SB Address window High (b24-b31) */
/* valid bits in SBSDIO_FUNC1_SBADDRxxx regs */
#define SBSDIO_SBADDRLOW_MASK 0x80 /* Valid address bits in SBADDRLOW */
#define SBSDIO_SBADDRMID_MASK 0xff /* Valid address bits in SBADDRMID */
#define SBSDIO_SBADDRHIGH_MASK 0xff /* Valid address bits in SBADDRHIGH */
#define SBSDIO_SB_OFT_ADDR_MASK 0x7FFF /* sb offset addr is <= 15 bits, 32k */
/* REVISIT: this flag doesn't seem to matter */
#define SBSDIO_SB_ACCESS_2_4B_FLAG 0x8000 /* forces 32-bit SB access */
/*
* Address map within the SDIO function address space (128K).
*
* Start End Description
* ------- ------- ------------------------------------------
* 0x00000 0x0ffff selected backplane address window (64K)
* 0x10000 0x1ffff backplane control registers (max 64K)
*
* The current address window is configured by writing to registers
* SBADDRLOW, SBADDRMID and SBADDRHIGH.
*
* In order to access the contents of a 32-bit Silicon Backplane address
* the backplane address window must be first loaded with the highest
* 16 bits of the target address. Then, an access must be done to the
* SDIO function address space using the lower 15 bits of the address.
* Bit 15 of the address must be set when doing 32 bit accesses.
*
* 10987654321098765432109876543210
* WWWWWWWWWWWWWWWWW SB Address Window
* OOOOOOOOOOOOOOOO Offset within SB Address Window
* a 32-bit access flag
*/
/*
* SSB I/O via SDIO.
*
* NOTE: SDIO address @addr is 17 bits long (SDIO address space is 128K).
*/
static inline struct device *ssb_sdio_dev(struct ssb_bus *bus)
{
return &bus->host_sdio->dev;
}
/* host claimed */
static int ssb_sdio_writeb(struct ssb_bus *bus, unsigned int addr, u8 val)
{
int error = 0;
sdio_writeb(bus->host_sdio, val, addr, &error);
if (unlikely(error)) {
dev_dbg(ssb_sdio_dev(bus), "%08X <- %02x, error %d\n",
addr, val, error);
}
return error;
}
#if 0
static u8 ssb_sdio_readb(struct ssb_bus *bus, unsigned int addr)
{
u8 val;
int error = 0;
val = sdio_readb(bus->host_sdio, addr, &error);
if (unlikely(error)) {
dev_dbg(ssb_sdio_dev(bus), "%08X -> %02x, error %d\n",
addr, val, error);
}
return val;
}
#endif
/* host claimed */
static int ssb_sdio_set_sbaddr_window(struct ssb_bus *bus, u32 address)
{
int error;
error = ssb_sdio_writeb(bus, SBSDIO_FUNC1_SBADDRLOW,
(address >> 8) & SBSDIO_SBADDRLOW_MASK);
if (error)
goto out;
error = ssb_sdio_writeb(bus, SBSDIO_FUNC1_SBADDRMID,
(address >> 16) & SBSDIO_SBADDRMID_MASK);
if (error)
goto out;
error = ssb_sdio_writeb(bus, SBSDIO_FUNC1_SBADDRHIGH,
(address >> 24) & SBSDIO_SBADDRHIGH_MASK);
if (error)
goto out;
bus->sdio_sbaddr = address;
out:
if (error) {
dev_dbg(ssb_sdio_dev(bus), "failed to set address window"
" to 0x%08x, error %d\n", address, error);
}
return error;
}
/* for enumeration use only */
u32 ssb_sdio_scan_read32(struct ssb_bus *bus, u16 offset)
{
u32 val;
int error;
sdio_claim_host(bus->host_sdio);
val = sdio_readl(bus->host_sdio, offset, &error);
sdio_release_host(bus->host_sdio);
if (unlikely(error)) {
dev_dbg(ssb_sdio_dev(bus), "%04X:%04X > %08x, error %d\n",
bus->sdio_sbaddr >> 16, offset, val, error);
}
return val;
}
/* for enumeration use only */
int ssb_sdio_scan_switch_coreidx(struct ssb_bus *bus, u8 coreidx)
{
u32 sbaddr;
int error;
sbaddr = (coreidx * SSB_CORE_SIZE) + SSB_ENUM_BASE;
sdio_claim_host(bus->host_sdio);
error = ssb_sdio_set_sbaddr_window(bus, sbaddr);
sdio_release_host(bus->host_sdio);
if (error) {
dev_err(ssb_sdio_dev(bus), "failed to switch to core %u,"
" error %d\n", coreidx, error);
goto out;
}
out:
return error;
}
/* host must be already claimed */
int ssb_sdio_switch_core(struct ssb_bus *bus, struct ssb_device *dev)
{
u8 coreidx = dev->core_index;
u32 sbaddr;
int error = 0;
sbaddr = (coreidx * SSB_CORE_SIZE) + SSB_ENUM_BASE;
if (unlikely(bus->sdio_sbaddr != sbaddr)) {
#if SSB_VERBOSE_SDIOCORESWITCH_DEBUG
dev_info(ssb_sdio_dev(bus),
"switching to %s core, index %d\n",
ssb_core_name(dev->id.coreid), coreidx);
#endif
error = ssb_sdio_set_sbaddr_window(bus, sbaddr);
if (error) {
dev_dbg(ssb_sdio_dev(bus), "failed to switch to"
" core %u, error %d\n", coreidx, error);
goto out;
}
bus->mapped_device = dev;
}
out:
return error;
}
static u8 ssb_sdio_read8(struct ssb_device *dev, u16 offset)
{
struct ssb_bus *bus = dev->bus;
u8 val = 0xff;
int error = 0;
sdio_claim_host(bus->host_sdio);
if (unlikely(ssb_sdio_switch_core(bus, dev)))
goto out;
offset |= bus->sdio_sbaddr & 0xffff;
offset &= SBSDIO_SB_OFT_ADDR_MASK;
val = sdio_readb(bus->host_sdio, offset, &error);
if (error) {
dev_dbg(ssb_sdio_dev(bus), "%04X:%04X > %02x, error %d\n",
bus->sdio_sbaddr >> 16, offset, val, error);
}
out:
sdio_release_host(bus->host_sdio);
return val;
}
static u16 ssb_sdio_read16(struct ssb_device *dev, u16 offset)
{
struct ssb_bus *bus = dev->bus;
u16 val = 0xffff;
int error = 0;
sdio_claim_host(bus->host_sdio);
if (unlikely(ssb_sdio_switch_core(bus, dev)))
goto out;
offset |= bus->sdio_sbaddr & 0xffff;
offset &= SBSDIO_SB_OFT_ADDR_MASK;
val = sdio_readw(bus->host_sdio, offset, &error);
if (error) {
dev_dbg(ssb_sdio_dev(bus), "%04X:%04X > %04x, error %d\n",
bus->sdio_sbaddr >> 16, offset, val, error);
}
out:
sdio_release_host(bus->host_sdio);
return val;
}
static u32 ssb_sdio_read32(struct ssb_device *dev, u16 offset)
{
struct ssb_bus *bus = dev->bus;
u32 val = 0xffffffff;
int error = 0;
sdio_claim_host(bus->host_sdio);
if (unlikely(ssb_sdio_switch_core(bus, dev)))
goto out;
offset |= bus->sdio_sbaddr & 0xffff;
offset &= SBSDIO_SB_OFT_ADDR_MASK;
offset |= SBSDIO_SB_ACCESS_2_4B_FLAG; /* 32 bit data access */
val = sdio_readl(bus->host_sdio, offset, &error);
if (error) {
dev_dbg(ssb_sdio_dev(bus), "%04X:%04X > %08x, error %d\n",
bus->sdio_sbaddr >> 16, offset, val, error);
}
out:
sdio_release_host(bus->host_sdio);
return val;
}
#ifdef CONFIG_SSB_BLOCKIO
static void ssb_sdio_block_read(struct ssb_device *dev, void *buffer,
size_t count, u16 offset, u8 reg_width)
{
size_t saved_count = count;
struct ssb_bus *bus = dev->bus;
int error = 0;
sdio_claim_host(bus->host_sdio);
if (unlikely(ssb_sdio_switch_core(bus, dev))) {
error = -EIO;
memset(buffer, 0xff, count);
goto err_out;
}
offset |= bus->sdio_sbaddr & 0xffff;
offset &= SBSDIO_SB_OFT_ADDR_MASK;
switch (reg_width) {
case sizeof(u8): {
error = sdio_readsb(bus->host_sdio, buffer, offset, count);
break;
}
case sizeof(u16): {
SSB_WARN_ON(count & 1);
error = sdio_readsb(bus->host_sdio, buffer, offset, count);
break;
}
case sizeof(u32): {
SSB_WARN_ON(count & 3);
offset |= SBSDIO_SB_ACCESS_2_4B_FLAG; /* 32 bit data access */
error = sdio_readsb(bus->host_sdio, buffer, offset, count);
break;
}
default:
SSB_WARN_ON(1);
}
if (!error)
goto out;
err_out:
dev_dbg(ssb_sdio_dev(bus), "%04X:%04X (width=%u, len=%zu), error %d\n",
bus->sdio_sbaddr >> 16, offset, reg_width, saved_count, error);
out:
sdio_release_host(bus->host_sdio);
}
#endif /* CONFIG_SSB_BLOCKIO */
static void ssb_sdio_write8(struct ssb_device *dev, u16 offset, u8 val)
{
struct ssb_bus *bus = dev->bus;
int error = 0;
sdio_claim_host(bus->host_sdio);
if (unlikely(ssb_sdio_switch_core(bus, dev)))
goto out;
offset |= bus->sdio_sbaddr & 0xffff;
offset &= SBSDIO_SB_OFT_ADDR_MASK;
sdio_writeb(bus->host_sdio, val, offset, &error);
if (error) {
dev_dbg(ssb_sdio_dev(bus), "%04X:%04X < %02x, error %d\n",
bus->sdio_sbaddr >> 16, offset, val, error);
}
out:
sdio_release_host(bus->host_sdio);
}
static void ssb_sdio_write16(struct ssb_device *dev, u16 offset, u16 val)
{
struct ssb_bus *bus = dev->bus;
int error = 0;
sdio_claim_host(bus->host_sdio);
if (unlikely(ssb_sdio_switch_core(bus, dev)))
goto out;
offset |= bus->sdio_sbaddr & 0xffff;
offset &= SBSDIO_SB_OFT_ADDR_MASK;
sdio_writew(bus->host_sdio, val, offset, &error);
if (error) {
dev_dbg(ssb_sdio_dev(bus), "%04X:%04X < %04x, error %d\n",
bus->sdio_sbaddr >> 16, offset, val, error);
}
out:
sdio_release_host(bus->host_sdio);
}
static void ssb_sdio_write32(struct ssb_device *dev, u16 offset, u32 val)
{
struct ssb_bus *bus = dev->bus;
int error = 0;
sdio_claim_host(bus->host_sdio);
if (unlikely(ssb_sdio_switch_core(bus, dev)))
goto out;
offset |= bus->sdio_sbaddr & 0xffff;
offset &= SBSDIO_SB_OFT_ADDR_MASK;
offset |= SBSDIO_SB_ACCESS_2_4B_FLAG; /* 32 bit data access */
sdio_writel(bus->host_sdio, val, offset, &error);
if (error) {
dev_dbg(ssb_sdio_dev(bus), "%04X:%04X < %08x, error %d\n",
bus->sdio_sbaddr >> 16, offset, val, error);
}
if (bus->quirks & SSB_QUIRK_SDIO_READ_AFTER_WRITE32)
sdio_readl(bus->host_sdio, 0, &error);
out:
sdio_release_host(bus->host_sdio);
}
#ifdef CONFIG_SSB_BLOCKIO
static void ssb_sdio_block_write(struct ssb_device *dev, const void *buffer,
size_t count, u16 offset, u8 reg_width)
{
size_t saved_count = count;
struct ssb_bus *bus = dev->bus;
int error = 0;
sdio_claim_host(bus->host_sdio);
if (unlikely(ssb_sdio_switch_core(bus, dev))) {
error = -EIO;
memset((void *)buffer, 0xff, count);
goto err_out;
}
offset |= bus->sdio_sbaddr & 0xffff;
offset &= SBSDIO_SB_OFT_ADDR_MASK;
switch (reg_width) {
case sizeof(u8):
error = sdio_writesb(bus->host_sdio, offset,
(void *)buffer, count);
break;
case sizeof(u16):
SSB_WARN_ON(count & 1);
error = sdio_writesb(bus->host_sdio, offset,
(void *)buffer, count);
break;
case sizeof(u32):
SSB_WARN_ON(count & 3);
offset |= SBSDIO_SB_ACCESS_2_4B_FLAG; /* 32 bit data access */
error = sdio_writesb(bus->host_sdio, offset,
(void *)buffer, count);
break;
default:
SSB_WARN_ON(1);
}
if (!error)
goto out;
err_out:
dev_dbg(ssb_sdio_dev(bus), "%04X:%04X (width=%u, len=%zu), error %d\n",
bus->sdio_sbaddr >> 16, offset, reg_width, saved_count, error);
out:
sdio_release_host(bus->host_sdio);
}
#endif /* CONFIG_SSB_BLOCKIO */
/* Not "static", as it's used in main.c */
const struct ssb_bus_ops ssb_sdio_ops = {
.read8 = ssb_sdio_read8,
.read16 = ssb_sdio_read16,
.read32 = ssb_sdio_read32,
.write8 = ssb_sdio_write8,
.write16 = ssb_sdio_write16,
.write32 = ssb_sdio_write32,
#ifdef CONFIG_SSB_BLOCKIO
.block_read = ssb_sdio_block_read,
.block_write = ssb_sdio_block_write,
#endif
};
#define GOTO_ERROR_ON(condition, description) do { \
if (unlikely(condition)) { \
error_description = description; \
goto error; \
} \
} while (0)
int ssb_sdio_get_invariants(struct ssb_bus *bus,
struct ssb_init_invariants *iv)
{
struct ssb_sprom *sprom = &iv->sprom;
struct ssb_boardinfo *bi = &iv->boardinfo;
const char *error_description = "none";
struct sdio_func_tuple *tuple;
void *mac;
memset(sprom, 0xFF, sizeof(*sprom));
sprom->boardflags_lo = 0;
sprom->boardflags_hi = 0;
tuple = bus->host_sdio->tuples;
while (tuple) {
switch (tuple->code) {
case 0x22: /* extended function */
switch (tuple->data[0]) {
case CISTPL_FUNCE_LAN_NODE_ID:
GOTO_ERROR_ON((tuple->size != 7) &&
(tuple->data[1] != 6),
"mac tpl size");
/* fetch the MAC address. */
mac = tuple->data + 2;
memcpy(sprom->il0mac, mac, ETH_ALEN);
memcpy(sprom->et1mac, mac, ETH_ALEN);
break;
default:
break;
}
break;
case 0x80: /* vendor specific tuple */
switch (tuple->data[0]) {
case SSB_SDIO_CIS_SROMREV:
GOTO_ERROR_ON(tuple->size != 2,
"sromrev tpl size");
sprom->revision = tuple->data[1];
break;
case SSB_SDIO_CIS_ID:
GOTO_ERROR_ON((tuple->size != 5) &&
(tuple->size != 7),
"id tpl size");
bi->vendor = tuple->data[1] |
(tuple->data[2]<<8);
break;
case SSB_SDIO_CIS_BOARDREV:
GOTO_ERROR_ON(tuple->size != 2,
"boardrev tpl size");
sprom->board_rev = tuple->data[1];
break;
case SSB_SDIO_CIS_PA:
GOTO_ERROR_ON((tuple->size != 9) &&
(tuple->size != 10),
"pa tpl size");
sprom->pa0b0 = tuple->data[1] |
((u16)tuple->data[2] << 8);
sprom->pa0b1 = tuple->data[3] |
((u16)tuple->data[4] << 8);
sprom->pa0b2 = tuple->data[5] |
((u16)tuple->data[6] << 8);
sprom->itssi_a = tuple->data[7];
sprom->itssi_bg = tuple->data[7];
sprom->maxpwr_a = tuple->data[8];
sprom->maxpwr_bg = tuple->data[8];
break;
case SSB_SDIO_CIS_OEMNAME:
/* Not present */
break;
case SSB_SDIO_CIS_CCODE:
GOTO_ERROR_ON(tuple->size != 2,
"ccode tpl size");
sprom->country_code = tuple->data[1];
break;
case SSB_SDIO_CIS_ANTENNA:
GOTO_ERROR_ON(tuple->size != 2,
"ant tpl size");
sprom->ant_available_a = tuple->data[1];
sprom->ant_available_bg = tuple->data[1];
break;
case SSB_SDIO_CIS_ANTGAIN:
GOTO_ERROR_ON(tuple->size != 2,
"antg tpl size");
sprom->antenna_gain.ghz24.a0 = tuple->data[1];
sprom->antenna_gain.ghz24.a1 = tuple->data[1];
sprom->antenna_gain.ghz24.a2 = tuple->data[1];
sprom->antenna_gain.ghz24.a3 = tuple->data[1];
sprom->antenna_gain.ghz5.a0 = tuple->data[1];
sprom->antenna_gain.ghz5.a1 = tuple->data[1];
sprom->antenna_gain.ghz5.a2 = tuple->data[1];
sprom->antenna_gain.ghz5.a3 = tuple->data[1];
break;
case SSB_SDIO_CIS_BFLAGS:
GOTO_ERROR_ON((tuple->size != 3) &&
(tuple->size != 5),
"bfl tpl size");
sprom->boardflags_lo = tuple->data[1] |
((u16)tuple->data[2] << 8);
break;
case SSB_SDIO_CIS_LEDS:
GOTO_ERROR_ON(tuple->size != 5,
"leds tpl size");
sprom->gpio0 = tuple->data[1];
sprom->gpio1 = tuple->data[2];
sprom->gpio2 = tuple->data[3];
sprom->gpio3 = tuple->data[4];
break;
default:
break;
}
break;
default:
break;
}
tuple = tuple->next;
}
return 0;
error:
dev_err(ssb_sdio_dev(bus), "failed to fetch device invariants: %s\n",
error_description);
return -ENODEV;
}
void ssb_sdio_exit(struct ssb_bus *bus)
{
if (bus->bustype != SSB_BUSTYPE_SDIO)
return;
/* Nothing to do here. */
}
int ssb_sdio_init(struct ssb_bus *bus)
{
if (bus->bustype != SSB_BUSTYPE_SDIO)
return 0;
bus->sdio_sbaddr = ~0;
return 0;
}
| gpl-2.0 |
friedrich420/S4-AEL-GPE-LOLLIPOP | drivers/hwmon/ad7414.c | 4940 | 7060 | /*
* An hwmon driver for the Analog Devices AD7414
*
* Copyright 2006 Stefan Roese <sr at denx.de>, DENX Software Engineering
*
* Copyright (c) 2008 PIKA Technologies
* Sean MacLennan <smaclennan@pikatech.com>
*
* Copyright (c) 2008 Spansion Inc.
* Frank Edelhaeuser <frank.edelhaeuser at spansion.com>
* (converted to "new style" I2C driver model, removed checkpatch.pl warnings)
*
* Based on ad7418.c
* Copyright 2006 Tower Technologies, Alessandro Zummo <a.zummo at towertech.it>
*
* 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/module.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>
#include <linux/slab.h>
/* AD7414 registers */
#define AD7414_REG_TEMP 0x00
#define AD7414_REG_CONF 0x01
#define AD7414_REG_T_HIGH 0x02
#define AD7414_REG_T_LOW 0x03
static u8 AD7414_REG_LIMIT[] = { AD7414_REG_T_HIGH, AD7414_REG_T_LOW };
struct ad7414_data {
struct device *hwmon_dev;
struct mutex lock; /* atomic read data updates */
char valid; /* !=0 if following fields are valid */
unsigned long next_update; /* In jiffies */
s16 temp_input; /* Register values */
s8 temps[ARRAY_SIZE(AD7414_REG_LIMIT)];
};
/* REG: (0.25C/bit, two's complement) << 6 */
static inline int ad7414_temp_from_reg(s16 reg)
{
/*
* use integer division instead of equivalent right shift to
* guarantee arithmetic shift and preserve the sign
*/
return ((int)reg / 64) * 250;
}
static inline int ad7414_read(struct i2c_client *client, u8 reg)
{
if (reg == AD7414_REG_TEMP)
return i2c_smbus_read_word_swapped(client, reg);
else
return i2c_smbus_read_byte_data(client, reg);
}
static inline int ad7414_write(struct i2c_client *client, u8 reg, u8 value)
{
return i2c_smbus_write_byte_data(client, reg, value);
}
static struct ad7414_data *ad7414_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct ad7414_data *data = i2c_get_clientdata(client);
mutex_lock(&data->lock);
if (time_after(jiffies, data->next_update) || !data->valid) {
int value, i;
dev_dbg(&client->dev, "starting ad7414 update\n");
value = ad7414_read(client, AD7414_REG_TEMP);
if (value < 0)
dev_dbg(&client->dev, "AD7414_REG_TEMP err %d\n",
value);
else
data->temp_input = value;
for (i = 0; i < ARRAY_SIZE(AD7414_REG_LIMIT); ++i) {
value = ad7414_read(client, AD7414_REG_LIMIT[i]);
if (value < 0)
dev_dbg(&client->dev, "AD7414 reg %d err %d\n",
AD7414_REG_LIMIT[i], value);
else
data->temps[i] = value;
}
data->next_update = jiffies + HZ + HZ / 2;
data->valid = 1;
}
mutex_unlock(&data->lock);
return data;
}
static ssize_t show_temp_input(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ad7414_data *data = ad7414_update_device(dev);
return sprintf(buf, "%d\n", ad7414_temp_from_reg(data->temp_input));
}
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp_input, NULL, 0);
static ssize_t show_max_min(struct device *dev, struct device_attribute *attr,
char *buf)
{
int index = to_sensor_dev_attr(attr)->index;
struct ad7414_data *data = ad7414_update_device(dev);
return sprintf(buf, "%d\n", data->temps[index] * 1000);
}
static ssize_t set_max_min(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct ad7414_data *data = i2c_get_clientdata(client);
int index = to_sensor_dev_attr(attr)->index;
u8 reg = AD7414_REG_LIMIT[index];
long temp;
int ret = kstrtol(buf, 10, &temp);
if (ret < 0)
return ret;
temp = SENSORS_LIMIT(temp, -40000, 85000);
temp = (temp + (temp < 0 ? -500 : 500)) / 1000;
mutex_lock(&data->lock);
data->temps[index] = temp;
ad7414_write(client, reg, temp);
mutex_unlock(&data->lock);
return count;
}
static SENSOR_DEVICE_ATTR(temp1_max, S_IWUSR | S_IRUGO,
show_max_min, set_max_min, 0);
static SENSOR_DEVICE_ATTR(temp1_min, S_IWUSR | S_IRUGO,
show_max_min, set_max_min, 1);
static ssize_t show_alarm(struct device *dev, struct device_attribute *attr,
char *buf)
{
int bitnr = to_sensor_dev_attr(attr)->index;
struct ad7414_data *data = ad7414_update_device(dev);
int value = (data->temp_input >> bitnr) & 1;
return sprintf(buf, "%d\n", value);
}
static SENSOR_DEVICE_ATTR(temp1_min_alarm, S_IRUGO, show_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_alarm, NULL, 4);
static struct attribute *ad7414_attributes[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_min_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group ad7414_group = {
.attrs = ad7414_attributes,
};
static int ad7414_probe(struct i2c_client *client,
const struct i2c_device_id *dev_id)
{
struct ad7414_data *data;
int conf;
int err;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_READ_WORD_DATA)) {
err = -EOPNOTSUPP;
goto exit;
}
data = kzalloc(sizeof(struct ad7414_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto exit;
}
i2c_set_clientdata(client, data);
mutex_init(&data->lock);
dev_info(&client->dev, "chip found\n");
/* Make sure the chip is powered up. */
conf = i2c_smbus_read_byte_data(client, AD7414_REG_CONF);
if (conf < 0)
dev_warn(&client->dev,
"ad7414_probe unable to read config register.\n");
else {
conf &= ~(1 << 7);
i2c_smbus_write_byte_data(client, AD7414_REG_CONF, conf);
}
/* Register sysfs hooks */
err = sysfs_create_group(&client->dev.kobj, &ad7414_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);
goto exit_remove;
}
return 0;
exit_remove:
sysfs_remove_group(&client->dev.kobj, &ad7414_group);
exit_free:
kfree(data);
exit:
return err;
}
static int __devexit ad7414_remove(struct i2c_client *client)
{
struct ad7414_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &ad7414_group);
kfree(data);
return 0;
}
static const struct i2c_device_id ad7414_id[] = {
{ "ad7414", 0 },
{}
};
MODULE_DEVICE_TABLE(i2c, ad7414_id);
static struct i2c_driver ad7414_driver = {
.driver = {
.name = "ad7414",
},
.probe = ad7414_probe,
.remove = __devexit_p(ad7414_remove),
.id_table = ad7414_id,
};
module_i2c_driver(ad7414_driver);
MODULE_AUTHOR("Stefan Roese <sr at denx.de>, "
"Frank Edelhaeuser <frank.edelhaeuser at spansion.com>");
MODULE_DESCRIPTION("AD7414 driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Fusion-Devices/android_kernel_htc_msm8974 | drivers/staging/bcm/nvm.c | 4940 | 166887 | #include "headers.h"
#define DWORD unsigned int
static INT BcmDoChipSelect(PMINI_ADAPTER Adapter, UINT offset);
static INT BcmGetActiveDSD(PMINI_ADAPTER Adapter);
static INT BcmGetActiveISO(PMINI_ADAPTER Adapter);
static UINT BcmGetEEPROMSize(PMINI_ADAPTER Adapter);
static INT BcmGetFlashCSInfo(PMINI_ADAPTER Adapter);
static UINT BcmGetFlashSectorSize(PMINI_ADAPTER Adapter, UINT FlashSectorSizeSig, UINT FlashSectorSize);
static VOID BcmValidateNvmType(PMINI_ADAPTER Adapter);
static INT BcmGetNvmSize(PMINI_ADAPTER Adapter);
static UINT BcmGetFlashSize(PMINI_ADAPTER Adapter);
static NVM_TYPE BcmGetNvmType(PMINI_ADAPTER Adapter);
static INT BcmGetSectionValEndOffset(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlash2xSectionVal);
static B_UINT8 IsOffsetWritable(PMINI_ADAPTER Adapter, UINT uiOffset);
static INT IsSectionWritable(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL Section);
static INT IsSectionExistInVendorInfo(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL section);
static INT ReadDSDPriority(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL dsd);
static INT ReadDSDSignature(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL dsd);
static INT ReadISOPriority(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL iso);
static INT ReadISOSignature(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL iso);
static INT CorruptDSDSig(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlash2xSectionVal);
static INT CorruptISOSig(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlash2xSectionVal);
static INT SaveHeaderIfPresent(PMINI_ADAPTER Adapter, PUCHAR pBuff, UINT uiSectAlignAddr);
static INT WriteToFlashWithoutSectorErase(PMINI_ADAPTER Adapter, PUINT pBuff,
FLASH2X_SECTION_VAL eFlash2xSectionVal,
UINT uiOffset, UINT uiNumBytes);
static FLASH2X_SECTION_VAL getHighestPriDSD(PMINI_ADAPTER Adapter);
static FLASH2X_SECTION_VAL getHighestPriISO(PMINI_ADAPTER Adapter);
static INT BeceemFlashBulkRead(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
UINT uiOffset,
UINT uiNumBytes);
static INT BeceemFlashBulkWrite(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
UINT uiOffset,
UINT uiNumBytes,
BOOLEAN bVerify);
static INT GetFlashBaseAddr(PMINI_ADAPTER Adapter);
static INT ReadBeceemEEPROMBulk(PMINI_ADAPTER Adapter,UINT dwAddress, UINT *pdwData, UINT dwNumData);
// Procedure: ReadEEPROMStatusRegister
//
// Description: Reads the standard EEPROM Status Register.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static UCHAR ReadEEPROMStatusRegister( PMINI_ADAPTER Adapter )
{
UCHAR uiData = 0;
DWORD dwRetries = MAX_EEPROM_RETRIES*RETRIES_PER_DELAY;
UINT uiStatus = 0;
UINT value = 0;
UINT value1 = 0;
/* Read the EEPROM status register */
value = EEPROM_READ_STATUS_REGISTER ;
wrmalt( Adapter, EEPROM_CMDQ_SPI_REG, &value, sizeof(value));
while ( dwRetries != 0 )
{
value=0;
uiStatus = 0 ;
rdmalt(Adapter, EEPROM_SPI_Q_STATUS1_REG, &uiStatus, sizeof(uiStatus));
if(Adapter->device_removed == TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Modem has got removed hence exiting....");
break;
}
/* Wait for Avail bit to be set. */
if ( ( uiStatus & EEPROM_READ_DATA_AVAIL) != 0 )
{
/* Clear the Avail/Full bits - which ever is set. */
value = uiStatus & (EEPROM_READ_DATA_AVAIL | EEPROM_READ_DATA_FULL);
wrmalt( Adapter, EEPROM_SPI_Q_STATUS1_REG, &value, sizeof(value));
value =0;
rdmalt(Adapter, EEPROM_READ_DATAQ_REG, &value, sizeof(value));
uiData = (UCHAR)value;
break;
}
dwRetries-- ;
if ( dwRetries == 0 )
{
rdmalt(Adapter, EEPROM_SPI_Q_STATUS1_REG, &value, sizeof(value));
rdmalt(Adapter, EEPROM_SPI_Q_STATUS_REG, &value1, sizeof(value1));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"0x3004 = %x 0x3008 = %x, retries = %d failed.\n",value,value1, MAX_EEPROM_RETRIES*RETRIES_PER_DELAY);
return uiData;
}
if( !(dwRetries%RETRIES_PER_DELAY) )
msleep(1);
uiStatus = 0 ;
}
return uiData;
} /* ReadEEPROMStatusRegister */
//-----------------------------------------------------------------------------
// Procedure: ReadBeceemEEPROMBulk
//
// Description: This routine reads 16Byte data from EEPROM
//
// Arguments:
// Adapter - ptr to Adapter object instance
// dwAddress - EEPROM Offset to read the data from.
// pdwData - Pointer to double word where data needs to be stored in. // dwNumWords - Number of words. Valid values are 4 ONLY.
//
// Returns:
// OSAL_STATUS_CODE:
//-----------------------------------------------------------------------------
INT ReadBeceemEEPROMBulk( PMINI_ADAPTER Adapter,
DWORD dwAddress,
DWORD *pdwData,
DWORD dwNumWords
)
{
DWORD dwIndex = 0;
DWORD dwRetries = MAX_EEPROM_RETRIES*RETRIES_PER_DELAY;
UINT uiStatus = 0;
UINT value= 0;
UINT value1 = 0;
UCHAR *pvalue;
/* Flush the read and cmd queue. */
value=( EEPROM_READ_QUEUE_FLUSH | EEPROM_CMD_QUEUE_FLUSH );
wrmalt( Adapter, SPI_FLUSH_REG, &value, sizeof(value) );
value=0;
wrmalt( Adapter, SPI_FLUSH_REG, &value, sizeof(value));
/* Clear the Avail/Full bits. */
value=( EEPROM_READ_DATA_AVAIL | EEPROM_READ_DATA_FULL );
wrmalt( Adapter, EEPROM_SPI_Q_STATUS1_REG,&value, sizeof(value));
value= dwAddress | ( (dwNumWords == 4) ? EEPROM_16_BYTE_PAGE_READ : EEPROM_4_BYTE_PAGE_READ );
wrmalt( Adapter, EEPROM_CMDQ_SPI_REG, &value, sizeof(value));
while ( dwRetries != 0 )
{
uiStatus = 0;
rdmalt(Adapter, EEPROM_SPI_Q_STATUS1_REG, &uiStatus, sizeof(uiStatus));
if(Adapter->device_removed == TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Modem has got Removed.hence exiting from loop...");
return -ENODEV;
}
/* If we are reading 16 bytes we want to be sure that the queue
* is full before we read. In the other cases we are ok if the
* queue has data available */
if ( dwNumWords == 4 )
{
if ( ( uiStatus & EEPROM_READ_DATA_FULL ) != 0 )
{
/* Clear the Avail/Full bits - which ever is set. */
value = ( uiStatus & (EEPROM_READ_DATA_AVAIL | EEPROM_READ_DATA_FULL) ) ;
wrmalt( Adapter, EEPROM_SPI_Q_STATUS1_REG,&value, sizeof(value));
break;
}
}
else if ( dwNumWords == 1 )
{
if ( ( uiStatus & EEPROM_READ_DATA_AVAIL ) != 0 )
{
/* We just got Avail and we have to read 32bits so we
* need this sleep for Cardbus kind of devices. */
if (Adapter->chip_id == 0xBECE0210 )
udelay(800);
/* Clear the Avail/Full bits - which ever is set. */
value=( uiStatus & (EEPROM_READ_DATA_AVAIL | EEPROM_READ_DATA_FULL) );
wrmalt( Adapter, EEPROM_SPI_Q_STATUS1_REG,&value, sizeof(value));
break;
}
}
uiStatus = 0;
dwRetries--;
if(dwRetries == 0)
{
value=0;
value1=0;
rdmalt(Adapter, EEPROM_SPI_Q_STATUS1_REG, &value, sizeof(value));
rdmalt(Adapter, EEPROM_SPI_Q_STATUS_REG, &value1, sizeof(value1));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "dwNumWords %d 0x3004 = %x 0x3008 = %x retries = %d failed.\n", dwNumWords, value, value1, MAX_EEPROM_RETRIES*RETRIES_PER_DELAY);
return STATUS_FAILURE;
}
if( !(dwRetries%RETRIES_PER_DELAY) )
msleep(1);
}
for ( dwIndex = 0; dwIndex < dwNumWords ; dwIndex++ )
{
/* We get only a byte at a time - from LSB to MSB. We shift it into an integer. */
pvalue = (PUCHAR)(pdwData + dwIndex);
value =0;
rdmalt(Adapter, EEPROM_READ_DATAQ_REG, &value, sizeof(value));
pvalue[0] = value;
value = 0;
rdmalt(Adapter, EEPROM_READ_DATAQ_REG, &value, sizeof(value));
pvalue[1] = value;
value =0;
rdmalt(Adapter, EEPROM_READ_DATAQ_REG, &value, sizeof(value));
pvalue[2] = value;
value = 0;
rdmalt(Adapter, EEPROM_READ_DATAQ_REG, &value, sizeof(value));
pvalue[3] = value;
}
return STATUS_SUCCESS;
} /* ReadBeceemEEPROMBulk() */
//-----------------------------------------------------------------------------
// Procedure: ReadBeceemEEPROM
//
// Description: This routine reads 4 data from EEPROM. It uses 1 or 2 page
// reads to do this operation.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// uiOffset - EEPROM Offset to read the data from.
// pBuffer - Pointer to word where data needs to be stored in.
//
// Returns:
// OSAL_STATUS_CODE:
//-----------------------------------------------------------------------------
INT ReadBeceemEEPROM( PMINI_ADAPTER Adapter,
DWORD uiOffset,
DWORD *pBuffer
)
{
UINT uiData[8] = {0};
UINT uiByteOffset = 0;
UINT uiTempOffset = 0;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL," ====> ");
uiTempOffset = uiOffset - (uiOffset % MAX_RW_SIZE);
uiByteOffset = uiOffset - uiTempOffset;
ReadBeceemEEPROMBulk(Adapter, uiTempOffset, (PUINT)&uiData[0], 4);
/* A word can overlap at most over 2 pages. In that case we read the
* next page too. */
if ( uiByteOffset > 12 )
{
ReadBeceemEEPROMBulk(Adapter, uiTempOffset + MAX_RW_SIZE, (PUINT)&uiData[4], 4);
}
memcpy( (PUCHAR) pBuffer, ( ((PUCHAR)&uiData[0]) + uiByteOffset ), 4);
return STATUS_SUCCESS;
} /* ReadBeceemEEPROM() */
INT ReadMacAddressFromNVM(PMINI_ADAPTER Adapter)
{
INT Status;
unsigned char puMacAddr[6];
Status = BeceemNVMRead(Adapter,
(PUINT)&puMacAddr[0],
INIT_PARAMS_1_MACADDRESS_ADDRESS,
MAC_ADDRESS_SIZE);
if(Status == STATUS_SUCCESS)
memcpy(Adapter->dev->dev_addr, puMacAddr, MAC_ADDRESS_SIZE);
return Status;
}
//-----------------------------------------------------------------------------
// Procedure: BeceemEEPROMBulkRead
//
// Description: Reads the EEPROM and returns the Data.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// pBuffer - Buffer to store the data read from EEPROM
// uiOffset - Offset of EEPROM from where data should be read
// uiNumBytes - Number of bytes to be read from the EEPROM.
//
// Returns:
// OSAL_STATUS_SUCCESS - if EEPROM read is successful.
// <FAILURE> - if failed.
//-----------------------------------------------------------------------------
INT BeceemEEPROMBulkRead(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
UINT uiOffset,
UINT uiNumBytes)
{
UINT uiData[4] = {0};
//UINT uiAddress = 0;
UINT uiBytesRemaining = uiNumBytes;
UINT uiIndex = 0;
UINT uiTempOffset = 0;
UINT uiExtraBytes = 0;
UINT uiFailureRetries = 0;
PUCHAR pcBuff = (PUCHAR)pBuffer;
if(uiOffset%MAX_RW_SIZE&& uiBytesRemaining)
{
uiTempOffset = uiOffset - (uiOffset%MAX_RW_SIZE);
uiExtraBytes = uiOffset-uiTempOffset;
ReadBeceemEEPROMBulk(Adapter,uiTempOffset,(PUINT)&uiData[0],4);
if(uiBytesRemaining >= (MAX_RW_SIZE - uiExtraBytes))
{
memcpy(pBuffer,(((PUCHAR)&uiData[0])+uiExtraBytes),MAX_RW_SIZE - uiExtraBytes);
uiBytesRemaining -= (MAX_RW_SIZE - uiExtraBytes);
uiIndex += (MAX_RW_SIZE - uiExtraBytes);
uiOffset += (MAX_RW_SIZE - uiExtraBytes);
}
else
{
memcpy(pBuffer,(((PUCHAR)&uiData[0])+uiExtraBytes),uiBytesRemaining);
uiIndex += uiBytesRemaining;
uiOffset += uiBytesRemaining;
uiBytesRemaining = 0;
}
}
while(uiBytesRemaining && uiFailureRetries != 128)
{
if(Adapter->device_removed )
{
return -1;
}
if(uiBytesRemaining >= MAX_RW_SIZE)
{
/* For the requests more than or equal to 16 bytes, use bulk
* read function to make the access faster.
* We read 4 Dwords of data */
if(0 == ReadBeceemEEPROMBulk(Adapter,uiOffset,&uiData[0],4))
{
memcpy(pcBuff+uiIndex,&uiData[0],MAX_RW_SIZE);
uiOffset += MAX_RW_SIZE;
uiBytesRemaining -= MAX_RW_SIZE;
uiIndex += MAX_RW_SIZE;
}
else
{
uiFailureRetries++;
mdelay(3);//sleep for a while before retry...
}
}
else if(uiBytesRemaining >= 4)
{
if(0 == ReadBeceemEEPROM(Adapter,uiOffset,&uiData[0]))
{
memcpy(pcBuff+uiIndex,&uiData[0],4);
uiOffset += 4;
uiBytesRemaining -= 4;
uiIndex +=4;
}
else
{
uiFailureRetries++;
mdelay(3);//sleep for a while before retry...
}
}
else
{ // Handle the reads less than 4 bytes...
PUCHAR pCharBuff = (PUCHAR)pBuffer;
pCharBuff += uiIndex;
if(0 == ReadBeceemEEPROM(Adapter,uiOffset,&uiData[0]))
{
memcpy(pCharBuff,&uiData[0],uiBytesRemaining);//copy only bytes requested.
uiBytesRemaining = 0;
}
else
{
uiFailureRetries++;
mdelay(3);//sleep for a while before retry...
}
}
}
return 0;
}
//-----------------------------------------------------------------------------
// Procedure: BeceemFlashBulkRead
//
// Description: Reads the FLASH and returns the Data.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// pBuffer - Buffer to store the data read from FLASH
// uiOffset - Offset of FLASH from where data should be read
// uiNumBytes - Number of bytes to be read from the FLASH.
//
// Returns:
// OSAL_STATUS_SUCCESS - if FLASH read is successful.
// <FAILURE> - if failed.
//-----------------------------------------------------------------------------
static INT BeceemFlashBulkRead(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
UINT uiOffset,
UINT uiNumBytes)
{
UINT uiIndex = 0;
UINT uiBytesToRead = uiNumBytes;
INT Status = 0;
UINT uiPartOffset = 0;
int bytes;
if(Adapter->device_removed )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Device Got Removed ");
return -ENODEV;
}
//Adding flash Base address
// uiOffset = uiOffset + GetFlashBaseAddr(Adapter);
#if defined(BCM_SHM_INTERFACE) && !defined(FLASH_DIRECT_ACCESS)
Status = bcmflash_raw_read((uiOffset/FLASH_PART_SIZE),(uiOffset % FLASH_PART_SIZE),( unsigned char *)pBuffer,uiNumBytes);
return Status;
#endif
Adapter->SelectedChip = RESET_CHIP_SELECT;
if(uiOffset % MAX_RW_SIZE)
{
BcmDoChipSelect(Adapter,uiOffset);
uiPartOffset = (uiOffset & (FLASH_PART_SIZE - 1)) + GetFlashBaseAddr(Adapter);
uiBytesToRead = MAX_RW_SIZE - (uiOffset%MAX_RW_SIZE);
uiBytesToRead = MIN(uiNumBytes,uiBytesToRead);
bytes = rdm(Adapter, uiPartOffset, (PCHAR)pBuffer+uiIndex, uiBytesToRead);
if (bytes < 0) {
Status = bytes;
Adapter->SelectedChip = RESET_CHIP_SELECT;
return Status;
}
uiIndex += uiBytesToRead;
uiOffset += uiBytesToRead;
uiNumBytes -= uiBytesToRead;
}
while(uiNumBytes)
{
BcmDoChipSelect(Adapter,uiOffset);
uiPartOffset = (uiOffset & (FLASH_PART_SIZE - 1)) + GetFlashBaseAddr(Adapter);
uiBytesToRead = MIN(uiNumBytes,MAX_RW_SIZE);
bytes = rdm(Adapter, uiPartOffset, (PCHAR)pBuffer+uiIndex, uiBytesToRead);
if (bytes < 0) {
Status = bytes;
break;
}
uiIndex += uiBytesToRead;
uiOffset += uiBytesToRead;
uiNumBytes -= uiBytesToRead;
}
Adapter->SelectedChip = RESET_CHIP_SELECT;
return Status;
}
//-----------------------------------------------------------------------------
// Procedure: BcmGetFlashSize
//
// Description: Finds the size of FLASH.
//
// Arguments:
// Adapter - ptr to Adapter object instance
//
// Returns:
// UINT - size of the FLASH Storage.
//
//-----------------------------------------------------------------------------
static UINT BcmGetFlashSize(PMINI_ADAPTER Adapter)
{
if(IsFlash2x(Adapter))
return (Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader + sizeof(DSD_HEADER));
else
return 32*1024;
}
//-----------------------------------------------------------------------------
// Procedure: BcmGetEEPROMSize
//
// Description: Finds the size of EEPROM.
//
// Arguments:
// Adapter - ptr to Adapter object instance
//
// Returns:
// UINT - size of the EEPROM Storage.
//
//-----------------------------------------------------------------------------
static UINT BcmGetEEPROMSize(PMINI_ADAPTER Adapter)
{
UINT uiData = 0;
UINT uiIndex = 0;
//
// if EEPROM is present and already Calibrated,it will have
// 'BECM' string at 0th offset.
// To find the EEPROM size read the possible boundaries of the
// EEPROM like 4K,8K etc..accessing the EEPROM beyond its size will
// result in wrap around. So when we get the End of the EEPROM we will
// get 'BECM' string which is indeed at offset 0.
//
BeceemEEPROMBulkRead(Adapter,&uiData,0x0,4);
if(uiData == BECM)
{
for(uiIndex = 2;uiIndex <=256; uiIndex*=2)
{
BeceemEEPROMBulkRead(Adapter,&uiData,uiIndex*1024,4);
if(uiData == BECM)
{
return uiIndex*1024;
}
}
}
else
{
//
// EEPROM may not be present or not programmed
//
uiData = 0xBABEFACE;
if(0 == BeceemEEPROMBulkWrite(Adapter,(PUCHAR)&uiData,0,4,TRUE))
{
uiData = 0;
for(uiIndex = 2;uiIndex <=256; uiIndex*=2)
{
BeceemEEPROMBulkRead(Adapter,&uiData,uiIndex*1024,4);
if(uiData == 0xBABEFACE)
{
return uiIndex*1024;
}
}
}
}
return 0;
}
//-----------------------------------------------------------------------------
// Procedure: FlashSectorErase
//
// Description: Finds the sector size of the FLASH.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// addr - sector start address
// numOfSectors - number of sectors to be erased.
//
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static INT FlashSectorErase(PMINI_ADAPTER Adapter,
UINT addr,
UINT numOfSectors)
{
UINT iIndex = 0, iRetries = 0;
UINT uiStatus = 0;
UINT value;
int bytes;
for(iIndex=0;iIndex<numOfSectors;iIndex++)
{
value = 0x06000000;
wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value));
value = (0xd8000000 | (addr & 0xFFFFFF));
wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value));
iRetries = 0;
do
{
value = (FLASH_CMD_STATUS_REG_READ << 24);
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value)) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Programing of FLASH_SPI_CMDQ_REG fails");
return STATUS_FAILURE;
}
bytes = rdmalt(Adapter, FLASH_SPI_READQ_REG, &uiStatus, sizeof(uiStatus));
if (bytes < 0) {
uiStatus = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Reading status of FLASH_SPI_READQ_REG fails");
return uiStatus;
}
iRetries++;
//After every try lets make the CPU free for 10 ms. generally time taken by the
//the sector erase cycle is 500 ms to 40000 msec. hence sleeping 10 ms
//won't hamper performance in any case.
msleep(10);
}while((uiStatus & 0x1) && (iRetries < 400));
if(uiStatus & 0x1)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"iRetries crossing the limit of 80000\n");
return STATUS_FAILURE;
}
addr += Adapter->uiSectorSize;
}
return 0;
}
//-----------------------------------------------------------------------------
// Procedure: flashByteWrite
//
// Description: Performs Byte by Byte write to flash
//
// Arguments:
// Adapter - ptr to Adapter object instance
// uiOffset - Offset of the flash where data needs to be written to.
// pData - Address of Data to be written.
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static INT flashByteWrite(
PMINI_ADAPTER Adapter,
UINT uiOffset,
PVOID pData)
{
UINT uiStatus = 0;
INT iRetries = MAX_FLASH_RETRIES * FLASH_PER_RETRIES_DELAY; //3
UINT value;
ULONG ulData = *(PUCHAR)pData;
int bytes;
//
// need not write 0xFF because write requires an erase and erase will
// make whole sector 0xFF.
//
if(0xFF == ulData)
{
return STATUS_SUCCESS;
}
// DumpDebug(NVM_RW,("flashWrite ====>\n"));
value = (FLASH_CMD_WRITE_ENABLE << 24);
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG,&value, sizeof(value)) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Write enable in FLASH_SPI_CMDQ_REG register fails");
return STATUS_FAILURE;
}
if(wrm(Adapter,FLASH_SPI_WRITEQ_REG, (PCHAR)&ulData, 4) < 0 )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"DATA Write on FLASH_SPI_WRITEQ_REG fails");
return STATUS_FAILURE;
}
value = (0x02000000 | (uiOffset & 0xFFFFFF));
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG,&value, sizeof(value)) < 0 )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Programming of FLASH_SPI_CMDQ_REG fails");
return STATUS_FAILURE;
}
//__udelay(950);
do
{
value = (FLASH_CMD_STATUS_REG_READ << 24);
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value)) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Programing of FLASH_SPI_CMDQ_REG fails");
return STATUS_FAILURE;
}
//__udelay(1);
bytes = rdmalt(Adapter, FLASH_SPI_READQ_REG, &uiStatus, sizeof(uiStatus));
if (bytes < 0) {
uiStatus = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Reading status of FLASH_SPI_READQ_REG fails");
return uiStatus;
}
iRetries--;
if( iRetries && ((iRetries % FLASH_PER_RETRIES_DELAY) == 0))
msleep(1);
}while((uiStatus & 0x1) && (iRetries >0) );
if(uiStatus & 0x1)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Flash Write fails even after checking status for 200 times.");
return STATUS_FAILURE ;
}
return STATUS_SUCCESS;
}
//-----------------------------------------------------------------------------
// Procedure: flashWrite
//
// Description: Performs write to flash
//
// Arguments:
// Adapter - ptr to Adapter object instance
// uiOffset - Offset of the flash where data needs to be written to.
// pData - Address of Data to be written.
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static INT flashWrite(
PMINI_ADAPTER Adapter,
UINT uiOffset,
PVOID pData)
{
//UINT uiStatus = 0;
//INT iRetries = 0;
//UINT uiReadBack = 0;
UINT uiStatus = 0;
INT iRetries = MAX_FLASH_RETRIES * FLASH_PER_RETRIES_DELAY; //3
UINT value;
UINT uiErasePattern[4] = {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF};
int bytes;
//
// need not write 0xFFFFFFFF because write requires an erase and erase will
// make whole sector 0xFFFFFFFF.
//
if (!memcmp(pData, uiErasePattern, MAX_RW_SIZE))
{
return 0;
}
value = (FLASH_CMD_WRITE_ENABLE << 24);
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG,&value, sizeof(value)) < 0 )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Write Enable of FLASH_SPI_CMDQ_REG fails");
return STATUS_FAILURE;
}
if(wrm(Adapter, uiOffset, (PCHAR)pData, MAX_RW_SIZE) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Data write fails...");
return STATUS_FAILURE;
}
//__udelay(950);
do
{
value = (FLASH_CMD_STATUS_REG_READ << 24);
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value)) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Programing of FLASH_SPI_CMDQ_REG fails");
return STATUS_FAILURE;
}
//__udelay(1);
bytes = rdmalt(Adapter, FLASH_SPI_READQ_REG, &uiStatus, sizeof(uiStatus));
if (bytes < 0) {
uiStatus = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Reading status of FLASH_SPI_READQ_REG fails");
return uiStatus;
}
iRetries--;
//this will ensure that in there will be no changes in the current path.
//currently one rdm/wrm takes 125 us.
//Hence 125 *2 * FLASH_PER_RETRIES_DELAY > 3 ms(worst case delay)
//Hence current implementation cycle will intoduce no delay in current path
if(iRetries && ((iRetries % FLASH_PER_RETRIES_DELAY) == 0))
msleep(1);
}while((uiStatus & 0x1) && (iRetries > 0));
if(uiStatus & 0x1)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Flash Write fails even after checking status for 200 times.");
return STATUS_FAILURE ;
}
return STATUS_SUCCESS;
}
//-----------------------------------------------------------------------------
// Procedure: flashByteWriteStatus
//
// Description: Performs byte by byte write to flash with write done status check
//
// Arguments:
// Adapter - ptr to Adapter object instance
// uiOffset - Offset of the flash where data needs to be written to.
// pData - Address of the Data to be written.
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static INT flashByteWriteStatus(
PMINI_ADAPTER Adapter,
UINT uiOffset,
PVOID pData)
{
UINT uiStatus = 0;
INT iRetries = MAX_FLASH_RETRIES * FLASH_PER_RETRIES_DELAY; //3
ULONG ulData = *(PUCHAR)pData;
UINT value;
int bytes;
//
// need not write 0xFFFFFFFF because write requires an erase and erase will
// make whole sector 0xFFFFFFFF.
//
if(0xFF == ulData)
{
return STATUS_SUCCESS;
}
// DumpDebug(NVM_RW,("flashWrite ====>\n"));
value = (FLASH_CMD_WRITE_ENABLE << 24);
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG,&value, sizeof(value)) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Write enable in FLASH_SPI_CMDQ_REG register fails");
return STATUS_SUCCESS;
}
if(wrm(Adapter,FLASH_SPI_WRITEQ_REG, (PCHAR)&ulData, 4) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"DATA Write on FLASH_SPI_WRITEQ_REG fails");
return STATUS_FAILURE;
}
value = (0x02000000 | (uiOffset & 0xFFFFFF));
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG,&value, sizeof(value)) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Programming of FLASH_SPI_CMDQ_REG fails");
return STATUS_FAILURE;
}
//msleep(1);
do
{
value = (FLASH_CMD_STATUS_REG_READ << 24);
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value)) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Programing of FLASH_SPI_CMDQ_REG fails");
return STATUS_FAILURE;
}
//__udelay(1);
bytes = rdmalt(Adapter, FLASH_SPI_READQ_REG, &uiStatus, sizeof(uiStatus));
if (bytes < 0) {
uiStatus = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Reading status of FLASH_SPI_READQ_REG fails");
return uiStatus;
}
iRetries--;
if( iRetries && ((iRetries % FLASH_PER_RETRIES_DELAY) == 0))
msleep(1);
}while((uiStatus & 0x1) && (iRetries > 0));
if(uiStatus & 0x1)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Flash Write fails even after checking status for 200 times.");
return STATUS_FAILURE ;
}
return STATUS_SUCCESS;
}
//-----------------------------------------------------------------------------
// Procedure: flashWriteStatus
//
// Description: Performs write to flash with write done status check
//
// Arguments:
// Adapter - ptr to Adapter object instance
// uiOffset - Offset of the flash where data needs to be written to.
// pData - Address of the Data to be written.
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static INT flashWriteStatus(
PMINI_ADAPTER Adapter,
UINT uiOffset,
PVOID pData)
{
UINT uiStatus = 0;
INT iRetries = MAX_FLASH_RETRIES * FLASH_PER_RETRIES_DELAY; //3
//UINT uiReadBack = 0;
UINT value;
UINT uiErasePattern[4] = {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF};
int bytes;
//
// need not write 0xFFFFFFFF because write requires an erase and erase will
// make whole sector 0xFFFFFFFF.
//
if (!memcmp(pData,uiErasePattern,MAX_RW_SIZE))
{
return 0;
}
value = (FLASH_CMD_WRITE_ENABLE << 24);
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG,&value, sizeof(value)) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Write Enable of FLASH_SPI_CMDQ_REG fails");
return STATUS_FAILURE;
}
if(wrm(Adapter, uiOffset, (PCHAR)pData, MAX_RW_SIZE) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Data write fails...");
return STATUS_FAILURE;
}
// __udelay(1);
do
{
value = (FLASH_CMD_STATUS_REG_READ << 24);
if(wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value)) < 0)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Programing of FLASH_SPI_CMDQ_REG fails");
return STATUS_FAILURE;
}
//__udelay(1);
bytes = rdmalt(Adapter, FLASH_SPI_READQ_REG, &uiStatus, sizeof(uiStatus));
if (bytes < 0) {
uiStatus = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Reading status of FLASH_SPI_READQ_REG fails");
return uiStatus;
}
iRetries--;
//this will ensure that in there will be no changes in the current path.
//currently one rdm/wrm takes 125 us.
//Hence 125 *2 * FLASH_PER_RETRIES_DELAY >3 ms(worst case delay)
//Hence current implementation cycle will intoduce no delay in current path
if(iRetries && ((iRetries % FLASH_PER_RETRIES_DELAY) == 0))
msleep(1);
}while((uiStatus & 0x1) && (iRetries >0));
if(uiStatus & 0x1)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Flash Write fails even after checking status for 200 times.");
return STATUS_FAILURE ;
}
return STATUS_SUCCESS;
}
//-----------------------------------------------------------------------------
// Procedure: BcmRestoreBlockProtectStatus
//
// Description: Restores the original block protection status.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// ulWriteStatus -Original status
// Returns:
// <VOID>
//
//-----------------------------------------------------------------------------
static VOID BcmRestoreBlockProtectStatus(PMINI_ADAPTER Adapter,ULONG ulWriteStatus)
{
UINT value;
value = (FLASH_CMD_WRITE_ENABLE<< 24);
wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value));
udelay(20);
value = (FLASH_CMD_STATUS_REG_WRITE<<24)|(ulWriteStatus << 16);
wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value));
udelay(20);
}
//-----------------------------------------------------------------------------
// Procedure: BcmFlashUnProtectBlock
//
// Description: UnProtects appropriate blocks for writing.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// uiOffset - Offset of the flash where data needs to be written to. This should be Sector aligned.
// Returns:
// ULONG - Status value before UnProtect.
//
//-----------------------------------------------------------------------------
static ULONG BcmFlashUnProtectBlock(PMINI_ADAPTER Adapter,UINT uiOffset, UINT uiLength)
{
ULONG ulStatus = 0;
ULONG ulWriteStatus = 0;
UINT value;
uiOffset = uiOffset&0x000FFFFF;
//
// Implemented only for 1MB Flash parts.
//
if(FLASH_PART_SST25VF080B == Adapter->ulFlashID)
{
//
// Get Current BP status.
//
value = (FLASH_CMD_STATUS_REG_READ << 24);
wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value));
udelay(10);
//
// Read status will be WWXXYYZZ. We have to take only WW.
//
rdmalt(Adapter, FLASH_SPI_READQ_REG, (PUINT)&ulStatus, sizeof(ulStatus));
ulStatus >>= 24;
ulWriteStatus = ulStatus;
//
// Bits [5-2] give current block level protection status.
// Bit5: BP3 - DONT CARE
// BP2-BP0: 0 - NO PROTECTION, 1 - UPPER 1/16, 2 - UPPER 1/8, 3 - UPPER 1/4
// 4 - UPPER 1/2. 5 to 7 - ALL BLOCKS
//
if(ulStatus)
{
if((uiOffset+uiLength) <= 0x80000)
{
//
// Offset comes in lower half of 1MB. Protect the upper half.
// Clear BP1 and BP0 and set BP2.
//
ulWriteStatus |= (0x4<<2);
ulWriteStatus &= ~(0x3<<2);
}
else if((uiOffset+uiLength) <= 0xC0000)
{
//
// Offset comes below Upper 1/4. Upper 1/4 can be protected.
// Clear BP2 and set BP1 and BP0.
//
ulWriteStatus |= (0x3<<2);
ulWriteStatus &= ~(0x1<<4);
}
else if((uiOffset+uiLength) <= 0xE0000)
{
//
// Offset comes below Upper 1/8. Upper 1/8 can be protected.
// Clear BP2 and BP0 and set BP1
//
ulWriteStatus |= (0x1<<3);
ulWriteStatus &= ~(0x5<<2);
}
else if((uiOffset+uiLength) <= 0xF0000)
{
//
// Offset comes below Upper 1/16. Only upper 1/16 can be protected.
// Set BP0 and Clear BP2,BP1.
//
ulWriteStatus |= (0x1<<2);
ulWriteStatus &= ~(0x3<<3);
}
else
{
//
// Unblock all.
// Clear BP2,BP1 and BP0.
//
ulWriteStatus &= ~(0x7<<2);
}
value = (FLASH_CMD_WRITE_ENABLE<< 24);
wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value));
udelay(20);
value = (FLASH_CMD_STATUS_REG_WRITE<<24)|(ulWriteStatus << 16);
wrmalt(Adapter, FLASH_SPI_CMDQ_REG, &value, sizeof(value));
udelay(20);
}
}
return ulStatus;
}
//-----------------------------------------------------------------------------
// Procedure: BeceemFlashBulkWrite
//
// Description: Performs write to the flash
//
// Arguments:
// Adapter - ptr to Adapter object instance
// pBuffer - Data to be written.
// uiOffset - Offset of the flash where data needs to be written to.
// uiNumBytes - Number of bytes to be written.
// bVerify - read verify flag.
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static INT BeceemFlashBulkWrite(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
UINT uiOffset,
UINT uiNumBytes,
BOOLEAN bVerify)
{
PCHAR pTempBuff = NULL;
PUCHAR pcBuffer = (PUCHAR)pBuffer;
UINT uiIndex = 0;
UINT uiOffsetFromSectStart = 0;
UINT uiSectAlignAddr = 0;
UINT uiCurrSectOffsetAddr = 0;
UINT uiSectBoundary = 0;
UINT uiNumSectTobeRead = 0;
UCHAR ucReadBk[16] = {0};
ULONG ulStatus = 0;
INT Status = STATUS_SUCCESS;
UINT uiTemp = 0;
UINT index = 0;
UINT uiPartOffset = 0;
#if defined(BCM_SHM_INTERFACE) && !defined(FLASH_DIRECT_ACCESS)
Status = bcmflash_raw_write((uiOffset/FLASH_PART_SIZE),(uiOffset % FLASH_PART_SIZE),( unsigned char *)pBuffer,uiNumBytes);
return Status;
#endif
uiOffsetFromSectStart = uiOffset & ~(Adapter->uiSectorSize - 1);
//Adding flash Base address
// uiOffset = uiOffset + GetFlashBaseAddr(Adapter);
uiSectAlignAddr = uiOffset & ~(Adapter->uiSectorSize - 1);
uiCurrSectOffsetAddr = uiOffset & (Adapter->uiSectorSize - 1);
uiSectBoundary = uiSectAlignAddr + Adapter->uiSectorSize;
pTempBuff = kmalloc(Adapter->uiSectorSize, GFP_KERNEL);
if(NULL == pTempBuff)
goto BeceemFlashBulkWrite_EXIT;
//
// check if the data to be written is overlapped across sectors
//
if(uiOffset+uiNumBytes < uiSectBoundary)
{
uiNumSectTobeRead = 1;
}
else
{
// Number of sectors = Last sector start address/First sector start address
uiNumSectTobeRead = (uiCurrSectOffsetAddr+uiNumBytes)/Adapter->uiSectorSize;
if((uiCurrSectOffsetAddr+uiNumBytes)%Adapter->uiSectorSize)
{
uiNumSectTobeRead++;
}
}
//Check whether Requested sector is writable or not in case of flash2x write. But if write call is
// for DSD calibration, allow it without checking of sector permission
if(IsFlash2x(Adapter) && (Adapter->bAllDSDWriteAllow == FALSE))
{
index = 0;
uiTemp = uiNumSectTobeRead ;
while(uiTemp)
{
if(IsOffsetWritable(Adapter, uiOffsetFromSectStart + index * Adapter->uiSectorSize ) == FALSE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Sector Starting at offset <0X%X> is not writable",
(uiOffsetFromSectStart + index * Adapter->uiSectorSize));
Status = SECTOR_IS_NOT_WRITABLE;
goto BeceemFlashBulkWrite_EXIT;
}
uiTemp = uiTemp - 1;
index = index + 1 ;
}
}
Adapter->SelectedChip = RESET_CHIP_SELECT;
while(uiNumSectTobeRead)
{
//do_gettimeofday(&tv1);
//BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "\nTime In start of write :%ld ms\n",(tv1.tv_sec *1000 + tv1.tv_usec /1000));
uiPartOffset = (uiSectAlignAddr & (FLASH_PART_SIZE - 1)) + GetFlashBaseAddr(Adapter);
BcmDoChipSelect(Adapter,uiSectAlignAddr);
if(0 != BeceemFlashBulkRead(Adapter,
(PUINT)pTempBuff,
uiOffsetFromSectStart,
Adapter->uiSectorSize))
{
Status = -1;
goto BeceemFlashBulkWrite_EXIT;
}
//do_gettimeofday(&tr);
//BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Total time taken by Read :%ld ms\n", (tr.tv_sec *1000 + tr.tv_usec/1000) - (tv1.tv_sec *1000 + tv1.tv_usec/1000));
ulStatus = BcmFlashUnProtectBlock(Adapter,uiSectAlignAddr,Adapter->uiSectorSize);
if(uiNumSectTobeRead > 1)
{
memcpy(&pTempBuff[uiCurrSectOffsetAddr],pcBuffer,uiSectBoundary-(uiSectAlignAddr+uiCurrSectOffsetAddr));
pcBuffer += ((uiSectBoundary-(uiSectAlignAddr+uiCurrSectOffsetAddr)));
uiNumBytes -= (uiSectBoundary-(uiSectAlignAddr+uiCurrSectOffsetAddr));
}
else
{
memcpy(&pTempBuff[uiCurrSectOffsetAddr],pcBuffer,uiNumBytes);
}
if(IsFlash2x(Adapter))
{
SaveHeaderIfPresent(Adapter,(PUCHAR)pTempBuff,uiOffsetFromSectStart);
}
FlashSectorErase(Adapter,uiPartOffset,1);
//do_gettimeofday(&te);
//BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Total time taken by Erase :%ld ms\n", (te.tv_sec *1000 + te.tv_usec/1000) - (tr.tv_sec *1000 + tr.tv_usec/1000));
for(uiIndex = 0; uiIndex < Adapter->uiSectorSize; uiIndex +=Adapter->ulFlashWriteSize)
{
if(Adapter->device_removed)
{
Status = -1;
goto BeceemFlashBulkWrite_EXIT;
}
if(STATUS_SUCCESS != (*Adapter->fpFlashWrite)(Adapter,uiPartOffset+uiIndex,(&pTempBuff[uiIndex])))
{
Status = -1;
goto BeceemFlashBulkWrite_EXIT;
}
}
//do_gettimeofday(&tw);
//BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Total time taken in Write to Flash :%ld ms\n", (tw.tv_sec *1000 + tw.tv_usec/1000) - (te.tv_sec *1000 + te.tv_usec/1000));
for(uiIndex = 0;uiIndex < Adapter->uiSectorSize;uiIndex += MAX_RW_SIZE)
{
if(STATUS_SUCCESS == BeceemFlashBulkRead(Adapter,(PUINT)ucReadBk,uiOffsetFromSectStart+uiIndex,MAX_RW_SIZE))
{
if(Adapter->ulFlashWriteSize == 1)
{
UINT uiReadIndex = 0;
for(uiReadIndex = 0; uiReadIndex < 16; uiReadIndex++)
{
if(ucReadBk[uiReadIndex] != pTempBuff[uiIndex+uiReadIndex])
{
if(STATUS_SUCCESS != (*Adapter->fpFlashWriteWithStatusCheck)(Adapter,uiPartOffset+uiIndex+uiReadIndex,&pTempBuff[uiIndex+uiReadIndex]))
{
Status = STATUS_FAILURE;
goto BeceemFlashBulkWrite_EXIT;
}
}
}
}
else
{
if(memcmp(ucReadBk,&pTempBuff[uiIndex],MAX_RW_SIZE))
{
if(STATUS_SUCCESS != (*Adapter->fpFlashWriteWithStatusCheck)(Adapter,uiPartOffset+uiIndex,&pTempBuff[uiIndex]))
{
Status = STATUS_FAILURE;
goto BeceemFlashBulkWrite_EXIT;
}
}
}
}
}
//do_gettimeofday(&twv);
//BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Total time taken in Write to Flash verification :%ld ms\n", (twv.tv_sec *1000 + twv.tv_usec/1000) - (tw.tv_sec *1000 + tw.tv_usec/1000));
if(ulStatus)
{
BcmRestoreBlockProtectStatus(Adapter,ulStatus);
ulStatus = 0;
}
uiCurrSectOffsetAddr = 0;
uiSectAlignAddr = uiSectBoundary;
uiSectBoundary += Adapter->uiSectorSize;
uiOffsetFromSectStart += Adapter->uiSectorSize;
uiNumSectTobeRead--;
}
//do_gettimeofday(&tv2);
//BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Time after Write :%ld ms\n",(tv2.tv_sec *1000 + tv2.tv_usec/1000));
//BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Total time taken by in Write is :%ld ms\n", (tv2.tv_sec *1000 + tv2.tv_usec/1000) - (tv1.tv_sec *1000 + tv1.tv_usec/1000));
//
// Cleanup.
//
BeceemFlashBulkWrite_EXIT:
if(ulStatus)
{
BcmRestoreBlockProtectStatus(Adapter,ulStatus);
}
kfree(pTempBuff);
Adapter->SelectedChip = RESET_CHIP_SELECT;
return Status;
}
//-----------------------------------------------------------------------------
// Procedure: BeceemFlashBulkWriteStatus
//
// Description: Writes to Flash. Checks the SPI status after each write.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// pBuffer - Data to be written.
// uiOffset - Offset of the flash where data needs to be written to.
// uiNumBytes - Number of bytes to be written.
// bVerify - read verify flag.
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static INT BeceemFlashBulkWriteStatus(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
UINT uiOffset,
UINT uiNumBytes,
BOOLEAN bVerify)
{
PCHAR pTempBuff = NULL;
PUCHAR pcBuffer = (PUCHAR)pBuffer;
UINT uiIndex = 0;
UINT uiOffsetFromSectStart = 0;
UINT uiSectAlignAddr = 0;
UINT uiCurrSectOffsetAddr = 0;
UINT uiSectBoundary = 0;
UINT uiNumSectTobeRead = 0;
UCHAR ucReadBk[16] = {0};
ULONG ulStatus = 0;
UINT Status = STATUS_SUCCESS;
UINT uiTemp = 0;
UINT index = 0;
UINT uiPartOffset = 0;
uiOffsetFromSectStart = uiOffset & ~(Adapter->uiSectorSize - 1);
//uiOffset += Adapter->ulFlashCalStart;
//Adding flash Base address
// uiOffset = uiOffset + GetFlashBaseAddr(Adapter);
uiSectAlignAddr = uiOffset & ~(Adapter->uiSectorSize - 1);
uiCurrSectOffsetAddr = uiOffset & (Adapter->uiSectorSize - 1);
uiSectBoundary = uiSectAlignAddr + Adapter->uiSectorSize;
pTempBuff = kmalloc(Adapter->uiSectorSize, GFP_KERNEL);
if(NULL == pTempBuff)
goto BeceemFlashBulkWriteStatus_EXIT;
//
// check if the data to be written is overlapped across sectors
//
if(uiOffset+uiNumBytes < uiSectBoundary)
{
uiNumSectTobeRead = 1;
}
else
{
// Number of sectors = Last sector start address/First sector start address
uiNumSectTobeRead = (uiCurrSectOffsetAddr+uiNumBytes)/Adapter->uiSectorSize;
if((uiCurrSectOffsetAddr+uiNumBytes)%Adapter->uiSectorSize)
{
uiNumSectTobeRead++;
}
}
if(IsFlash2x(Adapter) && (Adapter->bAllDSDWriteAllow == FALSE))
{
index = 0;
uiTemp = uiNumSectTobeRead ;
while(uiTemp)
{
if(IsOffsetWritable(Adapter,uiOffsetFromSectStart + index * Adapter->uiSectorSize ) == FALSE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Sector Starting at offset <0X%x> is not writable",
(uiOffsetFromSectStart + index * Adapter->uiSectorSize));
Status = SECTOR_IS_NOT_WRITABLE;
goto BeceemFlashBulkWriteStatus_EXIT;
}
uiTemp = uiTemp - 1;
index = index + 1 ;
}
}
Adapter->SelectedChip = RESET_CHIP_SELECT;
while(uiNumSectTobeRead)
{
uiPartOffset = (uiSectAlignAddr & (FLASH_PART_SIZE - 1)) + GetFlashBaseAddr(Adapter);
BcmDoChipSelect(Adapter,uiSectAlignAddr);
if(0 != BeceemFlashBulkRead(Adapter,
(PUINT)pTempBuff,
uiOffsetFromSectStart,
Adapter->uiSectorSize))
{
Status = -1;
goto BeceemFlashBulkWriteStatus_EXIT;
}
ulStatus = BcmFlashUnProtectBlock(Adapter,uiOffsetFromSectStart,Adapter->uiSectorSize);
if(uiNumSectTobeRead > 1)
{
memcpy(&pTempBuff[uiCurrSectOffsetAddr],pcBuffer,uiSectBoundary-(uiSectAlignAddr+uiCurrSectOffsetAddr));
pcBuffer += ((uiSectBoundary-(uiSectAlignAddr+uiCurrSectOffsetAddr)));
uiNumBytes -= (uiSectBoundary-(uiSectAlignAddr+uiCurrSectOffsetAddr));
}
else
{
memcpy(&pTempBuff[uiCurrSectOffsetAddr],pcBuffer,uiNumBytes);
}
if(IsFlash2x(Adapter))
{
SaveHeaderIfPresent(Adapter,(PUCHAR)pTempBuff,uiOffsetFromSectStart);
}
FlashSectorErase(Adapter,uiPartOffset,1);
for(uiIndex = 0; uiIndex < Adapter->uiSectorSize; uiIndex +=Adapter->ulFlashWriteSize)
{
if(Adapter->device_removed)
{
Status = -1;
goto BeceemFlashBulkWriteStatus_EXIT;
}
if(STATUS_SUCCESS != (*Adapter->fpFlashWriteWithStatusCheck)(Adapter,uiPartOffset+uiIndex,&pTempBuff[uiIndex]))
{
Status = -1;
goto BeceemFlashBulkWriteStatus_EXIT;
}
}
if(bVerify)
{
for(uiIndex = 0;uiIndex < Adapter->uiSectorSize;uiIndex += MAX_RW_SIZE)
{
if(STATUS_SUCCESS == BeceemFlashBulkRead(Adapter,(PUINT)ucReadBk,uiOffsetFromSectStart+uiIndex,MAX_RW_SIZE))
{
if(memcmp(ucReadBk,&pTempBuff[uiIndex],MAX_RW_SIZE))
{
Status = STATUS_FAILURE;
goto BeceemFlashBulkWriteStatus_EXIT;
}
}
}
}
if(ulStatus)
{
BcmRestoreBlockProtectStatus(Adapter,ulStatus);
ulStatus = 0;
}
uiCurrSectOffsetAddr = 0;
uiSectAlignAddr = uiSectBoundary;
uiSectBoundary += Adapter->uiSectorSize;
uiOffsetFromSectStart += Adapter->uiSectorSize;
uiNumSectTobeRead--;
}
//
// Cleanup.
//
BeceemFlashBulkWriteStatus_EXIT:
if(ulStatus)
{
BcmRestoreBlockProtectStatus(Adapter,ulStatus);
}
kfree(pTempBuff);
Adapter->SelectedChip = RESET_CHIP_SELECT;
return Status;
}
//-----------------------------------------------------------------------------
// Procedure: PropagateCalParamsFromEEPROMToMemory
//
// Description: Dumps the calibration section of EEPROM to DDR.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
INT PropagateCalParamsFromEEPROMToMemory(PMINI_ADAPTER Adapter)
{
PCHAR pBuff = kmalloc(BUFFER_4K, GFP_KERNEL);
UINT uiEepromSize = 0;
UINT uiIndex = 0;
UINT uiBytesToCopy = 0;
UINT uiCalStartAddr = EEPROM_CALPARAM_START;
UINT uiMemoryLoc = EEPROM_CAL_DATA_INTERNAL_LOC;
UINT value;
INT Status = 0;
if(pBuff == NULL)
{
return -1;
}
if(0 != BeceemEEPROMBulkRead(Adapter,&uiEepromSize,EEPROM_SIZE_OFFSET,4))
{
kfree(pBuff);
return -1;
}
uiEepromSize >>= 16;
if(uiEepromSize > 1024*1024)
{
kfree(pBuff);
return -1;
}
uiBytesToCopy = MIN(BUFFER_4K,uiEepromSize);
while(uiBytesToCopy)
{
if(0 != BeceemEEPROMBulkRead(Adapter,(PUINT)pBuff,uiCalStartAddr,uiBytesToCopy))
{
Status = -1;
break;
}
wrm(Adapter,uiMemoryLoc,(PCHAR)(((PULONG)pBuff)+uiIndex),uiBytesToCopy);
uiMemoryLoc += uiBytesToCopy;
uiEepromSize -= uiBytesToCopy;
uiCalStartAddr += uiBytesToCopy;
uiIndex += uiBytesToCopy/4;
uiBytesToCopy = MIN(BUFFER_4K,uiEepromSize);
}
value = 0xbeadbead;
wrmalt(Adapter, EEPROM_CAL_DATA_INTERNAL_LOC-4,&value, sizeof(value));
value = 0xbeadbead;
wrmalt(Adapter, EEPROM_CAL_DATA_INTERNAL_LOC-8,&value, sizeof(value));
kfree(pBuff);
return Status;
}
//-----------------------------------------------------------------------------
// Procedure: PropagateCalParamsFromFlashToMemory
//
// Description: Dumps the calibration section of EEPROM to DDR.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
INT PropagateCalParamsFromFlashToMemory(PMINI_ADAPTER Adapter)
{
PCHAR pBuff, pPtr;
UINT uiEepromSize = 0;
UINT uiBytesToCopy = 0;
//UINT uiIndex = 0;
UINT uiCalStartAddr = EEPROM_CALPARAM_START;
UINT uiMemoryLoc = EEPROM_CAL_DATA_INTERNAL_LOC;
UINT value;
INT Status = 0;
//
// Write the signature first. This will ensure firmware does not access EEPROM.
//
value = 0xbeadbead;
wrmalt(Adapter, EEPROM_CAL_DATA_INTERNAL_LOC - 4, &value, sizeof(value));
value = 0xbeadbead;
wrmalt(Adapter, EEPROM_CAL_DATA_INTERNAL_LOC - 8, &value, sizeof(value));
if(0 != BeceemNVMRead(Adapter,&uiEepromSize,EEPROM_SIZE_OFFSET, 4))
{
return -1;
}
uiEepromSize = ntohl(uiEepromSize);
uiEepromSize >>= 16;
//
// subtract the auto init section size
//
uiEepromSize -= EEPROM_CALPARAM_START;
if(uiEepromSize > 1024*1024)
{
return -1;
}
pBuff = kmalloc(uiEepromSize, GFP_KERNEL);
if ( pBuff == NULL )
return -1;
if(0 != BeceemNVMRead(Adapter,(PUINT)pBuff,uiCalStartAddr, uiEepromSize))
{
kfree(pBuff);
return -1;
}
pPtr = pBuff;
uiBytesToCopy = MIN(BUFFER_4K,uiEepromSize);
while(uiBytesToCopy)
{
Status = wrm(Adapter,uiMemoryLoc,(PCHAR)pPtr,uiBytesToCopy);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"wrm failed with status :%d",Status);
break;
}
pPtr += uiBytesToCopy;
uiEepromSize -= uiBytesToCopy;
uiMemoryLoc += uiBytesToCopy;
uiBytesToCopy = MIN(BUFFER_4K,uiEepromSize);
}
kfree(pBuff);
return Status;
}
//-----------------------------------------------------------------------------
// Procedure: BeceemEEPROMReadBackandVerify
//
// Description: Read back the data written and verifies.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// pBuffer - Data to be written.
// uiOffset - Offset of the flash where data needs to be written to.
// uiNumBytes - Number of bytes to be written.
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static INT BeceemEEPROMReadBackandVerify(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
UINT uiOffset,
UINT uiNumBytes)
{
UINT uiRdbk = 0;
UINT uiIndex = 0;
UINT uiData = 0;
UINT auiData[4] = {0};
while(uiNumBytes)
{
if(Adapter->device_removed )
{
return -1;
}
if(uiNumBytes >= MAX_RW_SIZE)
{// for the requests more than or equal to MAX_RW_SIZE bytes, use bulk read function to make the access faster.
BeceemEEPROMBulkRead(Adapter,&auiData[0],uiOffset,MAX_RW_SIZE);
if(memcmp(&pBuffer[uiIndex],&auiData[0],MAX_RW_SIZE))
{
// re-write
BeceemEEPROMBulkWrite(Adapter,(PUCHAR)(pBuffer+uiIndex),uiOffset,MAX_RW_SIZE,FALSE);
mdelay(3);
BeceemEEPROMBulkRead(Adapter,&auiData[0],uiOffset,MAX_RW_SIZE);
if(memcmp(&pBuffer[uiIndex],&auiData[0],MAX_RW_SIZE))
{
return -1;
}
}
uiOffset += MAX_RW_SIZE;
uiNumBytes -= MAX_RW_SIZE;
uiIndex += 4;
}
else if(uiNumBytes >= 4)
{
BeceemEEPROMBulkRead(Adapter,&uiData,uiOffset,4);
if(uiData != pBuffer[uiIndex])
{
//re-write
BeceemEEPROMBulkWrite(Adapter,(PUCHAR)(pBuffer+uiIndex),uiOffset,4,FALSE);
mdelay(3);
BeceemEEPROMBulkRead(Adapter,&uiData,uiOffset,4);
if(uiData != pBuffer[uiIndex])
{
return -1;
}
}
uiOffset += 4;
uiNumBytes -= 4;
uiIndex++;
}
else
{ // Handle the reads less than 4 bytes...
uiData = 0;
memcpy(&uiData,((PUCHAR)pBuffer)+(uiIndex*sizeof(UINT)),uiNumBytes);
BeceemEEPROMBulkRead(Adapter,&uiRdbk,uiOffset,4);
if(memcmp(&uiData, &uiRdbk, uiNumBytes))
return -1;
uiNumBytes = 0;
}
}
return 0;
}
static VOID BcmSwapWord(UINT *ptr1) {
UINT tempval = (UINT)*ptr1;
char *ptr2 = (char *)&tempval;
char *ptr = (char *)ptr1;
ptr[0] = ptr2[3];
ptr[1] = ptr2[2];
ptr[2] = ptr2[1];
ptr[3] = ptr2[0];
}
//-----------------------------------------------------------------------------
// Procedure: BeceemEEPROMWritePage
//
// Description: Performs page write (16bytes) to the EEPROM
//
// Arguments:
// Adapter - ptr to Adapter object instance
// uiData - Data to be written.
// uiOffset - Offset of the EEPROM where data needs to be written to.
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
static INT BeceemEEPROMWritePage( PMINI_ADAPTER Adapter, UINT uiData[], UINT uiOffset )
{
UINT uiRetries = MAX_EEPROM_RETRIES*RETRIES_PER_DELAY;
UINT uiStatus = 0;
UCHAR uiEpromStatus = 0;
UINT value =0 ;
/* Flush the Write/Read/Cmd queues. */
value = ( EEPROM_WRITE_QUEUE_FLUSH | EEPROM_CMD_QUEUE_FLUSH | EEPROM_READ_QUEUE_FLUSH );
wrmalt( Adapter, SPI_FLUSH_REG, &value, sizeof(value));
value = 0 ;
wrmalt( Adapter, SPI_FLUSH_REG, &value, sizeof(value) );
/* Clear the Empty/Avail/Full bits. After this it has been confirmed
* that the bit was cleared by reading back the register. See NOTE below.
* We also clear the Read queues as we do a EEPROM status register read
* later. */
value = ( EEPROM_WRITE_QUEUE_EMPTY | EEPROM_WRITE_QUEUE_AVAIL | EEPROM_WRITE_QUEUE_FULL | EEPROM_READ_DATA_AVAIL | EEPROM_READ_DATA_FULL ) ;
wrmalt( Adapter, EEPROM_SPI_Q_STATUS1_REG,&value, sizeof(value));
/* Enable write */
value = EEPROM_WRITE_ENABLE ;
wrmalt( Adapter, EEPROM_CMDQ_SPI_REG,&value, sizeof(value) );
/* We can write back to back 8bits * 16 into the queue and as we have
* checked for the queue to be empty we can write in a burst. */
value = uiData[0];
BcmSwapWord(&value);
wrm( Adapter, EEPROM_WRITE_DATAQ_REG, (PUCHAR)&value, 4);
value = uiData[1];
BcmSwapWord(&value);
wrm( Adapter, EEPROM_WRITE_DATAQ_REG, (PUCHAR)&value, 4);
value = uiData[2];
BcmSwapWord(&value);
wrm( Adapter, EEPROM_WRITE_DATAQ_REG, (PUCHAR)&value, 4);
value = uiData[3];
BcmSwapWord(&value);
wrm( Adapter, EEPROM_WRITE_DATAQ_REG, (PUCHAR)&value, 4);
/* NOTE : After this write, on readback of EEPROM_SPI_Q_STATUS1_REG
* shows that we see 7 for the EEPROM data write. Which means that
* queue got full, also space is available as well as the queue is empty.
* This may happen in sequence. */
value = EEPROM_16_BYTE_PAGE_WRITE | uiOffset ;
wrmalt( Adapter, EEPROM_CMDQ_SPI_REG, &value, sizeof(value) );
/* Ideally we should loop here without tries and eventually succeed.
* What we are checking if the previous write has completed, and this
* may take time. We should wait till the Empty bit is set. */
uiStatus = 0;
rdmalt(Adapter, EEPROM_SPI_Q_STATUS1_REG, &uiStatus, sizeof(uiStatus));
while ( ( uiStatus & EEPROM_WRITE_QUEUE_EMPTY ) == 0 )
{
uiRetries--;
if ( uiRetries == 0 )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "0x0f003004 = %x, %d retries failed.\n", uiStatus, MAX_EEPROM_RETRIES *RETRIES_PER_DELAY);
return STATUS_FAILURE ;
}
if( !(uiRetries%RETRIES_PER_DELAY) )
msleep(1);
uiStatus = 0;
rdmalt(Adapter, EEPROM_SPI_Q_STATUS1_REG, &uiStatus, sizeof(uiStatus));
if(Adapter->device_removed == TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Modem got removed hence exiting from loop....");
return -ENODEV;
}
}
if ( uiRetries != 0 )
{
/* Clear the ones that are set - either, Empty/Full/Avail bits */
value = ( uiStatus & ( EEPROM_WRITE_QUEUE_EMPTY | EEPROM_WRITE_QUEUE_AVAIL | EEPROM_WRITE_QUEUE_FULL ) );
wrmalt( Adapter, EEPROM_SPI_Q_STATUS1_REG, &value, sizeof(value));
}
/* Here we should check if the EEPROM status register is correct before
* proceeding. Bit 0 in the EEPROM Status register should be 0 before
* we proceed further. A 1 at Bit 0 indicates that the EEPROM is busy
* with the previous write. Note also that issuing this read finally
* means the previous write to the EEPROM has completed. */
uiRetries = MAX_EEPROM_RETRIES*RETRIES_PER_DELAY;
uiEpromStatus = 0;
while ( uiRetries != 0 )
{
uiEpromStatus = ReadEEPROMStatusRegister( Adapter) ;
if(Adapter->device_removed == TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Modem has got removed hence exiting from loop...");
return -ENODEV;
}
if ( ( EEPROM_STATUS_REG_WRITE_BUSY & uiEpromStatus ) == 0 )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "EEPROM status register = %x tries = %d\n", uiEpromStatus, (MAX_EEPROM_RETRIES * RETRIES_PER_DELAY- uiRetries) );
return STATUS_SUCCESS ;
}
uiRetries--;
if ( uiRetries == 0 )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "0x0f003004 = %x, for EEPROM status read %d retries failed.\n", uiEpromStatus, MAX_EEPROM_RETRIES *RETRIES_PER_DELAY);
return STATUS_FAILURE ;
}
uiEpromStatus = 0;
if( !(uiRetries%RETRIES_PER_DELAY) )
msleep(1);
}
return STATUS_SUCCESS ;
} /* BeceemEEPROMWritePage */
//-----------------------------------------------------------------------------
// Procedure: BeceemEEPROMBulkWrite
//
// Description: Performs write to the EEPROM
//
// Arguments:
// Adapter - ptr to Adapter object instance
// pBuffer - Data to be written.
// uiOffset - Offset of the EEPROM where data needs to be written to.
// uiNumBytes - Number of bytes to be written.
// bVerify - read verify flag.
// Returns:
// OSAL_STATUS_CODE
//
//-----------------------------------------------------------------------------
INT BeceemEEPROMBulkWrite(
PMINI_ADAPTER Adapter,
PUCHAR pBuffer,
UINT uiOffset,
UINT uiNumBytes,
BOOLEAN bVerify)
{
UINT uiBytesToCopy = uiNumBytes;
//UINT uiRdbk = 0;
UINT uiData[4] = {0};
UINT uiIndex = 0;
UINT uiTempOffset = 0;
UINT uiExtraBytes = 0;
//PUINT puiBuffer = (PUINT)pBuffer;
//INT value;
if(uiOffset%MAX_RW_SIZE && uiBytesToCopy)
{
uiTempOffset = uiOffset - (uiOffset%MAX_RW_SIZE);
uiExtraBytes = uiOffset-uiTempOffset;
BeceemEEPROMBulkRead(Adapter,&uiData[0],uiTempOffset,MAX_RW_SIZE);
if(uiBytesToCopy >= (16 -uiExtraBytes))
{
memcpy((((PUCHAR)&uiData[0])+uiExtraBytes),pBuffer,MAX_RW_SIZE- uiExtraBytes);
if ( STATUS_FAILURE == BeceemEEPROMWritePage( Adapter, uiData, uiTempOffset ) )
return STATUS_FAILURE;
uiBytesToCopy -= (MAX_RW_SIZE - uiExtraBytes);
uiIndex += (MAX_RW_SIZE - uiExtraBytes);
uiOffset += (MAX_RW_SIZE - uiExtraBytes);
}
else
{
memcpy((((PUCHAR)&uiData[0])+uiExtraBytes),pBuffer,uiBytesToCopy);
if ( STATUS_FAILURE == BeceemEEPROMWritePage( Adapter, uiData, uiTempOffset ) )
return STATUS_FAILURE;
uiIndex += uiBytesToCopy;
uiOffset += uiBytesToCopy;
uiBytesToCopy = 0;
}
}
while(uiBytesToCopy)
{
if(Adapter->device_removed)
{
return -1;
}
if(uiBytesToCopy >= MAX_RW_SIZE)
{
if (STATUS_FAILURE == BeceemEEPROMWritePage( Adapter, (PUINT) &pBuffer[uiIndex], uiOffset ) )
return STATUS_FAILURE;
uiIndex += MAX_RW_SIZE;
uiOffset += MAX_RW_SIZE;
uiBytesToCopy -= MAX_RW_SIZE;
}
else
{
//
// To program non 16byte aligned data, read 16byte and then update.
//
BeceemEEPROMBulkRead(Adapter,&uiData[0],uiOffset,16);
memcpy(&uiData[0],pBuffer+uiIndex,uiBytesToCopy);
if ( STATUS_FAILURE == BeceemEEPROMWritePage( Adapter, uiData, uiOffset ) )
return STATUS_FAILURE;
uiBytesToCopy = 0;
}
}
return 0;
}
//-----------------------------------------------------------------------------
// Procedure: BeceemNVMRead
//
// Description: Reads n number of bytes from NVM.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// pBuffer - Buffer to store the data read from NVM
// uiOffset - Offset of NVM from where data should be read
// uiNumBytes - Number of bytes to be read from the NVM.
//
// Returns:
// OSAL_STATUS_SUCCESS - if NVM read is successful.
// <FAILURE> - if failed.
//-----------------------------------------------------------------------------
INT BeceemNVMRead(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
UINT uiOffset,
UINT uiNumBytes)
{
INT Status = 0;
#if !defined(BCM_SHM_INTERFACE) || defined(FLASH_DIRECT_ACCESS)
UINT uiTemp = 0, value;
#endif
if(Adapter->eNVMType == NVM_FLASH)
{
if(Adapter->bFlashRawRead == FALSE)
{
if (IsSectionExistInVendorInfo(Adapter,Adapter->eActiveDSD))
return vendorextnReadSection(Adapter,(PUCHAR)pBuffer,Adapter->eActiveDSD,uiOffset,uiNumBytes);
uiOffset = uiOffset+ Adapter->ulFlashCalStart ;
}
#if defined(BCM_SHM_INTERFACE) && !defined(FLASH_DIRECT_ACCESS)
Status = bcmflash_raw_read((uiOffset/FLASH_PART_SIZE),(uiOffset % FLASH_PART_SIZE),( unsigned char *)pBuffer,uiNumBytes);
#else
rdmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
value = 0;
wrmalt(Adapter, 0x0f000C80,&value, sizeof(value));
Status = BeceemFlashBulkRead(Adapter,
pBuffer,
uiOffset,
uiNumBytes);
wrmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
#endif
}
else if(Adapter->eNVMType == NVM_EEPROM)
{
Status = BeceemEEPROMBulkRead(Adapter,
pBuffer,
uiOffset,
uiNumBytes);
}
else
{
Status = -1;
}
return Status;
}
//-----------------------------------------------------------------------------
// Procedure: BeceemNVMWrite
//
// Description: Writes n number of bytes to NVM.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// pBuffer - Buffer contains the data to be written.
// uiOffset - Offset of NVM where data to be written to.
// uiNumBytes - Number of bytes to be written..
//
// Returns:
// OSAL_STATUS_SUCCESS - if NVM write is successful.
// <FAILURE> - if failed.
//-----------------------------------------------------------------------------
INT BeceemNVMWrite(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
UINT uiOffset,
UINT uiNumBytes,
BOOLEAN bVerify)
{
INT Status = 0;
UINT uiTemp = 0;
UINT uiMemoryLoc = EEPROM_CAL_DATA_INTERNAL_LOC;
UINT uiIndex = 0;
#if !defined(BCM_SHM_INTERFACE) || defined(FLASH_DIRECT_ACCESS)
UINT value;
#endif
UINT uiFlashOffset = 0;
if(Adapter->eNVMType == NVM_FLASH)
{
if (IsSectionExistInVendorInfo(Adapter,Adapter->eActiveDSD))
Status = vendorextnWriteSection(Adapter,(PUCHAR)pBuffer,Adapter->eActiveDSD,uiOffset,uiNumBytes,bVerify);
else
{
uiFlashOffset = uiOffset + Adapter->ulFlashCalStart;
#if defined(BCM_SHM_INTERFACE) && !defined(FLASH_DIRECT_ACCESS)
Status = bcmflash_raw_write((uiFlashOffset/FLASH_PART_SIZE), (uiFlashOffset % FLASH_PART_SIZE), (unsigned char *)pBuffer,uiNumBytes);
#else
rdmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
value = 0;
wrmalt(Adapter, 0x0f000C80, &value, sizeof(value));
if(Adapter->bStatusWrite == TRUE)
{
Status = BeceemFlashBulkWriteStatus(Adapter,
pBuffer,
uiFlashOffset,
uiNumBytes ,
bVerify);
}
else
{
Status = BeceemFlashBulkWrite(Adapter,
pBuffer,
uiFlashOffset,
uiNumBytes,
bVerify);
}
#endif
}
if(uiOffset >= EEPROM_CALPARAM_START)
{
uiMemoryLoc += (uiOffset - EEPROM_CALPARAM_START);
while(uiNumBytes)
{
if(uiNumBytes > BUFFER_4K)
{
wrm(Adapter,(uiMemoryLoc+uiIndex),(PCHAR)(pBuffer+(uiIndex/4)),BUFFER_4K);
uiNumBytes -= BUFFER_4K;
uiIndex += BUFFER_4K;
}
else
{
wrm(Adapter,uiMemoryLoc+uiIndex,(PCHAR)(pBuffer+(uiIndex/4)),uiNumBytes);
uiNumBytes = 0;
break;
}
}
}
else
{
if((uiOffset+uiNumBytes) > EEPROM_CALPARAM_START)
{
ULONG ulBytesTobeSkipped = 0;
PUCHAR pcBuffer = (PUCHAR)pBuffer;// char pointer to take care of odd byte cases.
uiNumBytes -= (EEPROM_CALPARAM_START - uiOffset);
ulBytesTobeSkipped += (EEPROM_CALPARAM_START - uiOffset);
uiOffset += (EEPROM_CALPARAM_START - uiOffset);
while(uiNumBytes)
{
if(uiNumBytes > BUFFER_4K)
{
wrm(Adapter,uiMemoryLoc+uiIndex,(PCHAR )&pcBuffer[ulBytesTobeSkipped+uiIndex],BUFFER_4K);
uiNumBytes -= BUFFER_4K;
uiIndex += BUFFER_4K;
}
else
{
wrm(Adapter,uiMemoryLoc+uiIndex,(PCHAR)&pcBuffer[ulBytesTobeSkipped+uiIndex],uiNumBytes);
uiNumBytes = 0;
break;
}
}
}
}
// restore the values.
wrmalt(Adapter,0x0f000C80,&uiTemp, sizeof(uiTemp));
}
else if(Adapter->eNVMType == NVM_EEPROM)
{
Status = BeceemEEPROMBulkWrite(Adapter,
(PUCHAR)pBuffer,
uiOffset,
uiNumBytes,
bVerify);
if(bVerify)
{
Status = BeceemEEPROMReadBackandVerify(Adapter,(PUINT)pBuffer,uiOffset,uiNumBytes);
}
}
else
{
Status = -1;
}
return Status;
}
//-----------------------------------------------------------------------------
// Procedure: BcmUpdateSectorSize
//
// Description: Updates the sector size to FLASH.
//
// Arguments:
// Adapter - ptr to Adapter object instance
// uiSectorSize - sector size
//
// Returns:
// OSAL_STATUS_SUCCESS - if NVM write is successful.
// <FAILURE> - if failed.
//-----------------------------------------------------------------------------
INT BcmUpdateSectorSize(PMINI_ADAPTER Adapter,UINT uiSectorSize)
{
INT Status = -1;
FLASH_CS_INFO sFlashCsInfo = {0};
UINT uiTemp = 0;
UINT uiSectorSig = 0;
UINT uiCurrentSectorSize = 0;
UINT value;
rdmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
value = 0;
wrmalt(Adapter, 0x0f000C80,&value, sizeof(value));
//
// Before updating the sector size in the reserved area, check if already present.
//
BeceemFlashBulkRead(Adapter,(PUINT)&sFlashCsInfo,Adapter->ulFlashControlSectionStart,sizeof(sFlashCsInfo));
uiSectorSig = ntohl(sFlashCsInfo.FlashSectorSizeSig);
uiCurrentSectorSize = ntohl(sFlashCsInfo.FlashSectorSize);
if(uiSectorSig == FLASH_SECTOR_SIZE_SIG)
{
if((uiCurrentSectorSize <= MAX_SECTOR_SIZE) && (uiCurrentSectorSize >= MIN_SECTOR_SIZE))
{
if(uiSectorSize == uiCurrentSectorSize)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Provided sector size is same as programmed in Flash");
Status = STATUS_SUCCESS;
goto Restore ;
}
}
}
if((uiSectorSize <= MAX_SECTOR_SIZE) && (uiSectorSize >= MIN_SECTOR_SIZE))
{
sFlashCsInfo.FlashSectorSize = htonl(uiSectorSize);
sFlashCsInfo.FlashSectorSizeSig = htonl(FLASH_SECTOR_SIZE_SIG);
Status = BeceemFlashBulkWrite(Adapter,
(PUINT)&sFlashCsInfo,
Adapter->ulFlashControlSectionStart,
sizeof(sFlashCsInfo),
TRUE);
}
Restore :
// restore the values.
wrmalt(Adapter, 0x0f000C80,&uiTemp, sizeof(uiTemp));
return Status;
}
//-----------------------------------------------------------------------------
// Procedure: BcmGetFlashSectorSize
//
// Description: Finds the sector size of the FLASH.
//
// Arguments:
// Adapter - ptr to Adapter object instance
//
// Returns:
// UINT - sector size.
//
//-----------------------------------------------------------------------------
static UINT BcmGetFlashSectorSize(PMINI_ADAPTER Adapter, UINT FlashSectorSizeSig, UINT FlashSectorSize)
{
UINT uiSectorSize = 0;
UINT uiSectorSig = 0;
if(Adapter->bSectorSizeOverride &&
(Adapter->uiSectorSizeInCFG <= MAX_SECTOR_SIZE &&
Adapter->uiSectorSizeInCFG >= MIN_SECTOR_SIZE))
{
Adapter->uiSectorSize = Adapter->uiSectorSizeInCFG;
}
else
{
uiSectorSig = FlashSectorSizeSig;
if(uiSectorSig == FLASH_SECTOR_SIZE_SIG)
{
uiSectorSize = FlashSectorSize;
//
// If the sector size stored in the FLASH makes sense then use it.
//
if(uiSectorSize <= MAX_SECTOR_SIZE && uiSectorSize >= MIN_SECTOR_SIZE)
{
Adapter->uiSectorSize = uiSectorSize;
}
//No valid size in FLASH, check if Config file has it.
else if(Adapter->uiSectorSizeInCFG <= MAX_SECTOR_SIZE &&
Adapter->uiSectorSizeInCFG >= MIN_SECTOR_SIZE)
{
Adapter->uiSectorSize = Adapter->uiSectorSizeInCFG;
}
// Init to Default, if none of the above works.
else
{
Adapter->uiSectorSize = DEFAULT_SECTOR_SIZE;
}
}
else
{
if(Adapter->uiSectorSizeInCFG <= MAX_SECTOR_SIZE &&
Adapter->uiSectorSizeInCFG >= MIN_SECTOR_SIZE)
{
Adapter->uiSectorSize = Adapter->uiSectorSizeInCFG;
}
else
{
Adapter->uiSectorSize = DEFAULT_SECTOR_SIZE;
}
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Sector size :%x \n", Adapter->uiSectorSize);
return Adapter->uiSectorSize;
}
//-----------------------------------------------------------------------------
// Procedure: BcmInitEEPROMQueues
//
// Description: Initialization of EEPROM queues.
//
// Arguments:
// Adapter - ptr to Adapter object instance
//
// Returns:
// <OSAL_STATUS_CODE>
//-----------------------------------------------------------------------------
static INT BcmInitEEPROMQueues(PMINI_ADAPTER Adapter)
{
UINT value = 0;
/* CHIP Bug : Clear the Avail bits on the Read queue. The default
* value on this register is supposed to be 0x00001102.
* But we get 0x00001122. */
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Fixing reset value on 0x0f003004 register\n" );
value = EEPROM_READ_DATA_AVAIL;
wrmalt( Adapter, EEPROM_SPI_Q_STATUS1_REG, &value, sizeof(value));
/* Flush the all the EEPROM queues. */
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, " Flushing the queues\n");
value =EEPROM_ALL_QUEUE_FLUSH ;
wrmalt( Adapter, SPI_FLUSH_REG, &value, sizeof(value));
value = 0;
wrmalt( Adapter, SPI_FLUSH_REG, &value, sizeof(value) );
/* Read the EEPROM Status Register. Just to see, no real purpose. */
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "EEPROM Status register value = %x\n", ReadEEPROMStatusRegister(Adapter) );
return STATUS_SUCCESS;
} /* BcmInitEEPROMQueues() */
//-----------------------------------------------------------------------------
// Procedure: BcmInitNVM
//
// Description: Initialization of NVM, EEPROM size,FLASH size, sector size etc.
//
// Arguments:
// Adapter - ptr to Adapter object instance
//
// Returns:
// <OSAL_STATUS_CODE>
//-----------------------------------------------------------------------------
INT BcmInitNVM(PMINI_ADAPTER ps_adapter)
{
BcmValidateNvmType(ps_adapter);
BcmInitEEPROMQueues(ps_adapter);
if(ps_adapter->eNVMType == NVM_AUTODETECT)
{
ps_adapter->eNVMType = BcmGetNvmType(ps_adapter);
if(ps_adapter->eNVMType == NVM_UNKNOWN)
{
BCM_DEBUG_PRINT(ps_adapter,DBG_TYPE_PRINTK, 0, 0, "NVM Type is unknown!!\n");
}
}
else if(ps_adapter->eNVMType == NVM_FLASH)
{
BcmGetFlashCSInfo(ps_adapter);
}
BcmGetNvmSize(ps_adapter);
return STATUS_SUCCESS;
}
/***************************************************************************/
/*BcmGetNvmSize : set the EEPROM or flash size in Adapter.
*
*Input Parameter:
* Adapter data structure
*Return Value :
* 0. means success;
*/
/***************************************************************************/
static INT BcmGetNvmSize(PMINI_ADAPTER Adapter)
{
if(Adapter->eNVMType == NVM_EEPROM)
{
Adapter->uiNVMDSDSize = BcmGetEEPROMSize(Adapter);
}
else if(Adapter->eNVMType == NVM_FLASH)
{
Adapter->uiNVMDSDSize = BcmGetFlashSize(Adapter);
}
return 0;
}
//-----------------------------------------------------------------------------
// Procedure: BcmValidateNvm
//
// Description: Validates the NVM Type option selected against the device
//
// Arguments:
// Adapter - ptr to Adapter object instance
//
// Returns:
// <VOID>
//-----------------------------------------------------------------------------
static VOID BcmValidateNvmType(PMINI_ADAPTER Adapter)
{
//
// if forcing the FLASH through CFG file, we should ensure device really has a FLASH.
// Accessing the FLASH address without the FLASH being present can cause hang/freeze etc.
// So if NVM_FLASH is selected for older chipsets, change it to AUTODETECT where EEPROM is 1st choice.
//
if(Adapter->eNVMType == NVM_FLASH &&
Adapter->chip_id < 0xBECE3300)
{
Adapter->eNVMType = NVM_AUTODETECT;
}
}
//-----------------------------------------------------------------------------
// Procedure: BcmReadFlashRDID
//
// Description: Reads ID from Serial Flash
//
// Arguments:
// Adapter - ptr to Adapter object instance
//
// Returns:
// Flash ID
//-----------------------------------------------------------------------------
static ULONG BcmReadFlashRDID(PMINI_ADAPTER Adapter)
{
ULONG ulRDID = 0;
UINT value;
//
// Read ID Instruction.
//
value = (FLASH_CMD_READ_ID<<24);
wrmalt(Adapter, FLASH_SPI_CMDQ_REG,&value, sizeof(value));
//Delay
udelay(10);
//
// Read SPI READQ REG. The output will be WWXXYYZZ.
// The ID is 3Bytes long and is WWXXYY. ZZ needs to be Ignored.
//
rdmalt(Adapter, FLASH_SPI_READQ_REG, (PUINT)&ulRDID, sizeof(ulRDID));
return (ulRDID >>8);
}
INT BcmAllocFlashCSStructure(PMINI_ADAPTER psAdapter)
{
if(psAdapter == NULL)
{
BCM_DEBUG_PRINT(psAdapter,DBG_TYPE_PRINTK, 0, 0, "Adapter structure point is NULL");
return -EINVAL;
}
psAdapter->psFlashCSInfo = (PFLASH_CS_INFO)kzalloc(sizeof(FLASH_CS_INFO), GFP_KERNEL);
if(psAdapter->psFlashCSInfo == NULL)
{
BCM_DEBUG_PRINT(psAdapter,DBG_TYPE_PRINTK, 0, 0,"Can't Allocate memory for Flash 1.x");
return -ENOMEM;
}
psAdapter->psFlash2xCSInfo = (PFLASH2X_CS_INFO)kzalloc(sizeof(FLASH2X_CS_INFO), GFP_KERNEL);
if(psAdapter->psFlash2xCSInfo == NULL)
{
BCM_DEBUG_PRINT(psAdapter,DBG_TYPE_PRINTK, 0, 0,"Can't Allocate memory for Flash 2.x");
kfree(psAdapter->psFlashCSInfo);
return -ENOMEM;
}
psAdapter->psFlash2xVendorInfo = (PFLASH2X_VENDORSPECIFIC_INFO)kzalloc(sizeof(FLASH2X_VENDORSPECIFIC_INFO), GFP_KERNEL);
if(psAdapter->psFlash2xVendorInfo == NULL)
{
BCM_DEBUG_PRINT(psAdapter,DBG_TYPE_PRINTK, 0, 0,"Can't Allocate Vendor Info Memory for Flash 2.x");
kfree(psAdapter->psFlashCSInfo);
kfree(psAdapter->psFlash2xCSInfo);
return -ENOMEM;
}
return STATUS_SUCCESS;
}
INT BcmDeAllocFlashCSStructure(PMINI_ADAPTER psAdapter)
{
if(psAdapter == NULL)
{
BCM_DEBUG_PRINT(psAdapter,DBG_TYPE_PRINTK, 0, 0," Adapter structure point is NULL");
return -EINVAL;
}
kfree(psAdapter->psFlashCSInfo);
kfree(psAdapter->psFlash2xCSInfo);
kfree(psAdapter->psFlash2xVendorInfo);
return STATUS_SUCCESS ;
}
static INT BcmDumpFlash2XCSStructure(PFLASH2X_CS_INFO psFlash2xCSInfo,PMINI_ADAPTER Adapter)
{
UINT Index = 0;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "**********************FLASH2X CS Structure *******************");
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Signature is :%x", (psFlash2xCSInfo->MagicNumber));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Flash Major Version :%d", MAJOR_VERSION(psFlash2xCSInfo->FlashLayoutVersion));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Flash Minor Version :%d", MINOR_VERSION(psFlash2xCSInfo->FlashLayoutVersion));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, " ISOImageMajorVersion:0x%x", (psFlash2xCSInfo->ISOImageVersion));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "SCSIFirmwareMajorVersion :0x%x", (psFlash2xCSInfo->SCSIFirmwareVersion));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForPart1ISOImage :0x%x", (psFlash2xCSInfo->OffsetFromZeroForPart1ISOImage));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForScsiFirmware :0x%x", (psFlash2xCSInfo->OffsetFromZeroForScsiFirmware));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "SizeOfScsiFirmware :0x%x", (psFlash2xCSInfo->SizeOfScsiFirmware ));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForPart2ISOImage :0x%x", (psFlash2xCSInfo->OffsetFromZeroForPart2ISOImage));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForDSDStart :0x%x", (psFlash2xCSInfo->OffsetFromZeroForDSDStart));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForDSDEnd :0x%x", (psFlash2xCSInfo->OffsetFromZeroForDSDEnd));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForVSAStart :0x%x", (psFlash2xCSInfo->OffsetFromZeroForVSAStart));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForVSAEnd :0x%x", (psFlash2xCSInfo->OffsetFromZeroForVSAEnd));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForControlSectionStart :0x%x", (psFlash2xCSInfo->OffsetFromZeroForControlSectionStart));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForControlSectionData :0x%x", (psFlash2xCSInfo->OffsetFromZeroForControlSectionData));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "CDLessInactivityTimeout :0x%x", (psFlash2xCSInfo->CDLessInactivityTimeout));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "NewImageSignature :0x%x", (psFlash2xCSInfo->NewImageSignature));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "FlashSectorSizeSig :0x%x", (psFlash2xCSInfo->FlashSectorSizeSig));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "FlashSectorSize :0x%x", (psFlash2xCSInfo->FlashSectorSize));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "FlashWriteSupportSize :0x%x", (psFlash2xCSInfo->FlashWriteSupportSize));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "TotalFlashSize :0x%X", (psFlash2xCSInfo->TotalFlashSize));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "FlashBaseAddr :0x%x", (psFlash2xCSInfo->FlashBaseAddr));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "FlashPartMaxSize :0x%x", (psFlash2xCSInfo->FlashPartMaxSize));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "IsCDLessDeviceBootSig :0x%x", (psFlash2xCSInfo->IsCDLessDeviceBootSig));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "MassStorageTimeout :0x%x", (psFlash2xCSInfo->MassStorageTimeout));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage1Part1Start :0x%x", (psFlash2xCSInfo->OffsetISOImage1Part1Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage1Part1End :0x%x", (psFlash2xCSInfo->OffsetISOImage1Part1End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage1Part2Start :0x%x", (psFlash2xCSInfo->OffsetISOImage1Part2Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage1Part2End :0x%x", (psFlash2xCSInfo->OffsetISOImage1Part2End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage1Part3Start :0x%x", (psFlash2xCSInfo->OffsetISOImage1Part3Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage1Part3End :0x%x", (psFlash2xCSInfo->OffsetISOImage1Part3End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage2Part1Start :0x%x", (psFlash2xCSInfo->OffsetISOImage2Part1Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage2Part1End :0x%x", (psFlash2xCSInfo->OffsetISOImage2Part1End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage2Part2Start :0x%x", (psFlash2xCSInfo->OffsetISOImage2Part2Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage2Part2End :0x%x", (psFlash2xCSInfo->OffsetISOImage2Part2End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage2Part3Start :0x%x", (psFlash2xCSInfo->OffsetISOImage2Part3Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetISOImage2Part3End :0x%x", (psFlash2xCSInfo->OffsetISOImage2Part3End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromDSDStartForDSDHeader :0x%x", (psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForDSD1Start :0x%x", (psFlash2xCSInfo->OffsetFromZeroForDSD1Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForDSD1End :0x%x", (psFlash2xCSInfo->OffsetFromZeroForDSD1End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForDSD2Start :0x%x", (psFlash2xCSInfo->OffsetFromZeroForDSD2Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForDSD2End :0x%x", (psFlash2xCSInfo->OffsetFromZeroForDSD2End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForVSA1Start :0x%x", (psFlash2xCSInfo->OffsetFromZeroForVSA1Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForVSA1End :0x%x", (psFlash2xCSInfo->OffsetFromZeroForVSA1End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForVSA2Start :0x%x", (psFlash2xCSInfo->OffsetFromZeroForVSA2Start));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "OffsetFromZeroForVSA2End :0x%x", (psFlash2xCSInfo->OffsetFromZeroForVSA2End));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Sector Access Bit Map is Defined as :");
for(Index =0; Index <(FLASH2X_TOTAL_SIZE/(DEFAULT_SECTOR_SIZE *16)); Index++)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "SectorAccessBitMap[%d] :0x%x", Index,
(psFlash2xCSInfo->SectorAccessBitMap[Index]));
}
return STATUS_SUCCESS;
}
static INT ConvertEndianOf2XCSStructure(PFLASH2X_CS_INFO psFlash2xCSInfo)
{
UINT Index = 0;
psFlash2xCSInfo->MagicNumber = ntohl(psFlash2xCSInfo->MagicNumber);
psFlash2xCSInfo->FlashLayoutVersion= ntohl(psFlash2xCSInfo->FlashLayoutVersion);
//psFlash2xCSInfo->FlashLayoutMinorVersion = ntohs(psFlash2xCSInfo->FlashLayoutMinorVersion);
psFlash2xCSInfo->ISOImageVersion = ntohl(psFlash2xCSInfo->ISOImageVersion);
psFlash2xCSInfo->SCSIFirmwareVersion =ntohl(psFlash2xCSInfo->SCSIFirmwareVersion);
psFlash2xCSInfo->OffsetFromZeroForPart1ISOImage = ntohl(psFlash2xCSInfo->OffsetFromZeroForPart1ISOImage);
psFlash2xCSInfo->OffsetFromZeroForScsiFirmware = ntohl(psFlash2xCSInfo->OffsetFromZeroForScsiFirmware);
psFlash2xCSInfo->SizeOfScsiFirmware = ntohl(psFlash2xCSInfo->SizeOfScsiFirmware );
psFlash2xCSInfo->OffsetFromZeroForPart2ISOImage = ntohl(psFlash2xCSInfo->OffsetFromZeroForPart2ISOImage);
psFlash2xCSInfo->OffsetFromZeroForDSDStart = ntohl(psFlash2xCSInfo->OffsetFromZeroForDSDStart);
psFlash2xCSInfo->OffsetFromZeroForDSDEnd = ntohl(psFlash2xCSInfo->OffsetFromZeroForDSDEnd);
psFlash2xCSInfo->OffsetFromZeroForVSAStart = ntohl(psFlash2xCSInfo->OffsetFromZeroForVSAStart);
psFlash2xCSInfo->OffsetFromZeroForVSAEnd = ntohl(psFlash2xCSInfo->OffsetFromZeroForVSAEnd);
psFlash2xCSInfo->OffsetFromZeroForControlSectionStart = ntohl(psFlash2xCSInfo->OffsetFromZeroForControlSectionStart);
psFlash2xCSInfo->OffsetFromZeroForControlSectionData = ntohl(psFlash2xCSInfo->OffsetFromZeroForControlSectionData);
psFlash2xCSInfo->CDLessInactivityTimeout = ntohl(psFlash2xCSInfo->CDLessInactivityTimeout);
psFlash2xCSInfo->NewImageSignature = ntohl(psFlash2xCSInfo->NewImageSignature);
psFlash2xCSInfo->FlashSectorSizeSig = ntohl(psFlash2xCSInfo->FlashSectorSizeSig);
psFlash2xCSInfo->FlashSectorSize = ntohl(psFlash2xCSInfo->FlashSectorSize);
psFlash2xCSInfo->FlashWriteSupportSize = ntohl(psFlash2xCSInfo->FlashWriteSupportSize);
psFlash2xCSInfo->TotalFlashSize = ntohl(psFlash2xCSInfo->TotalFlashSize);
psFlash2xCSInfo->FlashBaseAddr = ntohl(psFlash2xCSInfo->FlashBaseAddr);
psFlash2xCSInfo->FlashPartMaxSize = ntohl(psFlash2xCSInfo->FlashPartMaxSize);
psFlash2xCSInfo->IsCDLessDeviceBootSig = ntohl(psFlash2xCSInfo->IsCDLessDeviceBootSig);
psFlash2xCSInfo->MassStorageTimeout = ntohl(psFlash2xCSInfo->MassStorageTimeout);
psFlash2xCSInfo->OffsetISOImage1Part1Start = ntohl(psFlash2xCSInfo->OffsetISOImage1Part1Start);
psFlash2xCSInfo->OffsetISOImage1Part1End = ntohl(psFlash2xCSInfo->OffsetISOImage1Part1End);
psFlash2xCSInfo->OffsetISOImage1Part2Start = ntohl(psFlash2xCSInfo->OffsetISOImage1Part2Start);
psFlash2xCSInfo->OffsetISOImage1Part2End = ntohl(psFlash2xCSInfo->OffsetISOImage1Part2End);
psFlash2xCSInfo->OffsetISOImage1Part3Start = ntohl(psFlash2xCSInfo->OffsetISOImage1Part3Start);
psFlash2xCSInfo->OffsetISOImage1Part3End = ntohl(psFlash2xCSInfo->OffsetISOImage1Part3End);
psFlash2xCSInfo->OffsetISOImage2Part1Start = ntohl(psFlash2xCSInfo->OffsetISOImage2Part1Start);
psFlash2xCSInfo->OffsetISOImage2Part1End = ntohl(psFlash2xCSInfo->OffsetISOImage2Part1End);
psFlash2xCSInfo->OffsetISOImage2Part2Start = ntohl(psFlash2xCSInfo->OffsetISOImage2Part2Start);
psFlash2xCSInfo->OffsetISOImage2Part2End = ntohl(psFlash2xCSInfo->OffsetISOImage2Part2End);
psFlash2xCSInfo->OffsetISOImage2Part3Start = ntohl(psFlash2xCSInfo->OffsetISOImage2Part3Start);
psFlash2xCSInfo->OffsetISOImage2Part3End = ntohl(psFlash2xCSInfo->OffsetISOImage2Part3End);
psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader = ntohl(psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader);
psFlash2xCSInfo->OffsetFromZeroForDSD1Start = ntohl(psFlash2xCSInfo->OffsetFromZeroForDSD1Start);
psFlash2xCSInfo->OffsetFromZeroForDSD1End = ntohl(psFlash2xCSInfo->OffsetFromZeroForDSD1End);
psFlash2xCSInfo->OffsetFromZeroForDSD2Start = ntohl(psFlash2xCSInfo->OffsetFromZeroForDSD2Start);
psFlash2xCSInfo->OffsetFromZeroForDSD2End = ntohl(psFlash2xCSInfo->OffsetFromZeroForDSD2End);
psFlash2xCSInfo->OffsetFromZeroForVSA1Start = ntohl(psFlash2xCSInfo->OffsetFromZeroForVSA1Start);
psFlash2xCSInfo->OffsetFromZeroForVSA1End = ntohl(psFlash2xCSInfo->OffsetFromZeroForVSA1End);
psFlash2xCSInfo->OffsetFromZeroForVSA2Start = ntohl(psFlash2xCSInfo->OffsetFromZeroForVSA2Start);
psFlash2xCSInfo->OffsetFromZeroForVSA2End = ntohl(psFlash2xCSInfo->OffsetFromZeroForVSA2End);
for(Index =0; Index <(FLASH2X_TOTAL_SIZE/(DEFAULT_SECTOR_SIZE *16)); Index++)
{
psFlash2xCSInfo->SectorAccessBitMap[Index] = ntohl(psFlash2xCSInfo->SectorAccessBitMap[Index]);
}
return STATUS_SUCCESS;
}
static INT ConvertEndianOfCSStructure(PFLASH_CS_INFO psFlashCSInfo)
{
//UINT Index = 0;
psFlashCSInfo->MagicNumber =ntohl(psFlashCSInfo->MagicNumber);
psFlashCSInfo->FlashLayoutVersion =ntohl(psFlashCSInfo->FlashLayoutVersion);
psFlashCSInfo->ISOImageVersion = ntohl(psFlashCSInfo->ISOImageVersion);
//won't convert according to old assumption
psFlashCSInfo->SCSIFirmwareVersion =(psFlashCSInfo->SCSIFirmwareVersion);
psFlashCSInfo->OffsetFromZeroForPart1ISOImage = ntohl(psFlashCSInfo->OffsetFromZeroForPart1ISOImage);
psFlashCSInfo->OffsetFromZeroForScsiFirmware = ntohl(psFlashCSInfo->OffsetFromZeroForScsiFirmware);
psFlashCSInfo->SizeOfScsiFirmware = ntohl(psFlashCSInfo->SizeOfScsiFirmware );
psFlashCSInfo->OffsetFromZeroForPart2ISOImage = ntohl(psFlashCSInfo->OffsetFromZeroForPart2ISOImage);
psFlashCSInfo->OffsetFromZeroForCalibrationStart = ntohl(psFlashCSInfo->OffsetFromZeroForCalibrationStart);
psFlashCSInfo->OffsetFromZeroForCalibrationEnd = ntohl(psFlashCSInfo->OffsetFromZeroForCalibrationEnd);
psFlashCSInfo->OffsetFromZeroForVSAStart = ntohl(psFlashCSInfo->OffsetFromZeroForVSAStart);
psFlashCSInfo->OffsetFromZeroForVSAEnd = ntohl(psFlashCSInfo->OffsetFromZeroForVSAEnd);
psFlashCSInfo->OffsetFromZeroForControlSectionStart = ntohl(psFlashCSInfo->OffsetFromZeroForControlSectionStart);
psFlashCSInfo->OffsetFromZeroForControlSectionData = ntohl(psFlashCSInfo->OffsetFromZeroForControlSectionData);
psFlashCSInfo->CDLessInactivityTimeout = ntohl(psFlashCSInfo->CDLessInactivityTimeout);
psFlashCSInfo->NewImageSignature = ntohl(psFlashCSInfo->NewImageSignature);
psFlashCSInfo->FlashSectorSizeSig = ntohl(psFlashCSInfo->FlashSectorSizeSig);
psFlashCSInfo->FlashSectorSize = ntohl(psFlashCSInfo->FlashSectorSize);
psFlashCSInfo->FlashWriteSupportSize = ntohl(psFlashCSInfo->FlashWriteSupportSize);
psFlashCSInfo->TotalFlashSize = ntohl(psFlashCSInfo->TotalFlashSize);
psFlashCSInfo->FlashBaseAddr = ntohl(psFlashCSInfo->FlashBaseAddr);
psFlashCSInfo->FlashPartMaxSize = ntohl(psFlashCSInfo->FlashPartMaxSize);
psFlashCSInfo->IsCDLessDeviceBootSig = ntohl(psFlashCSInfo->IsCDLessDeviceBootSig);
psFlashCSInfo->MassStorageTimeout = ntohl(psFlashCSInfo->MassStorageTimeout);
return STATUS_SUCCESS;
}
static INT IsSectionExistInVendorInfo(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL section)
{
return ( Adapter->uiVendorExtnFlag &&
(Adapter->psFlash2xVendorInfo->VendorSection[section].AccessFlags & FLASH2X_SECTION_PRESENT) &&
(Adapter->psFlash2xVendorInfo->VendorSection[section].OffsetFromZeroForSectionStart != UNINIT_PTR_IN_CS) );
}
static VOID UpdateVendorInfo(PMINI_ADAPTER Adapter)
{
B_UINT32 i = 0;
UINT uiSizeSection = 0;
Adapter->uiVendorExtnFlag = FALSE;
for(i = 0;i < TOTAL_SECTIONS;i++)
Adapter->psFlash2xVendorInfo->VendorSection[i].OffsetFromZeroForSectionStart = UNINIT_PTR_IN_CS;
if(STATUS_SUCCESS != vendorextnGetSectionInfo(Adapter, Adapter->psFlash2xVendorInfo))
return;
i = 0;
while(i < TOTAL_SECTIONS)
{
if(!(Adapter->psFlash2xVendorInfo->VendorSection[i].AccessFlags & FLASH2X_SECTION_PRESENT))
{
i++;
continue;
}
Adapter->uiVendorExtnFlag = TRUE;
uiSizeSection = (Adapter->psFlash2xVendorInfo->VendorSection[i].OffsetFromZeroForSectionEnd -
Adapter->psFlash2xVendorInfo->VendorSection[i].OffsetFromZeroForSectionStart);
switch(i)
{
case DSD0:
if(( uiSizeSection >= (Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader + sizeof(DSD_HEADER))) &&
(UNINIT_PTR_IN_CS != Adapter->psFlash2xVendorInfo->VendorSection[i].OffsetFromZeroForSectionStart))
Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDEnd = VENDOR_PTR_IN_CS;
else
Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDEnd = UNINIT_PTR_IN_CS;
break;
case DSD1:
if(( uiSizeSection >= (Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader + sizeof(DSD_HEADER))) &&
(UNINIT_PTR_IN_CS != Adapter->psFlash2xVendorInfo->VendorSection[i].OffsetFromZeroForSectionStart))
Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1Start = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1End = VENDOR_PTR_IN_CS;
else
Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1Start = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1End = UNINIT_PTR_IN_CS;
break;
case DSD2:
if(( uiSizeSection >= (Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader + sizeof(DSD_HEADER))) &&
(UNINIT_PTR_IN_CS != Adapter->psFlash2xVendorInfo->VendorSection[i].OffsetFromZeroForSectionStart))
Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2Start = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2End = VENDOR_PTR_IN_CS;
else
Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2Start = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2End = UNINIT_PTR_IN_CS;
break;
case VSA0:
if(UNINIT_PTR_IN_CS != Adapter->psFlash2xVendorInfo->VendorSection[i].OffsetFromZeroForSectionStart)
Adapter->psFlash2xCSInfo->OffsetFromZeroForVSAStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForVSAEnd = VENDOR_PTR_IN_CS;
else
Adapter->psFlash2xCSInfo->OffsetFromZeroForVSAStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForVSAEnd = UNINIT_PTR_IN_CS;
break;
case VSA1:
if(UNINIT_PTR_IN_CS != Adapter->psFlash2xVendorInfo->VendorSection[i].OffsetFromZeroForSectionStart)
Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA1Start = Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA1End = VENDOR_PTR_IN_CS;
else
Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA1Start = Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA1End = UNINIT_PTR_IN_CS;
break;
case VSA2:
if(UNINIT_PTR_IN_CS != Adapter->psFlash2xVendorInfo->VendorSection[i].OffsetFromZeroForSectionStart)
Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA2Start = Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA2End = VENDOR_PTR_IN_CS;
else
Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA2Start = Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA2End = UNINIT_PTR_IN_CS;
break;
default:
break;
}
i++;
}
}
//-----------------------------------------------------------------------------
// Procedure: BcmGetFlashCSInfo
//
// Description: Reads control structure and gets Cal section addresses.
//
// Arguments:
// Adapter - ptr to Adapter object instance
//
// Returns:
// <VOID>
//-----------------------------------------------------------------------------
static INT BcmGetFlashCSInfo(PMINI_ADAPTER Adapter)
{
//FLASH_CS_INFO sFlashCsInfo = {0};
#if !defined(BCM_SHM_INTERFACE) || defined(FLASH_DIRECT_ACCESS)
UINT value;
#endif
UINT uiFlashLayoutMajorVersion;
Adapter->uiFlashLayoutMinorVersion = 0;
Adapter->uiFlashLayoutMajorVersion = 0;
Adapter->ulFlashControlSectionStart = FLASH_CS_INFO_START_ADDR;
Adapter->uiFlashBaseAdd = 0;
Adapter->ulFlashCalStart = 0;
memset(Adapter->psFlashCSInfo, 0 ,sizeof(FLASH_CS_INFO));
memset(Adapter->psFlash2xCSInfo, 0 ,sizeof(FLASH2X_CS_INFO));
if(!Adapter->bDDRInitDone)
{
{
value = FLASH_CONTIGIOUS_START_ADDR_BEFORE_INIT;
wrmalt(Adapter, 0xAF00A080, &value, sizeof(value));
}
}
// Reading first 8 Bytes to get the Flash Layout
// MagicNumber(4 bytes) +FlashLayoutMinorVersion(2 Bytes) +FlashLayoutMajorVersion(2 Bytes)
BeceemFlashBulkRead(Adapter,(PUINT)Adapter->psFlashCSInfo,Adapter->ulFlashControlSectionStart,8);
Adapter->psFlashCSInfo->FlashLayoutVersion = ntohl(Adapter->psFlashCSInfo->FlashLayoutVersion);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Flash Layout Version :%X", (Adapter->psFlashCSInfo->FlashLayoutVersion));
//BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Flash Layout Minor Version :%d\n", ntohs(sFlashCsInfo.FlashLayoutMinorVersion));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Signature is :%x\n", ntohl(Adapter->psFlashCSInfo->MagicNumber));
if(FLASH_CONTROL_STRUCT_SIGNATURE == ntohl(Adapter->psFlashCSInfo->MagicNumber))
{
uiFlashLayoutMajorVersion = MAJOR_VERSION((Adapter->psFlashCSInfo->FlashLayoutVersion));
Adapter->uiFlashLayoutMinorVersion = MINOR_VERSION((Adapter->psFlashCSInfo->FlashLayoutVersion));
}
else
{
Adapter->uiFlashLayoutMinorVersion = 0;
uiFlashLayoutMajorVersion = 0;
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"FLASH LAYOUT MAJOR VERSION :%X", uiFlashLayoutMajorVersion);
if(uiFlashLayoutMajorVersion < FLASH_2X_MAJOR_NUMBER)
{
BeceemFlashBulkRead(Adapter,(PUINT)Adapter->psFlashCSInfo,Adapter->ulFlashControlSectionStart,sizeof(FLASH_CS_INFO));
ConvertEndianOfCSStructure(Adapter->psFlashCSInfo);
Adapter->ulFlashCalStart = (Adapter->psFlashCSInfo->OffsetFromZeroForCalibrationStart);
if(!((Adapter->uiFlashLayoutMajorVersion == 1) && (Adapter->uiFlashLayoutMinorVersion == 1)))
{
Adapter->ulFlashControlSectionStart = Adapter->psFlashCSInfo->OffsetFromZeroForControlSectionStart;
}
if((FLASH_CONTROL_STRUCT_SIGNATURE == (Adapter->psFlashCSInfo->MagicNumber)) &&
(SCSI_FIRMWARE_MINOR_VERSION <= MINOR_VERSION(Adapter->psFlashCSInfo->SCSIFirmwareVersion)) &&
(FLASH_SECTOR_SIZE_SIG == (Adapter->psFlashCSInfo->FlashSectorSizeSig)) &&
(BYTE_WRITE_SUPPORT == (Adapter->psFlashCSInfo->FlashWriteSupportSize)))
{
Adapter->ulFlashWriteSize = (Adapter->psFlashCSInfo->FlashWriteSupportSize);
Adapter->fpFlashWrite = flashByteWrite;
Adapter->fpFlashWriteWithStatusCheck = flashByteWriteStatus;
}
else
{
Adapter->ulFlashWriteSize = MAX_RW_SIZE;
Adapter->fpFlashWrite = flashWrite;
Adapter->fpFlashWriteWithStatusCheck = flashWriteStatus;
}
BcmGetFlashSectorSize(Adapter, (Adapter->psFlashCSInfo->FlashSectorSizeSig),
(Adapter->psFlashCSInfo->FlashSectorSize));
Adapter->uiFlashBaseAdd = Adapter->psFlashCSInfo->FlashBaseAddr & 0xFCFFFFFF;
}
else
{
if(BcmFlash2xBulkRead(Adapter,(PUINT)Adapter->psFlash2xCSInfo,NO_SECTION_VAL,
Adapter->ulFlashControlSectionStart,sizeof(FLASH2X_CS_INFO)))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Unable to read CS structure \n");
return STATUS_FAILURE;
}
ConvertEndianOf2XCSStructure(Adapter->psFlash2xCSInfo);
BcmDumpFlash2XCSStructure(Adapter->psFlash2xCSInfo,Adapter);
if((FLASH_CONTROL_STRUCT_SIGNATURE == Adapter->psFlash2xCSInfo->MagicNumber) &&
(SCSI_FIRMWARE_MINOR_VERSION <= MINOR_VERSION(Adapter->psFlash2xCSInfo->SCSIFirmwareVersion)) &&
(FLASH_SECTOR_SIZE_SIG == Adapter->psFlash2xCSInfo->FlashSectorSizeSig) &&
(BYTE_WRITE_SUPPORT == Adapter->psFlash2xCSInfo->FlashWriteSupportSize))
{
Adapter->ulFlashWriteSize = Adapter->psFlash2xCSInfo->FlashWriteSupportSize;
Adapter->fpFlashWrite = flashByteWrite;
Adapter->fpFlashWriteWithStatusCheck = flashByteWriteStatus;
}
else
{
Adapter->ulFlashWriteSize = MAX_RW_SIZE;
Adapter->fpFlashWrite = flashWrite;
Adapter->fpFlashWriteWithStatusCheck = flashWriteStatus;
}
BcmGetFlashSectorSize(Adapter, Adapter->psFlash2xCSInfo->FlashSectorSizeSig,
Adapter->psFlash2xCSInfo->FlashSectorSize);
UpdateVendorInfo(Adapter);
BcmGetActiveDSD(Adapter);
BcmGetActiveISO(Adapter);
Adapter->uiFlashBaseAdd = Adapter->psFlash2xCSInfo->FlashBaseAddr & 0xFCFFFFFF;
Adapter->ulFlashControlSectionStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForControlSectionStart;
}
/*
Concerns: what if CS sector size does not match with this sector size ???
what is the indication of AccessBitMap in CS in flash 2.x ????
*/
Adapter->ulFlashID = BcmReadFlashRDID(Adapter);
Adapter->uiFlashLayoutMajorVersion = uiFlashLayoutMajorVersion;
return STATUS_SUCCESS ;
}
//-----------------------------------------------------------------------------
// Procedure: BcmGetNvmType
//
// Description: Finds the type of NVM used.
//
// Arguments:
// Adapter - ptr to Adapter object instance
//
// Returns:
// NVM_TYPE
//
//-----------------------------------------------------------------------------
static NVM_TYPE BcmGetNvmType(PMINI_ADAPTER Adapter)
{
UINT uiData = 0;
BeceemEEPROMBulkRead(Adapter,&uiData,0x0,4);
if(uiData == BECM)
{
return NVM_EEPROM;
}
//
// Read control struct and get cal addresses before accessing the flash
//
BcmGetFlashCSInfo(Adapter);
BeceemFlashBulkRead(Adapter,&uiData,0x0 + Adapter->ulFlashCalStart,4);
if(uiData == BECM)
{
return NVM_FLASH;
}
//
// even if there is no valid signature on EEPROM/FLASH find out if they really exist.
// if exist select it.
//
if(BcmGetEEPROMSize(Adapter))
{
return NVM_EEPROM;
}
//TBD for Flash.
return NVM_UNKNOWN;
}
/**
* BcmGetSectionValStartOffset - this will calculate the section's starting offset if section val is given
* @Adapter : Drivers Private Data structure
* @eFlashSectionVal : Flash secion value defined in enum FLASH2X_SECTION_VAL
*
* Return value:-
* On success it return the start offset of the provided section val
* On Failure -returns STATUS_FAILURE
**/
INT BcmGetSectionValStartOffset(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlashSectionVal)
{
/*
* Considering all the section for which end offset can be calculated or directly given
* in CS Structure. if matching case does not exist, return STATUS_FAILURE indicating section
* endoffset can't be calculated or given in CS Structure.
*/
INT SectStartOffset = 0 ;
SectStartOffset = INVALID_OFFSET ;
if(IsSectionExistInVendorInfo(Adapter,eFlashSectionVal))
{
return Adapter->psFlash2xVendorInfo->VendorSection[eFlashSectionVal].OffsetFromZeroForSectionStart;
}
switch(eFlashSectionVal)
{
case ISO_IMAGE1 :
if((Adapter->psFlash2xCSInfo->OffsetISOImage1Part1Start != UNINIT_PTR_IN_CS) &&
(IsNonCDLessDevice(Adapter) == FALSE))
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage1Part1Start);
break;
case ISO_IMAGE2 :
if((Adapter->psFlash2xCSInfo->OffsetISOImage2Part1Start != UNINIT_PTR_IN_CS) &&
(IsNonCDLessDevice(Adapter) == FALSE))
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage2Part1Start);
break;
case DSD0 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDStart != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDStart);
break;
case DSD1 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1Start != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1Start);
break;
case DSD2 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2Start != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2Start);
break;
case VSA0 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForVSAStart != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForVSAStart);
break;
case VSA1 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA1Start != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA1Start);
break;
case VSA2 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA2Start != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA2Start);
break;
case SCSI :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForScsiFirmware != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForScsiFirmware);
break;
case CONTROL_SECTION :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForControlSectionStart != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForControlSectionStart);
break;
case ISO_IMAGE1_PART2 :
if(Adapter->psFlash2xCSInfo->OffsetISOImage1Part2Start != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage1Part2Start);
break;
case ISO_IMAGE1_PART3 :
if(Adapter->psFlash2xCSInfo->OffsetISOImage1Part3Start != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage1Part3Start);
break;
case ISO_IMAGE2_PART2 :
if(Adapter->psFlash2xCSInfo->OffsetISOImage2Part2Start != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage2Part2Start);
break;
case ISO_IMAGE2_PART3 :
if(Adapter->psFlash2xCSInfo->OffsetISOImage2Part3Start != UNINIT_PTR_IN_CS)
SectStartOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage2Part3Start);
break;
default :
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Section Does not exist in Flash 2.x");
SectStartOffset = INVALID_OFFSET;
}
return SectStartOffset;
}
/**
* BcmGetSectionValEndOffset - this will calculate the section's Ending offset if section val is given
* @Adapter : Drivers Private Data structure
* @eFlashSectionVal : Flash secion value defined in enum FLASH2X_SECTION_VAL
*
* Return value:-
* On success it return the end offset of the provided section val
* On Failure -returns STATUS_FAILURE
**/
INT BcmGetSectionValEndOffset(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlash2xSectionVal)
{
INT SectEndOffset = 0 ;
SectEndOffset = INVALID_OFFSET;
if(IsSectionExistInVendorInfo(Adapter,eFlash2xSectionVal))
{
return Adapter->psFlash2xVendorInfo->VendorSection[eFlash2xSectionVal].OffsetFromZeroForSectionEnd;
}
switch(eFlash2xSectionVal)
{
case ISO_IMAGE1 :
if((Adapter->psFlash2xCSInfo->OffsetISOImage1Part1End!= UNINIT_PTR_IN_CS) &&
(IsNonCDLessDevice(Adapter) == FALSE))
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage1Part1End);
break;
case ISO_IMAGE2 :
if((Adapter->psFlash2xCSInfo->OffsetISOImage2Part1End!= UNINIT_PTR_IN_CS) &&
(IsNonCDLessDevice(Adapter) == FALSE))
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage2Part1End);
break;
case DSD0 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDEnd != UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDEnd);
break;
case DSD1 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1End != UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1End);
break;
case DSD2 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2End != UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2End);
break;
case VSA0 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForVSAEnd != UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForVSAEnd);
break;
case VSA1 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA1End != UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA1End);
break;
case VSA2 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA2End != UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA2End);
break;
case SCSI :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForScsiFirmware != UNINIT_PTR_IN_CS)
SectEndOffset = ((Adapter->psFlash2xCSInfo->OffsetFromZeroForScsiFirmware) +
(Adapter->psFlash2xCSInfo->SizeOfScsiFirmware));
break;
case CONTROL_SECTION :
//Not Clear So Putting failure. confirm and fix it.
SectEndOffset = STATUS_FAILURE;
case ISO_IMAGE1_PART2 :
if(Adapter->psFlash2xCSInfo->OffsetISOImage1Part2End!= UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage1Part2End);
break;
case ISO_IMAGE1_PART3 :
if(Adapter->psFlash2xCSInfo->OffsetISOImage1Part3End!= UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage1Part3End);
break;
case ISO_IMAGE2_PART2 :
if(Adapter->psFlash2xCSInfo->OffsetISOImage2Part2End != UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage2Part2End);
break;
case ISO_IMAGE2_PART3 :
if(Adapter->psFlash2xCSInfo->OffsetISOImage2Part3End!= UNINIT_PTR_IN_CS)
SectEndOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage2Part3End);
break;
default :
SectEndOffset = INVALID_OFFSET;
}
return SectEndOffset ;
}
/*
* BcmFlash2xBulkRead:- Read API for Flash Map 2.x .
* @Adapter :Driver Private Data Structure
* @pBuffer : Buffer where data has to be put after reading
* @eFlashSectionVal :Flash Section Val defined in FLASH2X_SECTION_VAL
* @uiOffsetWithinSectionVal :- Offset with in provided section
* @uiNumBytes : Number of Bytes for Read
*
* Return value:-
* return true on success and STATUS_FAILURE on fail.
*/
INT BcmFlash2xBulkRead(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
FLASH2X_SECTION_VAL eFlash2xSectionVal,
UINT uiOffsetWithinSectionVal,
UINT uiNumBytes)
{
INT Status = STATUS_SUCCESS;
INT SectionStartOffset = 0;
UINT uiAbsoluteOffset = 0 ;
UINT uiTemp =0, value =0 ;
if(Adapter == NULL)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Adapter structure is NULL");
return -EINVAL;
}
if(Adapter->device_removed )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Device has been removed");
return -ENODEV;
}
//NO_SECTION_VAL means absolute offset is given.
if(eFlash2xSectionVal == NO_SECTION_VAL)
SectionStartOffset = 0;
else
SectionStartOffset = BcmGetSectionValStartOffset(Adapter,eFlash2xSectionVal);
if(SectionStartOffset == STATUS_FAILURE )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"This Section<%d> does not exixt in Flash 2.x Map ",eFlash2xSectionVal);
return -EINVAL;
}
if(IsSectionExistInVendorInfo(Adapter,eFlash2xSectionVal))
return vendorextnReadSection(Adapter,(PUCHAR)pBuffer, eFlash2xSectionVal, uiOffsetWithinSectionVal, uiNumBytes);
//calculating the absolute offset from FLASH;
uiAbsoluteOffset = uiOffsetWithinSectionVal + SectionStartOffset;
rdmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
value = 0;
wrmalt(Adapter, 0x0f000C80,&value, sizeof(value));
Status= BeceemFlashBulkRead(Adapter, pBuffer,uiAbsoluteOffset,uiNumBytes) ;
wrmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Flash Read Failed with Status :%d", Status);
return Status ;
}
return Status;
}
/*
* BcmFlash2xBulkWrite :-API for Writing on the Flash Map 2.x.
* @Adapter :Driver Private Data Structure
* @pBuffer : Buffer From where data has to taken for writing
* @eFlashSectionVal :Flash Section Val defined in FLASH2X_SECTION_VAL
* @uiOffsetWithinSectionVal :- Offset with in provided section
* @uiNumBytes : Number of Bytes for Write
*
* Return value:-
* return true on success and STATUS_FAILURE on fail.
*
*/
INT BcmFlash2xBulkWrite(
PMINI_ADAPTER Adapter,
PUINT pBuffer,
FLASH2X_SECTION_VAL eFlash2xSectVal,
UINT uiOffset,
UINT uiNumBytes,
UINT bVerify)
{
INT Status = STATUS_SUCCESS;
UINT FlashSectValStartOffset = 0;
UINT uiTemp = 0, value = 0;
if(Adapter == NULL)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Adapter structure is NULL");
return -EINVAL;
}
if(Adapter->device_removed )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Device has been removed");
return -ENODEV;
}
//NO_SECTION_VAL means absolute offset is given.
if(eFlash2xSectVal == NO_SECTION_VAL)
FlashSectValStartOffset = 0;
else
FlashSectValStartOffset = BcmGetSectionValStartOffset(Adapter,eFlash2xSectVal);
if(FlashSectValStartOffset == STATUS_FAILURE )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"This Section<%d> does not exixt in Flash Map 2.x",eFlash2xSectVal);
return -EINVAL;
}
if(IsSectionExistInVendorInfo(Adapter,eFlash2xSectVal))
return vendorextnWriteSection(Adapter, (PUCHAR)pBuffer, eFlash2xSectVal, uiOffset, uiNumBytes, bVerify);
//calculating the absolute offset from FLASH;
uiOffset = uiOffset + FlashSectValStartOffset;
rdmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
value = 0;
wrmalt(Adapter, 0x0f000C80,&value, sizeof(value));
Status = BeceemFlashBulkWrite(Adapter, pBuffer,uiOffset,uiNumBytes,bVerify);
wrmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Flash Write failed with Status :%d", Status);
return Status ;
}
return Status;
}
/**
* BcmGetActiveDSD : Set the Active DSD in Adapter Structure which has to be dumped in DDR
* @Adapter :-Drivers private Data Structure
*
* Return Value:-
* Return STATUS_SUCESS if get success in setting the right DSD else negaive error code
*
**/
static INT BcmGetActiveDSD(PMINI_ADAPTER Adapter)
{
FLASH2X_SECTION_VAL uiHighestPriDSD = 0 ;
uiHighestPriDSD = getHighestPriDSD(Adapter);
Adapter->eActiveDSD = uiHighestPriDSD;
if(DSD0 == uiHighestPriDSD)
Adapter->ulFlashCalStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDStart;
if(DSD1 == uiHighestPriDSD)
Adapter->ulFlashCalStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1Start;
if(DSD2 == uiHighestPriDSD)
Adapter->ulFlashCalStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2Start;
if(Adapter->eActiveDSD)
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Active DSD :%d", Adapter->eActiveDSD);
if(Adapter->eActiveDSD == 0)
{
//if No DSD gets Active, Make Active the DSD with WR permission
if(IsSectionWritable(Adapter,DSD2))
{
Adapter->eActiveDSD = DSD2;
Adapter->ulFlashCalStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2Start;
}
else if(IsSectionWritable(Adapter,DSD1))
{
Adapter->eActiveDSD = DSD1;
Adapter->ulFlashCalStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1Start;
}
else if(IsSectionWritable(Adapter,DSD0))
{
Adapter->eActiveDSD = DSD0;
Adapter->ulFlashCalStart = Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDStart;
}
}
return STATUS_SUCCESS;
}
/**
* BcmGetActiveISO :- Set the Active ISO in Adapter Data Structue
* @Adapter : Driver private Data Structure
*
* Return Value:-
* Sucsess:- STATUS_SUCESS
* Failure- : negative erro code
*
**/
static INT BcmGetActiveISO(PMINI_ADAPTER Adapter)
{
INT HighestPriISO = 0 ;
HighestPriISO = getHighestPriISO(Adapter);
Adapter->eActiveISO = HighestPriISO ;
if(Adapter->eActiveISO == ISO_IMAGE2)
Adapter->uiActiveISOOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage2Part1Start);
else if(Adapter->eActiveISO == ISO_IMAGE1)
Adapter->uiActiveISOOffset = (Adapter->psFlash2xCSInfo->OffsetISOImage1Part1Start);
if(Adapter->eActiveISO)
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Active ISO :%x", Adapter->eActiveISO);
return STATUS_SUCCESS;
}
/**
* IsOffsetWritable :- it will tell the access permission of the sector having passed offset
* @Adapter : Drivers Private Data Structure
* @uiOffset : Offset provided in the Flash
*
* Return Value:-
* Success:-TRUE , offset is writable
* Failure:-FALSE, offset is RO
*
**/
B_UINT8 IsOffsetWritable(PMINI_ADAPTER Adapter, UINT uiOffset)
{
UINT uiSectorNum = 0;
UINT uiWordOfSectorPermission =0;
UINT uiBitofSectorePermission = 0;
B_UINT32 permissionBits = 0;
uiSectorNum = uiOffset/Adapter->uiSectorSize;
//calculating the word having this Sector Access permission from SectorAccessBitMap Array
uiWordOfSectorPermission = Adapter->psFlash2xCSInfo->SectorAccessBitMap[uiSectorNum /16];
//calculating the bit index inside the word for this sector
uiBitofSectorePermission = 2*(15 - uiSectorNum %16);
//Setting Access permission
permissionBits = uiWordOfSectorPermission & (0x3 << uiBitofSectorePermission) ;
permissionBits = (permissionBits >> uiBitofSectorePermission) & 0x3;
if(permissionBits == SECTOR_READWRITE_PERMISSION)
return TRUE;
else
return FALSE;
}
static INT BcmDumpFlash2xSectionBitMap(PFLASH2X_BITMAP psFlash2xBitMap)
{
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "***************Flash 2.x Section Bitmap***************");
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"ISO_IMAGE1 :0X%x", psFlash2xBitMap->ISO_IMAGE1);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"ISO_IMAGE2 :0X%x", psFlash2xBitMap->ISO_IMAGE2);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"DSD0 :0X%x", psFlash2xBitMap->DSD0);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"DSD1 :0X%x", psFlash2xBitMap->DSD1);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"DSD2 :0X%x", psFlash2xBitMap->DSD2);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"VSA0 :0X%x", psFlash2xBitMap->VSA0);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"VSA1 :0X%x", psFlash2xBitMap->VSA1);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"VSA2 :0X%x", psFlash2xBitMap->VSA2);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"SCSI :0X%x", psFlash2xBitMap->SCSI);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"CONTROL_SECTION :0X%x", psFlash2xBitMap->CONTROL_SECTION);
return STATUS_SUCCESS;
}
/**
* BcmGetFlash2xSectionalBitMap :- It will provide the bit map of all the section present in Flash
* 8bit has been assigned to every section.
bit[0] :Section present or not
bit[1] :section is valid or not
bit[2] : Secton is read only or has write permission too.
bit[3] : Active Section -
bit[7...4] = Reserved .
@Adapter:-Driver private Data Structure
*
* Return value:-
* Success:- STATUS_SUCESS
* Failure:- negative error code
**/
INT BcmGetFlash2xSectionalBitMap(PMINI_ADAPTER Adapter, PFLASH2X_BITMAP psFlash2xBitMap)
{
PFLASH2X_CS_INFO psFlash2xCSInfo = Adapter->psFlash2xCSInfo;
FLASH2X_SECTION_VAL uiHighestPriDSD = 0 ;
FLASH2X_SECTION_VAL uiHighestPriISO= 0 ;
BOOLEAN SetActiveDSDDone = FALSE ;
BOOLEAN SetActiveISODone = FALSE ;
//For 1.x map all the section except DSD0 will be shown as not present
//This part will be used by calibration tool to detect the number of DSD present in Flash.
if(IsFlash2x(Adapter) == FALSE)
{
psFlash2xBitMap->ISO_IMAGE2 = 0;
psFlash2xBitMap->ISO_IMAGE1 = 0;
psFlash2xBitMap->DSD0 = FLASH2X_SECTION_VALID | FLASH2X_SECTION_ACT | FLASH2X_SECTION_PRESENT; //0xF; //0000(Reseved)1(Active)0(RW)1(valid)1(present)
psFlash2xBitMap->DSD1 = 0 ;
psFlash2xBitMap->DSD2 = 0 ;
psFlash2xBitMap->VSA0 = 0 ;
psFlash2xBitMap->VSA1 = 0 ;
psFlash2xBitMap->VSA2 = 0 ;
psFlash2xBitMap->CONTROL_SECTION = 0 ;
psFlash2xBitMap->SCSI= 0 ;
psFlash2xBitMap->Reserved0 = 0 ;
psFlash2xBitMap->Reserved1 = 0 ;
psFlash2xBitMap->Reserved2 = 0 ;
return STATUS_SUCCESS ;
}
uiHighestPriDSD = getHighestPriDSD(Adapter);
uiHighestPriISO = getHighestPriISO(Adapter);
///
// IS0 IMAGE 2
///
if((psFlash2xCSInfo->OffsetISOImage2Part1Start) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->ISO_IMAGE2= psFlash2xBitMap->ISO_IMAGE2 | FLASH2X_SECTION_PRESENT;
if(ReadISOSignature(Adapter,ISO_IMAGE2)== ISO_IMAGE_MAGIC_NUMBER)
psFlash2xBitMap->ISO_IMAGE2 |= FLASH2X_SECTION_VALID;
//Calculation for extrating the Access permission
if(IsSectionWritable(Adapter, ISO_IMAGE2) == FALSE)
psFlash2xBitMap->ISO_IMAGE2 |= FLASH2X_SECTION_RO;
if(SetActiveISODone == FALSE && uiHighestPriISO == ISO_IMAGE2)
{
psFlash2xBitMap->ISO_IMAGE2 |= FLASH2X_SECTION_ACT ;
SetActiveISODone = TRUE;
}
}
///
// IS0 IMAGE 1
///
if((psFlash2xCSInfo->OffsetISOImage1Part1Start) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->ISO_IMAGE1 = psFlash2xBitMap->ISO_IMAGE1 | FLASH2X_SECTION_PRESENT;
if(ReadISOSignature(Adapter,ISO_IMAGE1) == ISO_IMAGE_MAGIC_NUMBER)
psFlash2xBitMap->ISO_IMAGE1 |= FLASH2X_SECTION_VALID;
// Calculation for extrating the Access permission
if(IsSectionWritable(Adapter, ISO_IMAGE1) == FALSE)
psFlash2xBitMap->ISO_IMAGE1 |= FLASH2X_SECTION_RO;
if(SetActiveISODone == FALSE && uiHighestPriISO == ISO_IMAGE1)
{
psFlash2xBitMap->ISO_IMAGE1 |= FLASH2X_SECTION_ACT ;
SetActiveISODone = TRUE;
}
}
///
// DSD2
///
if((psFlash2xCSInfo->OffsetFromZeroForDSD2Start) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->DSD2= psFlash2xBitMap->DSD2 | FLASH2X_SECTION_PRESENT;
if(ReadDSDSignature(Adapter,DSD2)== DSD_IMAGE_MAGIC_NUMBER)
psFlash2xBitMap->DSD2 |= FLASH2X_SECTION_VALID;
//Calculation for extrating the Access permission
if(IsSectionWritable(Adapter, DSD2) == FALSE)
{
psFlash2xBitMap->DSD2 |= FLASH2X_SECTION_RO;
}
else
{
//Means section is writable
if((SetActiveDSDDone == FALSE) && (uiHighestPriDSD == DSD2))
{
psFlash2xBitMap->DSD2 |= FLASH2X_SECTION_ACT ;
SetActiveDSDDone =TRUE ;
}
}
}
///
// DSD 1
///
if((psFlash2xCSInfo->OffsetFromZeroForDSD1Start) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->DSD1= psFlash2xBitMap->DSD1 | FLASH2X_SECTION_PRESENT;
if(ReadDSDSignature(Adapter,DSD1)== DSD_IMAGE_MAGIC_NUMBER)
psFlash2xBitMap->DSD1 |= FLASH2X_SECTION_VALID;
//Calculation for extrating the Access permission
if(IsSectionWritable(Adapter, DSD1) == FALSE)
{
psFlash2xBitMap->DSD1 |= FLASH2X_SECTION_RO;
}
else
{
//Means section is writable
if((SetActiveDSDDone == FALSE) && (uiHighestPriDSD == DSD1))
{
psFlash2xBitMap->DSD1 |= FLASH2X_SECTION_ACT ;
SetActiveDSDDone =TRUE ;
}
}
}
///
//For DSD 0
//
if((psFlash2xCSInfo->OffsetFromZeroForDSDStart) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->DSD0 = psFlash2xBitMap->DSD0 | FLASH2X_SECTION_PRESENT;
if(ReadDSDSignature(Adapter,DSD0) == DSD_IMAGE_MAGIC_NUMBER)
psFlash2xBitMap->DSD0 |= FLASH2X_SECTION_VALID;
//Setting Access permission
if(IsSectionWritable(Adapter, DSD0) == FALSE)
{
psFlash2xBitMap->DSD0 |= FLASH2X_SECTION_RO;
}
else
{
//Means section is writable
if((SetActiveDSDDone == FALSE) &&(uiHighestPriDSD == DSD0))
{
psFlash2xBitMap->DSD0 |= FLASH2X_SECTION_ACT ;
SetActiveDSDDone =TRUE ;
}
}
}
///
// VSA 0
///
if((psFlash2xCSInfo->OffsetFromZeroForVSAStart) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->VSA0= psFlash2xBitMap->VSA0 | FLASH2X_SECTION_PRESENT;
//Setting the Access Bit. Map is not defined hece setting it always valid
psFlash2xBitMap->VSA0 |= FLASH2X_SECTION_VALID;
//Calculation for extrating the Access permission
if(IsSectionWritable(Adapter, VSA0) == FALSE)
psFlash2xBitMap->VSA0 |= FLASH2X_SECTION_RO;
//By Default section is Active
psFlash2xBitMap->VSA0 |= FLASH2X_SECTION_ACT ;
}
///
// VSA 1
///
if((psFlash2xCSInfo->OffsetFromZeroForVSA1Start) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->VSA1= psFlash2xBitMap->VSA1 | FLASH2X_SECTION_PRESENT;
//Setting the Access Bit. Map is not defined hece setting it always valid
psFlash2xBitMap->VSA1|= FLASH2X_SECTION_VALID;
//Checking For Access permission
if(IsSectionWritable(Adapter, VSA1) == FALSE)
psFlash2xBitMap->VSA1 |= FLASH2X_SECTION_RO;
//By Default section is Active
psFlash2xBitMap->VSA1 |= FLASH2X_SECTION_ACT ;
}
///
// VSA 2
///
if((psFlash2xCSInfo->OffsetFromZeroForVSA2Start) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->VSA2= psFlash2xBitMap->VSA2 | FLASH2X_SECTION_PRESENT;
//Setting the Access Bit. Map is not defined hece setting it always valid
psFlash2xBitMap->VSA2 |= FLASH2X_SECTION_VALID;
//Checking For Access permission
if(IsSectionWritable(Adapter, VSA2) == FALSE)
psFlash2xBitMap->VSA2 |= FLASH2X_SECTION_RO;
//By Default section is Active
psFlash2xBitMap->VSA2 |= FLASH2X_SECTION_ACT ;
}
///
// SCSI Section
///
if((psFlash2xCSInfo->OffsetFromZeroForScsiFirmware) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->SCSI= psFlash2xBitMap->SCSI | FLASH2X_SECTION_PRESENT;
//Setting the Access Bit. Map is not defined hece setting it always valid
psFlash2xBitMap->SCSI|= FLASH2X_SECTION_VALID;
//Checking For Access permission
if(IsSectionWritable(Adapter, SCSI) == FALSE)
psFlash2xBitMap->SCSI |= FLASH2X_SECTION_RO;
//By Default section is Active
psFlash2xBitMap->SCSI |= FLASH2X_SECTION_ACT ;
}
///
// Control Section
///
if((psFlash2xCSInfo->OffsetFromZeroForControlSectionStart) != UNINIT_PTR_IN_CS)
{
//Setting the 0th Bit representing the Section is present or not.
psFlash2xBitMap->CONTROL_SECTION = psFlash2xBitMap->CONTROL_SECTION | (FLASH2X_SECTION_PRESENT);
//Setting the Access Bit. Map is not defined hece setting it always valid
psFlash2xBitMap->CONTROL_SECTION |= FLASH2X_SECTION_VALID;
//Checking For Access permission
if(IsSectionWritable(Adapter, CONTROL_SECTION) == FALSE)
psFlash2xBitMap->CONTROL_SECTION |= FLASH2X_SECTION_RO;
//By Default section is Active
psFlash2xBitMap->CONTROL_SECTION |= FLASH2X_SECTION_ACT ;
}
///
// For Reserved Sections
///
psFlash2xBitMap->Reserved0 = 0;
psFlash2xBitMap->Reserved0 = 0;
psFlash2xBitMap->Reserved0 = 0;
BcmDumpFlash2xSectionBitMap(psFlash2xBitMap);
return STATUS_SUCCESS ;
}
/**
BcmSetActiveSection :- Set Active section is used to make priority field highest over other
section of same type.
@Adapater :- Bcm Driver Private Data Structure
@eFlash2xSectionVal :- Flash section val whose priority has to be made highest.
Return Value:- Make the priorit highest else return erorr code
**/
INT BcmSetActiveSection(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlash2xSectVal)
{
unsigned int SectImagePriority = 0;
INT Status =STATUS_SUCCESS;
//DSD_HEADER sDSD = {0};
//ISO_HEADER sISO = {0};
INT HighestPriDSD = 0 ;
INT HighestPriISO = 0;
Status = IsSectionWritable(Adapter,eFlash2xSectVal) ;
if(Status != TRUE )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Provided Section <%d> is not writable",eFlash2xSectVal);
return STATUS_FAILURE;
}
Adapter->bHeaderChangeAllowed = TRUE ;
switch(eFlash2xSectVal)
{
case ISO_IMAGE1 :
case ISO_IMAGE2 :
if(ReadISOSignature(Adapter,eFlash2xSectVal)== ISO_IMAGE_MAGIC_NUMBER )
{
HighestPriISO = getHighestPriISO(Adapter);
if(HighestPriISO == eFlash2xSectVal )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Given ISO<%x> already has highest priority",eFlash2xSectVal );
Status = STATUS_SUCCESS ;
break;
}
SectImagePriority = ReadISOPriority(Adapter, HighestPriISO) + 1;
if((SectImagePriority <= 0) && IsSectionWritable(Adapter,HighestPriISO))
{
// This is a SPECIAL Case which will only happen if the current highest priority ISO has priority value = 0x7FFFFFFF.
// We will write 1 to the current Highest priority ISO And then shall increase the priority of the requested ISO
// by user
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "SectImagePriority wraparound happened, eFlash2xSectVal: 0x%x\n",eFlash2xSectVal);
SectImagePriority = htonl(0x1);
Status = BcmFlash2xBulkWrite(Adapter,
&SectImagePriority,
HighestPriISO,
0 + FIELD_OFFSET_IN_HEADER(PISO_HEADER, ISOImagePriority),
SIGNATURE_SIZE,
TRUE);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Priority has not been written properly");
Status = STATUS_FAILURE;
break ;
}
HighestPriISO = getHighestPriISO(Adapter);
if(HighestPriISO == eFlash2xSectVal )
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Given ISO<%x> already has highest priority",eFlash2xSectVal );
Status = STATUS_SUCCESS ;
break;
}
SectImagePriority = 2;
}
SectImagePriority = htonl(SectImagePriority);
Status = BcmFlash2xBulkWrite(Adapter,
&SectImagePriority,
eFlash2xSectVal,
0 + FIELD_OFFSET_IN_HEADER(PISO_HEADER, ISOImagePriority),
SIGNATURE_SIZE,
TRUE);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Priority has not been written properly");
break ;
}
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Signature is currupted. Hence can't increase the priority");
Status = STATUS_FAILURE ;
break;
}
break;
case DSD0 :
case DSD1 :
case DSD2 :
if(ReadDSDSignature(Adapter,eFlash2xSectVal)== DSD_IMAGE_MAGIC_NUMBER)
{
HighestPriDSD = getHighestPriDSD(Adapter);
if((HighestPriDSD == eFlash2xSectVal))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Given DSD<%x> already has highest priority", eFlash2xSectVal);
Status = STATUS_SUCCESS ;
break;
}
SectImagePriority = ReadDSDPriority(Adapter, HighestPriDSD) + 1 ;
if(SectImagePriority <= 0)
{
// This is a SPECIAL Case which will only happen if the current highest priority DSD has priority value = 0x7FFFFFFF.
// We will write 1 to the current Highest priority DSD And then shall increase the priority of the requested DSD
// by user
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, NVM_RW, DBG_LVL_ALL, "SectImagePriority wraparound happened, eFlash2xSectVal: 0x%x\n",eFlash2xSectVal);
SectImagePriority = htonl(0x1);
Status = BcmFlash2xBulkWrite(Adapter,
&SectImagePriority,
HighestPriDSD,
Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader + FIELD_OFFSET_IN_HEADER(PDSD_HEADER, DSDImagePriority),
SIGNATURE_SIZE,
TRUE);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Priority has not been written properly");
break ;
}
HighestPriDSD = getHighestPriDSD(Adapter);
if((HighestPriDSD == eFlash2xSectVal))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Made the DSD: %x highest by reducing priority of other\n", eFlash2xSectVal);
Status = STATUS_SUCCESS ;
break;
}
SectImagePriority = htonl(0x2);
Status = BcmFlash2xBulkWrite(Adapter,
&SectImagePriority,
HighestPriDSD,
Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader + FIELD_OFFSET_IN_HEADER(PDSD_HEADER, DSDImagePriority),
SIGNATURE_SIZE,
TRUE);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Priority has not been written properly");
break ;
}
HighestPriDSD = getHighestPriDSD(Adapter);
if((HighestPriDSD == eFlash2xSectVal))
{
Status = STATUS_SUCCESS ;
break;
}
SectImagePriority = 3 ;
}
SectImagePriority = htonl(SectImagePriority);
Status = BcmFlash2xBulkWrite(Adapter,
&SectImagePriority,
eFlash2xSectVal,
Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader + FIELD_OFFSET_IN_HEADER(PDSD_HEADER, DSDImagePriority),
SIGNATURE_SIZE ,
TRUE);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Priority has not been written properly");
Status = STATUS_FAILURE ;
break ;
}
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Signature is currupted. Hence can't increase the priority");
Status = STATUS_FAILURE ;
break;
}
break;
case VSA0 :
case VSA1 :
case VSA2 :
//Has to be decided
break ;
default :
Status = STATUS_FAILURE ;
break;
}
Adapter->bHeaderChangeAllowed = FALSE ;
return Status;
}
/**
BcmCopyISO - Used only for copying the ISO section
@Adapater :- Bcm Driver Private Data Structure
@sCopySectStrut :- Section copy structure
Return value:- SUCCESS if copies successfully else negative error code
**/
INT BcmCopyISO(PMINI_ADAPTER Adapter, FLASH2X_COPY_SECTION sCopySectStrut)
{
PCHAR Buff = NULL;
FLASH2X_SECTION_VAL eISOReadPart = 0,eISOWritePart = 0;
UINT uiReadOffsetWithinPart = 0, uiWriteOffsetWithinPart = 0;
UINT uiTotalDataToCopy = 0;
BOOLEAN IsThisHeaderSector = FALSE ;
UINT sigOffset = 0;
UINT ISOLength = 0;
UINT Status = STATUS_SUCCESS;
UINT SigBuff[MAX_RW_SIZE];
UINT i = 0;
if(ReadISOSignature(Adapter,sCopySectStrut.SrcSection) != ISO_IMAGE_MAGIC_NUMBER)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "error as Source ISO Section does not have valid signature");
return STATUS_FAILURE;
}
Status = BcmFlash2xBulkRead(Adapter,
&ISOLength,
sCopySectStrut.SrcSection,
0 + FIELD_OFFSET_IN_HEADER(PISO_HEADER,ISOImageSize),
4);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Read failed while copying ISO\n");
return Status;
}
ISOLength = htonl(ISOLength);
if(ISOLength % Adapter->uiSectorSize)
{
ISOLength = Adapter->uiSectorSize*(1 + ISOLength/Adapter->uiSectorSize);
}
sigOffset = FIELD_OFFSET_IN_HEADER(PISO_HEADER, ISOImageMagicNumber);
Buff = kzalloc(Adapter->uiSectorSize, GFP_KERNEL);
if(Buff == NULL)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Memory allocation failed for section size");
return -ENOMEM;
}
if(sCopySectStrut.SrcSection ==ISO_IMAGE1 && sCopySectStrut.DstSection ==ISO_IMAGE2)
{
eISOReadPart = ISO_IMAGE1 ;
eISOWritePart = ISO_IMAGE2 ;
uiReadOffsetWithinPart = 0;
uiWriteOffsetWithinPart = 0 ;
uiTotalDataToCopy =(Adapter->psFlash2xCSInfo->OffsetISOImage1Part1End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part1Start)+
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part2End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part2Start)+
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part3End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part3Start);
if(uiTotalDataToCopy < ISOLength)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"error as Source ISO Section does not have valid signature");
Status = STATUS_FAILURE;
goto out;
}
uiTotalDataToCopy =(Adapter->psFlash2xCSInfo->OffsetISOImage2Part1End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part1Start)+
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part2End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part2Start)+
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part3End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part3Start);
if(uiTotalDataToCopy < ISOLength)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"error as Dest ISO Section does not have enough section size");
Status = STATUS_FAILURE;
goto out;
}
uiTotalDataToCopy = ISOLength;
CorruptISOSig(Adapter,ISO_IMAGE2);
while(uiTotalDataToCopy)
{
if(uiTotalDataToCopy == Adapter->uiSectorSize)
{
//Setting for write of first sector. First sector is assumed to be written in last
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Writing the signature sector");
eISOReadPart = ISO_IMAGE1 ;
uiReadOffsetWithinPart = 0;
eISOWritePart = ISO_IMAGE2;
uiWriteOffsetWithinPart = 0 ;
IsThisHeaderSector = TRUE ;
}
else
{
uiReadOffsetWithinPart = uiReadOffsetWithinPart + Adapter->uiSectorSize ;
uiWriteOffsetWithinPart = uiWriteOffsetWithinPart + Adapter->uiSectorSize ;
if((eISOReadPart == ISO_IMAGE1) && (uiReadOffsetWithinPart == (Adapter->psFlash2xCSInfo->OffsetISOImage1Part1End - Adapter->psFlash2xCSInfo->OffsetISOImage1Part1Start) ))
{
eISOReadPart = ISO_IMAGE1_PART2 ;
uiReadOffsetWithinPart = 0;
}
if((eISOReadPart == ISO_IMAGE1_PART2) && (uiReadOffsetWithinPart == (Adapter->psFlash2xCSInfo->OffsetISOImage1Part2End - Adapter->psFlash2xCSInfo->OffsetISOImage1Part2Start)))
{
eISOReadPart = ISO_IMAGE1_PART3 ;
uiReadOffsetWithinPart = 0;
}
if((eISOWritePart == ISO_IMAGE2) && (uiWriteOffsetWithinPart == (Adapter->psFlash2xCSInfo->OffsetISOImage2Part1End - Adapter->psFlash2xCSInfo->OffsetISOImage2Part1Start)))
{
eISOWritePart = ISO_IMAGE2_PART2 ;
uiWriteOffsetWithinPart = 0;
}
if((eISOWritePart == ISO_IMAGE2_PART2) && (uiWriteOffsetWithinPart == (Adapter->psFlash2xCSInfo->OffsetISOImage2Part2End - Adapter->psFlash2xCSInfo->OffsetISOImage2Part2Start)))
{
eISOWritePart = ISO_IMAGE2_PART3 ;
uiWriteOffsetWithinPart = 0;
}
}
Status = BcmFlash2xBulkRead(Adapter,
(PUINT)Buff,
eISOReadPart,
uiReadOffsetWithinPart,
Adapter->uiSectorSize
);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Read failed while copying ISO: Part: %x, OffsetWithinPart: %x\n", eISOReadPart, uiReadOffsetWithinPart);
break;
}
if(IsThisHeaderSector == TRUE)
{
//If this is header sector write 0xFFFFFFFF at the sig time and in last write sig
memcpy(SigBuff, Buff + sigOffset, MAX_RW_SIZE);
for(i = 0; i < MAX_RW_SIZE;i++)
*(Buff + sigOffset + i) = 0xFF;
}
Adapter->bHeaderChangeAllowed = TRUE ;
Status = BcmFlash2xBulkWrite(Adapter,
(PUINT)Buff,
eISOWritePart,
uiWriteOffsetWithinPart,
Adapter->uiSectorSize,
TRUE);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Write failed while copying ISO: Part: %x, OffsetWithinPart: %x\n", eISOWritePart, uiWriteOffsetWithinPart);
break;
}
Adapter->bHeaderChangeAllowed = FALSE;
if(IsThisHeaderSector == TRUE)
{
WriteToFlashWithoutSectorErase(Adapter,
SigBuff,
eISOWritePart,
sigOffset,
MAX_RW_SIZE);
IsThisHeaderSector = FALSE ;
}
//subtracting the written Data
uiTotalDataToCopy = uiTotalDataToCopy - Adapter->uiSectorSize ;
}
}
if(sCopySectStrut.SrcSection ==ISO_IMAGE2 && sCopySectStrut.DstSection ==ISO_IMAGE1)
{
eISOReadPart = ISO_IMAGE2 ;
eISOWritePart = ISO_IMAGE1 ;
uiReadOffsetWithinPart = 0;
uiWriteOffsetWithinPart = 0 ;
uiTotalDataToCopy =(Adapter->psFlash2xCSInfo->OffsetISOImage2Part1End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part1Start)+
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part2End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part2Start)+
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part3End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage2Part3Start);
if(uiTotalDataToCopy < ISOLength)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"error as Source ISO Section does not have valid signature");
Status = STATUS_FAILURE;
goto out;
}
uiTotalDataToCopy =(Adapter->psFlash2xCSInfo->OffsetISOImage1Part1End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part1Start)+
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part2End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part2Start)+
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part3End) -
(Adapter->psFlash2xCSInfo->OffsetISOImage1Part3Start);
if(uiTotalDataToCopy < ISOLength)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"error as Dest ISO Section does not have enough section size");
Status = STATUS_FAILURE;
goto out;
}
uiTotalDataToCopy = ISOLength;
CorruptISOSig(Adapter,ISO_IMAGE1);
while(uiTotalDataToCopy)
{
if(uiTotalDataToCopy == Adapter->uiSectorSize)
{
//Setting for write of first sector. First sector is assumed to be written in last
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Writing the signature sector");
eISOReadPart = ISO_IMAGE2 ;
uiReadOffsetWithinPart = 0;
eISOWritePart = ISO_IMAGE1;
uiWriteOffsetWithinPart = 0 ;
IsThisHeaderSector = TRUE;
}
else
{
uiReadOffsetWithinPart = uiReadOffsetWithinPart + Adapter->uiSectorSize ;
uiWriteOffsetWithinPart = uiWriteOffsetWithinPart + Adapter->uiSectorSize ;
if((eISOReadPart == ISO_IMAGE2) && (uiReadOffsetWithinPart == (Adapter->psFlash2xCSInfo->OffsetISOImage2Part1End - Adapter->psFlash2xCSInfo->OffsetISOImage2Part1Start) ))
{
eISOReadPart = ISO_IMAGE2_PART2 ;
uiReadOffsetWithinPart = 0;
}
if((eISOReadPart == ISO_IMAGE2_PART2) && (uiReadOffsetWithinPart == (Adapter->psFlash2xCSInfo->OffsetISOImage2Part2End - Adapter->psFlash2xCSInfo->OffsetISOImage2Part2Start)))
{
eISOReadPart = ISO_IMAGE2_PART3 ;
uiReadOffsetWithinPart = 0;
}
if((eISOWritePart == ISO_IMAGE1) && (uiWriteOffsetWithinPart == (Adapter->psFlash2xCSInfo->OffsetISOImage1Part1End - Adapter->psFlash2xCSInfo->OffsetISOImage1Part1Start)))
{
eISOWritePart = ISO_IMAGE1_PART2 ;
uiWriteOffsetWithinPart = 0;
}
if((eISOWritePart == ISO_IMAGE1_PART2) && (uiWriteOffsetWithinPart == (Adapter->psFlash2xCSInfo->OffsetISOImage1Part2End - Adapter->psFlash2xCSInfo->OffsetISOImage1Part2Start)))
{
eISOWritePart = ISO_IMAGE1_PART3 ;
uiWriteOffsetWithinPart = 0;
}
}
Status = BcmFlash2xBulkRead(Adapter,
(PUINT)Buff,
eISOReadPart,
uiReadOffsetWithinPart,
Adapter->uiSectorSize
);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Read failed while copying ISO: Part: %x, OffsetWithinPart: %x\n", eISOReadPart, uiReadOffsetWithinPart);
break;
}
if(IsThisHeaderSector == TRUE)
{
//If this is header sector write 0xFFFFFFFF at the sig time and in last write sig
memcpy(SigBuff, Buff + sigOffset, MAX_RW_SIZE);
for(i = 0; i < MAX_RW_SIZE;i++)
*(Buff + sigOffset + i) = 0xFF;
}
Adapter->bHeaderChangeAllowed = TRUE ;
Status = BcmFlash2xBulkWrite(Adapter,
(PUINT)Buff,
eISOWritePart,
uiWriteOffsetWithinPart,
Adapter->uiSectorSize,
TRUE);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Write failed while copying ISO: Part: %x, OffsetWithinPart: %x\n", eISOWritePart, uiWriteOffsetWithinPart);
break;
}
Adapter->bHeaderChangeAllowed = FALSE ;
if(IsThisHeaderSector == TRUE)
{
WriteToFlashWithoutSectorErase(Adapter,
SigBuff,
eISOWritePart,
sigOffset,
MAX_RW_SIZE);
IsThisHeaderSector = FALSE ;
}
//subtracting the written Data
uiTotalDataToCopy = uiTotalDataToCopy - Adapter->uiSectorSize ;
}
}
out:
kfree(Buff);
return Status;
}
/**
BcmFlash2xCorruptSig : this API is used to corrupt the written sig in Bcm Header present in flash section.
It will corrupt the sig, if Section is writable, by making first bytes as zero.
@Adapater :- Bcm Driver Private Data Structure
@eFlash2xSectionVal :- Flash section val which has header
Return Value :-
Success :- If Section is present and writable, corrupt the sig and return STATUS_SUCCESS
Failure :-Return negative error code
**/
INT BcmFlash2xCorruptSig(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlash2xSectionVal)
{
INT Status = STATUS_SUCCESS ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Section Value :%x \n", eFlash2xSectionVal);
if((eFlash2xSectionVal == DSD0) || (eFlash2xSectionVal == DSD1) || (eFlash2xSectionVal == DSD2))
{
Status = CorruptDSDSig(Adapter, eFlash2xSectionVal);
}
else if(eFlash2xSectionVal == ISO_IMAGE1 || eFlash2xSectionVal == ISO_IMAGE2)
{
Status = CorruptISOSig(Adapter, eFlash2xSectionVal);
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Given Section <%d>does not have Header",eFlash2xSectionVal);
return STATUS_SUCCESS;
}
return Status;
}
/**
BcmFlash2xWriteSig :-this API is used to Write the sig if requested Section has
header and Write Permission.
@Adapater :- Bcm Driver Private Data Structure
@eFlashSectionVal :- Flash section val which has header
Return Value :-
Success :- If Section is present and writable write the sig and return STATUS_SUCCESS
Failure :-Return negative error code
**/
INT BcmFlash2xWriteSig(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlashSectionVal)
{
UINT uiSignature = 0 ;
UINT uiOffset = 0;
//DSD_HEADER dsdHeader = {0};
if(Adapter->bSigCorrupted == FALSE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Signature is not corrupted by driver, hence not restoring\n");
return STATUS_SUCCESS;
}
if(Adapter->bAllDSDWriteAllow == FALSE)
{
if(IsSectionWritable(Adapter,eFlashSectionVal) == FALSE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Section is not Writable...Hence can't Write signature");
return SECTOR_IS_NOT_WRITABLE;
}
}
if((eFlashSectionVal == DSD0) ||(eFlashSectionVal == DSD1) || (eFlashSectionVal == DSD2))
{
uiSignature = htonl(DSD_IMAGE_MAGIC_NUMBER) ;
uiOffset = Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader ;
uiOffset += FIELD_OFFSET_IN_HEADER(PDSD_HEADER,DSDImageMagicNumber);
if((ReadDSDSignature(Adapter,eFlashSectionVal) & 0xFF000000) != CORRUPTED_PATTERN)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Corrupted Pattern is not there. Hence won't write sig");
return STATUS_FAILURE;
}
}
else if((eFlashSectionVal == ISO_IMAGE1) || (eFlashSectionVal == ISO_IMAGE2))
{
uiSignature = htonl(ISO_IMAGE_MAGIC_NUMBER);
//uiOffset = 0;
uiOffset = FIELD_OFFSET_IN_HEADER(PISO_HEADER,ISOImageMagicNumber);
if((ReadISOSignature(Adapter,eFlashSectionVal) & 0xFF000000) != CORRUPTED_PATTERN)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Currupted Pattern is not there. Hence won't write sig");
return STATUS_FAILURE;
}
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"GIVEN SECTION< %d > IS NOT VALID FOR SIG WRITE...", eFlashSectionVal);
return STATUS_FAILURE;
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Restoring the signature");
Adapter->bHeaderChangeAllowed = TRUE;
Adapter->bSigCorrupted = FALSE;
BcmFlash2xBulkWrite(Adapter, &uiSignature,eFlashSectionVal,uiOffset,SIGNATURE_SIZE,TRUE);
Adapter->bHeaderChangeAllowed = FALSE;
return STATUS_SUCCESS;
}
/**
validateFlash2xReadWrite :- This API is used to validate the user request for Read/Write.
if requested Bytes goes beyond the Requested section, it reports error.
@Adapater :- Bcm Driver Private Data Structure
@psFlash2xReadWrite :-Flash2x Read/write structure pointer
Return values:-Return TRUE is request is valid else FALSE.
**/
INT validateFlash2xReadWrite(PMINI_ADAPTER Adapter, PFLASH2X_READWRITE psFlash2xReadWrite)
{
UINT uiNumOfBytes = 0 ;
UINT uiSectStartOffset = 0 ;
UINT uiSectEndOffset = 0;
uiNumOfBytes = psFlash2xReadWrite->numOfBytes;
if(IsSectionExistInFlash(Adapter,psFlash2xReadWrite->Section) != TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Section<%x> does not exixt in Flash",psFlash2xReadWrite->Section);
return FALSE;
}
uiSectStartOffset = BcmGetSectionValStartOffset(Adapter,psFlash2xReadWrite->Section);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Start offset :%x ,section :%d\n",uiSectStartOffset,psFlash2xReadWrite->Section);
if((psFlash2xReadWrite->Section == ISO_IMAGE1) ||(psFlash2xReadWrite->Section == ISO_IMAGE2))
{
if(psFlash2xReadWrite->Section == ISO_IMAGE1)
{
uiSectEndOffset = BcmGetSectionValEndOffset(Adapter,ISO_IMAGE1) -
BcmGetSectionValStartOffset(Adapter,ISO_IMAGE1)+
BcmGetSectionValEndOffset(Adapter,ISO_IMAGE1_PART2) -
BcmGetSectionValStartOffset(Adapter,ISO_IMAGE1_PART2)+
BcmGetSectionValEndOffset(Adapter,ISO_IMAGE1_PART3) -
BcmGetSectionValStartOffset(Adapter,ISO_IMAGE1_PART3);
}
else if(psFlash2xReadWrite->Section == ISO_IMAGE2)
{
uiSectEndOffset = BcmGetSectionValEndOffset(Adapter,ISO_IMAGE2) -
BcmGetSectionValStartOffset(Adapter,ISO_IMAGE2)+
BcmGetSectionValEndOffset(Adapter,ISO_IMAGE2_PART2) -
BcmGetSectionValStartOffset(Adapter,ISO_IMAGE2_PART2)+
BcmGetSectionValEndOffset(Adapter,ISO_IMAGE2_PART3) -
BcmGetSectionValStartOffset(Adapter,ISO_IMAGE2_PART3);
}
//since this uiSectEndoffset is the size of iso Image. hence for calculating the vitual endoffset
//it should be added in startoffset. so that check done in last of this function can be valued.
uiSectEndOffset = uiSectStartOffset + uiSectEndOffset ;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Total size of the ISO Image :%x",uiSectEndOffset);
}
else
uiSectEndOffset = BcmGetSectionValEndOffset(Adapter,psFlash2xReadWrite->Section);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "End offset :%x \n",uiSectEndOffset);
//Checking the boundary condition
if((uiSectStartOffset + psFlash2xReadWrite->offset + uiNumOfBytes) <= uiSectEndOffset)
return TRUE;
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Invalid Request....");
return FALSE;
}
}
/**
IsFlash2x :- check for Flash 2.x
@Adapater :- Bcm Driver Private Data Structure
Return value:-
return TRUE if flah2.x of hgher version else return false.
**/
INT IsFlash2x(PMINI_ADAPTER Adapter)
{
if(Adapter->uiFlashLayoutMajorVersion >= FLASH_2X_MAJOR_NUMBER)
return TRUE ;
else
return FALSE;
}
/**
GetFlashBaseAddr :- Calculate the Flash Base address
@Adapater :- Bcm Driver Private Data Structure
Return Value:-
Success :- Base Address of the Flash
**/
static INT GetFlashBaseAddr(PMINI_ADAPTER Adapter)
{
UINT uiBaseAddr = 0;
if(Adapter->bDDRInitDone)
{
/*
For All Valid Flash Versions... except 1.1, take the value from FlashBaseAddr
In case of Raw Read... use the default value
*/
if(Adapter->uiFlashLayoutMajorVersion && (Adapter->bFlashRawRead == FALSE) &&
!((Adapter->uiFlashLayoutMajorVersion == 1) && (Adapter->uiFlashLayoutMinorVersion == 1))
)
uiBaseAddr = Adapter->uiFlashBaseAdd ;
else
uiBaseAddr = FLASH_CONTIGIOUS_START_ADDR_AFTER_INIT;
}
else
{
/*
For All Valid Flash Versions... except 1.1, take the value from FlashBaseAddr
In case of Raw Read... use the default value
*/
if(Adapter->uiFlashLayoutMajorVersion && (Adapter->bFlashRawRead == FALSE) &&
!((Adapter->uiFlashLayoutMajorVersion == 1) && (Adapter->uiFlashLayoutMinorVersion == 1))
)
uiBaseAddr = Adapter->uiFlashBaseAdd | FLASH_CONTIGIOUS_START_ADDR_BEFORE_INIT;
else
uiBaseAddr = FLASH_CONTIGIOUS_START_ADDR_BEFORE_INIT;
}
return uiBaseAddr ;
}
/**
BcmCopySection :- This API is used to copy the One section in another. Both section should
be contiuous and of same size. Hence this Will not be applicabe to copy ISO.
@Adapater :- Bcm Driver Private Data Structure
@SrcSection :- Source section From where data has to be copied
@DstSection :- Destination section to which data has to be copied
@offset :- Offset from/to where data has to be copied from one section to another.
@numOfBytes :- number of byes that has to be copyed from one section to another at given offset.
in case of numofBytes equal zero complete section will be copied.
Return Values-
Success : Return STATUS_SUCCESS
Faillure :- return negative error code
**/
INT BcmCopySection(PMINI_ADAPTER Adapter,
FLASH2X_SECTION_VAL SrcSection,
FLASH2X_SECTION_VAL DstSection,
UINT offset,
UINT numOfBytes)
{
UINT BuffSize = 0 ;
UINT BytesToBeCopied = 0;
PUCHAR pBuff = NULL ;
INT Status = STATUS_SUCCESS ;
if(SrcSection == DstSection)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Source and Destination should be different ...try again");
return -EINVAL;
}
if((SrcSection != DSD0) && (SrcSection != DSD1) && (SrcSection != DSD2))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Source should be DSD subsection");
return -EINVAL;
}
if((DstSection != DSD0) && (DstSection != DSD1) && (DstSection != DSD2))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Destination should be DSD subsection");
return -EINVAL;
}
//if offset zero means have to copy complete secton
if(numOfBytes == 0)
{
numOfBytes = BcmGetSectionValEndOffset(Adapter,SrcSection)
- BcmGetSectionValStartOffset(Adapter,SrcSection);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL," Section Size :0x%x",numOfBytes);
}
if((offset + numOfBytes) > BcmGetSectionValEndOffset(Adapter,SrcSection)
- BcmGetSectionValStartOffset(Adapter,SrcSection))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0," Input parameters going beyond the section offS: %x numB: %x of Source Section\n",
offset, numOfBytes);
return -EINVAL;
}
if((offset + numOfBytes) > BcmGetSectionValEndOffset(Adapter,DstSection)
- BcmGetSectionValStartOffset(Adapter,DstSection))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0," Input parameters going beyond the section offS: %x numB: %x of Destination Section\n",
offset, numOfBytes);
return -EINVAL;
}
if(numOfBytes > Adapter->uiSectorSize )
BuffSize = Adapter->uiSectorSize;
else
BuffSize = numOfBytes ;
pBuff = (PCHAR)kzalloc(BuffSize, GFP_KERNEL);
if(pBuff == NULL)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Memory allocation failed.. ");
return -ENOMEM;
}
BytesToBeCopied = Adapter->uiSectorSize ;
if(offset % Adapter->uiSectorSize)
BytesToBeCopied = Adapter->uiSectorSize - (offset % Adapter->uiSectorSize);
if(BytesToBeCopied > numOfBytes)
BytesToBeCopied = numOfBytes ;
Adapter->bHeaderChangeAllowed = TRUE;
do
{
Status = BcmFlash2xBulkRead(Adapter, (PUINT)pBuff, SrcSection , offset,BytesToBeCopied);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Read failed at offset :%d for NOB :%d", SrcSection,BytesToBeCopied);
break;
}
Status = BcmFlash2xBulkWrite(Adapter,(PUINT)pBuff,DstSection,offset,BytesToBeCopied,FALSE);
if(Status)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Write failed at offset :%d for NOB :%d", DstSection,BytesToBeCopied);
break;
}
offset = offset + BytesToBeCopied;
numOfBytes = numOfBytes - BytesToBeCopied ;
if(numOfBytes)
{
if(numOfBytes > Adapter->uiSectorSize )
BytesToBeCopied = Adapter->uiSectorSize;
else
BytesToBeCopied = numOfBytes;
}
}while(numOfBytes > 0) ;
kfree(pBuff);
Adapter->bHeaderChangeAllowed = FALSE ;
return Status;
}
/**
SaveHeaderIfPresent :- This API is use to Protect the Header in case of Header Sector write
@Adapater :- Bcm Driver Private Data Structure
@pBuff :- Data buffer that has to be written in sector having the header map.
@uiOffset :- Flash offset that has to be written.
Return value :-
Success :- On success return STATUS_SUCCESS
Faillure :- Return negative error code
**/
INT SaveHeaderIfPresent(PMINI_ADAPTER Adapter, PUCHAR pBuff, UINT uiOffset)
{
UINT offsetToProtect = 0,HeaderSizeToProtect =0;
BOOLEAN bHasHeader = FALSE ;
PUCHAR pTempBuff =NULL;
UINT uiSectAlignAddr = 0;
UINT sig = 0;
//making the offset sector aligned
uiSectAlignAddr = uiOffset & ~(Adapter->uiSectorSize - 1);
if((uiSectAlignAddr == BcmGetSectionValEndOffset(Adapter,DSD2)- Adapter->uiSectorSize)||
(uiSectAlignAddr == BcmGetSectionValEndOffset(Adapter,DSD1)- Adapter->uiSectorSize)||
(uiSectAlignAddr == BcmGetSectionValEndOffset(Adapter,DSD0)- Adapter->uiSectorSize))
{
//offset from the sector boundary having the header map
offsetToProtect = Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader % Adapter->uiSectorSize;
HeaderSizeToProtect = sizeof(DSD_HEADER);
bHasHeader = TRUE ;
}
if(uiSectAlignAddr == BcmGetSectionValStartOffset(Adapter,ISO_IMAGE1) ||
uiSectAlignAddr == BcmGetSectionValStartOffset(Adapter,ISO_IMAGE2))
{
offsetToProtect = 0;
HeaderSizeToProtect = sizeof(ISO_HEADER);
bHasHeader = TRUE;
}
//If Header is present overwrite passed buffer with this
if(bHasHeader && (Adapter->bHeaderChangeAllowed == FALSE))
{
pTempBuff = (PUCHAR)kzalloc(HeaderSizeToProtect, GFP_KERNEL);
if(pTempBuff == NULL)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Memory allocation failed ");
return -ENOMEM;
}
//Read header
BeceemFlashBulkRead(Adapter,(PUINT)pTempBuff,(uiSectAlignAddr + offsetToProtect),HeaderSizeToProtect);
BCM_DEBUG_PRINT_BUFFER(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,pTempBuff ,HeaderSizeToProtect);
//Replace Buffer content with Header
memcpy(pBuff +offsetToProtect,pTempBuff,HeaderSizeToProtect);
kfree(pTempBuff);
}
if(bHasHeader && Adapter->bSigCorrupted)
{
sig = *((PUINT)(pBuff + offsetToProtect + FIELD_OFFSET_IN_HEADER(PDSD_HEADER,DSDImageMagicNumber)));
sig = ntohl(sig);
if((sig & 0xFF000000) != CORRUPTED_PATTERN)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Desired pattern is not at sig offset. Hence won't restore");
Adapter->bSigCorrupted = FALSE;
return STATUS_SUCCESS;
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL," Corrupted sig is :%X", sig);
*((PUINT)(pBuff + offsetToProtect + FIELD_OFFSET_IN_HEADER(PDSD_HEADER,DSDImageMagicNumber)))= htonl(DSD_IMAGE_MAGIC_NUMBER);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Restoring the signature in Header Write only");
Adapter->bSigCorrupted = FALSE;
}
return STATUS_SUCCESS ;
}
/**
BcmDoChipSelect : This will selcet the appropriate chip for writing.
@Adapater :- Bcm Driver Private Data Structure
OutPut:-
Select the Appropriate chip and retrn status Success
**/
static INT BcmDoChipSelect(PMINI_ADAPTER Adapter, UINT offset)
{
UINT FlashConfig = 0;
INT ChipNum = 0;
UINT GPIOConfig = 0;
UINT PartNum = 0;
ChipNum = offset / FLASH_PART_SIZE ;
//
// Chip Select mapping to enable flash0.
// To select flash 0, we have to OR with (0<<12).
// ORing 0 will have no impact so not doing that part.
// In future if Chip select value changes from 0 to non zero,
// That needs be taken care with backward comaptibility. No worries for now.
//
/*
SelectedChip Variable is the selection that the host is 100% Sure the same as what the register will hold. This can be ONLY ensured
if the Chip doesn't goes to low power mode while the flash operation is in progress (NVMRdmWrmLock is taken)
Before every new Flash Write operation, we reset the variable. This is to ensure that after any wake-up from
power down modes (Idle mode/shutdown mode), the values in the register will be different.
*/
if(Adapter->SelectedChip == ChipNum)
return STATUS_SUCCESS;
//BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL, "Selected Chip :%x", ChipNum);
Adapter->SelectedChip = ChipNum ;
//bit[13..12] will select the appropriate chip
rdmalt(Adapter, FLASH_CONFIG_REG, &FlashConfig, 4);
rdmalt(Adapter, FLASH_GPIO_CONFIG_REG, &GPIOConfig, 4);
{
switch(ChipNum)
{
case 0:
PartNum = 0;
break;
case 1:
PartNum = 3;
GPIOConfig |= (0x4 << CHIP_SELECT_BIT12);
break;
case 2:
PartNum = 1;
GPIOConfig |= (0x1 << CHIP_SELECT_BIT12);
break;
case 3:
PartNum = 2;
GPIOConfig |= (0x2 << CHIP_SELECT_BIT12);
break;
}
}
/* In case the bits already written in the FLASH_CONFIG_REG is same as what the user desired,
nothing to do... can return immediately.
ASSUMPTION: FLASH_GPIO_CONFIG_REG will be in sync with FLASH_CONFIG_REG.
Even if the chip goes to low power mode, it should wake with values in each register in sync with each other.
These values are not written by host other than during CHIP_SELECT.
*/
if(PartNum == ((FlashConfig >> CHIP_SELECT_BIT12) & 0x3))
return STATUS_SUCCESS;
//clearing the bit[13..12]
FlashConfig &= 0xFFFFCFFF;
FlashConfig = (FlashConfig | (PartNum<<CHIP_SELECT_BIT12)); //00
wrmalt(Adapter,FLASH_GPIO_CONFIG_REG, &GPIOConfig, 4);
udelay(100);
wrmalt(Adapter,FLASH_CONFIG_REG, &FlashConfig, 4);
udelay(100);
return STATUS_SUCCESS;
}
INT ReadDSDSignature(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL dsd)
{
UINT uiDSDsig = 0;
//UINT sigoffsetInMap = 0;
//DSD_HEADER dsdHeader = {0};
//sigoffsetInMap =(PUCHAR)&(dsdHeader.DSDImageMagicNumber) -(PUCHAR)&dsdHeader;
if(dsd != DSD0 && dsd != DSD1 && dsd != DSD2)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"passed section value is not for DSDs");
return STATUS_FAILURE;
}
BcmFlash2xBulkRead(Adapter,
&uiDSDsig,
dsd,
Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader + FIELD_OFFSET_IN_HEADER(PDSD_HEADER,DSDImageMagicNumber),
SIGNATURE_SIZE);
uiDSDsig = ntohl(uiDSDsig);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"DSD SIG :%x", uiDSDsig);
return uiDSDsig ;
}
INT ReadDSDPriority(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL dsd)
{
//UINT priOffsetInMap = 0 ;
unsigned int uiDSDPri = STATUS_FAILURE;
//DSD_HEADER dsdHeader = {0};
//priOffsetInMap = (PUCHAR)&(dsdHeader.DSDImagePriority) -(PUCHAR)&dsdHeader;
if(IsSectionWritable(Adapter,dsd))
{
if(ReadDSDSignature(Adapter,dsd)== DSD_IMAGE_MAGIC_NUMBER)
{
BcmFlash2xBulkRead(Adapter,
&uiDSDPri,
dsd,
Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader +FIELD_OFFSET_IN_HEADER(PDSD_HEADER, DSDImagePriority),
4);
uiDSDPri = ntohl(uiDSDPri);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"DSD<%x> Priority :%x", dsd, uiDSDPri);
}
}
return uiDSDPri;
}
FLASH2X_SECTION_VAL getHighestPriDSD(PMINI_ADAPTER Adapter)
{
INT DSDHighestPri = STATUS_FAILURE;
INT DsdPri= 0 ;
FLASH2X_SECTION_VAL HighestPriDSD = 0 ;
if(IsSectionWritable(Adapter,DSD2))
{
DSDHighestPri = ReadDSDPriority(Adapter,DSD2);
HighestPriDSD = DSD2 ;
}
if(IsSectionWritable(Adapter,DSD1))
{
DsdPri = ReadDSDPriority(Adapter,DSD1);
if(DSDHighestPri < DsdPri)
{
DSDHighestPri = DsdPri ;
HighestPriDSD = DSD1;
}
}
if(IsSectionWritable(Adapter,DSD0))
{
DsdPri = ReadDSDPriority(Adapter,DSD0);
if(DSDHighestPri < DsdPri)
{
DSDHighestPri = DsdPri ;
HighestPriDSD = DSD0;
}
}
if(HighestPriDSD)
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Highest DSD :%x , and its Pri :%x", HighestPriDSD, DSDHighestPri);
return HighestPriDSD ;
}
INT ReadISOSignature(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL iso)
{
UINT uiISOsig = 0;
//UINT sigoffsetInMap = 0;
//ISO_HEADER ISOHeader = {0};
//sigoffsetInMap =(PUCHAR)&(ISOHeader.ISOImageMagicNumber) -(PUCHAR)&ISOHeader;
if(iso != ISO_IMAGE1 && iso != ISO_IMAGE2)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"passed section value is not for ISOs");
return STATUS_FAILURE;
}
BcmFlash2xBulkRead(Adapter,
&uiISOsig,
iso,
0 + FIELD_OFFSET_IN_HEADER(PISO_HEADER,ISOImageMagicNumber),
SIGNATURE_SIZE);
uiISOsig = ntohl(uiISOsig);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"ISO SIG :%x", uiISOsig);
return uiISOsig ;
}
INT ReadISOPriority(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL iso)
{
unsigned int ISOPri = STATUS_FAILURE;
if(IsSectionWritable(Adapter,iso))
{
if(ReadISOSignature(Adapter,iso)== ISO_IMAGE_MAGIC_NUMBER)
{
BcmFlash2xBulkRead(Adapter,
&ISOPri,
iso,
0 + FIELD_OFFSET_IN_HEADER(PISO_HEADER, ISOImagePriority),
4);
ISOPri = ntohl(ISOPri);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"ISO<%x> Priority :%x", iso, ISOPri);
}
}
return ISOPri;
}
FLASH2X_SECTION_VAL getHighestPriISO(PMINI_ADAPTER Adapter)
{
INT ISOHighestPri = STATUS_FAILURE;
INT ISOPri= 0 ;
FLASH2X_SECTION_VAL HighestPriISO = NO_SECTION_VAL ;
if(IsSectionWritable(Adapter,ISO_IMAGE2))
{
ISOHighestPri = ReadISOPriority(Adapter,ISO_IMAGE2);
HighestPriISO = ISO_IMAGE2 ;
}
if(IsSectionWritable(Adapter,ISO_IMAGE1))
{
ISOPri = ReadISOPriority(Adapter,ISO_IMAGE1);
if(ISOHighestPri < ISOPri)
{
ISOHighestPri = ISOPri ;
HighestPriISO = ISO_IMAGE1;
}
}
if(HighestPriISO)
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Highest ISO :%x and its Pri :%x",HighestPriISO,ISOHighestPri);
return HighestPriISO ;
}
INT WriteToFlashWithoutSectorErase(PMINI_ADAPTER Adapter,
PUINT pBuff,
FLASH2X_SECTION_VAL eFlash2xSectionVal,
UINT uiOffset,
UINT uiNumBytes
)
{
#if !defined(BCM_SHM_INTERFACE) || defined(FLASH_DIRECT_ACCESS)
UINT uiTemp = 0, value = 0 ;
UINT i = 0;
UINT uiPartOffset = 0;
#endif
UINT uiStartOffset = 0;
//Adding section start address
INT Status = STATUS_SUCCESS;
PUCHAR pcBuff = (PUCHAR)pBuff;
if(uiNumBytes % Adapter->ulFlashWriteSize)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Writing without Sector Erase for non-FlashWriteSize number of bytes 0x%x\n", uiNumBytes);
return STATUS_FAILURE;
}
uiStartOffset = BcmGetSectionValStartOffset(Adapter,eFlash2xSectionVal);
if(IsSectionExistInVendorInfo(Adapter,eFlash2xSectionVal))
{
return vendorextnWriteSectionWithoutErase(Adapter, pcBuff, eFlash2xSectionVal, uiOffset, uiNumBytes);
}
uiOffset = uiOffset + uiStartOffset;
#if defined(BCM_SHM_INTERFACE) && !defined(FLASH_DIRECT_ACCESS)
Status = bcmflash_raw_writenoerase((uiOffset/FLASH_PART_SIZE),(uiOffset % FLASH_PART_SIZE), pcBuff,uiNumBytes);
#else
rdmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
value = 0;
wrmalt(Adapter, 0x0f000C80,&value, sizeof(value));
Adapter->SelectedChip = RESET_CHIP_SELECT;
BcmDoChipSelect(Adapter,uiOffset);
uiPartOffset = (uiOffset & (FLASH_PART_SIZE - 1)) + GetFlashBaseAddr(Adapter);
for(i = 0 ; i< uiNumBytes; i += Adapter->ulFlashWriteSize)
{
if(Adapter->ulFlashWriteSize == BYTE_WRITE_SUPPORT)
Status = flashByteWrite(Adapter,uiPartOffset, pcBuff);
else
Status = flashWrite(Adapter,uiPartOffset, pcBuff);
if(Status != STATUS_SUCCESS)
break;
pcBuff = pcBuff + Adapter->ulFlashWriteSize;
uiPartOffset = uiPartOffset + Adapter->ulFlashWriteSize;
}
wrmalt(Adapter, 0x0f000C80, &uiTemp, sizeof(uiTemp));
Adapter->SelectedChip = RESET_CHIP_SELECT;
#endif
return Status;
}
BOOLEAN IsSectionExistInFlash(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL section)
{
BOOLEAN SectionPresent = FALSE ;
switch(section)
{
case ISO_IMAGE1 :
if((Adapter->psFlash2xCSInfo->OffsetISOImage1Part1Start != UNINIT_PTR_IN_CS) &&
(IsNonCDLessDevice(Adapter) == FALSE))
SectionPresent = TRUE ;
break;
case ISO_IMAGE2 :
if((Adapter->psFlash2xCSInfo->OffsetISOImage2Part1Start != UNINIT_PTR_IN_CS) &&
(IsNonCDLessDevice(Adapter) == FALSE))
SectionPresent = TRUE ;
break;
case DSD0 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForDSDStart != UNINIT_PTR_IN_CS)
SectionPresent = TRUE ;
break;
case DSD1 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD1Start != UNINIT_PTR_IN_CS)
SectionPresent = TRUE ;
break;
case DSD2 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForDSD2Start != UNINIT_PTR_IN_CS)
SectionPresent = TRUE ;
break;
case VSA0 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForVSAStart != UNINIT_PTR_IN_CS)
SectionPresent = TRUE ;
break;
case VSA1 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA1Start != UNINIT_PTR_IN_CS)
SectionPresent = TRUE ;
break;
case VSA2 :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForVSA2Start != UNINIT_PTR_IN_CS)
SectionPresent = TRUE ;
break;
case SCSI :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForScsiFirmware != UNINIT_PTR_IN_CS)
SectionPresent = TRUE ;
break;
case CONTROL_SECTION :
if(Adapter->psFlash2xCSInfo->OffsetFromZeroForControlSectionStart != UNINIT_PTR_IN_CS)
SectionPresent = TRUE ;
break;
default :
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Section Does not exist in Flash 2.x");
SectionPresent = FALSE;
}
return SectionPresent ;
}
INT IsSectionWritable(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL Section)
{
INT offset = STATUS_FAILURE;
INT Status = FALSE;
if(IsSectionExistInFlash(Adapter,Section) == FALSE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Section <%d> does not exixt", Section);
return FALSE;
}
offset = BcmGetSectionValStartOffset(Adapter,Section);
if(offset == INVALID_OFFSET)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Section<%d> does not exixt", Section);
return FALSE;
}
if(IsSectionExistInVendorInfo(Adapter,Section))
{
return !(Adapter->psFlash2xVendorInfo->VendorSection[Section].AccessFlags & FLASH2X_SECTION_RO);
}
Status = IsOffsetWritable(Adapter,offset);
return Status ;
}
static INT CorruptDSDSig(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlash2xSectionVal)
{
PUCHAR pBuff = NULL;
UINT sig = 0;
UINT uiOffset = 0;
UINT BlockStatus = 0;
UINT uiSectAlignAddr = 0;
Adapter->bSigCorrupted = FALSE;
if(Adapter->bAllDSDWriteAllow == FALSE)
{
if(IsSectionWritable(Adapter,eFlash2xSectionVal) != TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Section is not Writable...Hence can't Corrupt signature");
return SECTOR_IS_NOT_WRITABLE;
}
}
pBuff = (PUCHAR)kzalloc(MAX_RW_SIZE, GFP_KERNEL);
if(pBuff == NULL)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0, "Can't allocate memorey");
return -ENOMEM ;
}
uiOffset = Adapter->psFlash2xCSInfo->OffsetFromDSDStartForDSDHeader + sizeof(DSD_HEADER);
uiOffset -= MAX_RW_SIZE ;
BcmFlash2xBulkRead(Adapter, (PUINT)pBuff,eFlash2xSectionVal,uiOffset,MAX_RW_SIZE);
sig = *((PUINT)(pBuff +12));
sig =ntohl(sig);
BCM_DEBUG_PRINT_BUFFER(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,pBuff,MAX_RW_SIZE);
//Now corrupting the sig by corrupting 4th last Byte.
*(pBuff + 12) = 0;
if(sig == DSD_IMAGE_MAGIC_NUMBER)
{
Adapter->bSigCorrupted = TRUE;
if(Adapter->ulFlashWriteSize == BYTE_WRITE_SUPPORT)
{
uiSectAlignAddr = uiOffset & ~(Adapter->uiSectorSize -1);
BlockStatus = BcmFlashUnProtectBlock(Adapter,uiSectAlignAddr,Adapter->uiSectorSize);
WriteToFlashWithoutSectorErase(Adapter,(PUINT)(pBuff + 12),eFlash2xSectionVal,
(uiOffset + 12),BYTE_WRITE_SUPPORT);
if(BlockStatus)
{
BcmRestoreBlockProtectStatus(Adapter,BlockStatus);
BlockStatus = 0;
}
}
else
{
WriteToFlashWithoutSectorErase(Adapter,(PUINT)pBuff,eFlash2xSectionVal,
uiOffset ,MAX_RW_SIZE);
}
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"BCM Signature is not present in header");
kfree(pBuff);
return STATUS_FAILURE;
}
kfree(pBuff);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Corrupted the signature");
return STATUS_SUCCESS ;
}
static INT CorruptISOSig(PMINI_ADAPTER Adapter, FLASH2X_SECTION_VAL eFlash2xSectionVal)
{
PUCHAR pBuff = NULL;
UINT sig = 0;
UINT uiOffset = 0;
Adapter->bSigCorrupted = FALSE;
if(IsSectionWritable(Adapter,eFlash2xSectionVal) != TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Section is not Writable...Hence can't Corrupt signature");
return SECTOR_IS_NOT_WRITABLE;
}
pBuff = (PUCHAR)kzalloc(MAX_RW_SIZE, GFP_KERNEL);
if(pBuff == NULL)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Can't allocate memorey");
return -ENOMEM ;
}
uiOffset = 0;
BcmFlash2xBulkRead(Adapter, (PUINT)pBuff,eFlash2xSectionVal,uiOffset, MAX_RW_SIZE);
sig = *((PUINT)pBuff);
sig =ntohl(sig);
//corrupt signature
*pBuff = 0;
if(sig == ISO_IMAGE_MAGIC_NUMBER)
{
Adapter->bSigCorrupted = TRUE;
WriteToFlashWithoutSectorErase(Adapter,(PUINT)pBuff,eFlash2xSectionVal,
uiOffset ,Adapter->ulFlashWriteSize);
}
else
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"BCM Signature is not present in header");
kfree(pBuff);
return STATUS_FAILURE;
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,"Corrupted the signature");
BCM_DEBUG_PRINT_BUFFER(Adapter,DBG_TYPE_OTHERS, NVM_RW, DBG_LVL_ALL,pBuff,MAX_RW_SIZE);
kfree(pBuff);
return STATUS_SUCCESS ;
}
BOOLEAN IsNonCDLessDevice(PMINI_ADAPTER Adapter)
{
if(Adapter->psFlash2xCSInfo->IsCDLessDeviceBootSig == NON_CDLESS_DEVICE_BOOT_SIG)
return TRUE;
else
return FALSE ;
}
| gpl-2.0 |
jfdsmabalot/kernel_moto-x | fs/hostfs/hostfs_user.c | 4940 | 7300 | /*
* Copyright (C) 2000 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <stddef.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/vfs.h>
#include "hostfs.h"
#include "os.h"
#include <utime.h>
static void stat64_to_hostfs(const struct stat64 *buf, struct hostfs_stat *p)
{
p->ino = buf->st_ino;
p->mode = buf->st_mode;
p->nlink = buf->st_nlink;
p->uid = buf->st_uid;
p->gid = buf->st_gid;
p->size = buf->st_size;
p->atime.tv_sec = buf->st_atime;
p->atime.tv_nsec = 0;
p->ctime.tv_sec = buf->st_ctime;
p->ctime.tv_nsec = 0;
p->mtime.tv_sec = buf->st_mtime;
p->mtime.tv_nsec = 0;
p->blksize = buf->st_blksize;
p->blocks = buf->st_blocks;
p->maj = os_major(buf->st_rdev);
p->min = os_minor(buf->st_rdev);
}
int stat_file(const char *path, struct hostfs_stat *p, int fd)
{
struct stat64 buf;
if (fd >= 0) {
if (fstat64(fd, &buf) < 0)
return -errno;
} else if (lstat64(path, &buf) < 0) {
return -errno;
}
stat64_to_hostfs(&buf, p);
return 0;
}
int access_file(char *path, int r, int w, int x)
{
int mode = 0;
if (r)
mode = R_OK;
if (w)
mode |= W_OK;
if (x)
mode |= X_OK;
if (access(path, mode) != 0)
return -errno;
else return 0;
}
int open_file(char *path, int r, int w, int append)
{
int mode = 0, fd;
if (r && !w)
mode = O_RDONLY;
else if (!r && w)
mode = O_WRONLY;
else if (r && w)
mode = O_RDWR;
else panic("Impossible mode in open_file");
if (append)
mode |= O_APPEND;
fd = open64(path, mode);
if (fd < 0)
return -errno;
else return fd;
}
void *open_dir(char *path, int *err_out)
{
DIR *dir;
dir = opendir(path);
*err_out = errno;
return dir;
}
char *read_dir(void *stream, unsigned long long *pos,
unsigned long long *ino_out, int *len_out,
unsigned int *type_out)
{
DIR *dir = stream;
struct dirent *ent;
seekdir(dir, *pos);
ent = readdir(dir);
if (ent == NULL)
return NULL;
*len_out = strlen(ent->d_name);
*ino_out = ent->d_ino;
*type_out = ent->d_type;
*pos = telldir(dir);
return ent->d_name;
}
int read_file(int fd, unsigned long long *offset, char *buf, int len)
{
int n;
n = pread64(fd, buf, len, *offset);
if (n < 0)
return -errno;
*offset += n;
return n;
}
int write_file(int fd, unsigned long long *offset, const char *buf, int len)
{
int n;
n = pwrite64(fd, buf, len, *offset);
if (n < 0)
return -errno;
*offset += n;
return n;
}
int lseek_file(int fd, long long offset, int whence)
{
int ret;
ret = lseek64(fd, offset, whence);
if (ret < 0)
return -errno;
return 0;
}
int fsync_file(int fd, int datasync)
{
int ret;
if (datasync)
ret = fdatasync(fd);
else
ret = fsync(fd);
if (ret < 0)
return -errno;
return 0;
}
int replace_file(int oldfd, int fd)
{
return dup2(oldfd, fd);
}
void close_file(void *stream)
{
close(*((int *) stream));
}
void close_dir(void *stream)
{
closedir(stream);
}
int file_create(char *name, int ur, int uw, int ux, int gr,
int gw, int gx, int or, int ow, int ox)
{
int mode, fd;
mode = 0;
mode |= ur ? S_IRUSR : 0;
mode |= uw ? S_IWUSR : 0;
mode |= ux ? S_IXUSR : 0;
mode |= gr ? S_IRGRP : 0;
mode |= gw ? S_IWGRP : 0;
mode |= gx ? S_IXGRP : 0;
mode |= or ? S_IROTH : 0;
mode |= ow ? S_IWOTH : 0;
mode |= ox ? S_IXOTH : 0;
fd = open64(name, O_CREAT | O_RDWR, mode);
if (fd < 0)
return -errno;
return fd;
}
int set_attr(const char *file, struct hostfs_iattr *attrs, int fd)
{
struct hostfs_stat st;
struct timeval times[2];
int err, ma;
if (attrs->ia_valid & HOSTFS_ATTR_MODE) {
if (fd >= 0) {
if (fchmod(fd, attrs->ia_mode) != 0)
return -errno;
} else if (chmod(file, attrs->ia_mode) != 0) {
return -errno;
}
}
if (attrs->ia_valid & HOSTFS_ATTR_UID) {
if (fd >= 0) {
if (fchown(fd, attrs->ia_uid, -1))
return -errno;
} else if (chown(file, attrs->ia_uid, -1)) {
return -errno;
}
}
if (attrs->ia_valid & HOSTFS_ATTR_GID) {
if (fd >= 0) {
if (fchown(fd, -1, attrs->ia_gid))
return -errno;
} else if (chown(file, -1, attrs->ia_gid)) {
return -errno;
}
}
if (attrs->ia_valid & HOSTFS_ATTR_SIZE) {
if (fd >= 0) {
if (ftruncate(fd, attrs->ia_size))
return -errno;
} else if (truncate(file, attrs->ia_size)) {
return -errno;
}
}
/*
* Update accessed and/or modified time, in two parts: first set
* times according to the changes to perform, and then call futimes()
* or utimes() to apply them.
*/
ma = (HOSTFS_ATTR_ATIME_SET | HOSTFS_ATTR_MTIME_SET);
if (attrs->ia_valid & ma) {
err = stat_file(file, &st, fd);
if (err != 0)
return err;
times[0].tv_sec = st.atime.tv_sec;
times[0].tv_usec = st.atime.tv_nsec / 1000;
times[1].tv_sec = st.mtime.tv_sec;
times[1].tv_usec = st.mtime.tv_nsec / 1000;
if (attrs->ia_valid & HOSTFS_ATTR_ATIME_SET) {
times[0].tv_sec = attrs->ia_atime.tv_sec;
times[0].tv_usec = attrs->ia_atime.tv_nsec / 1000;
}
if (attrs->ia_valid & HOSTFS_ATTR_MTIME_SET) {
times[1].tv_sec = attrs->ia_mtime.tv_sec;
times[1].tv_usec = attrs->ia_mtime.tv_nsec / 1000;
}
if (fd >= 0) {
if (futimes(fd, times) != 0)
return -errno;
} else if (utimes(file, times) != 0) {
return -errno;
}
}
/* Note: ctime is not handled */
if (attrs->ia_valid & (HOSTFS_ATTR_ATIME | HOSTFS_ATTR_MTIME)) {
err = stat_file(file, &st, fd);
attrs->ia_atime = st.atime;
attrs->ia_mtime = st.mtime;
if (err != 0)
return err;
}
return 0;
}
int make_symlink(const char *from, const char *to)
{
int err;
err = symlink(to, from);
if (err)
return -errno;
return 0;
}
int unlink_file(const char *file)
{
int err;
err = unlink(file);
if (err)
return -errno;
return 0;
}
int do_mkdir(const char *file, int mode)
{
int err;
err = mkdir(file, mode);
if (err)
return -errno;
return 0;
}
int do_rmdir(const char *file)
{
int err;
err = rmdir(file);
if (err)
return -errno;
return 0;
}
int do_mknod(const char *file, int mode, unsigned int major, unsigned int minor)
{
int err;
err = mknod(file, mode, os_makedev(major, minor));
if (err)
return -errno;
return 0;
}
int link_file(const char *to, const char *from)
{
int err;
err = link(to, from);
if (err)
return -errno;
return 0;
}
int hostfs_do_readlink(char *file, char *buf, int size)
{
int n;
n = readlink(file, buf, size);
if (n < 0)
return -errno;
if (n < size)
buf[n] = '\0';
return n;
}
int rename_file(char *from, char *to)
{
int err;
err = rename(from, to);
if (err < 0)
return -errno;
return 0;
}
int do_statfs(char *root, long *bsize_out, long long *blocks_out,
long long *bfree_out, long long *bavail_out,
long long *files_out, long long *ffree_out,
void *fsid_out, int fsid_size, long *namelen_out)
{
struct statfs64 buf;
int err;
err = statfs64(root, &buf);
if (err < 0)
return -errno;
*bsize_out = buf.f_bsize;
*blocks_out = buf.f_blocks;
*bfree_out = buf.f_bfree;
*bavail_out = buf.f_bavail;
*files_out = buf.f_files;
*ffree_out = buf.f_ffree;
memcpy(fsid_out, &buf.f_fsid,
sizeof(buf.f_fsid) > fsid_size ? fsid_size :
sizeof(buf.f_fsid));
*namelen_out = buf.f_namelen;
return 0;
}
| gpl-2.0 |
lolhi/ef52-kernel | drivers/hwmon/adcxx.c | 4940 | 6781 | /*
* adcxx.c
*
* The adcxx4s is an AD converter family from National Semiconductor (NS).
*
* Copyright (c) 2008 Marc Pignat <marc.pignat@hevs.ch>
*
* The adcxx4s communicates with a host processor via an SPI/Microwire Bus
* interface. This driver supports the whole family of devices with name
* ADC<bb><c>S<sss>, where
* * bb is the resolution in number of bits (8, 10, 12)
* * c is the number of channels (1, 2, 4, 8)
* * sss is the maximum conversion speed (021 for 200 kSPS, 051 for 500 kSPS
* and 101 for 1 MSPS)
*
* Complete datasheets are available at National's website here:
* http://www.national.com/ds/DC/ADC<bb><c>S<sss>.pdf
*
* Handling of 8, 10 and 12 bits converters are the same, the
* unavailable bits are 0 :)
*
* 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/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/sysfs.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/mutex.h>
#include <linux/mod_devicetable.h>
#include <linux/spi/spi.h>
#define DRVNAME "adcxx"
struct adcxx {
struct device *hwmon_dev;
struct mutex lock;
u32 channels;
u32 reference; /* in millivolts */
};
/* sysfs hook function */
static ssize_t adcxx_read(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
struct adcxx *adc = spi_get_drvdata(spi);
u8 tx_buf[2];
u8 rx_buf[2];
int status;
u32 value;
if (mutex_lock_interruptible(&adc->lock))
return -ERESTARTSYS;
if (adc->channels == 1) {
status = spi_read(spi, rx_buf, sizeof(rx_buf));
} else {
tx_buf[0] = attr->index << 3; /* other bits are don't care */
status = spi_write_then_read(spi, tx_buf, sizeof(tx_buf),
rx_buf, sizeof(rx_buf));
}
if (status < 0) {
dev_warn(dev, "SPI synch. transfer failed with status %d\n",
status);
goto out;
}
value = (rx_buf[0] << 8) + rx_buf[1];
dev_dbg(dev, "raw value = 0x%x\n", value);
value = value * adc->reference >> 12;
status = sprintf(buf, "%d\n", value);
out:
mutex_unlock(&adc->lock);
return status;
}
static ssize_t adcxx_show_min(struct device *dev,
struct device_attribute *devattr, char *buf)
{
/* The minimum reference is 0 for this chip family */
return sprintf(buf, "0\n");
}
static ssize_t adcxx_show_max(struct device *dev,
struct device_attribute *devattr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct adcxx *adc = spi_get_drvdata(spi);
u32 reference;
if (mutex_lock_interruptible(&adc->lock))
return -ERESTARTSYS;
reference = adc->reference;
mutex_unlock(&adc->lock);
return sprintf(buf, "%d\n", reference);
}
static ssize_t adcxx_set_max(struct device *dev,
struct device_attribute *devattr, const char *buf, size_t count)
{
struct spi_device *spi = to_spi_device(dev);
struct adcxx *adc = spi_get_drvdata(spi);
unsigned long value;
if (kstrtoul(buf, 10, &value))
return -EINVAL;
if (mutex_lock_interruptible(&adc->lock))
return -ERESTARTSYS;
adc->reference = value;
mutex_unlock(&adc->lock);
return count;
}
static ssize_t adcxx_show_name(struct device *dev, struct device_attribute
*devattr, char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct adcxx *adc = spi_get_drvdata(spi);
return sprintf(buf, "adcxx%ds\n", adc->channels);
}
static struct sensor_device_attribute ad_input[] = {
SENSOR_ATTR(name, S_IRUGO, adcxx_show_name, NULL, 0),
SENSOR_ATTR(in_min, S_IRUGO, adcxx_show_min, NULL, 0),
SENSOR_ATTR(in_max, S_IWUSR | S_IRUGO, adcxx_show_max,
adcxx_set_max, 0),
SENSOR_ATTR(in0_input, S_IRUGO, adcxx_read, NULL, 0),
SENSOR_ATTR(in1_input, S_IRUGO, adcxx_read, NULL, 1),
SENSOR_ATTR(in2_input, S_IRUGO, adcxx_read, NULL, 2),
SENSOR_ATTR(in3_input, S_IRUGO, adcxx_read, NULL, 3),
SENSOR_ATTR(in4_input, S_IRUGO, adcxx_read, NULL, 4),
SENSOR_ATTR(in5_input, S_IRUGO, adcxx_read, NULL, 5),
SENSOR_ATTR(in6_input, S_IRUGO, adcxx_read, NULL, 6),
SENSOR_ATTR(in7_input, S_IRUGO, adcxx_read, NULL, 7),
};
/*----------------------------------------------------------------------*/
static int __devinit adcxx_probe(struct spi_device *spi)
{
int channels = spi_get_device_id(spi)->driver_data;
struct adcxx *adc;
int status;
int i;
adc = kzalloc(sizeof *adc, GFP_KERNEL);
if (!adc)
return -ENOMEM;
/* set a default value for the reference */
adc->reference = 3300;
adc->channels = channels;
mutex_init(&adc->lock);
mutex_lock(&adc->lock);
spi_set_drvdata(spi, adc);
for (i = 0; i < 3 + adc->channels; i++) {
status = device_create_file(&spi->dev, &ad_input[i].dev_attr);
if (status) {
dev_err(&spi->dev, "device_create_file failed.\n");
goto out_err;
}
}
adc->hwmon_dev = hwmon_device_register(&spi->dev);
if (IS_ERR(adc->hwmon_dev)) {
dev_err(&spi->dev, "hwmon_device_register failed.\n");
status = PTR_ERR(adc->hwmon_dev);
goto out_err;
}
mutex_unlock(&adc->lock);
return 0;
out_err:
for (i--; i >= 0; i--)
device_remove_file(&spi->dev, &ad_input[i].dev_attr);
spi_set_drvdata(spi, NULL);
mutex_unlock(&adc->lock);
kfree(adc);
return status;
}
static int __devexit adcxx_remove(struct spi_device *spi)
{
struct adcxx *adc = spi_get_drvdata(spi);
int i;
mutex_lock(&adc->lock);
hwmon_device_unregister(adc->hwmon_dev);
for (i = 0; i < 3 + adc->channels; i++)
device_remove_file(&spi->dev, &ad_input[i].dev_attr);
spi_set_drvdata(spi, NULL);
mutex_unlock(&adc->lock);
kfree(adc);
return 0;
}
static const struct spi_device_id adcxx_ids[] = {
{ "adcxx1s", 1 },
{ "adcxx2s", 2 },
{ "adcxx4s", 4 },
{ "adcxx8s", 8 },
{ },
};
MODULE_DEVICE_TABLE(spi, adcxx_ids);
static struct spi_driver adcxx_driver = {
.driver = {
.name = "adcxx",
.owner = THIS_MODULE,
},
.id_table = adcxx_ids,
.probe = adcxx_probe,
.remove = __devexit_p(adcxx_remove),
};
module_spi_driver(adcxx_driver);
MODULE_AUTHOR("Marc Pignat");
MODULE_DESCRIPTION("National Semiconductor adcxx8sxxx Linux driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Abhinav1997/android_kernel_riogrande | arch/arm/mach-omap2/voltagedomains44xx_data.c | 4940 | 2787 | /*
* OMAP3/OMAP4 Voltage Management Routines
*
* Author: Thara Gopinath <thara@ti.com>
*
* Copyright (C) 2007 Texas Instruments, Inc.
* Rajendra Nayak <rnayak@ti.com>
* Lesly A M <x0080970@ti.com>
*
* Copyright (C) 2008 Nokia Corporation
* Kalle Jokiniemi
*
* Copyright (C) 2010 Texas Instruments, Inc.
* Thara Gopinath <thara@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/kernel.h>
#include <linux/err.h>
#include <linux/init.h>
#include "common.h"
#include "prm-regbits-44xx.h"
#include "prm44xx.h"
#include "prcm44xx.h"
#include "prminst44xx.h"
#include "voltage.h"
#include "omap_opp_data.h"
#include "vc.h"
#include "vp.h"
static const struct omap_vfsm_instance omap4_vdd_mpu_vfsm = {
.voltsetup_reg = OMAP4_PRM_VOLTSETUP_MPU_RET_SLEEP_OFFSET,
};
static const struct omap_vfsm_instance omap4_vdd_iva_vfsm = {
.voltsetup_reg = OMAP4_PRM_VOLTSETUP_IVA_RET_SLEEP_OFFSET,
};
static const struct omap_vfsm_instance omap4_vdd_core_vfsm = {
.voltsetup_reg = OMAP4_PRM_VOLTSETUP_CORE_RET_SLEEP_OFFSET,
};
static struct voltagedomain omap4_voltdm_mpu = {
.name = "mpu",
.scalable = true,
.read = omap4_prm_vcvp_read,
.write = omap4_prm_vcvp_write,
.rmw = omap4_prm_vcvp_rmw,
.vc = &omap4_vc_mpu,
.vfsm = &omap4_vdd_mpu_vfsm,
.vp = &omap4_vp_mpu,
};
static struct voltagedomain omap4_voltdm_iva = {
.name = "iva",
.scalable = true,
.read = omap4_prm_vcvp_read,
.write = omap4_prm_vcvp_write,
.rmw = omap4_prm_vcvp_rmw,
.vc = &omap4_vc_iva,
.vfsm = &omap4_vdd_iva_vfsm,
.vp = &omap4_vp_iva,
};
static struct voltagedomain omap4_voltdm_core = {
.name = "core",
.scalable = true,
.read = omap4_prm_vcvp_read,
.write = omap4_prm_vcvp_write,
.rmw = omap4_prm_vcvp_rmw,
.vc = &omap4_vc_core,
.vfsm = &omap4_vdd_core_vfsm,
.vp = &omap4_vp_core,
};
static struct voltagedomain omap4_voltdm_wkup = {
.name = "wakeup",
};
static struct voltagedomain *voltagedomains_omap4[] __initdata = {
&omap4_voltdm_mpu,
&omap4_voltdm_iva,
&omap4_voltdm_core,
&omap4_voltdm_wkup,
NULL,
};
static const char *sys_clk_name __initdata = "sys_clkin_ck";
void __init omap44xx_voltagedomains_init(void)
{
struct voltagedomain *voltdm;
int i;
/*
* XXX Will depend on the process, validation, and binning
* for the currently-running IC
*/
#ifdef CONFIG_PM_OPP
omap4_voltdm_mpu.volt_data = omap44xx_vdd_mpu_volt_data;
omap4_voltdm_iva.volt_data = omap44xx_vdd_iva_volt_data;
omap4_voltdm_core.volt_data = omap44xx_vdd_core_volt_data;
#endif
for (i = 0; voltdm = voltagedomains_omap4[i], voltdm; i++)
voltdm->sys_clk.name = sys_clk_name;
voltdm_init(voltagedomains_omap4);
};
| gpl-2.0 |
DJSteve/G800F-LL_Kernel | drivers/gpu/drm/ati_pcigart.c | 5196 | 5731 | /**
* \file ati_pcigart.c
* ATI PCI GART support
*
* \author Gareth Hughes <gareth@valinux.com>
*/
/*
* Created: Wed Dec 13 21:52:19 2000 by gareth@valinux.com
*
* Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
* 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
* PRECISION INSIGHT 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 <linux/export.h>
#include "drmP.h"
# define ATI_PCIGART_PAGE_SIZE 4096 /**< PCI GART page size */
static int drm_ati_alloc_pcigart_table(struct drm_device *dev,
struct drm_ati_pcigart_info *gart_info)
{
gart_info->table_handle = drm_pci_alloc(dev, gart_info->table_size,
PAGE_SIZE);
if (gart_info->table_handle == NULL)
return -ENOMEM;
return 0;
}
static void drm_ati_free_pcigart_table(struct drm_device *dev,
struct drm_ati_pcigart_info *gart_info)
{
drm_pci_free(dev, gart_info->table_handle);
gart_info->table_handle = NULL;
}
int drm_ati_pcigart_cleanup(struct drm_device *dev, struct drm_ati_pcigart_info *gart_info)
{
struct drm_sg_mem *entry = dev->sg;
unsigned long pages;
int i;
int max_pages;
/* we need to support large memory configurations */
if (!entry) {
DRM_ERROR("no scatter/gather memory!\n");
return 0;
}
if (gart_info->bus_addr) {
max_pages = (gart_info->table_size / sizeof(u32));
pages = (entry->pages <= max_pages)
? entry->pages : max_pages;
for (i = 0; i < pages; i++) {
if (!entry->busaddr[i])
break;
pci_unmap_page(dev->pdev, entry->busaddr[i],
PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
}
if (gart_info->gart_table_location == DRM_ATI_GART_MAIN)
gart_info->bus_addr = 0;
}
if (gart_info->gart_table_location == DRM_ATI_GART_MAIN &&
gart_info->table_handle) {
drm_ati_free_pcigart_table(dev, gart_info);
}
return 1;
}
EXPORT_SYMBOL(drm_ati_pcigart_cleanup);
int drm_ati_pcigart_init(struct drm_device *dev, struct drm_ati_pcigart_info *gart_info)
{
struct drm_local_map *map = &gart_info->mapping;
struct drm_sg_mem *entry = dev->sg;
void *address = NULL;
unsigned long pages;
u32 *pci_gart = NULL, page_base, gart_idx;
dma_addr_t bus_address = 0;
int i, j, ret = 0;
int max_ati_pages, max_real_pages;
if (!entry) {
DRM_ERROR("no scatter/gather memory!\n");
goto done;
}
if (gart_info->gart_table_location == DRM_ATI_GART_MAIN) {
DRM_DEBUG("PCI: no table in VRAM: using normal RAM\n");
if (pci_set_dma_mask(dev->pdev, gart_info->table_mask)) {
DRM_ERROR("fail to set dma mask to 0x%Lx\n",
(unsigned long long)gart_info->table_mask);
ret = 1;
goto done;
}
ret = drm_ati_alloc_pcigart_table(dev, gart_info);
if (ret) {
DRM_ERROR("cannot allocate PCI GART page!\n");
goto done;
}
pci_gart = gart_info->table_handle->vaddr;
address = gart_info->table_handle->vaddr;
bus_address = gart_info->table_handle->busaddr;
} else {
address = gart_info->addr;
bus_address = gart_info->bus_addr;
DRM_DEBUG("PCI: Gart Table: VRAM %08LX mapped at %08lX\n",
(unsigned long long)bus_address,
(unsigned long)address);
}
max_ati_pages = (gart_info->table_size / sizeof(u32));
max_real_pages = max_ati_pages / (PAGE_SIZE / ATI_PCIGART_PAGE_SIZE);
pages = (entry->pages <= max_real_pages)
? entry->pages : max_real_pages;
if (gart_info->gart_table_location == DRM_ATI_GART_MAIN) {
memset(pci_gart, 0, max_ati_pages * sizeof(u32));
} else {
memset_io((void __iomem *)map->handle, 0, max_ati_pages * sizeof(u32));
}
gart_idx = 0;
for (i = 0; i < pages; i++) {
/* we need to support large memory configurations */
entry->busaddr[i] = pci_map_page(dev->pdev, entry->pagelist[i],
0, PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
if (pci_dma_mapping_error(dev->pdev, entry->busaddr[i])) {
DRM_ERROR("unable to map PCIGART pages!\n");
drm_ati_pcigart_cleanup(dev, gart_info);
address = NULL;
bus_address = 0;
goto done;
}
page_base = (u32) entry->busaddr[i];
for (j = 0; j < (PAGE_SIZE / ATI_PCIGART_PAGE_SIZE); j++) {
u32 val;
switch(gart_info->gart_reg_if) {
case DRM_ATI_GART_IGP:
val = page_base | 0xc;
break;
case DRM_ATI_GART_PCIE:
val = (page_base >> 8) | 0xc;
break;
default:
case DRM_ATI_GART_PCI:
val = page_base;
break;
}
if (gart_info->gart_table_location ==
DRM_ATI_GART_MAIN)
pci_gart[gart_idx] = cpu_to_le32(val);
else
DRM_WRITE32(map, gart_idx * sizeof(u32), val);
gart_idx++;
page_base += ATI_PCIGART_PAGE_SIZE;
}
}
ret = 1;
#if defined(__i386__) || defined(__x86_64__)
wbinvd();
#else
mb();
#endif
done:
gart_info->addr = address;
gart_info->bus_addr = bus_address;
return ret;
}
EXPORT_SYMBOL(drm_ati_pcigart_init);
| gpl-2.0 |
bmproject/TrinityCore | src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp | 77 | 18067 | /*
* Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.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, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Trial Of the Champion
SD%Complete:
SDComment:
SDCategory: trial_of_the_champion
EndScriptData */
/* ContentData
npc_announcer_toc5
EndContentData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "trial_of_the_champion.h"
#include "Vehicle.h"
#include "Player.h"
enum Yells
{
SAY_INTRO_1 = 0,
SAY_INTRO_2 = 1,
SAY_INTRO_3 = 2,
SAY_AGGRO = 3,
SAY_PHASE_2 = 4,
SAY_PHASE_3 = 5,
SAY_KILL_PLAYER = 6,
SAY_DEATH = 7
};
#define GOSSIP_START_EVENT1 "I'm ready to start challenge."
#define GOSSIP_START_EVENT2 "I'm ready for the next challenge."
#define ORIENTATION 4.714f
/*######
## npc_announcer_toc5
######*/
const Position SpawnPosition = {746.261f, 657.401f, 411.681f, 4.65f};
class npc_announcer_toc5 : public CreatureScript
{
public:
npc_announcer_toc5() : CreatureScript("npc_announcer_toc5") { }
struct npc_announcer_toc5AI : public ScriptedAI
{
npc_announcer_toc5AI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
uiSummonTimes = 0;
uiPosition = 0;
uiLesserChampions = 0;
uiFirstBoss = 0;
uiSecondBoss = 0;
uiThirdBoss = 0;
uiArgentChampion = 0;
uiPhase = 0;
uiTimer = 0;
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
SetGrandChampionsForEncounter();
SetArgentChampion();
}
InstanceScript* instance;
uint8 uiSummonTimes;
uint8 uiPosition;
uint8 uiLesserChampions;
uint32 uiArgentChampion;
uint32 uiFirstBoss;
uint32 uiSecondBoss;
uint32 uiThirdBoss;
uint32 uiPhase;
uint32 uiTimer;
ObjectGuid uiVehicle1GUID;
ObjectGuid uiVehicle2GUID;
ObjectGuid uiVehicle3GUID;
GuidList Champion1List;
GuidList Champion2List;
GuidList Champion3List;
void NextStep(uint32 uiTimerStep, bool bNextStep = true, uint8 uiPhaseStep = 0)
{
uiTimer = uiTimerStep;
if (bNextStep)
++uiPhase;
else
uiPhase = uiPhaseStep;
}
void SetData(uint32 uiType, uint32 /*uiData*/) override
{
switch (uiType)
{
case DATA_START:
DoSummonGrandChampion(uiFirstBoss);
NextStep(10000, false, 1);
break;
case DATA_IN_POSITION: //movement done.
me->GetMotionMaster()->MovePoint(1, 735.81f, 661.92f, 412.39f);
if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_MAIN_GATE)))
instance->HandleGameObject(go->GetGUID(), false);
NextStep(10000, false, 3);
break;
case DATA_LESSER_CHAMPIONS_DEFEATED:
{
++uiLesserChampions;
GuidList TempList;
if (uiLesserChampions == 3 || uiLesserChampions == 6)
{
switch (uiLesserChampions)
{
case 3:
TempList = Champion2List;
break;
case 6:
TempList = Champion3List;
break;
}
for (GuidList::const_iterator itr = TempList.begin(); itr != TempList.end(); ++itr)
if (Creature* summon = ObjectAccessor::GetCreature(*me, *itr))
AggroAllPlayers(summon);
}else if (uiLesserChampions == 9)
StartGrandChampionsAttack();
break;
}
}
}
void StartGrandChampionsAttack()
{
Creature* pGrandChampion1 = ObjectAccessor::GetCreature(*me, uiVehicle1GUID);
Creature* pGrandChampion2 = ObjectAccessor::GetCreature(*me, uiVehicle2GUID);
Creature* pGrandChampion3 = ObjectAccessor::GetCreature(*me, uiVehicle3GUID);
if (pGrandChampion1 && pGrandChampion2 && pGrandChampion3)
{
AggroAllPlayers(pGrandChampion1);
AggroAllPlayers(pGrandChampion2);
AggroAllPlayers(pGrandChampion3);
}
}
void MovementInform(uint32 uiType, uint32 uiPointId) override
{
if (uiType != POINT_MOTION_TYPE)
return;
if (uiPointId == 1)
me->SetFacingTo(ORIENTATION);
}
void DoSummonGrandChampion(uint32 uiBoss)
{
++uiSummonTimes;
uint32 VEHICLE_TO_SUMMON1 = 0;
uint32 VEHICLE_TO_SUMMON2 = 0;
switch (uiBoss)
{
case 0:
VEHICLE_TO_SUMMON1 = VEHICLE_MOKRA_SKILLCRUSHER_MOUNT;
VEHICLE_TO_SUMMON2 = VEHICLE_ORGRIMMAR_WOLF;
break;
case 1:
VEHICLE_TO_SUMMON1 = VEHICLE_ERESSEA_DAWNSINGER_MOUNT;
VEHICLE_TO_SUMMON2 = VEHICLE_SILVERMOON_HAWKSTRIDER;
break;
case 2:
VEHICLE_TO_SUMMON1 = VEHICLE_RUNOK_WILDMANE_MOUNT;
VEHICLE_TO_SUMMON2 = VEHICLE_THUNDER_BLUFF_KODO;
break;
case 3:
VEHICLE_TO_SUMMON1 = VEHICLE_ZUL_TORE_MOUNT;
VEHICLE_TO_SUMMON2 = VEHICLE_DARKSPEAR_RAPTOR;
break;
case 4:
VEHICLE_TO_SUMMON1 = VEHICLE_DEATHSTALKER_VESCERI_MOUNT;
VEHICLE_TO_SUMMON2 = VEHICLE_FORSAKE_WARHORSE;
break;
default:
return;
}
if (Creature* pBoss = me->SummonCreature(VEHICLE_TO_SUMMON1, SpawnPosition))
{
switch (uiSummonTimes)
{
case 1:
{
uiVehicle1GUID = pBoss->GetGUID();
ObjectGuid uiGrandChampionBoss1;
if (Vehicle* pVehicle = pBoss->GetVehicleKit())
if (Unit* unit = pVehicle->GetPassenger(0))
uiGrandChampionBoss1 = unit->GetGUID();
instance->SetGuidData(DATA_GRAND_CHAMPION_VEHICLE_1, uiVehicle1GUID);
instance->SetGuidData(DATA_GRAND_CHAMPION_1, uiGrandChampionBoss1);
pBoss->AI()->SetData(1, 0);
break;
}
case 2:
{
uiVehicle2GUID = pBoss->GetGUID();
ObjectGuid uiGrandChampionBoss2;
if (Vehicle* pVehicle = pBoss->GetVehicleKit())
if (Unit* unit = pVehicle->GetPassenger(0))
uiGrandChampionBoss2 = unit->GetGUID();
instance->SetGuidData(DATA_GRAND_CHAMPION_VEHICLE_2, uiVehicle2GUID);
instance->SetGuidData(DATA_GRAND_CHAMPION_2, uiGrandChampionBoss2);
pBoss->AI()->SetData(2, 0);
break;
}
case 3:
{
uiVehicle3GUID = pBoss->GetGUID();
ObjectGuid uiGrandChampionBoss3;
if (Vehicle* pVehicle = pBoss->GetVehicleKit())
if (Unit* unit = pVehicle->GetPassenger(0))
uiGrandChampionBoss3 = unit->GetGUID();
instance->SetGuidData(DATA_GRAND_CHAMPION_VEHICLE_3, uiVehicle3GUID);
instance->SetGuidData(DATA_GRAND_CHAMPION_3, uiGrandChampionBoss3);
pBoss->AI()->SetData(3, 0);
break;
}
default:
return;
}
for (uint8 i = 0; i < 3; ++i)
{
if (Creature* pAdd = me->SummonCreature(VEHICLE_TO_SUMMON2, SpawnPosition, TEMPSUMMON_CORPSE_DESPAWN))
{
switch (uiSummonTimes)
{
case 1:
Champion1List.push_back(pAdd->GetGUID());
break;
case 2:
Champion2List.push_back(pAdd->GetGUID());
break;
case 3:
Champion3List.push_back(pAdd->GetGUID());
break;
}
switch (i)
{
case 0:
pAdd->GetMotionMaster()->MoveFollow(pBoss, 2.0f, float(M_PI));
break;
case 1:
pAdd->GetMotionMaster()->MoveFollow(pBoss, 2.0f, float(M_PI) / 2);
break;
case 2:
pAdd->GetMotionMaster()->MoveFollow(pBoss, 2.0f, float(M_PI) / 2 + float(M_PI));
break;
}
}
}
}
}
void DoStartArgentChampionEncounter()
{
me->GetMotionMaster()->MovePoint(1, 735.81f, 661.92f, 412.39f);
if (me->SummonCreature(uiArgentChampion, SpawnPosition))
{
for (uint8 i = 0; i < 3; ++i)
{
if (Creature* pTrash = me->SummonCreature(NPC_ARGENT_LIGHWIELDER, SpawnPosition))
pTrash->AI()->SetData(i, 0);
if (Creature* pTrash = me->SummonCreature(NPC_ARGENT_MONK, SpawnPosition))
pTrash->AI()->SetData(i, 0);
if (Creature* pTrash = me->SummonCreature(NPC_PRIESTESS, SpawnPosition))
pTrash->AI()->SetData(i, 0);
}
}
}
void SetGrandChampionsForEncounter()
{
uiFirstBoss = urand(0, 4);
while (uiSecondBoss == uiFirstBoss || uiThirdBoss == uiFirstBoss || uiThirdBoss == uiSecondBoss)
{
uiSecondBoss = urand(0, 4);
uiThirdBoss = urand(0, 4);
}
}
void SetArgentChampion()
{
uint8 uiTempBoss = urand(0, 1);
switch (uiTempBoss)
{
case 0:
uiArgentChampion = NPC_EADRIC;
break;
case 1:
uiArgentChampion = NPC_PALETRESS;
break;
}
}
void StartEncounter()
{
me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
if (instance->GetData(BOSS_BLACK_KNIGHT) == NOT_STARTED)
{
if (instance->GetData(BOSS_ARGENT_CHALLENGE_E) == NOT_STARTED && instance->GetData(BOSS_ARGENT_CHALLENGE_P) == NOT_STARTED)
{
if (instance->GetData(BOSS_GRAND_CHAMPIONS) == NOT_STARTED)
SetData(DATA_START, 0);
if (instance->GetData(BOSS_GRAND_CHAMPIONS) == DONE)
DoStartArgentChampionEncounter();
}
if ((instance->GetData(BOSS_GRAND_CHAMPIONS) == DONE &&
instance->GetData(BOSS_ARGENT_CHALLENGE_E) == DONE) ||
instance->GetData(BOSS_ARGENT_CHALLENGE_P) == DONE)
me->SummonCreature(VEHICLE_BLACK_KNIGHT, 769.834f, 651.915f, 447.035f, 0);
}
}
void AggroAllPlayers(Creature* temp)
{
Map::PlayerList const &PlList = me->GetMap()->GetPlayers();
if (PlList.isEmpty())
return;
for (Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i)
{
if (Player* player = i->GetSource())
{
if (player->IsGameMaster())
continue;
if (player->IsAlive())
{
temp->SetHomePosition(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation());
temp->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
temp->SetReactState(REACT_AGGRESSIVE);
temp->SetInCombatWith(player);
player->SetInCombatWith(temp);
temp->AddThreat(player, 0.0f);
}
}
}
}
void UpdateAI(uint32 uiDiff) override
{
ScriptedAI::UpdateAI(uiDiff);
if (uiTimer <= uiDiff)
{
switch (uiPhase)
{
case 1:
DoSummonGrandChampion(uiSecondBoss);
NextStep(10000, true);
break;
case 2:
DoSummonGrandChampion(uiThirdBoss);
NextStep(0, false);
break;
case 3:
if (!Champion1List.empty())
{
for (GuidList::const_iterator itr = Champion1List.begin(); itr != Champion1List.end(); ++itr)
if (Creature* summon = ObjectAccessor::GetCreature(*me, *itr))
AggroAllPlayers(summon);
NextStep(0, false);
}
break;
}
} else uiTimer -= uiDiff;
if (!UpdateVictim())
return;
}
void JustSummoned(Creature* summon) override
{
if (instance->GetData(BOSS_GRAND_CHAMPIONS) == NOT_STARTED)
{
summon->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
summon->SetReactState(REACT_PASSIVE);
}
}
void SummonedCreatureDespawn(Creature* summon) override
{
switch (summon->GetEntry())
{
case VEHICLE_DARNASSIA_NIGHTSABER:
case VEHICLE_EXODAR_ELEKK:
case VEHICLE_STORMWIND_STEED:
case VEHICLE_GNOMEREGAN_MECHANOSTRIDER:
case VEHICLE_IRONFORGE_RAM:
case VEHICLE_FORSAKE_WARHORSE:
case VEHICLE_THUNDER_BLUFF_KODO:
case VEHICLE_ORGRIMMAR_WOLF:
case VEHICLE_SILVERMOON_HAWKSTRIDER:
case VEHICLE_DARKSPEAR_RAPTOR:
SetData(DATA_LESSER_CHAMPIONS_DEFEATED, 0);
break;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_announcer_toc5AI>(creature);
}
bool OnGossipHello(Player* player, Creature* creature) override
{
InstanceScript* instance = creature->GetInstanceScript();
if (instance &&
((instance->GetData(BOSS_GRAND_CHAMPIONS) == DONE &&
instance->GetData(BOSS_BLACK_KNIGHT) == DONE &&
instance->GetData(BOSS_ARGENT_CHALLENGE_E) == DONE) ||
instance->GetData(BOSS_ARGENT_CHALLENGE_P) == DONE))
return false;
if (instance &&
instance->GetData(BOSS_GRAND_CHAMPIONS) == NOT_STARTED &&
instance->GetData(BOSS_ARGENT_CHALLENGE_E) == NOT_STARTED &&
instance->GetData(BOSS_ARGENT_CHALLENGE_P) == NOT_STARTED &&
instance->GetData(BOSS_BLACK_KNIGHT) == NOT_STARTED)
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_START_EVENT1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
else if (instance)
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_START_EVENT2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID());
return true;
}
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override
{
player->PlayerTalkClass->ClearMenus();
if (action == GOSSIP_ACTION_INFO_DEF+1)
{
player->CLOSE_GOSSIP_MENU();
ENSURE_AI(npc_announcer_toc5::npc_announcer_toc5AI, creature->AI())->StartEncounter();
}
return true;
}
};
void AddSC_trial_of_the_champion()
{
new npc_announcer_toc5();
}
| gpl-2.0 |
chuck1/kernel | drivers/staging/dgap/dgap.c | 77 | 164822 | /*
* Copyright 2003 Digi International (www.digi.com)
* Scott H Kilau <Scott_Kilau at digi dot 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, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
*/
/*
* In the original out of kernel Digi dgap driver, firmware
* loading was done via user land to driver handshaking.
*
* For cards that support a concentrator (port expander),
* I believe the concentrator its self told the card which
* concentrator is actually attached and then that info
* was used to tell user land which concentrator firmware
* image was to be downloaded. I think even the BIOS or
* FEP images required could change with the connection
* of a particular concentrator.
*
* Since I have no access to any of these cards or
* concentrators, I cannot put the correct concentrator
* firmware file names into the firmware_info structure
* as is now done for the BIOS and FEP images.
*
* I think, but am not certain, that the cards supporting
* concentrators will function without them. So support
* of these cards has been left in this driver.
*
* In order to fully support those cards, they would
* either have to be acquired for dissection or maybe
* Digi International could provide some assistance.
*/
#undef DIGI_CONCENTRATORS_SUPPORTED
#define pr_fmt(fmt) "dgap: " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/delay.h> /* For udelay */
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/sched.h>
#include <linux/interrupt.h> /* For tasklet and interrupt structs/defines */
#include <linux/ctype.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial_reg.h>
#include <linux/io.h> /* For read[bwl]/write[bwl] */
#include <linux/string.h>
#include <linux/device.h>
#include <linux/kdev_t.h>
#include <linux/firmware.h>
#include "dgap.h"
/*
* File operations permitted on Control/Management major.
*/
static const struct file_operations dgap_board_fops = {
.owner = THIS_MODULE,
};
static uint dgap_numboards;
static struct board_t *dgap_board[MAXBOARDS];
static ulong dgap_poll_counter;
static int dgap_driver_state = DRIVER_INITIALIZED;
static int dgap_poll_tick = 20; /* Poll interval - 20 ms */
static struct class *dgap_class;
static uint dgap_count = 500;
/*
* Poller stuff
*/
static DEFINE_SPINLOCK(dgap_poll_lock); /* Poll scheduling lock */
static ulong dgap_poll_time; /* Time of next poll */
static uint dgap_poll_stop; /* Used to tell poller to stop */
static struct timer_list dgap_poll_timer;
/*
SUPPORTED PRODUCTS
Card Model Number of Ports Interface
----------------------------------------------------------------
Acceleport Xem 4 - 64 (EIA232 & EIA422)
Acceleport Xr 4 & 8 (EIA232)
Acceleport Xr 920 4 & 8 (EIA232)
Acceleport C/X 8 - 128 (EIA232)
Acceleport EPC/X 8 - 224 (EIA232)
Acceleport Xr/422 4 & 8 (EIA422)
Acceleport 2r/920 2 (EIA232)
Acceleport 4r/920 4 (EIA232)
Acceleport 8r/920 8 (EIA232)
IBM 8-Port Asynchronous PCI Adapter (EIA232)
IBM 128-Port Asynchronous PCI Adapter (EIA232 & EIA422)
*/
static struct pci_device_id dgap_pci_tbl[] = {
{ DIGI_VID, PCI_DEV_XEM_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
{ DIGI_VID, PCI_DEV_CX_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 1 },
{ DIGI_VID, PCI_DEV_CX_IBM_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 2 },
{ DIGI_VID, PCI_DEV_EPCJ_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 3 },
{ DIGI_VID, PCI_DEV_920_2_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 4 },
{ DIGI_VID, PCI_DEV_920_4_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 5 },
{ DIGI_VID, PCI_DEV_920_8_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 6 },
{ DIGI_VID, PCI_DEV_XR_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 7 },
{ DIGI_VID, PCI_DEV_XRJ_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 8 },
{ DIGI_VID, PCI_DEV_XR_422_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 9 },
{ DIGI_VID, PCI_DEV_XR_IBM_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 10 },
{ DIGI_VID, PCI_DEV_XR_SAIP_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 11 },
{ DIGI_VID, PCI_DEV_XR_BULL_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 12 },
{ DIGI_VID, PCI_DEV_920_8_HP_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 13 },
{ DIGI_VID, PCI_DEV_XEM_HP_DID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 14 },
{0,} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, dgap_pci_tbl);
/*
* A generic list of Product names, PCI Vendor ID, and PCI Device ID.
*/
struct board_id {
uint config_type;
u8 *name;
uint maxports;
uint dpatype;
};
static struct board_id dgap_ids[] = {
{ PPCM, PCI_DEV_XEM_NAME, 64, (T_PCXM|T_PCLITE|T_PCIBUS) },
{ PCX, PCI_DEV_CX_NAME, 128, (T_CX|T_PCIBUS) },
{ PCX, PCI_DEV_CX_IBM_NAME, 128, (T_CX|T_PCIBUS) },
{ PEPC, PCI_DEV_EPCJ_NAME, 224, (T_EPC|T_PCIBUS) },
{ APORT2_920P, PCI_DEV_920_2_NAME, 2, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ APORT4_920P, PCI_DEV_920_4_NAME, 4, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ APORT8_920P, PCI_DEV_920_8_NAME, 8, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ PAPORT8, PCI_DEV_XR_NAME, 8, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ PAPORT8, PCI_DEV_XRJ_NAME, 8, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ PAPORT8, PCI_DEV_XR_422_NAME, 8, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ PAPORT8, PCI_DEV_XR_IBM_NAME, 8, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ PAPORT8, PCI_DEV_XR_SAIP_NAME, 8, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ PAPORT8, PCI_DEV_XR_BULL_NAME, 8, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ APORT8_920P, PCI_DEV_920_8_HP_NAME, 8, (T_PCXR|T_PCLITE|T_PCIBUS) },
{ PPCM, PCI_DEV_XEM_HP_NAME, 64, (T_PCXM|T_PCLITE|T_PCIBUS) },
{0,} /* 0 terminated list. */
};
struct firmware_info {
u8 *conf_name; /* dgap.conf */
u8 *bios_name; /* BIOS filename */
u8 *fep_name; /* FEP filename */
u8 *con_name; /* Concentrator filename FIXME*/
int num; /* sequence number */
};
/*
* Firmware - BIOS, FEP, and CONC filenames
*/
static struct firmware_info fw_info[] = {
{ "dgap/dgap.conf", "dgap/sxbios.bin", "dgap/sxfep.bin", NULL, 0 },
{ "dgap/dgap.conf", "dgap/cxpbios.bin", "dgap/cxpfep.bin", NULL, 1 },
{ "dgap/dgap.conf", "dgap/cxpbios.bin", "dgap/cxpfep.bin", NULL, 2 },
{ "dgap/dgap.conf", "dgap/pcibios.bin", "dgap/pcifep.bin", NULL, 3 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 4 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 5 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 6 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 7 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 8 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 9 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 10 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 11 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 12 },
{ "dgap/dgap.conf", "dgap/xrbios.bin", "dgap/xrfep.bin", NULL, 13 },
{ "dgap/dgap.conf", "dgap/sxbios.bin", "dgap/sxfep.bin", NULL, 14 },
{NULL,}
};
/*
* Default transparent print information.
*/
static struct digi_t dgap_digi_init = {
.digi_flags = DIGI_COOK, /* Flags */
.digi_maxcps = 100, /* Max CPS */
.digi_maxchar = 50, /* Max chars in print queue */
.digi_bufsize = 100, /* Printer buffer size */
.digi_onlen = 4, /* size of printer on string */
.digi_offlen = 4, /* size of printer off string */
.digi_onstr = "\033[5i", /* ANSI printer on string ] */
.digi_offstr = "\033[4i", /* ANSI printer off string ] */
.digi_term = "ansi" /* default terminal type */
};
/*
* Define a local default termios struct. All ports will be created
* with this termios initially.
*
* This defines a raw port at 9600 baud, 8 data bits, no parity,
* 1 stop bit.
*/
static struct ktermios dgap_default_termios = {
.c_iflag = (DEFAULT_IFLAGS), /* iflags */
.c_oflag = (DEFAULT_OFLAGS), /* oflags */
.c_cflag = (DEFAULT_CFLAGS), /* cflags */
.c_lflag = (DEFAULT_LFLAGS), /* lflags */
.c_cc = INIT_C_CC,
.c_line = 0,
};
/*
* Our needed internal static variables from dgap_parse.c
*/
static struct cnode dgap_head;
#define MAXCWORD 200
static char dgap_cword[MAXCWORD];
struct toklist {
int token;
char *string;
};
static struct toklist dgap_brdtype[] = {
{ PCX, "Digi_AccelePort_C/X_PCI" },
{ PEPC, "Digi_AccelePort_EPC/X_PCI" },
{ PPCM, "Digi_AccelePort_Xem_PCI" },
{ APORT2_920P, "Digi_AccelePort_2r_920_PCI" },
{ APORT4_920P, "Digi_AccelePort_4r_920_PCI" },
{ APORT8_920P, "Digi_AccelePort_8r_920_PCI" },
{ PAPORT4, "Digi_AccelePort_4r_PCI(EIA-232/RS-422)" },
{ PAPORT8, "Digi_AccelePort_8r_PCI(EIA-232/RS-422)" },
{ 0, NULL }
};
static struct toklist dgap_tlist[] = {
{ BEGIN, "config_begin" },
{ END, "config_end" },
{ BOARD, "board" },
{ IO, "io" },
{ PCIINFO, "pciinfo" },
{ LINE, "line" },
{ CONC, "conc" },
{ CONC, "concentrator" },
{ CX, "cx" },
{ CX, "ccon" },
{ EPC, "epccon" },
{ EPC, "epc" },
{ MOD, "module" },
{ ID, "id" },
{ STARTO, "start" },
{ SPEED, "speed" },
{ CABLE, "cable" },
{ CONNECT, "connect" },
{ METHOD, "method" },
{ STATUS, "status" },
{ CUSTOM, "Custom" },
{ BASIC, "Basic" },
{ MEM, "mem" },
{ MEM, "memory" },
{ PORTS, "ports" },
{ MODEM, "modem" },
{ NPORTS, "nports" },
{ TTYN, "ttyname" },
{ CU, "cuname" },
{ PRINT, "prname" },
{ CMAJOR, "major" },
{ ALTPIN, "altpin" },
{ USEINTR, "useintr" },
{ TTSIZ, "ttysize" },
{ CHSIZ, "chsize" },
{ BSSIZ, "boardsize" },
{ UNTSIZ, "schedsize" },
{ F2SIZ, "f2200size" },
{ VPSIZ, "vpixsize" },
{ 0, NULL }
};
/*
* dgap_sindex: much like index(), but it looks for a match of any character in
* the group, and returns that position. If the first character is a ^, then
* this will match the first occurrence not in that group.
*/
static char *dgap_sindex(char *string, char *group)
{
char *ptr;
if (!string || !group)
return NULL;
if (*group == '^') {
group++;
for (; *string; string++) {
for (ptr = group; *ptr; ptr++) {
if (*ptr == *string)
break;
}
if (*ptr == '\0')
return string;
}
} else {
for (; *string; string++) {
for (ptr = group; *ptr; ptr++) {
if (*ptr == *string)
return string;
}
}
}
return NULL;
}
/*
* get a word from the input stream, also keep track of current line number.
* words are separated by whitespace.
*/
static char *dgap_getword(char **in)
{
char *ret_ptr = *in;
char *ptr = dgap_sindex(*in, " \t\n");
/* If no word found, return null */
if (!ptr)
return NULL;
/* Mark new location for our buffer */
*ptr = '\0';
*in = ptr + 1;
/* Eat any extra spaces/tabs/newlines that might be present */
while (*in && **in && ((**in == ' ') ||
(**in == '\t') ||
(**in == '\n'))) {
**in = '\0';
*in = *in + 1;
}
return ret_ptr;
}
/*
* Get a token from the input file; return 0 if end of file is reached
*/
static int dgap_gettok(char **in)
{
char *w;
struct toklist *t;
if (strstr(dgap_cword, "board")) {
w = dgap_getword(in);
snprintf(dgap_cword, MAXCWORD, "%s", w);
for (t = dgap_brdtype; t->token != 0; t++) {
if (!strcmp(w, t->string))
return t->token;
}
} else {
while ((w = dgap_getword(in))) {
snprintf(dgap_cword, MAXCWORD, "%s", w);
for (t = dgap_tlist; t->token != 0; t++) {
if (!strcmp(w, t->string))
return t->token;
}
}
}
return 0;
}
/*
* dgap_checknode: see if all the necessary info has been supplied for a node
* before creating the next node.
*/
static int dgap_checknode(struct cnode *p)
{
switch (p->type) {
case LNODE:
if (p->u.line.v_speed == 0) {
pr_err("line speed not specified");
return 1;
}
return 0;
case CNODE:
if (p->u.conc.v_speed == 0) {
pr_err("concentrator line speed not specified");
return 1;
}
if (p->u.conc.v_nport == 0) {
pr_err("number of ports on concentrator not specified");
return 1;
}
if (p->u.conc.v_id == 0) {
pr_err("concentrator id letter not specified");
return 1;
}
return 0;
case MNODE:
if (p->u.module.v_nport == 0) {
pr_err("number of ports on EBI module not specified");
return 1;
}
if (p->u.module.v_id == 0) {
pr_err("EBI module id letter not specified");
return 1;
}
return 0;
}
return 0;
}
/*
* Given a board pointer, returns whether we should use interrupts or not.
*/
static uint dgap_config_get_useintr(struct board_t *bd)
{
struct cnode *p;
if (!bd)
return 0;
for (p = bd->bd_config; p; p = p->next) {
if (p->type == INTRNODE) {
/*
* check for pcxr types.
*/
return p->u.useintr;
}
}
/* If not found, then don't turn on interrupts. */
return 0;
}
/*
* Given a board pointer, returns whether we turn on altpin or not.
*/
static uint dgap_config_get_altpin(struct board_t *bd)
{
struct cnode *p;
if (!bd)
return 0;
for (p = bd->bd_config; p; p = p->next) {
if (p->type == ANODE) {
/*
* check for pcxr types.
*/
return p->u.altpin;
}
}
/* If not found, then don't turn on interrupts. */
return 0;
}
/*
* Given a specific type of board, if found, detached link and
* returns the first occurrence in the list.
*/
static struct cnode *dgap_find_config(int type, int bus, int slot)
{
struct cnode *p, *prev, *prev2, *found;
p = &dgap_head;
while (p->next) {
prev = p;
p = p->next;
if (p->type != BNODE)
continue;
if (p->u.board.type != type)
continue;
if (p->u.board.v_pcibus &&
p->u.board.pcibus != bus)
continue;
if (p->u.board.v_pcislot &&
p->u.board.pcislot != slot)
continue;
found = p;
/*
* Keep walking thru the list till we
* find the next board.
*/
while (p->next) {
prev2 = p;
p = p->next;
if (p->type != BNODE)
continue;
/*
* Mark the end of our 1 board
* chain of configs.
*/
prev2->next = NULL;
/*
* Link the "next" board to the
* previous board, effectively
* "unlinking" our board from
* the main config.
*/
prev->next = p;
return found;
}
/*
* It must be the last board in the list.
*/
prev->next = NULL;
return found;
}
return NULL;
}
/*
* Given a board pointer, walks the config link, counting up
* all ports user specified should be on the board.
* (This does NOT mean they are all actually present right now tho)
*/
static uint dgap_config_get_num_prts(struct board_t *bd)
{
int count = 0;
struct cnode *p;
if (!bd)
return 0;
for (p = bd->bd_config; p; p = p->next) {
switch (p->type) {
case BNODE:
/*
* check for pcxr types.
*/
if (p->u.board.type > EPCFE)
count += p->u.board.nport;
break;
case CNODE:
count += p->u.conc.nport;
break;
case MNODE:
count += p->u.module.nport;
break;
}
}
return count;
}
static char *dgap_create_config_string(struct board_t *bd, char *string)
{
char *ptr = string;
struct cnode *p;
struct cnode *q;
int speed;
if (!bd) {
*ptr = 0xff;
return string;
}
for (p = bd->bd_config; p; p = p->next) {
switch (p->type) {
case LNODE:
*ptr = '\0';
ptr++;
*ptr = p->u.line.speed;
ptr++;
break;
case CNODE:
/*
* Because the EPC/con concentrators can have EM modules
* hanging off of them, we have to walk ahead in the
* list and keep adding the number of ports on each EM
* to the config. UGH!
*/
speed = p->u.conc.speed;
q = p->next;
if (q && (q->type == MNODE)) {
*ptr = (p->u.conc.nport + 0x80);
ptr++;
p = q;
while (q->next && (q->next->type) == MNODE) {
*ptr = (q->u.module.nport + 0x80);
ptr++;
p = q;
q = q->next;
}
*ptr = q->u.module.nport;
ptr++;
} else {
*ptr = p->u.conc.nport;
ptr++;
}
*ptr = speed;
ptr++;
break;
}
}
*ptr = 0xff;
return string;
}
/*
* Parse a configuration file read into memory as a string.
*/
static int dgap_parsefile(char **in)
{
struct cnode *p, *brd, *line, *conc;
int rc;
char *s;
int linecnt = 0;
p = &dgap_head;
brd = line = conc = NULL;
/* perhaps we are adding to an existing list? */
while (p->next)
p = p->next;
/* file must start with a BEGIN */
while ((rc = dgap_gettok(in)) != BEGIN) {
if (rc == 0) {
pr_err("unexpected EOF");
return -1;
}
}
for (; ;) {
int board_type = 0;
int conc_type = 0;
int module_type = 0;
rc = dgap_gettok(in);
if (rc == 0) {
pr_err("unexpected EOF");
return -1;
}
switch (rc) {
case BEGIN: /* should only be 1 begin */
pr_err("unexpected config_begin\n");
return -1;
case END:
return 0;
case BOARD: /* board info */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = BNODE;
p->u.board.status = kstrdup("No", GFP_KERNEL);
line = conc = NULL;
brd = p;
linecnt = -1;
board_type = dgap_gettok(in);
if (board_type == 0) {
pr_err("board !!type not specified");
return -1;
}
p->u.board.type = board_type;
break;
case IO: /* i/o port */
if (p->type != BNODE) {
pr_err("IO port only valid for boards");
return -1;
}
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
p->u.board.portstr = kstrdup(s, GFP_KERNEL);
if (kstrtol(s, 0, &p->u.board.port)) {
pr_err("bad number for IO port");
return -1;
}
p->u.board.v_port = 1;
break;
case MEM: /* memory address */
if (p->type != BNODE) {
pr_err("memory address only valid for boards");
return -1;
}
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
p->u.board.addrstr = kstrdup(s, GFP_KERNEL);
if (kstrtoul(s, 0, &p->u.board.addr)) {
pr_err("bad number for memory address");
return -1;
}
p->u.board.v_addr = 1;
break;
case PCIINFO: /* pci information */
if (p->type != BNODE) {
pr_err("memory address only valid for boards");
return -1;
}
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
p->u.board.pcibusstr = kstrdup(s, GFP_KERNEL);
if (kstrtoul(s, 0, &p->u.board.pcibus)) {
pr_err("bad number for pci bus");
return -1;
}
p->u.board.v_pcibus = 1;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
p->u.board.pcislotstr = kstrdup(s, GFP_KERNEL);
if (kstrtoul(s, 0, &p->u.board.pcislot)) {
pr_err("bad number for pci slot");
return -1;
}
p->u.board.v_pcislot = 1;
break;
case METHOD:
if (p->type != BNODE) {
pr_err("install method only valid for boards");
return -1;
}
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
p->u.board.method = kstrdup(s, GFP_KERNEL);
p->u.board.v_method = 1;
break;
case STATUS:
if (p->type != BNODE) {
pr_err("config status only valid for boards");
return -1;
}
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
p->u.board.status = kstrdup(s, GFP_KERNEL);
break;
case NPORTS: /* number of ports */
if (p->type == BNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.board.nport)) {
pr_err("bad number for number of ports");
return -1;
}
p->u.board.v_nport = 1;
} else if (p->type == CNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.conc.nport)) {
pr_err("bad number for number of ports");
return -1;
}
p->u.conc.v_nport = 1;
} else if (p->type == MNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.module.nport)) {
pr_err("bad number for number of ports");
return -1;
}
p->u.module.v_nport = 1;
} else {
pr_err("nports only valid for concentrators or modules");
return -1;
}
break;
case ID: /* letter ID used in tty name */
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
p->u.board.status = kstrdup(s, GFP_KERNEL);
if (p->type == CNODE) {
p->u.conc.id = kstrdup(s, GFP_KERNEL);
p->u.conc.v_id = 1;
} else if (p->type == MNODE) {
p->u.module.id = kstrdup(s, GFP_KERNEL);
p->u.module.v_id = 1;
} else {
pr_err("id only valid for concentrators or modules");
return -1;
}
break;
case STARTO: /* start offset of ID */
if (p->type == BNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.board.start)) {
pr_err("bad number for start of tty count");
return -1;
}
p->u.board.v_start = 1;
} else if (p->type == CNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.conc.start)) {
pr_err("bad number for start of tty count");
return -1;
}
p->u.conc.v_start = 1;
} else if (p->type == MNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.module.start)) {
pr_err("bad number for start of tty count");
return -1;
}
p->u.module.v_start = 1;
} else {
pr_err("start only valid for concentrators or modules");
return -1;
}
break;
case TTYN: /* tty name prefix */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = TNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpeced end of file");
return -1;
}
p->u.ttyname = kstrdup(s, GFP_KERNEL);
if (!p->u.ttyname)
return -1;
break;
case CU: /* cu name prefix */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = CUNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpeced end of file");
return -1;
}
p->u.cuname = kstrdup(s, GFP_KERNEL);
if (!p->u.cuname)
return -1;
break;
case LINE: /* line information */
if (dgap_checknode(p))
return -1;
if (!brd) {
pr_err("must specify board before line info");
return -1;
}
switch (brd->u.board.type) {
case PPCM:
pr_err("line not valid for PC/em");
return -1;
}
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = LNODE;
conc = NULL;
line = p;
linecnt++;
break;
case CONC: /* concentrator information */
if (dgap_checknode(p))
return -1;
if (!line) {
pr_err("must specify line info before concentrator");
return -1;
}
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = CNODE;
conc = p;
if (linecnt)
brd->u.board.conc2++;
else
brd->u.board.conc1++;
conc_type = dgap_gettok(in);
if (conc_type == 0 || conc_type != CX ||
conc_type != EPC) {
pr_err("failed to set a type of concentratros");
return -1;
}
p->u.conc.type = conc_type;
break;
case MOD: /* EBI module */
if (dgap_checknode(p))
return -1;
if (!brd) {
pr_err("must specify board info before EBI modules");
return -1;
}
switch (brd->u.board.type) {
case PPCM:
linecnt = 0;
break;
default:
if (!conc) {
pr_err("must specify concentrator info before EBI module");
return -1;
}
}
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = MNODE;
if (linecnt)
brd->u.board.module2++;
else
brd->u.board.module1++;
module_type = dgap_gettok(in);
if (module_type == 0 || module_type != PORTS ||
module_type != MODEM) {
pr_err("failed to set a type of module");
return -1;
}
p->u.module.type = module_type;
break;
case CABLE:
if (p->type == LNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
p->u.line.cable = kstrdup(s, GFP_KERNEL);
p->u.line.v_cable = 1;
}
break;
case SPEED: /* sync line speed indication */
if (p->type == LNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.line.speed)) {
pr_err("bad number for line speed");
return -1;
}
p->u.line.v_speed = 1;
} else if (p->type == CNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.conc.speed)) {
pr_err("bad number for line speed");
return -1;
}
p->u.conc.v_speed = 1;
} else {
pr_err("speed valid only for lines or concentrators.");
return -1;
}
break;
case CONNECT:
if (p->type == CNODE) {
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
p->u.conc.connect = kstrdup(s, GFP_KERNEL);
p->u.conc.v_connect = 1;
}
break;
case PRINT: /* transparent print name prefix */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = PNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpeced end of file");
return -1;
}
p->u.printname = kstrdup(s, GFP_KERNEL);
if (!p->u.printname)
return -1;
break;
case CMAJOR: /* major number */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = JNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.majornumber)) {
pr_err("bad number for major number");
return -1;
}
break;
case ALTPIN: /* altpin setting */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = ANODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.altpin)) {
pr_err("bad number for altpin");
return -1;
}
break;
case USEINTR: /* enable interrupt setting */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = INTRNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.useintr)) {
pr_err("bad number for useintr");
return -1;
}
break;
case TTSIZ: /* size of tty structure */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = TSNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.ttysize)) {
pr_err("bad number for ttysize");
return -1;
}
break;
case CHSIZ: /* channel structure size */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = CSNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.chsize)) {
pr_err("bad number for chsize");
return -1;
}
break;
case BSSIZ: /* board structure size */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = BSNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.bssize)) {
pr_err("bad number for bssize");
return -1;
}
break;
case UNTSIZ: /* sched structure size */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = USNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.unsize)) {
pr_err("bad number for schedsize");
return -1;
}
break;
case F2SIZ: /* f2200 structure size */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = FSNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.f2size)) {
pr_err("bad number for f2200size");
return -1;
}
break;
case VPSIZ: /* vpix structure size */
if (dgap_checknode(p))
return -1;
p->next = kzalloc(sizeof(struct cnode), GFP_KERNEL);
if (!p->next)
return -1;
p = p->next;
p->type = VSNODE;
s = dgap_getword(in);
if (!s) {
pr_err("unexpected end of file");
return -1;
}
if (kstrtol(s, 0, &p->u.vpixsize)) {
pr_err("bad number for vpixsize");
return -1;
}
break;
}
}
}
static void dgap_cleanup_nodes(void)
{
struct cnode *p;
p = &dgap_head;
while (p) {
struct cnode *tmp = p->next;
if (p->type == NULLNODE) {
p = tmp;
continue;
}
switch (p->type) {
case BNODE:
kfree(p->u.board.portstr);
kfree(p->u.board.addrstr);
kfree(p->u.board.pcibusstr);
kfree(p->u.board.pcislotstr);
kfree(p->u.board.method);
break;
case CNODE:
kfree(p->u.conc.id);
kfree(p->u.conc.connect);
break;
case MNODE:
kfree(p->u.module.id);
break;
case TNODE:
kfree(p->u.ttyname);
break;
case CUNODE:
kfree(p->u.cuname);
break;
case LNODE:
kfree(p->u.line.cable);
break;
case PNODE:
kfree(p->u.printname);
break;
}
kfree(p->u.board.status);
kfree(p);
p = tmp;
}
}
/*
* Retrives the current custom baud rate from FEP memory,
* and returns it back to the user.
* Returns 0 on error.
*/
static uint dgap_get_custom_baud(struct channel_t *ch)
{
u8 __iomem *vaddr;
ulong offset;
uint value;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
if (!ch->ch_bd || ch->ch_bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (!(ch->ch_bd->bd_flags & BD_FEP5PLUS))
return 0;
vaddr = ch->ch_bd->re_map_membase;
if (!vaddr)
return 0;
/*
* Go get from fep mem, what the fep
* believes the custom baud rate is.
*/
offset = (ioread16(vaddr + ECS_SEG) << 4) + (ch->ch_portnum * 0x28)
+ LINE_SPEED;
value = readw(vaddr + offset);
return value;
}
/*
* Remap PCI memory.
*/
static int dgap_remap(struct board_t *brd)
{
if (!brd || brd->magic != DGAP_BOARD_MAGIC)
return -EIO;
if (!request_mem_region(brd->membase, 0x200000, "dgap"))
return -ENOMEM;
if (!request_mem_region(brd->membase + PCI_IO_OFFSET, 0x200000,
"dgap")) {
release_mem_region(brd->membase, 0x200000);
return -ENOMEM;
}
brd->re_map_membase = ioremap(brd->membase, 0x200000);
if (!brd->re_map_membase) {
release_mem_region(brd->membase, 0x200000);
release_mem_region(brd->membase + PCI_IO_OFFSET, 0x200000);
return -ENOMEM;
}
brd->re_map_port = ioremap((brd->membase + PCI_IO_OFFSET), 0x200000);
if (!brd->re_map_port) {
release_mem_region(brd->membase, 0x200000);
release_mem_region(brd->membase + PCI_IO_OFFSET, 0x200000);
iounmap(brd->re_map_membase);
return -ENOMEM;
}
return 0;
}
static void dgap_unmap(struct board_t *brd)
{
iounmap(brd->re_map_port);
iounmap(brd->re_map_membase);
release_mem_region(brd->membase + PCI_IO_OFFSET, 0x200000);
release_mem_region(brd->membase, 0x200000);
}
/*
* dgap_parity_scan()
*
* Convert the FEP5 way of reporting parity errors and breaks into
* the Linux line discipline way.
*/
static void dgap_parity_scan(struct channel_t *ch, unsigned char *cbuf,
unsigned char *fbuf, int *len)
{
int l = *len;
int count = 0;
unsigned char *in, *cout, *fout;
unsigned char c;
in = cbuf;
cout = cbuf;
fout = fbuf;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
while (l--) {
c = *in++;
switch (ch->pscan_state) {
default:
/* reset to sanity and fall through */
ch->pscan_state = 0;
case 0:
/* No FF seen yet */
if (c == (unsigned char) '\377')
/* delete this character from stream */
ch->pscan_state = 1;
else {
*cout++ = c;
*fout++ = TTY_NORMAL;
count += 1;
}
break;
case 1:
/* first FF seen */
if (c == (unsigned char) '\377') {
/* doubled ff, transform to single ff */
*cout++ = c;
*fout++ = TTY_NORMAL;
count += 1;
ch->pscan_state = 0;
} else {
/* save value examination in next state */
ch->pscan_savechar = c;
ch->pscan_state = 2;
}
break;
case 2:
/* third character of ff sequence */
*cout++ = c;
if (ch->pscan_savechar == 0x0) {
if (c == 0x0) {
ch->ch_err_break++;
*fout++ = TTY_BREAK;
} else {
ch->ch_err_parity++;
*fout++ = TTY_PARITY;
}
}
count += 1;
ch->pscan_state = 0;
}
}
*len = count;
}
/*=======================================================================
*
* dgap_input - Process received data.
*
* ch - Pointer to channel structure.
*
*=======================================================================*/
static void dgap_input(struct channel_t *ch)
{
struct board_t *bd;
struct bs_t __iomem *bs;
struct tty_struct *tp;
struct tty_ldisc *ld;
uint rmask;
uint head;
uint tail;
int data_len;
ulong lock_flags;
ulong lock_flags2;
int flip_len;
int len;
int n;
u8 *buf;
u8 tmpchar;
int s;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
tp = ch->ch_tun.un_tty;
bs = ch->ch_bs;
if (!bs)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
/*
* Figure the number of characters in the buffer.
* Exit immediately if none.
*/
rmask = ch->ch_rsize - 1;
head = readw(&(bs->rx_head));
head &= rmask;
tail = readw(&(bs->rx_tail));
tail &= rmask;
data_len = (head - tail) & rmask;
if (data_len == 0) {
writeb(1, &(bs->idata));
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return;
}
/*
* If the device is not open, or CREAD is off, flush
* input data and return immediately.
*/
if ((bd->state != BOARD_READY) || !tp ||
(tp->magic != TTY_MAGIC) ||
!(ch->ch_tun.un_flags & UN_ISOPEN) ||
!(tp->termios.c_cflag & CREAD) ||
(ch->ch_tun.un_flags & UN_CLOSING)) {
writew(head, &(bs->rx_tail));
writeb(1, &(bs->idata));
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return;
}
/*
* If we are throttled, simply don't read any data.
*/
if (ch->ch_flags & CH_RXBLOCK) {
writeb(1, &(bs->idata));
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return;
}
/*
* Ignore oruns.
*/
tmpchar = readb(&(bs->orun));
if (tmpchar) {
ch->ch_err_overrun++;
writeb(0, &(bs->orun));
}
/* Decide how much data we can send into the tty layer */
flip_len = TTY_FLIPBUF_SIZE;
/* Chop down the length, if needed */
len = min(data_len, flip_len);
len = min(len, (N_TTY_BUF_SIZE - 1));
ld = tty_ldisc_ref(tp);
#ifdef TTY_DONT_FLIP
/*
* If the DONT_FLIP flag is on, don't flush our buffer, and act
* like the ld doesn't have any space to put the data right now.
*/
if (test_bit(TTY_DONT_FLIP, &tp->flags))
len = 0;
#endif
/*
* If we were unable to get a reference to the ld,
* don't flush our buffer, and act like the ld doesn't
* have any space to put the data right now.
*/
if (!ld) {
len = 0;
} else {
/*
* If ld doesn't have a pointer to a receive_buf function,
* flush the data, then act like the ld doesn't have any
* space to put the data right now.
*/
if (!ld->ops->receive_buf) {
writew(head, &(bs->rx_tail));
len = 0;
}
}
if (len <= 0) {
writeb(1, &(bs->idata));
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
if (ld)
tty_ldisc_deref(ld);
return;
}
buf = ch->ch_bd->flipbuf;
n = len;
/*
* n now contains the most amount of data we can copy,
* bounded either by our buffer size or the amount
* of data the card actually has pending...
*/
while (n) {
s = ((head >= tail) ? head : ch->ch_rsize) - tail;
s = min(s, n);
if (s <= 0)
break;
memcpy_fromio(buf, ch->ch_raddr + tail, s);
tail += s;
buf += s;
n -= s;
/* Flip queue if needed */
tail &= rmask;
}
writew(tail, &(bs->rx_tail));
writeb(1, &(bs->idata));
ch->ch_rxcount += len;
/*
* If we are completely raw, we don't need to go through a lot
* of the tty layers that exist.
* In this case, we take the shortest and fastest route we
* can to relay the data to the user.
*
* On the other hand, if we are not raw, we need to go through
* the tty layer, which has its API more well defined.
*/
if (I_PARMRK(tp) || I_BRKINT(tp) || I_INPCK(tp)) {
dgap_parity_scan(ch, ch->ch_bd->flipbuf,
ch->ch_bd->flipflagbuf, &len);
len = tty_buffer_request_room(tp->port, len);
tty_insert_flip_string_flags(tp->port, ch->ch_bd->flipbuf,
ch->ch_bd->flipflagbuf, len);
} else {
len = tty_buffer_request_room(tp->port, len);
tty_insert_flip_string(tp->port, ch->ch_bd->flipbuf, len);
}
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
/* Tell the tty layer its okay to "eat" the data now */
tty_flip_buffer_push(tp->port);
if (ld)
tty_ldisc_deref(ld);
}
static void dgap_write_wakeup(struct board_t *bd, struct channel_t *ch,
struct un_t *un, u32 mask,
unsigned long *irq_flags1,
unsigned long *irq_flags2)
{
if (!(un->un_flags & mask))
return;
un->un_flags &= ~mask;
if (!(un->un_flags & UN_ISOPEN))
return;
if ((un->un_tty->flags & (1 << TTY_DO_WRITE_WAKEUP)) &&
un->un_tty->ldisc->ops->write_wakeup) {
spin_unlock_irqrestore(&ch->ch_lock, *irq_flags2);
spin_unlock_irqrestore(&bd->bd_lock, *irq_flags1);
(un->un_tty->ldisc->ops->write_wakeup)(un->un_tty);
spin_lock_irqsave(&bd->bd_lock, *irq_flags1);
spin_lock_irqsave(&ch->ch_lock, *irq_flags2);
}
wake_up_interruptible(&un->un_tty->write_wait);
wake_up_interruptible(&un->un_flags_wait);
}
/************************************************************************
* Determines when CARRIER changes state and takes appropriate
* action.
************************************************************************/
static void dgap_carrier(struct channel_t *ch)
{
struct board_t *bd;
int virt_carrier = 0;
int phys_carrier = 0;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
/* Make sure altpin is always set correctly */
if (ch->ch_digi.digi_flags & DIGI_ALTPIN) {
ch->ch_dsr = DM_CD;
ch->ch_cd = DM_DSR;
} else {
ch->ch_dsr = DM_DSR;
ch->ch_cd = DM_CD;
}
if (ch->ch_mistat & D_CD(ch))
phys_carrier = 1;
if (ch->ch_digi.digi_flags & DIGI_FORCEDCD)
virt_carrier = 1;
if (ch->ch_c_cflag & CLOCAL)
virt_carrier = 1;
/*
* Test for a VIRTUAL carrier transition to HIGH.
*/
if (((ch->ch_flags & CH_FCAR) == 0) && (virt_carrier == 1)) {
/*
* When carrier rises, wake any threads waiting
* for carrier in the open routine.
*/
if (waitqueue_active(&(ch->ch_flags_wait)))
wake_up_interruptible(&ch->ch_flags_wait);
}
/*
* Test for a PHYSICAL carrier transition to HIGH.
*/
if (((ch->ch_flags & CH_CD) == 0) && (phys_carrier == 1)) {
/*
* When carrier rises, wake any threads waiting
* for carrier in the open routine.
*/
if (waitqueue_active(&(ch->ch_flags_wait)))
wake_up_interruptible(&ch->ch_flags_wait);
}
/*
* Test for a PHYSICAL transition to low, so long as we aren't
* currently ignoring physical transitions (which is what "virtual
* carrier" indicates).
*
* The transition of the virtual carrier to low really doesn't
* matter... it really only means "ignore carrier state", not
* "make pretend that carrier is there".
*/
if ((virt_carrier == 0) &&
((ch->ch_flags & CH_CD) != 0) &&
(phys_carrier == 0)) {
/*
* When carrier drops:
*
* Drop carrier on all open units.
*
* Flush queues, waking up any task waiting in the
* line discipline.
*
* Send a hangup to the control terminal.
*
* Enable all select calls.
*/
if (waitqueue_active(&(ch->ch_flags_wait)))
wake_up_interruptible(&ch->ch_flags_wait);
if (ch->ch_tun.un_open_count > 0)
tty_hangup(ch->ch_tun.un_tty);
if (ch->ch_pun.un_open_count > 0)
tty_hangup(ch->ch_pun.un_tty);
}
/*
* Make sure that our cached values reflect the current reality.
*/
if (virt_carrier == 1)
ch->ch_flags |= CH_FCAR;
else
ch->ch_flags &= ~CH_FCAR;
if (phys_carrier == 1)
ch->ch_flags |= CH_CD;
else
ch->ch_flags &= ~CH_CD;
}
/*=======================================================================
*
* dgap_event - FEP to host event processing routine.
*
* bd - Board of current event.
*
*=======================================================================*/
static int dgap_event(struct board_t *bd)
{
struct channel_t *ch;
ulong lock_flags;
ulong lock_flags2;
struct bs_t __iomem *bs;
u8 __iomem *event;
u8 __iomem *vaddr;
struct ev_t __iomem *eaddr;
uint head;
uint tail;
int port;
int reason;
int modem;
int b1;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return -EIO;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
vaddr = bd->re_map_membase;
if (!vaddr) {
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return -EIO;
}
eaddr = (struct ev_t __iomem *) (vaddr + EVBUF);
/* Get our head and tail */
head = readw(&(eaddr->ev_head));
tail = readw(&(eaddr->ev_tail));
/*
* Forget it if pointers out of range.
*/
if (head >= EVMAX - EVSTART || tail >= EVMAX - EVSTART ||
(head | tail) & 03) {
/* Let go of board lock */
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return -EIO;
}
/*
* Loop to process all the events in the buffer.
*/
while (tail != head) {
/*
* Get interrupt information.
*/
event = bd->re_map_membase + tail + EVSTART;
port = ioread8(event);
reason = ioread8(event + 1);
modem = ioread8(event + 2);
b1 = ioread8(event + 3);
/*
* Make sure the interrupt is valid.
*/
if (port >= bd->nasync)
goto next;
if (!(reason & (IFMODEM | IFBREAK | IFTLW | IFTEM | IFDATA)))
goto next;
ch = bd->channels[port];
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
goto next;
/*
* If we have made it here, the event was valid.
* Lock down the channel.
*/
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
bs = ch->ch_bs;
if (!bs) {
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
goto next;
}
/*
* Process received data.
*/
if (reason & IFDATA) {
/*
* ALL LOCKS *MUST* BE DROPPED BEFORE CALLING INPUT!
* input could send some data to ld, which in turn
* could do a callback to one of our other functions.
*/
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
dgap_input(ch);
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
if (ch->ch_flags & CH_RACTIVE)
ch->ch_flags |= CH_RENABLE;
else
writeb(1, &(bs->idata));
if (ch->ch_flags & CH_RWAIT) {
ch->ch_flags &= ~CH_RWAIT;
wake_up_interruptible
(&ch->ch_tun.un_flags_wait);
}
}
/*
* Process Modem change signals.
*/
if (reason & IFMODEM) {
ch->ch_mistat = modem;
dgap_carrier(ch);
}
/*
* Process break.
*/
if (reason & IFBREAK) {
if (ch->ch_tun.un_tty) {
/* A break has been indicated */
ch->ch_err_break++;
tty_buffer_request_room
(ch->ch_tun.un_tty->port, 1);
tty_insert_flip_char(ch->ch_tun.un_tty->port,
0, TTY_BREAK);
tty_flip_buffer_push(ch->ch_tun.un_tty->port);
}
}
/*
* Process Transmit low.
*/
if (reason & IFTLW) {
dgap_write_wakeup(bd, ch, &ch->ch_tun, UN_LOW,
&lock_flags, &lock_flags2);
dgap_write_wakeup(bd, ch, &ch->ch_pun, UN_LOW,
&lock_flags, &lock_flags2);
if (ch->ch_flags & CH_WLOW) {
ch->ch_flags &= ~CH_WLOW;
wake_up_interruptible(&ch->ch_flags_wait);
}
}
/*
* Process Transmit empty.
*/
if (reason & IFTEM) {
dgap_write_wakeup(bd, ch, &ch->ch_tun, UN_EMPTY,
&lock_flags, &lock_flags2);
dgap_write_wakeup(bd, ch, &ch->ch_pun, UN_EMPTY,
&lock_flags, &lock_flags2);
if (ch->ch_flags & CH_WEMPTY) {
ch->ch_flags &= ~CH_WEMPTY;
wake_up_interruptible(&ch->ch_flags_wait);
}
}
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
next:
tail = (tail + 4) & (EVMAX - EVSTART - 4);
}
writew(tail, &(eaddr->ev_tail));
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
}
/*
* Our board poller function.
*/
static void dgap_poll_tasklet(unsigned long data)
{
struct board_t *bd = (struct board_t *) data;
ulong lock_flags;
char __iomem *vaddr;
u16 head, tail;
if (!bd || (bd->magic != DGAP_BOARD_MAGIC))
return;
if (bd->inhibit_poller)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
vaddr = bd->re_map_membase;
/*
* If board is ready, parse deeper to see if there is anything to do.
*/
if (bd->state == BOARD_READY) {
struct ev_t __iomem *eaddr;
if (!bd->re_map_membase) {
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return;
}
if (!bd->re_map_port) {
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return;
}
if (!bd->nasync)
goto out;
eaddr = (struct ev_t __iomem *) (vaddr + EVBUF);
/* Get our head and tail */
head = readw(&(eaddr->ev_head));
tail = readw(&(eaddr->ev_tail));
/*
* If there is an event pending. Go service it.
*/
if (head != tail) {
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
dgap_event(bd);
spin_lock_irqsave(&bd->bd_lock, lock_flags);
}
out:
/*
* If board is doing interrupts, ACK the interrupt.
*/
if (bd && bd->intr_running)
readb(bd->re_map_port + 2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return;
}
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
}
/*
* dgap_found_board()
*
* A board has been found, init it.
*/
static struct board_t *dgap_found_board(struct pci_dev *pdev, int id,
int boardnum)
{
struct board_t *brd;
unsigned int pci_irq;
int i;
int ret;
/* get the board structure and prep it */
brd = kzalloc(sizeof(struct board_t), GFP_KERNEL);
if (!brd)
return ERR_PTR(-ENOMEM);
/* store the info for the board we've found */
brd->magic = DGAP_BOARD_MAGIC;
brd->boardnum = boardnum;
brd->vendor = dgap_pci_tbl[id].vendor;
brd->device = dgap_pci_tbl[id].device;
brd->pdev = pdev;
brd->pci_bus = pdev->bus->number;
brd->pci_slot = PCI_SLOT(pdev->devfn);
brd->name = dgap_ids[id].name;
brd->maxports = dgap_ids[id].maxports;
brd->type = dgap_ids[id].config_type;
brd->dpatype = dgap_ids[id].dpatype;
brd->dpastatus = BD_NOFEP;
init_waitqueue_head(&brd->state_wait);
spin_lock_init(&brd->bd_lock);
brd->inhibit_poller = FALSE;
brd->wait_for_bios = 0;
brd->wait_for_fep = 0;
for (i = 0; i < MAXPORTS; i++)
brd->channels[i] = NULL;
/* store which card & revision we have */
pci_read_config_word(pdev, PCI_SUBSYSTEM_VENDOR_ID, &brd->subvendor);
pci_read_config_word(pdev, PCI_SUBSYSTEM_ID, &brd->subdevice);
pci_read_config_byte(pdev, PCI_REVISION_ID, &brd->rev);
pci_irq = pdev->irq;
brd->irq = pci_irq;
/* get the PCI Base Address Registers */
/* Xr Jupiter and EPC use BAR 2 */
if (brd->device == PCI_DEV_XRJ_DID || brd->device == PCI_DEV_EPCJ_DID) {
brd->membase = pci_resource_start(pdev, 2);
brd->membase_end = pci_resource_end(pdev, 2);
}
/* Everyone else uses BAR 0 */
else {
brd->membase = pci_resource_start(pdev, 0);
brd->membase_end = pci_resource_end(pdev, 0);
}
if (!brd->membase) {
ret = -ENODEV;
goto free_brd;
}
if (brd->membase & 1)
brd->membase &= ~3;
else
brd->membase &= ~15;
/*
* On the PCI boards, there is no IO space allocated
* The I/O registers will be in the first 3 bytes of the
* upper 2MB of the 4MB memory space. The board memory
* will be mapped into the low 2MB of the 4MB memory space
*/
brd->port = brd->membase + PCI_IO_OFFSET;
brd->port_end = brd->port + PCI_IO_SIZE;
/*
* Special initialization for non-PLX boards
*/
if (brd->device != PCI_DEV_XRJ_DID && brd->device != PCI_DEV_EPCJ_DID) {
unsigned short cmd;
pci_write_config_byte(pdev, 0x40, 0);
pci_write_config_byte(pdev, 0x46, 0);
/* Limit burst length to 2 doubleword transactions */
pci_write_config_byte(pdev, 0x42, 1);
/*
* Enable IO and mem if not already done.
* This was needed for support on Itanium.
*/
pci_read_config_word(pdev, PCI_COMMAND, &cmd);
cmd |= (PCI_COMMAND_IO | PCI_COMMAND_MEMORY);
pci_write_config_word(pdev, PCI_COMMAND, cmd);
}
/* init our poll helper tasklet */
tasklet_init(&brd->helper_tasklet, dgap_poll_tasklet,
(unsigned long) brd);
ret = dgap_remap(brd);
if (ret)
goto free_brd;
pr_info("dgap: board %d: %s (rev %d), irq %ld\n",
boardnum, brd->name, brd->rev, brd->irq);
return brd;
free_brd:
kfree(brd);
return ERR_PTR(ret);
}
/*
* dgap_intr()
*
* Driver interrupt handler.
*/
static irqreturn_t dgap_intr(int irq, void *voidbrd)
{
struct board_t *brd = voidbrd;
if (!brd)
return IRQ_NONE;
/*
* Check to make sure its for us.
*/
if (brd->magic != DGAP_BOARD_MAGIC)
return IRQ_NONE;
brd->intr_count++;
/*
* Schedule tasklet to run at a better time.
*/
tasklet_schedule(&brd->helper_tasklet);
return IRQ_HANDLED;
}
/*****************************************************************************
*
* Function:
*
* dgap_poll_handler
*
* Author:
*
* Scott H Kilau
*
* Parameters:
*
* dummy -- ignored
*
* Return Values:
*
* none
*
* Description:
*
* As each timer expires, it determines (a) whether the "transmit"
* waiter needs to be woken up, and (b) whether the poller needs to
* be rescheduled.
*
******************************************************************************/
static void dgap_poll_handler(ulong dummy)
{
unsigned int i;
struct board_t *brd;
unsigned long lock_flags;
ulong new_time;
dgap_poll_counter++;
/*
* Do not start the board state machine until
* driver tells us its up and running, and has
* everything it needs.
*/
if (dgap_driver_state != DRIVER_READY)
goto schedule_poller;
/*
* If we have just 1 board, or the system is not SMP,
* then use the typical old style poller.
* Otherwise, use our new tasklet based poller, which should
* speed things up for multiple boards.
*/
if ((dgap_numboards == 1) || (num_online_cpus() <= 1)) {
for (i = 0; i < dgap_numboards; i++) {
brd = dgap_board[i];
if (brd->state == BOARD_FAILED)
continue;
if (!brd->intr_running)
/* Call the real board poller directly */
dgap_poll_tasklet((unsigned long) brd);
}
} else {
/*
* Go thru each board, kicking off a
* tasklet for each if needed
*/
for (i = 0; i < dgap_numboards; i++) {
brd = dgap_board[i];
/*
* Attempt to grab the board lock.
*
* If we can't get it, no big deal, the next poll
* will get it. Basically, I just really don't want
* to spin in here, because I want to kick off my
* tasklets as fast as I can, and then get out the
* poller.
*/
if (!spin_trylock(&brd->bd_lock))
continue;
/*
* If board is in a failed state, don't bother
* scheduling a tasklet
*/
if (brd->state == BOARD_FAILED) {
spin_unlock(&brd->bd_lock);
continue;
}
/* Schedule a poll helper task */
if (!brd->intr_running)
tasklet_schedule(&brd->helper_tasklet);
/*
* Can't do DGAP_UNLOCK here, as we don't have
* lock_flags because we did a trylock above.
*/
spin_unlock(&brd->bd_lock);
}
}
schedule_poller:
/*
* Schedule ourself back at the nominal wakeup interval.
*/
spin_lock_irqsave(&dgap_poll_lock, lock_flags);
dgap_poll_time += dgap_jiffies_from_ms(dgap_poll_tick);
new_time = dgap_poll_time - jiffies;
if ((ulong) new_time >= 2 * dgap_poll_tick) {
dgap_poll_time =
jiffies + dgap_jiffies_from_ms(dgap_poll_tick);
}
dgap_poll_timer.function = dgap_poll_handler;
dgap_poll_timer.data = 0;
dgap_poll_timer.expires = dgap_poll_time;
spin_unlock_irqrestore(&dgap_poll_lock, lock_flags);
if (!dgap_poll_stop)
add_timer(&dgap_poll_timer);
}
/*=======================================================================
*
* dgap_cmdb - Sends a 2 byte command to the FEP.
*
* ch - Pointer to channel structure.
* cmd - Command to be sent.
* byte1 - Integer containing first byte to be sent.
* byte2 - Integer containing second byte to be sent.
* ncmds - Wait until ncmds or fewer cmds are left
* in the cmd buffer before returning.
*
*=======================================================================*/
static void dgap_cmdb(struct channel_t *ch, u8 cmd, u8 byte1,
u8 byte2, uint ncmds)
{
char __iomem *vaddr;
struct __iomem cm_t *cm_addr;
uint count;
uint n;
u16 head;
u16 tail;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
/*
* Check if board is still alive.
*/
if (ch->ch_bd->state == BOARD_FAILED)
return;
/*
* Make sure the pointers are in range before
* writing to the FEP memory.
*/
vaddr = ch->ch_bd->re_map_membase;
if (!vaddr)
return;
cm_addr = (struct cm_t __iomem *) (vaddr + CMDBUF);
head = readw(&(cm_addr->cm_head));
/*
* Forget it if pointers out of range.
*/
if (head >= (CMDMAX - CMDSTART) || (head & 03)) {
ch->ch_bd->state = BOARD_FAILED;
return;
}
/*
* Put the data in the circular command buffer.
*/
writeb(cmd, (vaddr + head + CMDSTART + 0));
writeb((u8) ch->ch_portnum, (vaddr + head + CMDSTART + 1));
writeb(byte1, (vaddr + head + CMDSTART + 2));
writeb(byte2, (vaddr + head + CMDSTART + 3));
head = (head + 4) & (CMDMAX - CMDSTART - 4);
writew(head, &(cm_addr->cm_head));
/*
* Wait if necessary before updating the head
* pointer to limit the number of outstanding
* commands to the FEP. If the time spent waiting
* is outlandish, declare the FEP dead.
*/
for (count = dgap_count ;;) {
head = readw(&(cm_addr->cm_head));
tail = readw(&(cm_addr->cm_tail));
n = (head - tail) & (CMDMAX - CMDSTART - 4);
if (n <= ncmds * sizeof(struct cm_t))
break;
if (--count == 0) {
ch->ch_bd->state = BOARD_FAILED;
return;
}
udelay(10);
}
}
/*=======================================================================
*
* dgap_cmdw - Sends a 1 word command to the FEP.
*
* ch - Pointer to channel structure.
* cmd - Command to be sent.
* word - Integer containing word to be sent.
* ncmds - Wait until ncmds or fewer cmds are left
* in the cmd buffer before returning.
*
*=======================================================================*/
static void dgap_cmdw(struct channel_t *ch, u8 cmd, u16 word, uint ncmds)
{
char __iomem *vaddr;
struct __iomem cm_t *cm_addr;
uint count;
uint n;
u16 head;
u16 tail;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
/*
* Check if board is still alive.
*/
if (ch->ch_bd->state == BOARD_FAILED)
return;
/*
* Make sure the pointers are in range before
* writing to the FEP memory.
*/
vaddr = ch->ch_bd->re_map_membase;
if (!vaddr)
return;
cm_addr = (struct cm_t __iomem *) (vaddr + CMDBUF);
head = readw(&(cm_addr->cm_head));
/*
* Forget it if pointers out of range.
*/
if (head >= (CMDMAX - CMDSTART) || (head & 03)) {
ch->ch_bd->state = BOARD_FAILED;
return;
}
/*
* Put the data in the circular command buffer.
*/
writeb(cmd, (vaddr + head + CMDSTART + 0));
writeb((u8) ch->ch_portnum, (vaddr + head + CMDSTART + 1));
writew((u16) word, (vaddr + head + CMDSTART + 2));
head = (head + 4) & (CMDMAX - CMDSTART - 4);
writew(head, &(cm_addr->cm_head));
/*
* Wait if necessary before updating the head
* pointer to limit the number of outstanding
* commands to the FEP. If the time spent waiting
* is outlandish, declare the FEP dead.
*/
for (count = dgap_count ;;) {
head = readw(&(cm_addr->cm_head));
tail = readw(&(cm_addr->cm_tail));
n = (head - tail) & (CMDMAX - CMDSTART - 4);
if (n <= ncmds * sizeof(struct cm_t))
break;
if (--count == 0) {
ch->ch_bd->state = BOARD_FAILED;
return;
}
udelay(10);
}
}
/*=======================================================================
*
* dgap_cmdw_ext - Sends a extended word command to the FEP.
*
* ch - Pointer to channel structure.
* cmd - Command to be sent.
* word - Integer containing word to be sent.
* ncmds - Wait until ncmds or fewer cmds are left
* in the cmd buffer before returning.
*
*=======================================================================*/
static void dgap_cmdw_ext(struct channel_t *ch, u16 cmd, u16 word, uint ncmds)
{
char __iomem *vaddr;
struct __iomem cm_t *cm_addr;
uint count;
uint n;
u16 head;
u16 tail;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
/*
* Check if board is still alive.
*/
if (ch->ch_bd->state == BOARD_FAILED)
return;
/*
* Make sure the pointers are in range before
* writing to the FEP memory.
*/
vaddr = ch->ch_bd->re_map_membase;
if (!vaddr)
return;
cm_addr = (struct cm_t __iomem *) (vaddr + CMDBUF);
head = readw(&(cm_addr->cm_head));
/*
* Forget it if pointers out of range.
*/
if (head >= (CMDMAX - CMDSTART) || (head & 03)) {
ch->ch_bd->state = BOARD_FAILED;
return;
}
/*
* Put the data in the circular command buffer.
*/
/* Write an FF to tell the FEP that we want an extended command */
writeb((u8) 0xff, (vaddr + head + CMDSTART + 0));
writeb((u8) ch->ch_portnum, (vaddr + head + CMDSTART + 1));
writew((u16) cmd, (vaddr + head + CMDSTART + 2));
/*
* If the second part of the command won't fit,
* put it at the beginning of the circular buffer.
*/
if (((head + 4) >= ((CMDMAX - CMDSTART)) || (head & 03)))
writew((u16) word, (vaddr + CMDSTART));
else
writew((u16) word, (vaddr + head + CMDSTART + 4));
head = (head + 8) & (CMDMAX - CMDSTART - 4);
writew(head, &(cm_addr->cm_head));
/*
* Wait if necessary before updating the head
* pointer to limit the number of outstanding
* commands to the FEP. If the time spent waiting
* is outlandish, declare the FEP dead.
*/
for (count = dgap_count ;;) {
head = readw(&(cm_addr->cm_head));
tail = readw(&(cm_addr->cm_tail));
n = (head - tail) & (CMDMAX - CMDSTART - 4);
if (n <= ncmds * sizeof(struct cm_t))
break;
if (--count == 0) {
ch->ch_bd->state = BOARD_FAILED;
return;
}
udelay(10);
}
}
/*=======================================================================
*
* dgap_wmove - Write data to FEP buffer.
*
* ch - Pointer to channel structure.
* buf - Poiter to characters to be moved.
* cnt - Number of characters to move.
*
*=======================================================================*/
static void dgap_wmove(struct channel_t *ch, char *buf, uint cnt)
{
int n;
char __iomem *taddr;
struct bs_t __iomem *bs;
u16 head;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
/*
* Check parameters.
*/
bs = ch->ch_bs;
head = readw(&(bs->tx_head));
/*
* If pointers are out of range, just return.
*/
if ((cnt > ch->ch_tsize) ||
(unsigned)(head - ch->ch_tstart) >= ch->ch_tsize)
return;
/*
* If the write wraps over the top of the circular buffer,
* move the portion up to the wrap point, and reset the
* pointers to the bottom.
*/
n = ch->ch_tstart + ch->ch_tsize - head;
if (cnt >= n) {
cnt -= n;
taddr = ch->ch_taddr + head;
memcpy_toio(taddr, buf, n);
head = ch->ch_tstart;
buf += n;
}
/*
* Move rest of data.
*/
taddr = ch->ch_taddr + head;
n = cnt;
memcpy_toio(taddr, buf, n);
head += cnt;
writew(head, &(bs->tx_head));
}
/*
* Calls the firmware to reset this channel.
*/
static void dgap_firmware_reset_port(struct channel_t *ch)
{
dgap_cmdb(ch, CHRESET, 0, 0, 0);
/*
* Now that the channel is reset, we need to make sure
* all the current settings get reapplied to the port
* in the firmware.
*
* So we will set the driver's cache of firmware
* settings all to 0, and then call param.
*/
ch->ch_fepiflag = 0;
ch->ch_fepcflag = 0;
ch->ch_fepoflag = 0;
ch->ch_fepstartc = 0;
ch->ch_fepstopc = 0;
ch->ch_fepastartc = 0;
ch->ch_fepastopc = 0;
ch->ch_mostat = 0;
ch->ch_hflow = 0;
}
/*=======================================================================
*
* dgap_param - Set Digi parameters.
*
* struct tty_struct * - TTY for port.
*
*=======================================================================*/
static int dgap_param(struct channel_t *ch, struct board_t *bd, u32 un_type)
{
u16 head;
u16 cflag;
u16 iflag;
u8 mval;
u8 hflow;
/*
* If baud rate is zero, flush queues, and set mval to drop DTR.
*/
if ((ch->ch_c_cflag & (CBAUD)) == 0) {
/* flush rx */
head = readw(&(ch->ch_bs->rx_head));
writew(head, &(ch->ch_bs->rx_tail));
/* flush tx */
head = readw(&(ch->ch_bs->tx_head));
writew(head, &(ch->ch_bs->tx_tail));
ch->ch_flags |= (CH_BAUD0);
/* Drop RTS and DTR */
ch->ch_mval &= ~(D_RTS(ch)|D_DTR(ch));
mval = D_DTR(ch) | D_RTS(ch);
ch->ch_baud_info = 0;
} else if (ch->ch_custom_speed && (bd->bd_flags & BD_FEP5PLUS)) {
/*
* Tell the fep to do the command
*/
dgap_cmdw_ext(ch, 0xff01, ch->ch_custom_speed, 0);
/*
* Now go get from fep mem, what the fep
* believes the custom baud rate is.
*/
ch->ch_custom_speed = dgap_get_custom_baud(ch);
ch->ch_baud_info = ch->ch_custom_speed;
/* Handle transition from B0 */
if (ch->ch_flags & CH_BAUD0) {
ch->ch_flags &= ~(CH_BAUD0);
ch->ch_mval |= (D_RTS(ch)|D_DTR(ch));
}
mval = D_DTR(ch) | D_RTS(ch);
} else {
/*
* Set baud rate, character size, and parity.
*/
int iindex = 0;
int jindex = 0;
int baud = 0;
ulong bauds[4][16] = {
{ /* slowbaud */
0, 50, 75, 110,
134, 150, 200, 300,
600, 1200, 1800, 2400,
4800, 9600, 19200, 38400 },
{ /* slowbaud & CBAUDEX */
0, 57600, 115200, 230400,
460800, 150, 200, 921600,
600, 1200, 1800, 2400,
4800, 9600, 19200, 38400 },
{ /* fastbaud */
0, 57600, 76800, 115200,
14400, 57600, 230400, 76800,
115200, 230400, 28800, 460800,
921600, 9600, 19200, 38400 },
{ /* fastbaud & CBAUDEX */
0, 57600, 115200, 230400,
460800, 150, 200, 921600,
600, 1200, 1800, 2400,
4800, 9600, 19200, 38400 }
};
/*
* Only use the TXPrint baud rate if the
* terminal unit is NOT open
*/
if (!(ch->ch_tun.un_flags & UN_ISOPEN) &&
un_type == DGAP_PRINT)
baud = C_BAUD(ch->ch_pun.un_tty) & 0xff;
else
baud = C_BAUD(ch->ch_tun.un_tty) & 0xff;
if (ch->ch_c_cflag & CBAUDEX)
iindex = 1;
if (ch->ch_digi.digi_flags & DIGI_FAST)
iindex += 2;
jindex = baud;
if ((iindex >= 0) && (iindex < 4) &&
(jindex >= 0) && (jindex < 16))
baud = bauds[iindex][jindex];
else
baud = 0;
if (baud == 0)
baud = 9600;
ch->ch_baud_info = baud;
/*
* CBAUD has bit position 0x1000 set these days to
* indicate Linux baud rate remap.
* We use a different bit assignment for high speed.
* Clear this bit out while grabbing the parts of
* "cflag" we want.
*/
cflag = ch->ch_c_cflag & ((CBAUD ^ CBAUDEX) | PARODD | PARENB |
CSTOPB | CSIZE);
/*
* HUPCL bit is used by FEP to indicate fast baud
* table is to be used.
*/
if ((ch->ch_digi.digi_flags & DIGI_FAST) ||
(ch->ch_c_cflag & CBAUDEX))
cflag |= HUPCL;
if ((ch->ch_c_cflag & CBAUDEX) &&
!(ch->ch_digi.digi_flags & DIGI_FAST)) {
/*
* The below code is trying to guarantee that only
* baud rates 115200, 230400, 460800, 921600 are
* remapped. We use exclusive or because the various
* baud rates share common bit positions and therefore
* can't be tested for easily.
*/
tcflag_t tcflag = (ch->ch_c_cflag & CBAUD) | CBAUDEX;
int baudpart = 0;
/*
* Map high speed requests to index
* into FEP's baud table
*/
switch (tcflag) {
case B57600:
baudpart = 1;
break;
#ifdef B76800
case B76800:
baudpart = 2;
break;
#endif
case B115200:
baudpart = 3;
break;
case B230400:
baudpart = 9;
break;
case B460800:
baudpart = 11;
break;
#ifdef B921600
case B921600:
baudpart = 12;
break;
#endif
default:
baudpart = 0;
}
if (baudpart)
cflag = (cflag & ~(CBAUD | CBAUDEX)) | baudpart;
}
cflag &= 0xffff;
if (cflag != ch->ch_fepcflag) {
ch->ch_fepcflag = (u16) (cflag & 0xffff);
/*
* Okay to have channel and board
* locks held calling this
*/
dgap_cmdw(ch, SCFLAG, (u16) cflag, 0);
}
/* Handle transition from B0 */
if (ch->ch_flags & CH_BAUD0) {
ch->ch_flags &= ~(CH_BAUD0);
ch->ch_mval |= (D_RTS(ch)|D_DTR(ch));
}
mval = D_DTR(ch) | D_RTS(ch);
}
/*
* Get input flags.
*/
iflag = ch->ch_c_iflag & (IGNBRK | BRKINT | IGNPAR | PARMRK |
INPCK | ISTRIP | IXON | IXANY | IXOFF);
if ((ch->ch_startc == _POSIX_VDISABLE) ||
(ch->ch_stopc == _POSIX_VDISABLE)) {
iflag &= ~(IXON | IXOFF);
ch->ch_c_iflag &= ~(IXON | IXOFF);
}
/*
* Only the IBM Xr card can switch between
* 232 and 422 modes on the fly
*/
if (bd->device == PCI_DEV_XR_IBM_DID) {
if (ch->ch_digi.digi_flags & DIGI_422)
dgap_cmdb(ch, SCOMMODE, MODE_422, 0, 0);
else
dgap_cmdb(ch, SCOMMODE, MODE_232, 0, 0);
}
if (ch->ch_digi.digi_flags & DIGI_ALTPIN)
iflag |= IALTPIN;
if (iflag != ch->ch_fepiflag) {
ch->ch_fepiflag = iflag;
/* Okay to have channel and board locks held calling this */
dgap_cmdw(ch, SIFLAG, (u16) ch->ch_fepiflag, 0);
}
/*
* Select hardware handshaking.
*/
hflow = 0;
if (ch->ch_c_cflag & CRTSCTS)
hflow |= (D_RTS(ch) | D_CTS(ch));
if (ch->ch_digi.digi_flags & RTSPACE)
hflow |= D_RTS(ch);
if (ch->ch_digi.digi_flags & DTRPACE)
hflow |= D_DTR(ch);
if (ch->ch_digi.digi_flags & CTSPACE)
hflow |= D_CTS(ch);
if (ch->ch_digi.digi_flags & DSRPACE)
hflow |= D_DSR(ch);
if (ch->ch_digi.digi_flags & DCDPACE)
hflow |= D_CD(ch);
if (hflow != ch->ch_hflow) {
ch->ch_hflow = hflow;
/* Okay to have channel and board locks held calling this */
dgap_cmdb(ch, SHFLOW, (u8) hflow, 0xff, 0);
}
/*
* Set RTS and/or DTR Toggle if needed,
* but only if product is FEP5+ based.
*/
if (bd->bd_flags & BD_FEP5PLUS) {
u16 hflow2 = 0;
if (ch->ch_digi.digi_flags & DIGI_RTS_TOGGLE)
hflow2 |= (D_RTS(ch));
if (ch->ch_digi.digi_flags & DIGI_DTR_TOGGLE)
hflow2 |= (D_DTR(ch));
dgap_cmdw_ext(ch, 0xff03, hflow2, 0);
}
/*
* Set modem control lines.
*/
mval ^= ch->ch_mforce & (mval ^ ch->ch_mval);
if (ch->ch_mostat ^ mval) {
ch->ch_mostat = mval;
/* Okay to have channel and board locks held calling this */
dgap_cmdb(ch, SMODEM, (u8) mval, D_RTS(ch)|D_DTR(ch), 0);
}
/*
* Read modem signals, and then call carrier function.
*/
ch->ch_mistat = readb(&(ch->ch_bs->m_stat));
dgap_carrier(ch);
/*
* Set the start and stop characters.
*/
if (ch->ch_startc != ch->ch_fepstartc ||
ch->ch_stopc != ch->ch_fepstopc) {
ch->ch_fepstartc = ch->ch_startc;
ch->ch_fepstopc = ch->ch_stopc;
/* Okay to have channel and board locks held calling this */
dgap_cmdb(ch, SFLOWC, ch->ch_fepstartc, ch->ch_fepstopc, 0);
}
/*
* Set the Auxiliary start and stop characters.
*/
if (ch->ch_astartc != ch->ch_fepastartc ||
ch->ch_astopc != ch->ch_fepastopc) {
ch->ch_fepastartc = ch->ch_astartc;
ch->ch_fepastopc = ch->ch_astopc;
/* Okay to have channel and board locks held calling this */
dgap_cmdb(ch, SAFLOWC, ch->ch_fepastartc, ch->ch_fepastopc, 0);
}
return 0;
}
/*
* dgap_block_til_ready()
*
* Wait for DCD, if needed.
*/
static int dgap_block_til_ready(struct tty_struct *tty, struct file *file,
struct channel_t *ch)
{
int retval = 0;
struct un_t *un;
ulong lock_flags;
uint old_flags;
int sleep_on_un_flags;
if (!tty || tty->magic != TTY_MAGIC || !file || !ch ||
ch->magic != DGAP_CHANNEL_MAGIC)
return -EIO;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return -EIO;
spin_lock_irqsave(&ch->ch_lock, lock_flags);
ch->ch_wopen++;
/* Loop forever */
while (1) {
sleep_on_un_flags = 0;
/*
* If board has failed somehow during our sleep,
* bail with error.
*/
if (ch->ch_bd->state == BOARD_FAILED) {
retval = -EIO;
break;
}
/* If tty was hung up, break out of loop and set error. */
if (tty_hung_up_p(file)) {
retval = -EAGAIN;
break;
}
/*
* If either unit is in the middle of the fragile part of close,
* we just cannot touch the channel safely.
* Go back to sleep, knowing that when the channel can be
* touched safely, the close routine will signal the
* ch_wait_flags to wake us back up.
*/
if (!((ch->ch_tun.un_flags | ch->ch_pun.un_flags) &
UN_CLOSING)) {
/*
* Our conditions to leave cleanly and happily:
* 1) NONBLOCKING on the tty is set.
* 2) CLOCAL is set.
* 3) DCD (fake or real) is active.
*/
if (file->f_flags & O_NONBLOCK)
break;
if (tty->flags & (1 << TTY_IO_ERROR))
break;
if (ch->ch_flags & CH_CD)
break;
if (ch->ch_flags & CH_FCAR)
break;
} else {
sleep_on_un_flags = 1;
}
/*
* If there is a signal pending, the user probably
* interrupted (ctrl-c) us.
* Leave loop with error set.
*/
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
/*
* Store the flags before we let go of channel lock
*/
if (sleep_on_un_flags)
old_flags = ch->ch_tun.un_flags | ch->ch_pun.un_flags;
else
old_flags = ch->ch_flags;
/*
* Let go of channel lock before calling schedule.
* Our poller will get any FEP events and wake us up when DCD
* eventually goes active.
*/
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
/*
* Wait for something in the flags to change
* from the current value.
*/
if (sleep_on_un_flags) {
retval = wait_event_interruptible(un->un_flags_wait,
(old_flags != (ch->ch_tun.un_flags |
ch->ch_pun.un_flags)));
} else {
retval = wait_event_interruptible(ch->ch_flags_wait,
(old_flags != ch->ch_flags));
}
/*
* We got woken up for some reason.
* Before looping around, grab our channel lock.
*/
spin_lock_irqsave(&ch->ch_lock, lock_flags);
}
ch->ch_wopen--;
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
return retval;
}
/*
* dgap_tty_flush_buffer()
*
* Flush Tx buffer (make in == out)
*/
static void dgap_tty_flush_buffer(struct tty_struct *tty)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
ulong lock_flags2;
u16 head;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
ch->ch_flags &= ~CH_STOP;
head = readw(&(ch->ch_bs->tx_head));
dgap_cmdw(ch, FLUSHTX, (u16) head, 0);
dgap_cmdw(ch, RESUMETX, 0, 0);
if (ch->ch_tun.un_flags & (UN_LOW|UN_EMPTY)) {
ch->ch_tun.un_flags &= ~(UN_LOW|UN_EMPTY);
wake_up_interruptible(&ch->ch_tun.un_flags_wait);
}
if (ch->ch_pun.un_flags & (UN_LOW|UN_EMPTY)) {
ch->ch_pun.un_flags &= ~(UN_LOW|UN_EMPTY);
wake_up_interruptible(&ch->ch_pun.un_flags_wait);
}
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
if (waitqueue_active(&tty->write_wait))
wake_up_interruptible(&tty->write_wait);
tty_wakeup(tty);
}
/*
* dgap_tty_hangup()
*
* Hangup the port. Like a close, but don't wait for output to drain.
*/
static void dgap_tty_hangup(struct tty_struct *tty)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
/* flush the transmit queues */
dgap_tty_flush_buffer(tty);
}
/*
* dgap_tty_chars_in_buffer()
*
* Return number of characters that have not been transmitted yet.
*
* This routine is used by the line discipline to determine if there
* is data waiting to be transmitted/drained/flushed or not.
*/
static int dgap_tty_chars_in_buffer(struct tty_struct *tty)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
struct bs_t __iomem *bs;
u8 tbusy;
uint chars;
u16 thead, ttail, tmask, chead, ctail;
ulong lock_flags = 0;
ulong lock_flags2 = 0;
if (!tty)
return 0;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
bs = ch->ch_bs;
if (!bs)
return 0;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
tmask = (ch->ch_tsize - 1);
/* Get Transmit queue pointers */
thead = readw(&(bs->tx_head)) & tmask;
ttail = readw(&(bs->tx_tail)) & tmask;
/* Get tbusy flag */
tbusy = readb(&(bs->tbusy));
/* Get Command queue pointers */
chead = readw(&(ch->ch_cm->cm_head));
ctail = readw(&(ch->ch_cm->cm_tail));
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
/*
* The only way we know for sure if there is no pending
* data left to be transferred, is if:
* 1) Transmit head and tail are equal (empty).
* 2) Command queue head and tail are equal (empty).
* 3) The "TBUSY" flag is 0. (Transmitter not busy).
*/
if ((ttail == thead) && (tbusy == 0) && (chead == ctail)) {
chars = 0;
} else {
if (thead >= ttail)
chars = thead - ttail;
else
chars = thead - ttail + ch->ch_tsize;
/*
* Fudge factor here.
* If chars is zero, we know that the command queue had
* something in it or tbusy was set. Because we cannot
* be sure if there is still some data to be transmitted,
* lets lie, and tell ld we have 1 byte left.
*/
if (chars == 0) {
/*
* If TBUSY is still set, and our tx buffers are empty,
* force the firmware to send me another wakeup after
* TBUSY has been cleared.
*/
if (tbusy != 0) {
spin_lock_irqsave(&ch->ch_lock, lock_flags);
un->un_flags |= UN_EMPTY;
writeb(1, &(bs->iempty));
spin_unlock_irqrestore(&ch->ch_lock,
lock_flags);
}
chars = 1;
}
}
return chars;
}
static int dgap_wait_for_drain(struct tty_struct *tty)
{
struct channel_t *ch;
struct un_t *un;
struct bs_t __iomem *bs;
int ret = 0;
uint count = 1;
ulong lock_flags = 0;
if (!tty || tty->magic != TTY_MAGIC)
return -EIO;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return -EIO;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return -EIO;
bs = ch->ch_bs;
if (!bs)
return -EIO;
/* Loop until data is drained */
while (count != 0) {
count = dgap_tty_chars_in_buffer(tty);
if (count == 0)
break;
/* Set flag waiting for drain */
spin_lock_irqsave(&ch->ch_lock, lock_flags);
un->un_flags |= UN_EMPTY;
writeb(1, &(bs->iempty));
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
/* Go to sleep till we get woken up */
ret = wait_event_interruptible(un->un_flags_wait,
((un->un_flags & UN_EMPTY) == 0));
/* If ret is non-zero, user ctrl-c'ed us */
if (ret)
break;
}
spin_lock_irqsave(&ch->ch_lock, lock_flags);
un->un_flags &= ~(UN_EMPTY);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
return ret;
}
/*
* dgap_maxcps_room
*
* Reduces bytes_available to the max number of characters
* that can be sent currently given the maxcps value, and
* returns the new bytes_available. This only affects printer
* output.
*/
static int dgap_maxcps_room(struct channel_t *ch, struct un_t *un,
int bytes_available)
{
/*
* If its not the Transparent print device, return
* the full data amount.
*/
if (un->un_type != DGAP_PRINT)
return bytes_available;
if (ch->ch_digi.digi_maxcps > 0 && ch->ch_digi.digi_bufsize > 0) {
int cps_limit = 0;
unsigned long current_time = jiffies;
unsigned long buffer_time = current_time +
(HZ * ch->ch_digi.digi_bufsize) /
ch->ch_digi.digi_maxcps;
if (ch->ch_cpstime < current_time) {
/* buffer is empty */
ch->ch_cpstime = current_time; /* reset ch_cpstime */
cps_limit = ch->ch_digi.digi_bufsize;
} else if (ch->ch_cpstime < buffer_time) {
/* still room in the buffer */
cps_limit = ((buffer_time - ch->ch_cpstime) *
ch->ch_digi.digi_maxcps) / HZ;
} else {
/* no room in the buffer */
cps_limit = 0;
}
bytes_available = min(cps_limit, bytes_available);
}
return bytes_available;
}
static inline void dgap_set_firmware_event(struct un_t *un, unsigned int event)
{
struct channel_t *ch;
struct bs_t __iomem *bs;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bs = ch->ch_bs;
if (!bs)
return;
if ((event & UN_LOW) != 0) {
if ((un->un_flags & UN_LOW) == 0) {
un->un_flags |= UN_LOW;
writeb(1, &(bs->ilow));
}
}
if ((event & UN_LOW) != 0) {
if ((un->un_flags & UN_EMPTY) == 0) {
un->un_flags |= UN_EMPTY;
writeb(1, &(bs->iempty));
}
}
}
/*
* dgap_tty_write_room()
*
* Return space available in Tx buffer
*/
static int dgap_tty_write_room(struct tty_struct *tty)
{
struct channel_t *ch;
struct un_t *un;
struct bs_t __iomem *bs;
u16 head, tail, tmask;
int ret;
ulong lock_flags = 0;
if (!tty)
return 0;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bs = ch->ch_bs;
if (!bs)
return 0;
spin_lock_irqsave(&ch->ch_lock, lock_flags);
tmask = ch->ch_tsize - 1;
head = readw(&(bs->tx_head)) & tmask;
tail = readw(&(bs->tx_tail)) & tmask;
ret = tail - head - 1;
if (ret < 0)
ret += ch->ch_tsize;
/* Limit printer to maxcps */
ret = dgap_maxcps_room(ch, un, ret);
/*
* If we are printer device, leave space for
* possibly both the on and off strings.
*/
if (un->un_type == DGAP_PRINT) {
if (!(ch->ch_flags & CH_PRON))
ret -= ch->ch_digi.digi_onlen;
ret -= ch->ch_digi.digi_offlen;
} else {
if (ch->ch_flags & CH_PRON)
ret -= ch->ch_digi.digi_offlen;
}
if (ret < 0)
ret = 0;
/*
* Schedule FEP to wake us up if needed.
*
* TODO: This might be overkill...
* Do we really need to schedule callbacks from the FEP
* in every case? Can we get smarter based on ret?
*/
dgap_set_firmware_event(un, UN_LOW | UN_EMPTY);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
return ret;
}
/*
* dgap_tty_write()
*
* Take data from the user or kernel and send it out to the FEP.
* In here exists all the Transparent Print magic as well.
*/
static int dgap_tty_write(struct tty_struct *tty, const unsigned char *buf,
int count)
{
struct channel_t *ch;
struct un_t *un;
struct bs_t __iomem *bs;
char __iomem *vaddr;
u16 head, tail, tmask, remain;
int bufcount, n;
ulong lock_flags;
if (!tty)
return 0;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bs = ch->ch_bs;
if (!bs)
return 0;
if (!count)
return 0;
spin_lock_irqsave(&ch->ch_lock, lock_flags);
/* Get our space available for the channel from the board */
tmask = ch->ch_tsize - 1;
head = readw(&(bs->tx_head)) & tmask;
tail = readw(&(bs->tx_tail)) & tmask;
bufcount = tail - head - 1;
if (bufcount < 0)
bufcount += ch->ch_tsize;
/*
* Limit printer output to maxcps overall, with bursts allowed
* up to bufsize characters.
*/
bufcount = dgap_maxcps_room(ch, un, bufcount);
/*
* Take minimum of what the user wants to send, and the
* space available in the FEP buffer.
*/
count = min(count, bufcount);
/*
* Bail if no space left.
*/
if (count <= 0) {
dgap_set_firmware_event(un, UN_LOW | UN_EMPTY);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
return 0;
}
/*
* Output the printer ON string, if we are in terminal mode, but
* need to be in printer mode.
*/
if ((un->un_type == DGAP_PRINT) && !(ch->ch_flags & CH_PRON)) {
dgap_wmove(ch, ch->ch_digi.digi_onstr,
(int) ch->ch_digi.digi_onlen);
head = readw(&(bs->tx_head)) & tmask;
ch->ch_flags |= CH_PRON;
}
/*
* On the other hand, output the printer OFF string, if we are
* currently in printer mode, but need to output to the terminal.
*/
if ((un->un_type != DGAP_PRINT) && (ch->ch_flags & CH_PRON)) {
dgap_wmove(ch, ch->ch_digi.digi_offstr,
(int) ch->ch_digi.digi_offlen);
head = readw(&(bs->tx_head)) & tmask;
ch->ch_flags &= ~CH_PRON;
}
n = count;
/*
* If the write wraps over the top of the circular buffer,
* move the portion up to the wrap point, and reset the
* pointers to the bottom.
*/
remain = ch->ch_tstart + ch->ch_tsize - head;
if (n >= remain) {
n -= remain;
vaddr = ch->ch_taddr + head;
memcpy_toio(vaddr, (u8 *) buf, remain);
head = ch->ch_tstart;
buf += remain;
}
if (n > 0) {
/*
* Move rest of data.
*/
vaddr = ch->ch_taddr + head;
remain = n;
memcpy_toio(vaddr, (u8 *) buf, remain);
head += remain;
}
if (count) {
ch->ch_txcount += count;
head &= tmask;
writew(head, &(bs->tx_head));
}
dgap_set_firmware_event(un, UN_LOW | UN_EMPTY);
/*
* If this is the print device, and the
* printer is still on, we need to turn it
* off before going idle. If the buffer is
* non-empty, wait until it goes empty.
* Otherwise turn it off right now.
*/
if ((un->un_type == DGAP_PRINT) && (ch->ch_flags & CH_PRON)) {
tail = readw(&(bs->tx_tail)) & tmask;
if (tail != head) {
un->un_flags |= UN_EMPTY;
writeb(1, &(bs->iempty));
} else {
dgap_wmove(ch, ch->ch_digi.digi_offstr,
(int) ch->ch_digi.digi_offlen);
head = readw(&(bs->tx_head)) & tmask;
ch->ch_flags &= ~CH_PRON;
}
}
/* Update printer buffer empty time. */
if ((un->un_type == DGAP_PRINT) && (ch->ch_digi.digi_maxcps > 0)
&& (ch->ch_digi.digi_bufsize > 0)) {
ch->ch_cpstime += (HZ * count) / ch->ch_digi.digi_maxcps;
}
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
return count;
}
/*
* dgap_tty_put_char()
*
* Put a character into ch->ch_buf
*
* - used by the line discipline for OPOST processing
*/
static int dgap_tty_put_char(struct tty_struct *tty, unsigned char c)
{
/*
* Simply call tty_write.
*/
dgap_tty_write(tty, &c, 1);
return 1;
}
/*
* Return modem signals to ld.
*/
static int dgap_tty_tiocmget(struct tty_struct *tty)
{
struct channel_t *ch;
struct un_t *un;
int result;
u8 mstat;
ulong lock_flags;
if (!tty || tty->magic != TTY_MAGIC)
return -EIO;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return -EIO;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return -EIO;
spin_lock_irqsave(&ch->ch_lock, lock_flags);
mstat = readb(&(ch->ch_bs->m_stat));
/* Append any outbound signals that might be pending... */
mstat |= ch->ch_mostat;
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
result = 0;
if (mstat & D_DTR(ch))
result |= TIOCM_DTR;
if (mstat & D_RTS(ch))
result |= TIOCM_RTS;
if (mstat & D_CTS(ch))
result |= TIOCM_CTS;
if (mstat & D_DSR(ch))
result |= TIOCM_DSR;
if (mstat & D_RI(ch))
result |= TIOCM_RI;
if (mstat & D_CD(ch))
result |= TIOCM_CD;
return result;
}
/*
* dgap_tty_tiocmset()
*
* Set modem signals, called by ld.
*/
static int dgap_tty_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
ulong lock_flags2;
if (!tty || tty->magic != TTY_MAGIC)
return -EIO;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return -EIO;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return -EIO;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return -EIO;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
if (set & TIOCM_RTS) {
ch->ch_mforce |= D_RTS(ch);
ch->ch_mval |= D_RTS(ch);
}
if (set & TIOCM_DTR) {
ch->ch_mforce |= D_DTR(ch);
ch->ch_mval |= D_DTR(ch);
}
if (clear & TIOCM_RTS) {
ch->ch_mforce |= D_RTS(ch);
ch->ch_mval &= ~(D_RTS(ch));
}
if (clear & TIOCM_DTR) {
ch->ch_mforce |= D_DTR(ch);
ch->ch_mval &= ~(D_DTR(ch));
}
dgap_param(ch, bd, un->un_type);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
}
/*
* dgap_tty_send_break()
*
* Send a Break, called by ld.
*/
static int dgap_tty_send_break(struct tty_struct *tty, int msec)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
ulong lock_flags2;
if (!tty || tty->magic != TTY_MAGIC)
return -EIO;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return -EIO;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return -EIO;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return -EIO;
switch (msec) {
case -1:
msec = 0xFFFF;
break;
case 0:
msec = 1;
break;
default:
msec /= 10;
break;
}
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
#if 0
dgap_cmdw(ch, SBREAK, (u16) SBREAK_TIME, 0);
#endif
dgap_cmdw(ch, SBREAK, (u16) msec, 0);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
}
/*
* dgap_tty_wait_until_sent()
*
* wait until data has been transmitted, called by ld.
*/
static void dgap_tty_wait_until_sent(struct tty_struct *tty, int timeout)
{
dgap_wait_for_drain(tty);
}
/*
* dgap_send_xchar()
*
* send a high priority character, called by ld.
*/
static void dgap_tty_send_xchar(struct tty_struct *tty, char c)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
ulong lock_flags2;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
/*
* This is technically what we should do.
* However, the NIST tests specifically want
* to see each XON or XOFF character that it
* sends, so lets just send each character
* by hand...
*/
#if 0
if (c == STOP_CHAR(tty))
dgap_cmdw(ch, RPAUSE, 0, 0);
else if (c == START_CHAR(tty))
dgap_cmdw(ch, RRESUME, 0, 0);
else
dgap_wmove(ch, &c, 1);
#else
dgap_wmove(ch, &c, 1);
#endif
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
}
/*
* Return modem signals to ld.
*/
static int dgap_get_modem_info(struct channel_t *ch, unsigned int __user *value)
{
int result;
u8 mstat;
ulong lock_flags;
int rc;
spin_lock_irqsave(&ch->ch_lock, lock_flags);
mstat = readb(&(ch->ch_bs->m_stat));
/* Append any outbound signals that might be pending... */
mstat |= ch->ch_mostat;
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
result = 0;
if (mstat & D_DTR(ch))
result |= TIOCM_DTR;
if (mstat & D_RTS(ch))
result |= TIOCM_RTS;
if (mstat & D_CTS(ch))
result |= TIOCM_CTS;
if (mstat & D_DSR(ch))
result |= TIOCM_DSR;
if (mstat & D_RI(ch))
result |= TIOCM_RI;
if (mstat & D_CD(ch))
result |= TIOCM_CD;
rc = put_user(result, value);
return rc;
}
/*
* dgap_set_modem_info()
*
* Set modem signals, called by ld.
*/
static int dgap_set_modem_info(struct channel_t *ch, struct board_t *bd,
struct un_t *un, unsigned int command,
unsigned int __user *value)
{
int ret;
unsigned int arg;
ulong lock_flags;
ulong lock_flags2;
ret = get_user(arg, value);
if (ret)
return ret;
switch (command) {
case TIOCMBIS:
if (arg & TIOCM_RTS) {
ch->ch_mforce |= D_RTS(ch);
ch->ch_mval |= D_RTS(ch);
}
if (arg & TIOCM_DTR) {
ch->ch_mforce |= D_DTR(ch);
ch->ch_mval |= D_DTR(ch);
}
break;
case TIOCMBIC:
if (arg & TIOCM_RTS) {
ch->ch_mforce |= D_RTS(ch);
ch->ch_mval &= ~(D_RTS(ch));
}
if (arg & TIOCM_DTR) {
ch->ch_mforce |= D_DTR(ch);
ch->ch_mval &= ~(D_DTR(ch));
}
break;
case TIOCMSET:
ch->ch_mforce = D_DTR(ch)|D_RTS(ch);
if (arg & TIOCM_RTS)
ch->ch_mval |= D_RTS(ch);
else
ch->ch_mval &= ~(D_RTS(ch));
if (arg & TIOCM_DTR)
ch->ch_mval |= (D_DTR(ch));
else
ch->ch_mval &= ~(D_DTR(ch));
break;
default:
return -EINVAL;
}
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
dgap_param(ch, bd, un->un_type);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
}
/*
* dgap_tty_digigeta()
*
* Ioctl to get the information for ditty.
*
*
*
*/
static int dgap_tty_digigeta(struct channel_t *ch,
struct digi_t __user *retinfo)
{
struct digi_t tmp;
ulong lock_flags;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
spin_lock_irqsave(&ch->ch_lock, lock_flags);
memcpy(&tmp, &ch->ch_digi, sizeof(tmp));
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
/*
* dgap_tty_digiseta()
*
* Ioctl to set the information for ditty.
*
*
*
*/
static int dgap_tty_digiseta(struct channel_t *ch, struct board_t *bd,
struct un_t *un, struct digi_t __user *new_info)
{
struct digi_t new_digi;
ulong lock_flags = 0;
unsigned long lock_flags2;
if (copy_from_user(&new_digi, new_info, sizeof(struct digi_t)))
return -EFAULT;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
memcpy(&ch->ch_digi, &new_digi, sizeof(struct digi_t));
if (ch->ch_digi.digi_maxcps < 1)
ch->ch_digi.digi_maxcps = 1;
if (ch->ch_digi.digi_maxcps > 10000)
ch->ch_digi.digi_maxcps = 10000;
if (ch->ch_digi.digi_bufsize < 10)
ch->ch_digi.digi_bufsize = 10;
if (ch->ch_digi.digi_maxchar < 1)
ch->ch_digi.digi_maxchar = 1;
if (ch->ch_digi.digi_maxchar > ch->ch_digi.digi_bufsize)
ch->ch_digi.digi_maxchar = ch->ch_digi.digi_bufsize;
if (ch->ch_digi.digi_onlen > DIGI_PLEN)
ch->ch_digi.digi_onlen = DIGI_PLEN;
if (ch->ch_digi.digi_offlen > DIGI_PLEN)
ch->ch_digi.digi_offlen = DIGI_PLEN;
dgap_param(ch, bd, un->un_type);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
}
/*
* dgap_tty_digigetedelay()
*
* Ioctl to get the current edelay setting.
*
*
*
*/
static int dgap_tty_digigetedelay(struct tty_struct *tty, int __user *retinfo)
{
struct channel_t *ch;
struct un_t *un;
int tmp;
ulong lock_flags;
if (!retinfo)
return -EFAULT;
if (!tty || tty->magic != TTY_MAGIC)
return -EFAULT;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return -EFAULT;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
spin_lock_irqsave(&ch->ch_lock, lock_flags);
tmp = readw(&(ch->ch_bs->edelay));
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
/*
* dgap_tty_digisetedelay()
*
* Ioctl to set the EDELAY setting
*
*/
static int dgap_tty_digisetedelay(struct channel_t *ch, struct board_t *bd,
struct un_t *un, int __user *new_info)
{
int new_digi;
ulong lock_flags;
ulong lock_flags2;
if (copy_from_user(&new_digi, new_info, sizeof(int)))
return -EFAULT;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
writew((u16) new_digi, &(ch->ch_bs->edelay));
dgap_param(ch, bd, un->un_type);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
}
/*
* dgap_tty_digigetcustombaud()
*
* Ioctl to get the current custom baud rate setting.
*/
static int dgap_tty_digigetcustombaud(struct channel_t *ch, struct un_t *un,
int __user *retinfo)
{
int tmp;
ulong lock_flags;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
spin_lock_irqsave(&ch->ch_lock, lock_flags);
tmp = dgap_get_custom_baud(ch);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
/*
* dgap_tty_digisetcustombaud()
*
* Ioctl to set the custom baud rate setting
*/
static int dgap_tty_digisetcustombaud(struct channel_t *ch, struct board_t *bd,
struct un_t *un, int __user *new_info)
{
uint new_rate;
ulong lock_flags;
ulong lock_flags2;
if (copy_from_user(&new_rate, new_info, sizeof(unsigned int)))
return -EFAULT;
if (bd->bd_flags & BD_FEP5PLUS) {
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
ch->ch_custom_speed = new_rate;
dgap_param(ch, bd, un->un_type);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
}
return 0;
}
/*
* dgap_set_termios()
*/
static void dgap_tty_set_termios(struct tty_struct *tty,
struct ktermios *old_termios)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
unsigned long lock_flags;
unsigned long lock_flags2;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
ch->ch_c_cflag = tty->termios.c_cflag;
ch->ch_c_iflag = tty->termios.c_iflag;
ch->ch_c_oflag = tty->termios.c_oflag;
ch->ch_c_lflag = tty->termios.c_lflag;
ch->ch_startc = tty->termios.c_cc[VSTART];
ch->ch_stopc = tty->termios.c_cc[VSTOP];
dgap_carrier(ch);
dgap_param(ch, bd, un->un_type);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
}
static void dgap_tty_throttle(struct tty_struct *tty)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
ulong lock_flags2;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
ch->ch_flags |= (CH_RXBLOCK);
#if 1
dgap_cmdw(ch, RPAUSE, 0, 0);
#endif
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
}
static void dgap_tty_unthrottle(struct tty_struct *tty)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
ulong lock_flags2;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
ch->ch_flags &= ~(CH_RXBLOCK);
#if 1
dgap_cmdw(ch, RRESUME, 0, 0);
#endif
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
}
static struct board_t *find_board_by_major(unsigned int major)
{
unsigned int i;
for (i = 0; i < MAXBOARDS; i++) {
struct board_t *brd = dgap_board[i];
if (!brd)
return NULL;
if (major == brd->serial_driver->major ||
major == brd->print_driver->major)
return brd;
}
return NULL;
}
/************************************************************************
*
* TTY Entry points and helper functions
*
************************************************************************/
/*
* dgap_tty_open()
*
*/
static int dgap_tty_open(struct tty_struct *tty, struct file *file)
{
struct board_t *brd;
struct channel_t *ch;
struct un_t *un;
struct bs_t __iomem *bs;
uint major;
uint minor;
int rc;
ulong lock_flags;
ulong lock_flags2;
u16 head;
major = MAJOR(tty_devnum(tty));
minor = MINOR(tty_devnum(tty));
brd = find_board_by_major(major);
if (!brd)
return -EIO;
/*
* If board is not yet up to a state of READY, go to
* sleep waiting for it to happen or they cancel the open.
*/
rc = wait_event_interruptible(brd->state_wait,
(brd->state & BOARD_READY));
if (rc)
return rc;
spin_lock_irqsave(&brd->bd_lock, lock_flags);
/* The wait above should guarantee this cannot happen */
if (brd->state != BOARD_READY) {
spin_unlock_irqrestore(&brd->bd_lock, lock_flags);
return -EIO;
}
/* If opened device is greater than our number of ports, bail. */
if (MINOR(tty_devnum(tty)) > brd->nasync) {
spin_unlock_irqrestore(&brd->bd_lock, lock_flags);
return -EIO;
}
ch = brd->channels[minor];
if (!ch) {
spin_unlock_irqrestore(&brd->bd_lock, lock_flags);
return -EIO;
}
/* Grab channel lock */
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
/* Figure out our type */
if (major == brd->serial_driver->major) {
un = &brd->channels[minor]->ch_tun;
un->un_type = DGAP_SERIAL;
} else if (major == brd->print_driver->major) {
un = &brd->channels[minor]->ch_pun;
un->un_type = DGAP_PRINT;
} else {
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&brd->bd_lock, lock_flags);
return -EIO;
}
/* Store our unit into driver_data, so we always have it available. */
tty->driver_data = un;
/*
* Error if channel info pointer is NULL.
*/
bs = ch->ch_bs;
if (!bs) {
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&brd->bd_lock, lock_flags);
return -EIO;
}
/*
* Initialize tty's
*/
if (!(un->un_flags & UN_ISOPEN)) {
/* Store important variables. */
un->un_tty = tty;
/* Maybe do something here to the TTY struct as well? */
}
/*
* Initialize if neither terminal or printer is open.
*/
if (!((ch->ch_tun.un_flags | ch->ch_pun.un_flags) & UN_ISOPEN)) {
ch->ch_mforce = 0;
ch->ch_mval = 0;
/*
* Flush input queue.
*/
head = readw(&(bs->rx_head));
writew(head, &(bs->rx_tail));
ch->ch_flags = 0;
ch->pscan_state = 0;
ch->pscan_savechar = 0;
ch->ch_c_cflag = tty->termios.c_cflag;
ch->ch_c_iflag = tty->termios.c_iflag;
ch->ch_c_oflag = tty->termios.c_oflag;
ch->ch_c_lflag = tty->termios.c_lflag;
ch->ch_startc = tty->termios.c_cc[VSTART];
ch->ch_stopc = tty->termios.c_cc[VSTOP];
/* TODO: flush our TTY struct here? */
}
dgap_carrier(ch);
/*
* Run param in case we changed anything
*/
dgap_param(ch, brd, un->un_type);
/*
* follow protocol for opening port
*/
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&brd->bd_lock, lock_flags);
rc = dgap_block_til_ready(tty, file, ch);
if (!un->un_tty)
return -ENODEV;
/* No going back now, increment our unit and channel counters */
spin_lock_irqsave(&ch->ch_lock, lock_flags);
ch->ch_open_count++;
un->un_open_count++;
un->un_flags |= (UN_ISOPEN);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
return rc;
}
/*
* dgap_tty_close()
*
*/
static void dgap_tty_close(struct tty_struct *tty, struct file *file)
{
struct ktermios *ts;
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
ts = &tty->termios;
spin_lock_irqsave(&ch->ch_lock, lock_flags);
/*
* Determine if this is the last close or not - and if we agree about
* which type of close it is with the Line Discipline
*/
if ((tty->count == 1) && (un->un_open_count != 1)) {
/*
* Uh, oh. tty->count is 1, which means that the tty
* structure will be freed. un_open_count should always
* be one in these conditions. If it's greater than
* one, we've got real problems, since it means the
* serial port won't be shutdown.
*/
un->un_open_count = 1;
}
if (--un->un_open_count < 0)
un->un_open_count = 0;
ch->ch_open_count--;
if (ch->ch_open_count && un->un_open_count) {
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
return;
}
/* OK, its the last close on the unit */
un->un_flags |= UN_CLOSING;
tty->closing = 1;
/*
* Only officially close channel if count is 0 and
* DIGI_PRINTER bit is not set.
*/
if ((ch->ch_open_count == 0) &&
!(ch->ch_digi.digi_flags & DIGI_PRINTER)) {
ch->ch_flags &= ~(CH_RXBLOCK);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
/* wait for output to drain */
/* This will also return if we take an interrupt */
dgap_wait_for_drain(tty);
dgap_tty_flush_buffer(tty);
tty_ldisc_flush(tty);
spin_lock_irqsave(&ch->ch_lock, lock_flags);
tty->closing = 0;
/*
* If we have HUPCL set, lower DTR and RTS
*/
if (ch->ch_c_cflag & HUPCL) {
ch->ch_mostat &= ~(D_RTS(ch)|D_DTR(ch));
dgap_cmdb(ch, SMODEM, 0, D_DTR(ch)|D_RTS(ch), 0);
/*
* Go to sleep to ensure RTS/DTR
* have been dropped for modems to see it.
*/
spin_unlock_irqrestore(&ch->ch_lock,
lock_flags);
/* .25 second delay for dropping RTS/DTR */
schedule_timeout_interruptible(msecs_to_jiffies(250));
spin_lock_irqsave(&ch->ch_lock, lock_flags);
}
ch->pscan_state = 0;
ch->pscan_savechar = 0;
ch->ch_baud_info = 0;
}
/*
* turn off print device when closing print device.
*/
if ((un->un_type == DGAP_PRINT) && (ch->ch_flags & CH_PRON)) {
dgap_wmove(ch, ch->ch_digi.digi_offstr,
(int) ch->ch_digi.digi_offlen);
ch->ch_flags &= ~CH_PRON;
}
un->un_tty = NULL;
un->un_flags &= ~(UN_ISOPEN | UN_CLOSING);
tty->driver_data = NULL;
wake_up_interruptible(&ch->ch_flags_wait);
wake_up_interruptible(&un->un_flags_wait);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags);
}
static void dgap_tty_start(struct tty_struct *tty)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
ulong lock_flags2;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
dgap_cmdw(ch, RESUMETX, 0, 0);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
}
static void dgap_tty_stop(struct tty_struct *tty)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
ulong lock_flags2;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
dgap_cmdw(ch, PAUSETX, 0, 0);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
}
/*
* dgap_tty_flush_chars()
*
* Flush the cook buffer
*
* Note to self, and any other poor souls who venture here:
*
* flush in this case DOES NOT mean dispose of the data.
* instead, it means "stop buffering and send it if you
* haven't already." Just guess how I figured that out... SRW 2-Jun-98
*
* It is also always called in interrupt context - JAR 8-Sept-99
*/
static void dgap_tty_flush_chars(struct tty_struct *tty)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
ulong lock_flags;
ulong lock_flags2;
if (!tty || tty->magic != TTY_MAGIC)
return;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
/* TODO: Do something here */
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
}
/*****************************************************************************
*
* The IOCTL function and all of its helpers
*
*****************************************************************************/
/*
* dgap_tty_ioctl()
*
* The usual assortment of ioctl's
*/
static int dgap_tty_ioctl(struct tty_struct *tty, unsigned int cmd,
unsigned long arg)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
int rc;
u16 head;
ulong lock_flags = 0;
ulong lock_flags2 = 0;
void __user *uarg = (void __user *) arg;
if (!tty || tty->magic != TTY_MAGIC)
return -ENODEV;
un = tty->driver_data;
if (!un || un->magic != DGAP_UNIT_MAGIC)
return -ENODEV;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return -ENODEV;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return -ENODEV;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
if (un->un_open_count <= 0) {
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return -EIO;
}
switch (cmd) {
/* Here are all the standard ioctl's that we MUST implement */
case TCSBRK:
/*
* TCSBRK is SVID version: non-zero arg --> no break
* this behaviour is exploited by tcdrain().
*
* According to POSIX.1 spec (7.2.2.1.2) breaks should be
* between 0.25 and 0.5 seconds so we'll ask for something
* in the middle: 0.375 seconds.
*/
rc = tty_check_change(tty);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
if (rc)
return rc;
rc = dgap_wait_for_drain(tty);
if (rc)
return -EINTR;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
if (((cmd == TCSBRK) && (!arg)) || (cmd == TCSBRKP))
dgap_cmdw(ch, SBREAK, (u16) SBREAK_TIME, 0);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
case TCSBRKP:
/* support for POSIX tcsendbreak()
* According to POSIX.1 spec (7.2.2.1.2) breaks should be
* between 0.25 and 0.5 seconds so we'll ask for something
* in the middle: 0.375 seconds.
*/
rc = tty_check_change(tty);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
if (rc)
return rc;
rc = dgap_wait_for_drain(tty);
if (rc)
return -EINTR;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
dgap_cmdw(ch, SBREAK, (u16) SBREAK_TIME, 0);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
case TIOCSBRK:
/*
* FEP5 doesn't support turning on a break unconditionally.
* The FEP5 device will stop sending a break automatically
* after the specified time value that was sent when turning on
* the break.
*/
rc = tty_check_change(tty);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
if (rc)
return rc;
rc = dgap_wait_for_drain(tty);
if (rc)
return -EINTR;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
dgap_cmdw(ch, SBREAK, (u16) SBREAK_TIME, 0);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
case TIOCCBRK:
/*
* FEP5 doesn't support turning off a break unconditionally.
* The FEP5 device will stop sending a break automatically
* after the specified time value that was sent when turning on
* the break.
*/
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
case TIOCGSOFTCAR:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
rc = put_user(C_CLOCAL(tty) ? 1 : 0,
(unsigned long __user *) arg);
return rc;
case TIOCSSOFTCAR:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
rc = get_user(arg, (unsigned long __user *) arg);
if (rc)
return rc;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
tty->termios.c_cflag = ((tty->termios.c_cflag & ~CLOCAL) |
(arg ? CLOCAL : 0));
dgap_param(ch, bd, un->un_type);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
case TIOCMGET:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return dgap_get_modem_info(ch, uarg);
case TIOCMBIS:
case TIOCMBIC:
case TIOCMSET:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return dgap_set_modem_info(ch, bd, un, cmd, uarg);
/*
* Here are any additional ioctl's that we want to implement
*/
case TCFLSH:
/*
* The linux tty driver doesn't have a flush
* input routine for the driver, assuming all backed
* up data is in the line disc. buffers. However,
* we all know that's not the case. Here, we
* act on the ioctl, but then lie and say we didn't
* so the line discipline will process the flush
* also.
*/
rc = tty_check_change(tty);
if (rc) {
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return rc;
}
if ((arg == TCIFLUSH) || (arg == TCIOFLUSH)) {
if (!(un->un_type == DGAP_PRINT)) {
head = readw(&(ch->ch_bs->rx_head));
writew(head, &(ch->ch_bs->rx_tail));
writeb(0, &(ch->ch_bs->orun));
}
}
if ((arg != TCOFLUSH) && (arg != TCIOFLUSH)) {
/* pretend we didn't recognize this IOCTL */
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return -ENOIOCTLCMD;
}
ch->ch_flags &= ~CH_STOP;
head = readw(&(ch->ch_bs->tx_head));
dgap_cmdw(ch, FLUSHTX, (u16) head, 0);
dgap_cmdw(ch, RESUMETX, 0, 0);
if (ch->ch_tun.un_flags & (UN_LOW|UN_EMPTY)) {
ch->ch_tun.un_flags &= ~(UN_LOW|UN_EMPTY);
wake_up_interruptible(&ch->ch_tun.un_flags_wait);
}
if (ch->ch_pun.un_flags & (UN_LOW|UN_EMPTY)) {
ch->ch_pun.un_flags &= ~(UN_LOW|UN_EMPTY);
wake_up_interruptible(&ch->ch_pun.un_flags_wait);
}
if (waitqueue_active(&tty->write_wait))
wake_up_interruptible(&tty->write_wait);
/* Can't hold any locks when calling tty_wakeup! */
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
tty_wakeup(tty);
/* pretend we didn't recognize this IOCTL */
return -ENOIOCTLCMD;
case TCSETSF:
case TCSETSW:
/*
* The linux tty driver doesn't have a flush
* input routine for the driver, assuming all backed
* up data is in the line disc. buffers. However,
* we all know that's not the case. Here, we
* act on the ioctl, but then lie and say we didn't
* so the line discipline will process the flush
* also.
*/
if (cmd == TCSETSF) {
/* flush rx */
ch->ch_flags &= ~CH_STOP;
head = readw(&(ch->ch_bs->rx_head));
writew(head, &(ch->ch_bs->rx_tail));
}
/* now wait for all the output to drain */
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
rc = dgap_wait_for_drain(tty);
if (rc)
return -EINTR;
/* pretend we didn't recognize this */
return -ENOIOCTLCMD;
case TCSETAW:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
rc = dgap_wait_for_drain(tty);
if (rc)
return -EINTR;
/* pretend we didn't recognize this */
return -ENOIOCTLCMD;
case TCXONC:
/*
* The Linux Line Discipline (LD) would do this for us if we
* let it, but we have the special firmware options to do this
* the "right way" regardless of hardware or software flow
* control so we'll do it outselves instead of letting the LD
* do it.
*/
rc = tty_check_change(tty);
if (rc) {
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return rc;
}
switch (arg) {
case TCOON:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
dgap_tty_start(tty);
return 0;
case TCOOFF:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
dgap_tty_stop(tty);
return 0;
case TCION:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
/* Make the ld do it */
return -ENOIOCTLCMD;
case TCIOFF:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
/* Make the ld do it */
return -ENOIOCTLCMD;
default:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return -EINVAL;
}
case DIGI_GETA:
/* get information for ditty */
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return dgap_tty_digigeta(ch, uarg);
case DIGI_SETAW:
case DIGI_SETAF:
/* set information for ditty */
if (cmd == (DIGI_SETAW)) {
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
rc = dgap_wait_for_drain(tty);
if (rc)
return -EINTR;
spin_lock_irqsave(&bd->bd_lock, lock_flags);
spin_lock_irqsave(&ch->ch_lock, lock_flags2);
} else
tty_ldisc_flush(tty);
/* fall thru */
case DIGI_SETA:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return dgap_tty_digiseta(ch, bd, un, uarg);
case DIGI_GEDELAY:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return dgap_tty_digigetedelay(tty, uarg);
case DIGI_SEDELAY:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return dgap_tty_digisetedelay(ch, bd, un, uarg);
case DIGI_GETCUSTOMBAUD:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return dgap_tty_digigetcustombaud(ch, un, uarg);
case DIGI_SETCUSTOMBAUD:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return dgap_tty_digisetcustombaud(ch, bd, un, uarg);
case DIGI_RESET_PORT:
dgap_firmware_reset_port(ch);
dgap_param(ch, bd, un->un_type);
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return 0;
default:
spin_unlock_irqrestore(&ch->ch_lock, lock_flags2);
spin_unlock_irqrestore(&bd->bd_lock, lock_flags);
return -ENOIOCTLCMD;
}
}
static const struct tty_operations dgap_tty_ops = {
.open = dgap_tty_open,
.close = dgap_tty_close,
.write = dgap_tty_write,
.write_room = dgap_tty_write_room,
.flush_buffer = dgap_tty_flush_buffer,
.chars_in_buffer = dgap_tty_chars_in_buffer,
.flush_chars = dgap_tty_flush_chars,
.ioctl = dgap_tty_ioctl,
.set_termios = dgap_tty_set_termios,
.stop = dgap_tty_stop,
.start = dgap_tty_start,
.throttle = dgap_tty_throttle,
.unthrottle = dgap_tty_unthrottle,
.hangup = dgap_tty_hangup,
.put_char = dgap_tty_put_char,
.tiocmget = dgap_tty_tiocmget,
.tiocmset = dgap_tty_tiocmset,
.break_ctl = dgap_tty_send_break,
.wait_until_sent = dgap_tty_wait_until_sent,
.send_xchar = dgap_tty_send_xchar
};
/************************************************************************
*
* TTY Initialization/Cleanup Functions
*
************************************************************************/
/*
* dgap_tty_register()
*
* Init the tty subsystem for this board.
*/
static int dgap_tty_register(struct board_t *brd)
{
int rc;
brd->serial_driver = tty_alloc_driver(MAXPORTS,
TTY_DRIVER_REAL_RAW |
TTY_DRIVER_DYNAMIC_DEV |
TTY_DRIVER_HARDWARE_BREAK);
if (IS_ERR(brd->serial_driver))
return PTR_ERR(brd->serial_driver);
snprintf(brd->serial_name, MAXTTYNAMELEN, "tty_dgap_%d_",
brd->boardnum);
brd->serial_driver->name = brd->serial_name;
brd->serial_driver->name_base = 0;
brd->serial_driver->major = 0;
brd->serial_driver->minor_start = 0;
brd->serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
brd->serial_driver->subtype = SERIAL_TYPE_NORMAL;
brd->serial_driver->init_termios = dgap_default_termios;
brd->serial_driver->driver_name = DRVSTR;
/*
* Entry points for driver. Called by the kernel from
* tty_io.c and n_tty.c.
*/
tty_set_operations(brd->serial_driver, &dgap_tty_ops);
/*
* If we're doing transparent print, we have to do all of the above
* again, separately so we don't get the LD confused about what major
* we are when we get into the dgap_tty_open() routine.
*/
brd->print_driver = tty_alloc_driver(MAXPORTS,
TTY_DRIVER_REAL_RAW |
TTY_DRIVER_DYNAMIC_DEV |
TTY_DRIVER_HARDWARE_BREAK);
if (IS_ERR(brd->print_driver)) {
rc = PTR_ERR(brd->print_driver);
goto free_serial_drv;
}
snprintf(brd->print_name, MAXTTYNAMELEN, "pr_dgap_%d_",
brd->boardnum);
brd->print_driver->name = brd->print_name;
brd->print_driver->name_base = 0;
brd->print_driver->major = 0;
brd->print_driver->minor_start = 0;
brd->print_driver->type = TTY_DRIVER_TYPE_SERIAL;
brd->print_driver->subtype = SERIAL_TYPE_NORMAL;
brd->print_driver->init_termios = dgap_default_termios;
brd->print_driver->driver_name = DRVSTR;
/*
* Entry points for driver. Called by the kernel from
* tty_io.c and n_tty.c.
*/
tty_set_operations(brd->print_driver, &dgap_tty_ops);
/* Register tty devices */
rc = tty_register_driver(brd->serial_driver);
if (rc < 0)
goto free_print_drv;
/* Register Transparent Print devices */
rc = tty_register_driver(brd->print_driver);
if (rc < 0)
goto unregister_serial_drv;
return 0;
unregister_serial_drv:
tty_unregister_driver(brd->serial_driver);
free_print_drv:
put_tty_driver(brd->print_driver);
free_serial_drv:
put_tty_driver(brd->serial_driver);
return rc;
}
static void dgap_tty_unregister(struct board_t *brd)
{
tty_unregister_driver(brd->print_driver);
tty_unregister_driver(brd->serial_driver);
put_tty_driver(brd->print_driver);
put_tty_driver(brd->serial_driver);
}
static int dgap_alloc_flipbuf(struct board_t *brd)
{
/*
* allocate flip buffer for board.
*/
brd->flipbuf = kmalloc(MYFLIPLEN, GFP_KERNEL);
if (!brd->flipbuf)
return -ENOMEM;
brd->flipflagbuf = kmalloc(MYFLIPLEN, GFP_KERNEL);
if (!brd->flipflagbuf) {
kfree(brd->flipbuf);
return -ENOMEM;
}
return 0;
}
static void dgap_free_flipbuf(struct board_t *brd)
{
kfree(brd->flipbuf);
kfree(brd->flipflagbuf);
}
static struct board_t *dgap_verify_board(struct device *p)
{
struct board_t *bd;
if (!p)
return NULL;
bd = dev_get_drvdata(p);
if (!bd || bd->magic != DGAP_BOARD_MAGIC || bd->state != BOARD_READY)
return NULL;
return bd;
}
static ssize_t dgap_ports_state_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++) {
count += snprintf(buf + count, PAGE_SIZE - count,
"%d %s\n", bd->channels[i]->ch_portnum,
bd->channels[i]->ch_open_count ? "Open" : "Closed");
}
return count;
}
static DEVICE_ATTR(ports_state, S_IRUSR, dgap_ports_state_show, NULL);
static ssize_t dgap_ports_baud_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++) {
count += snprintf(buf + count, PAGE_SIZE - count, "%d %d\n",
bd->channels[i]->ch_portnum,
bd->channels[i]->ch_baud_info);
}
return count;
}
static DEVICE_ATTR(ports_baud, S_IRUSR, dgap_ports_baud_show, NULL);
static ssize_t dgap_ports_msignals_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++) {
if (bd->channels[i]->ch_open_count)
count += snprintf(buf + count, PAGE_SIZE - count,
"%d %s %s %s %s %s %s\n",
bd->channels[i]->ch_portnum,
(bd->channels[i]->ch_mostat &
UART_MCR_RTS) ? "RTS" : "",
(bd->channels[i]->ch_mistat &
UART_MSR_CTS) ? "CTS" : "",
(bd->channels[i]->ch_mostat &
UART_MCR_DTR) ? "DTR" : "",
(bd->channels[i]->ch_mistat &
UART_MSR_DSR) ? "DSR" : "",
(bd->channels[i]->ch_mistat &
UART_MSR_DCD) ? "DCD" : "",
(bd->channels[i]->ch_mistat &
UART_MSR_RI) ? "RI" : "");
else
count += snprintf(buf + count, PAGE_SIZE - count,
"%d\n", bd->channels[i]->ch_portnum);
}
return count;
}
static DEVICE_ATTR(ports_msignals, S_IRUSR, dgap_ports_msignals_show, NULL);
static ssize_t dgap_ports_iflag_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++)
count += snprintf(buf + count, PAGE_SIZE - count, "%d %x\n",
bd->channels[i]->ch_portnum,
bd->channels[i]->ch_c_iflag);
return count;
}
static DEVICE_ATTR(ports_iflag, S_IRUSR, dgap_ports_iflag_show, NULL);
static ssize_t dgap_ports_cflag_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++)
count += snprintf(buf + count, PAGE_SIZE - count, "%d %x\n",
bd->channels[i]->ch_portnum,
bd->channels[i]->ch_c_cflag);
return count;
}
static DEVICE_ATTR(ports_cflag, S_IRUSR, dgap_ports_cflag_show, NULL);
static ssize_t dgap_ports_oflag_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++)
count += snprintf(buf + count, PAGE_SIZE - count, "%d %x\n",
bd->channels[i]->ch_portnum,
bd->channels[i]->ch_c_oflag);
return count;
}
static DEVICE_ATTR(ports_oflag, S_IRUSR, dgap_ports_oflag_show, NULL);
static ssize_t dgap_ports_lflag_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++)
count += snprintf(buf + count, PAGE_SIZE - count, "%d %x\n",
bd->channels[i]->ch_portnum,
bd->channels[i]->ch_c_lflag);
return count;
}
static DEVICE_ATTR(ports_lflag, S_IRUSR, dgap_ports_lflag_show, NULL);
static ssize_t dgap_ports_digi_flag_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++)
count += snprintf(buf + count, PAGE_SIZE - count, "%d %x\n",
bd->channels[i]->ch_portnum,
bd->channels[i]->ch_digi.digi_flags);
return count;
}
static DEVICE_ATTR(ports_digi_flag, S_IRUSR, dgap_ports_digi_flag_show, NULL);
static ssize_t dgap_ports_rxcount_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++)
count += snprintf(buf + count, PAGE_SIZE - count, "%d %ld\n",
bd->channels[i]->ch_portnum,
bd->channels[i]->ch_rxcount);
return count;
}
static DEVICE_ATTR(ports_rxcount, S_IRUSR, dgap_ports_rxcount_show, NULL);
static ssize_t dgap_ports_txcount_show(struct device *p,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
int count = 0;
unsigned int i;
bd = dgap_verify_board(p);
if (!bd)
return 0;
for (i = 0; i < bd->nasync; i++)
count += snprintf(buf + count, PAGE_SIZE - count, "%d %ld\n",
bd->channels[i]->ch_portnum,
bd->channels[i]->ch_txcount);
return count;
}
static DEVICE_ATTR(ports_txcount, S_IRUSR, dgap_ports_txcount_show, NULL);
static ssize_t dgap_tty_state_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
return snprintf(buf, PAGE_SIZE, "%s", un->un_open_count ?
"Open" : "Closed");
}
static DEVICE_ATTR(state, S_IRUSR, dgap_tty_state_show, NULL);
static ssize_t dgap_tty_baud_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
return snprintf(buf, PAGE_SIZE, "%d\n", ch->ch_baud_info);
}
static DEVICE_ATTR(baud, S_IRUSR, dgap_tty_baud_show, NULL);
static ssize_t dgap_tty_msignals_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
if (ch->ch_open_count) {
return snprintf(buf, PAGE_SIZE, "%s %s %s %s %s %s\n",
(ch->ch_mostat & UART_MCR_RTS) ? "RTS" : "",
(ch->ch_mistat & UART_MSR_CTS) ? "CTS" : "",
(ch->ch_mostat & UART_MCR_DTR) ? "DTR" : "",
(ch->ch_mistat & UART_MSR_DSR) ? "DSR" : "",
(ch->ch_mistat & UART_MSR_DCD) ? "DCD" : "",
(ch->ch_mistat & UART_MSR_RI) ? "RI" : "");
}
return 0;
}
static DEVICE_ATTR(msignals, S_IRUSR, dgap_tty_msignals_show, NULL);
static ssize_t dgap_tty_iflag_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
return snprintf(buf, PAGE_SIZE, "%x\n", ch->ch_c_iflag);
}
static DEVICE_ATTR(iflag, S_IRUSR, dgap_tty_iflag_show, NULL);
static ssize_t dgap_tty_cflag_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
return snprintf(buf, PAGE_SIZE, "%x\n", ch->ch_c_cflag);
}
static DEVICE_ATTR(cflag, S_IRUSR, dgap_tty_cflag_show, NULL);
static ssize_t dgap_tty_oflag_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
return snprintf(buf, PAGE_SIZE, "%x\n", ch->ch_c_oflag);
}
static DEVICE_ATTR(oflag, S_IRUSR, dgap_tty_oflag_show, NULL);
static ssize_t dgap_tty_lflag_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
return snprintf(buf, PAGE_SIZE, "%x\n", ch->ch_c_lflag);
}
static DEVICE_ATTR(lflag, S_IRUSR, dgap_tty_lflag_show, NULL);
static ssize_t dgap_tty_digi_flag_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
return snprintf(buf, PAGE_SIZE, "%x\n", ch->ch_digi.digi_flags);
}
static DEVICE_ATTR(digi_flag, S_IRUSR, dgap_tty_digi_flag_show, NULL);
static ssize_t dgap_tty_rxcount_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
return snprintf(buf, PAGE_SIZE, "%ld\n", ch->ch_rxcount);
}
static DEVICE_ATTR(rxcount, S_IRUSR, dgap_tty_rxcount_show, NULL);
static ssize_t dgap_tty_txcount_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
return snprintf(buf, PAGE_SIZE, "%ld\n", ch->ch_txcount);
}
static DEVICE_ATTR(txcount, S_IRUSR, dgap_tty_txcount_show, NULL);
static ssize_t dgap_tty_name_show(struct device *d,
struct device_attribute *attr,
char *buf)
{
struct board_t *bd;
struct channel_t *ch;
struct un_t *un;
int cn;
int bn;
struct cnode *cptr;
int found = FALSE;
int ncount = 0;
int starto = 0;
int i;
if (!d)
return 0;
un = dev_get_drvdata(d);
if (!un || un->magic != DGAP_UNIT_MAGIC)
return 0;
ch = un->un_ch;
if (!ch || ch->magic != DGAP_CHANNEL_MAGIC)
return 0;
bd = ch->ch_bd;
if (!bd || bd->magic != DGAP_BOARD_MAGIC)
return 0;
if (bd->state != BOARD_READY)
return 0;
bn = bd->boardnum;
cn = ch->ch_portnum;
for (cptr = bd->bd_config; cptr; cptr = cptr->next) {
if ((cptr->type == BNODE) &&
((cptr->u.board.type == APORT2_920P) ||
(cptr->u.board.type == APORT4_920P) ||
(cptr->u.board.type == APORT8_920P) ||
(cptr->u.board.type == PAPORT4) ||
(cptr->u.board.type == PAPORT8))) {
found = TRUE;
if (cptr->u.board.v_start)
starto = cptr->u.board.start;
else
starto = 1;
}
if (cptr->type == TNODE && found == TRUE) {
char *ptr1;
if (strstr(cptr->u.ttyname, "tty")) {
ptr1 = cptr->u.ttyname;
ptr1 += 3;
} else
ptr1 = cptr->u.ttyname;
for (i = 0; i < dgap_config_get_num_prts(bd); i++) {
if (cn != i)
continue;
return snprintf(buf, PAGE_SIZE, "%s%s%02d\n",
(un->un_type == DGAP_PRINT) ?
"pr" : "tty",
ptr1, i + starto);
}
}
if (cptr->type == CNODE) {
for (i = 0; i < cptr->u.conc.nport; i++) {
if (cn != (i + ncount))
continue;
return snprintf(buf, PAGE_SIZE, "%s%s%02ld\n",
(un->un_type == DGAP_PRINT) ?
"pr" : "tty",
cptr->u.conc.id,
i + (cptr->u.conc.v_start ?
cptr->u.conc.start : 1));
}
ncount += cptr->u.conc.nport;
}
if (cptr->type == MNODE) {
for (i = 0; i < cptr->u.module.nport; i++) {
if (cn != (i + ncount))
continue;
return snprintf(buf, PAGE_SIZE, "%s%s%02ld\n",
(un->un_type == DGAP_PRINT) ?
"pr" : "tty",
cptr->u.module.id,
i + (cptr->u.module.v_start ?
cptr->u.module.start : 1));
}
ncount += cptr->u.module.nport;
}
}
return snprintf(buf, PAGE_SIZE, "%s_dgap_%d_%d\n",
(un->un_type == DGAP_PRINT) ? "pr" : "tty", bn, cn);
}
static DEVICE_ATTR(custom_name, S_IRUSR, dgap_tty_name_show, NULL);
static struct attribute *dgap_sysfs_tty_entries[] = {
&dev_attr_state.attr,
&dev_attr_baud.attr,
&dev_attr_msignals.attr,
&dev_attr_iflag.attr,
&dev_attr_cflag.attr,
&dev_attr_oflag.attr,
&dev_attr_lflag.attr,
&dev_attr_digi_flag.attr,
&dev_attr_rxcount.attr,
&dev_attr_txcount.attr,
&dev_attr_custom_name.attr,
NULL
};
/* this function creates the sys files that will export each signal status
* to sysfs each value will be put in a separate filename
*/
static void dgap_create_ports_sysfiles(struct board_t *bd)
{
dev_set_drvdata(&bd->pdev->dev, bd);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_state);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_baud);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_msignals);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_iflag);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_cflag);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_oflag);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_lflag);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_digi_flag);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_rxcount);
device_create_file(&(bd->pdev->dev), &dev_attr_ports_txcount);
}
/* removes all the sys files created for that port */
static void dgap_remove_ports_sysfiles(struct board_t *bd)
{
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_state);
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_baud);
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_msignals);
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_iflag);
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_cflag);
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_oflag);
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_lflag);
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_digi_flag);
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_rxcount);
device_remove_file(&(bd->pdev->dev), &dev_attr_ports_txcount);
}
/*
* Copies the BIOS code from the user to the board,
* and starts the BIOS running.
*/
static void dgap_do_bios_load(struct board_t *brd, const u8 *ubios, int len)
{
u8 __iomem *addr;
uint offset;
unsigned int i;
if (!brd || (brd->magic != DGAP_BOARD_MAGIC) || !brd->re_map_membase)
return;
addr = brd->re_map_membase;
/*
* clear POST area
*/
for (i = 0; i < 16; i++)
writeb(0, addr + POSTAREA + i);
/*
* Download bios
*/
offset = 0x1000;
memcpy_toio(addr + offset, ubios, len);
writel(0x0bf00401, addr);
writel(0, (addr + 4));
/* Clear the reset, and change states. */
writeb(FEPCLR, brd->re_map_port);
}
/*
* Checks to see if the BIOS completed running on the card.
*/
static int dgap_test_bios(struct board_t *brd)
{
u8 __iomem *addr;
u16 word;
u16 err1;
u16 err2;
if (!brd || (brd->magic != DGAP_BOARD_MAGIC) || !brd->re_map_membase)
return -EINVAL;
addr = brd->re_map_membase;
word = readw(addr + POSTAREA);
/*
* It can take 5-6 seconds for a board to
* pass the bios self test and post results.
* Give it 10 seconds.
*/
brd->wait_for_bios = 0;
while (brd->wait_for_bios < 1000) {
/* Check to see if BIOS thinks board is good. (GD). */
if (word == *(u16 *) "GD")
return 0;
msleep_interruptible(10);
brd->wait_for_bios++;
word = readw(addr + POSTAREA);
}
/* Gave up on board after too long of time taken */
err1 = readw(addr + SEQUENCE);
err2 = readw(addr + ERROR);
dev_warn(&brd->pdev->dev, "%s failed diagnostics. Error #(%x,%x).\n",
brd->name, err1, err2);
brd->state = BOARD_FAILED;
brd->dpastatus = BD_NOBIOS;
return -EIO;
}
/*
* Copies the FEP code from the user to the board,
* and starts the FEP running.
*/
static void dgap_do_fep_load(struct board_t *brd, const u8 *ufep, int len)
{
u8 __iomem *addr;
uint offset;
if (!brd || (brd->magic != DGAP_BOARD_MAGIC) || !brd->re_map_membase)
return;
addr = brd->re_map_membase;
/*
* Download FEP
*/
offset = 0x1000;
memcpy_toio(addr + offset, ufep, len);
/*
* If board is a concentrator product, we need to give
* it its config string describing how the concentrators look.
*/
if ((brd->type == PCX) || (brd->type == PEPC)) {
u8 string[100];
u8 __iomem *config;
u8 *xconfig;
unsigned int i = 0;
xconfig = dgap_create_config_string(brd, string);
/* Write string to board memory */
config = addr + CONFIG;
for (; i < CONFIGSIZE; i++, config++, xconfig++) {
writeb(*xconfig, config);
if ((*xconfig & 0xff) == 0xff)
break;
}
}
writel(0xbfc01004, (addr + 0xc34));
writel(0x3, (addr + 0xc30));
}
/*
* Waits for the FEP to report thats its ready for us to use.
*/
static int dgap_test_fep(struct board_t *brd)
{
u8 __iomem *addr;
u16 word;
u16 err1;
u16 err2;
if (!brd || (brd->magic != DGAP_BOARD_MAGIC) || !brd->re_map_membase)
return -EINVAL;
addr = brd->re_map_membase;
word = readw(addr + FEPSTAT);
/*
* It can take 2-3 seconds for the FEP to
* be up and running. Give it 5 secs.
*/
brd->wait_for_fep = 0;
while (brd->wait_for_fep < 500) {
/* Check to see if FEP is up and running now. */
if (word == *(u16 *) "OS") {
/*
* Check to see if the board can support FEP5+ commands.
*/
word = readw(addr + FEP5_PLUS);
if (word == *(u16 *) "5A")
brd->bd_flags |= BD_FEP5PLUS;
return 0;
}
msleep_interruptible(10);
brd->wait_for_fep++;
word = readw(addr + FEPSTAT);
}
/* Gave up on board after too long of time taken */
err1 = readw(addr + SEQUENCE);
err2 = readw(addr + ERROR);
dev_warn(&brd->pdev->dev,
"FEPOS for %s not functioning. Error #(%x,%x).\n",
brd->name, err1, err2);
brd->state = BOARD_FAILED;
brd->dpastatus = BD_NOFEP;
return -EIO;
}
/*
* Physically forces the FEP5 card to reset itself.
*/
static void dgap_do_reset_board(struct board_t *brd)
{
u8 check;
u32 check1;
u32 check2;
unsigned int i;
if (!brd || (brd->magic != DGAP_BOARD_MAGIC) ||
!brd->re_map_membase || !brd->re_map_port)
return;
/* FEPRST does not vary among supported boards */
writeb(FEPRST, brd->re_map_port);
for (i = 0; i <= 1000; i++) {
check = readb(brd->re_map_port) & 0xe;
if (check == FEPRST)
break;
udelay(10);
}
if (i > 1000) {
dev_warn(&brd->pdev->dev,
"dgap: Board not resetting... Failing board.\n");
brd->state = BOARD_FAILED;
brd->dpastatus = BD_NOFEP;
return;
}
/*
* Make sure there really is memory out there.
*/
writel(0xa55a3cc3, (brd->re_map_membase + LOWMEM));
writel(0x5aa5c33c, (brd->re_map_membase + HIGHMEM));
check1 = readl(brd->re_map_membase + LOWMEM);
check2 = readl(brd->re_map_membase + HIGHMEM);
if ((check1 != 0xa55a3cc3) || (check2 != 0x5aa5c33c)) {
dev_warn(&brd->pdev->dev,
"No memory at %p for board.\n",
brd->re_map_membase);
brd->state = BOARD_FAILED;
brd->dpastatus = BD_NOFEP;
return;
}
}
#ifdef DIGI_CONCENTRATORS_SUPPORTED
/*
* Sends a concentrator image into the FEP5 board.
*/
static void dgap_do_conc_load(struct board_t *brd, u8 *uaddr, int len)
{
char __iomem *vaddr;
u16 offset;
struct downld_t *to_dp;
if (!brd || (brd->magic != DGAP_BOARD_MAGIC) || !brd->re_map_membase)
return;
vaddr = brd->re_map_membase;
offset = readw((u16 *) (vaddr + DOWNREQ));
to_dp = (struct downld_t *) (vaddr + (int) offset);
memcpy_toio(to_dp, uaddr, len);
/* Tell card we have data for it */
writew(0, vaddr + (DOWNREQ));
brd->conc_dl_status = NO_PENDING_CONCENTRATOR_REQUESTS;
}
#endif
#define EXPANSION_ROM_SIZE (64 * 1024)
#define FEP5_ROM_MAGIC (0xFEFFFFFF)
static void dgap_get_vpd(struct board_t *brd)
{
u32 magic;
u32 base_offset;
u16 rom_offset;
u16 vpd_offset;
u16 image_length;
u16 i;
u8 byte1;
u8 byte2;
/*
* Poke the magic number at the PCI Rom Address location.
* If VPD is supported, the value read from that address
* will be non-zero.
*/
magic = FEP5_ROM_MAGIC;
pci_write_config_dword(brd->pdev, PCI_ROM_ADDRESS, magic);
pci_read_config_dword(brd->pdev, PCI_ROM_ADDRESS, &magic);
/* VPD not supported, bail */
if (!magic)
return;
/*
* To get to the OTPROM memory, we have to send the boards base
* address or'ed with 1 into the PCI Rom Address location.
*/
magic = brd->membase | 0x01;
pci_write_config_dword(brd->pdev, PCI_ROM_ADDRESS, magic);
pci_read_config_dword(brd->pdev, PCI_ROM_ADDRESS, &magic);
byte1 = readb(brd->re_map_membase);
byte2 = readb(brd->re_map_membase + 1);
/*
* If the board correctly swapped to the OTPROM memory,
* the first 2 bytes (header) should be 0x55, 0xAA
*/
if (byte1 == 0x55 && byte2 == 0xAA) {
base_offset = 0;
/*
* We have to run through all the OTPROM memory looking
* for the VPD offset.
*/
while (base_offset <= EXPANSION_ROM_SIZE) {
/*
* Lots of magic numbers here.
*
* The VPD offset is located inside the ROM Data
* Structure.
*
* We also have to remember the length of each
* ROM Data Structure, so we can "hop" to the next
* entry if the VPD isn't in the current
* ROM Data Structure.
*/
rom_offset = readw(brd->re_map_membase +
base_offset + 0x18);
image_length = readw(brd->re_map_membase +
rom_offset + 0x10) * 512;
vpd_offset = readw(brd->re_map_membase +
rom_offset + 0x08);
/* Found the VPD entry */
if (vpd_offset)
break;
/* We didn't find a VPD entry, go to next ROM entry. */
base_offset += image_length;
byte1 = readb(brd->re_map_membase + base_offset);
byte2 = readb(brd->re_map_membase + base_offset + 1);
/*
* If the new ROM offset doesn't have 0x55, 0xAA
* as its header, we have run out of ROM.
*/
if (byte1 != 0x55 || byte2 != 0xAA)
break;
}
/*
* If we have a VPD offset, then mark the board
* as having a valid VPD, and copy VPDSIZE (512) bytes of
* that VPD to the buffer we have in our board structure.
*/
if (vpd_offset) {
brd->bd_flags |= BD_HAS_VPD;
for (i = 0; i < VPDSIZE; i++) {
brd->vpd[i] = readb(brd->re_map_membase +
vpd_offset + i);
}
}
}
/*
* We MUST poke the magic number at the PCI Rom Address location again.
* This makes the card report the regular board memory back to us,
* rather than the OTPROM memory.
*/
magic = FEP5_ROM_MAGIC;
pci_write_config_dword(brd->pdev, PCI_ROM_ADDRESS, magic);
}
static ssize_t dgap_driver_version_show(struct device_driver *ddp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", DG_PART);
}
static DRIVER_ATTR(version, S_IRUSR, dgap_driver_version_show, NULL);
static ssize_t dgap_driver_boards_show(struct device_driver *ddp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", dgap_numboards);
}
static DRIVER_ATTR(boards, S_IRUSR, dgap_driver_boards_show, NULL);
static ssize_t dgap_driver_maxboards_show(struct device_driver *ddp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", MAXBOARDS);
}
static DRIVER_ATTR(maxboards, S_IRUSR, dgap_driver_maxboards_show, NULL);
static ssize_t dgap_driver_pollcounter_show(struct device_driver *ddp,
char *buf)
{
return snprintf(buf, PAGE_SIZE, "%ld\n", dgap_poll_counter);
}
static DRIVER_ATTR(pollcounter, S_IRUSR, dgap_driver_pollcounter_show, NULL);
static ssize_t dgap_driver_pollrate_show(struct device_driver *ddp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%dms\n", dgap_poll_tick);
}
static ssize_t dgap_driver_pollrate_store(struct device_driver *ddp,
const char *buf, size_t count)
{
if (sscanf(buf, "%d\n", &dgap_poll_tick) != 1)
return -EINVAL;
return count;
}
static DRIVER_ATTR(pollrate, (S_IRUSR | S_IWUSR), dgap_driver_pollrate_show,
dgap_driver_pollrate_store);
static int dgap_create_driver_sysfiles(struct pci_driver *dgap_driver)
{
int rc = 0;
struct device_driver *driverfs = &dgap_driver->driver;
rc |= driver_create_file(driverfs, &driver_attr_version);
rc |= driver_create_file(driverfs, &driver_attr_boards);
rc |= driver_create_file(driverfs, &driver_attr_maxboards);
rc |= driver_create_file(driverfs, &driver_attr_pollrate);
rc |= driver_create_file(driverfs, &driver_attr_pollcounter);
return rc;
}
static void dgap_remove_driver_sysfiles(struct pci_driver *dgap_driver)
{
struct device_driver *driverfs = &dgap_driver->driver;
driver_remove_file(driverfs, &driver_attr_version);
driver_remove_file(driverfs, &driver_attr_boards);
driver_remove_file(driverfs, &driver_attr_maxboards);
driver_remove_file(driverfs, &driver_attr_pollrate);
driver_remove_file(driverfs, &driver_attr_pollcounter);
}
static struct attribute_group dgap_tty_attribute_group = {
.name = NULL,
.attrs = dgap_sysfs_tty_entries,
};
static void dgap_create_tty_sysfs(struct un_t *un, struct device *c)
{
int ret;
ret = sysfs_create_group(&c->kobj, &dgap_tty_attribute_group);
if (ret)
return;
dev_set_drvdata(c, un);
}
static void dgap_remove_tty_sysfs(struct device *c)
{
sysfs_remove_group(&c->kobj, &dgap_tty_attribute_group);
}
/*
* Create pr and tty device entries
*/
static int dgap_tty_register_ports(struct board_t *brd)
{
struct channel_t *ch;
int i;
int ret;
brd->serial_ports = kcalloc(brd->nasync, sizeof(*brd->serial_ports),
GFP_KERNEL);
if (!brd->serial_ports)
return -ENOMEM;
brd->printer_ports = kcalloc(brd->nasync, sizeof(*brd->printer_ports),
GFP_KERNEL);
if (!brd->printer_ports) {
ret = -ENOMEM;
goto free_serial_ports;
}
for (i = 0; i < brd->nasync; i++) {
tty_port_init(&brd->serial_ports[i]);
tty_port_init(&brd->printer_ports[i]);
}
ch = brd->channels[0];
for (i = 0; i < brd->nasync; i++, ch = brd->channels[i]) {
struct device *classp;
classp = tty_port_register_device(&brd->serial_ports[i],
brd->serial_driver,
i, NULL);
if (IS_ERR(classp)) {
ret = PTR_ERR(classp);
goto unregister_ttys;
}
dgap_create_tty_sysfs(&ch->ch_tun, classp);
ch->ch_tun.un_sysfs = classp;
classp = tty_port_register_device(&brd->printer_ports[i],
brd->print_driver,
i, NULL);
if (IS_ERR(classp)) {
ret = PTR_ERR(classp);
goto unregister_ttys;
}
dgap_create_tty_sysfs(&ch->ch_pun, classp);
ch->ch_pun.un_sysfs = classp;
}
dgap_create_ports_sysfiles(brd);
return 0;
unregister_ttys:
while (i >= 0) {
ch = brd->channels[i];
if (ch->ch_tun.un_sysfs) {
dgap_remove_tty_sysfs(ch->ch_tun.un_sysfs);
tty_unregister_device(brd->serial_driver, i);
}
if (ch->ch_pun.un_sysfs) {
dgap_remove_tty_sysfs(ch->ch_pun.un_sysfs);
tty_unregister_device(brd->print_driver, i);
}
i--;
}
for (i = 0; i < brd->nasync; i++) {
tty_port_destroy(&brd->serial_ports[i]);
tty_port_destroy(&brd->printer_ports[i]);
}
kfree(brd->printer_ports);
brd->printer_ports = NULL;
free_serial_ports:
kfree(brd->serial_ports);
brd->serial_ports = NULL;
return ret;
}
/*
* dgap_cleanup_tty()
*
* Uninitialize the TTY portion of this driver. Free all memory and
* resources.
*/
static void dgap_cleanup_tty(struct board_t *brd)
{
struct device *dev;
unsigned int i;
for (i = 0; i < brd->nasync; i++) {
tty_port_destroy(&brd->serial_ports[i]);
dev = brd->channels[i]->ch_tun.un_sysfs;
dgap_remove_tty_sysfs(dev);
tty_unregister_device(brd->serial_driver, i);
}
tty_unregister_driver(brd->serial_driver);
put_tty_driver(brd->serial_driver);
kfree(brd->serial_ports);
for (i = 0; i < brd->nasync; i++) {
tty_port_destroy(&brd->printer_ports[i]);
dev = brd->channels[i]->ch_pun.un_sysfs;
dgap_remove_tty_sysfs(dev);
tty_unregister_device(brd->print_driver, i);
}
tty_unregister_driver(brd->print_driver);
put_tty_driver(brd->print_driver);
kfree(brd->printer_ports);
}
static int dgap_request_irq(struct board_t *brd)
{
int rc;
if (!brd || brd->magic != DGAP_BOARD_MAGIC)
return -ENODEV;
/*
* Set up our interrupt handler if we are set to do interrupts.
*/
if (dgap_config_get_useintr(brd) && brd->irq) {
rc = request_irq(brd->irq, dgap_intr, IRQF_SHARED, "DGAP", brd);
if (!rc)
brd->intr_used = 1;
}
return 0;
}
static void dgap_free_irq(struct board_t *brd)
{
if (brd->intr_used && brd->irq)
free_irq(brd->irq, brd);
}
static int dgap_firmware_load(struct pci_dev *pdev, int card_type,
struct board_t *brd)
{
const struct firmware *fw;
char *tmp_ptr;
int ret;
char *dgap_config_buf;
dgap_get_vpd(brd);
dgap_do_reset_board(brd);
if (fw_info[card_type].conf_name) {
ret = request_firmware(&fw, fw_info[card_type].conf_name,
&pdev->dev);
if (ret) {
dev_err(&pdev->dev, "config file %s not found\n",
fw_info[card_type].conf_name);
return ret;
}
dgap_config_buf = kzalloc(fw->size + 1, GFP_KERNEL);
if (!dgap_config_buf) {
release_firmware(fw);
return -ENOMEM;
}
memcpy(dgap_config_buf, fw->data, fw->size);
release_firmware(fw);
/*
* preserve dgap_config_buf
* as dgap_parsefile would
* otherwise alter it.
*/
tmp_ptr = dgap_config_buf;
if (dgap_parsefile(&tmp_ptr) != 0) {
kfree(dgap_config_buf);
return -EINVAL;
}
kfree(dgap_config_buf);
}
/*
* Match this board to a config the user created for us.
*/
brd->bd_config =
dgap_find_config(brd->type, brd->pci_bus, brd->pci_slot);
/*
* Because the 4 port Xr products share the same PCI ID
* as the 8 port Xr products, if we receive a NULL config
* back, and this is a PAPORT8 board, retry with a
* PAPORT4 attempt as well.
*/
if (brd->type == PAPORT8 && !brd->bd_config)
brd->bd_config =
dgap_find_config(PAPORT4, brd->pci_bus, brd->pci_slot);
if (!brd->bd_config) {
dev_err(&pdev->dev, "No valid configuration found\n");
return -EINVAL;
}
if (fw_info[card_type].bios_name) {
ret = request_firmware(&fw, fw_info[card_type].bios_name,
&pdev->dev);
if (ret) {
dev_err(&pdev->dev, "bios file %s not found\n",
fw_info[card_type].bios_name);
return ret;
}
dgap_do_bios_load(brd, fw->data, fw->size);
release_firmware(fw);
/* Wait for BIOS to test board... */
ret = dgap_test_bios(brd);
if (ret)
return ret;
}
if (fw_info[card_type].fep_name) {
ret = request_firmware(&fw, fw_info[card_type].fep_name,
&pdev->dev);
if (ret) {
dev_err(&pdev->dev, "dgap: fep file %s not found\n",
fw_info[card_type].fep_name);
return ret;
}
dgap_do_fep_load(brd, fw->data, fw->size);
release_firmware(fw);
/* Wait for FEP to load on board... */
ret = dgap_test_fep(brd);
if (ret)
return ret;
}
#ifdef DIGI_CONCENTRATORS_SUPPORTED
/*
* If this is a CX or EPCX, we need to see if the firmware
* is requesting a concentrator image from us.
*/
if ((bd->type == PCX) || (bd->type == PEPC)) {
chk_addr = (u16 *) (vaddr + DOWNREQ);
/* Nonzero if FEP is requesting concentrator image. */
check = readw(chk_addr);
vaddr = brd->re_map_membase;
}
if (fw_info[card_type].con_name && check && vaddr) {
ret = request_firmware(&fw, fw_info[card_type].con_name,
&pdev->dev);
if (ret) {
dev_err(&pdev->dev, "conc file %s not found\n",
fw_info[card_type].con_name);
return ret;
}
/* Put concentrator firmware loading code here */
offset = readw((u16 *) (vaddr + DOWNREQ));
memcpy_toio(offset, fw->data, fw->size);
dgap_do_conc_load(brd, (char *)fw->data, fw->size)
release_firmware(fw);
}
#endif
return 0;
}
/*
* dgap_tty_init()
*
* Init the tty subsystem. Called once per board after board has been
* downloaded and init'ed.
*/
static int dgap_tty_init(struct board_t *brd)
{
int i;
int tlw;
uint true_count;
u8 __iomem *vaddr;
u8 modem;
struct channel_t *ch;
struct bs_t __iomem *bs;
struct cm_t __iomem *cm;
int ret;
/*
* Initialize board structure elements.
*/
vaddr = brd->re_map_membase;
true_count = readw((vaddr + NCHAN));
brd->nasync = dgap_config_get_num_prts(brd);
if (!brd->nasync)
brd->nasync = brd->maxports;
if (brd->nasync > brd->maxports)
brd->nasync = brd->maxports;
if (true_count != brd->nasync) {
dev_warn(&brd->pdev->dev,
"%s configured for %d ports, has %d ports.\n",
brd->name, brd->nasync, true_count);
if ((brd->type == PPCM) &&
(true_count == 64 || true_count == 0)) {
dev_warn(&brd->pdev->dev,
"Please make SURE the EBI cable running from the card\n");
dev_warn(&brd->pdev->dev,
"to each EM module is plugged into EBI IN!\n");
}
brd->nasync = true_count;
/* If no ports, don't bother going any further */
if (!brd->nasync) {
brd->state = BOARD_FAILED;
brd->dpastatus = BD_NOFEP;
return -EIO;
}
}
/*
* Allocate channel memory that might not have been allocated
* when the driver was first loaded.
*/
for (i = 0; i < brd->nasync; i++) {
brd->channels[i] =
kzalloc(sizeof(struct channel_t), GFP_KERNEL);
if (!brd->channels[i]) {
ret = -ENOMEM;
goto free_chan;
}
}
ch = brd->channels[0];
vaddr = brd->re_map_membase;
bs = (struct bs_t __iomem *) ((ulong) vaddr + CHANBUF);
cm = (struct cm_t __iomem *) ((ulong) vaddr + CMDBUF);
brd->bd_bs = bs;
/* Set up channel variables */
for (i = 0; i < brd->nasync; i++, ch = brd->channels[i], bs++) {
spin_lock_init(&ch->ch_lock);
/* Store all our magic numbers */
ch->magic = DGAP_CHANNEL_MAGIC;
ch->ch_tun.magic = DGAP_UNIT_MAGIC;
ch->ch_tun.un_type = DGAP_SERIAL;
ch->ch_tun.un_ch = ch;
ch->ch_tun.un_dev = i;
ch->ch_pun.magic = DGAP_UNIT_MAGIC;
ch->ch_pun.un_type = DGAP_PRINT;
ch->ch_pun.un_ch = ch;
ch->ch_pun.un_dev = i;
ch->ch_vaddr = vaddr;
ch->ch_bs = bs;
ch->ch_cm = cm;
ch->ch_bd = brd;
ch->ch_portnum = i;
ch->ch_digi = dgap_digi_init;
/*
* Set up digi dsr and dcd bits based on altpin flag.
*/
if (dgap_config_get_altpin(brd)) {
ch->ch_dsr = DM_CD;
ch->ch_cd = DM_DSR;
ch->ch_digi.digi_flags |= DIGI_ALTPIN;
} else {
ch->ch_cd = DM_CD;
ch->ch_dsr = DM_DSR;
}
ch->ch_taddr = vaddr + (ioread16(&(ch->ch_bs->tx_seg)) << 4);
ch->ch_raddr = vaddr + (ioread16(&(ch->ch_bs->rx_seg)) << 4);
ch->ch_tx_win = 0;
ch->ch_rx_win = 0;
ch->ch_tsize = readw(&(ch->ch_bs->tx_max)) + 1;
ch->ch_rsize = readw(&(ch->ch_bs->rx_max)) + 1;
ch->ch_tstart = 0;
ch->ch_rstart = 0;
/*
* Set queue water marks, interrupt mask,
* and general tty parameters.
*/
tlw = ch->ch_tsize >= 2000 ? ((ch->ch_tsize * 5) / 8) :
ch->ch_tsize / 2;
ch->ch_tlw = tlw;
dgap_cmdw(ch, STLOW, tlw, 0);
dgap_cmdw(ch, SRLOW, ch->ch_rsize / 2, 0);
dgap_cmdw(ch, SRHIGH, 7 * ch->ch_rsize / 8, 0);
ch->ch_mistat = readb(&(ch->ch_bs->m_stat));
init_waitqueue_head(&ch->ch_flags_wait);
init_waitqueue_head(&ch->ch_tun.un_flags_wait);
init_waitqueue_head(&ch->ch_pun.un_flags_wait);
/* Turn on all modem interrupts for now */
modem = (DM_CD | DM_DSR | DM_CTS | DM_RI);
writeb(modem, &(ch->ch_bs->m_int));
/*
* Set edelay to 0 if interrupts are turned on,
* otherwise set edelay to the usual 100.
*/
if (brd->intr_used)
writew(0, &(ch->ch_bs->edelay));
else
writew(100, &(ch->ch_bs->edelay));
writeb(1, &(ch->ch_bs->idata));
}
return 0;
free_chan:
while (--i >= 0) {
kfree(brd->channels[i]);
brd->channels[i] = NULL;
}
return ret;
}
/*
* dgap_tty_free()
*
* Free the channles which are allocated in dgap_tty_init().
*/
static void dgap_tty_free(struct board_t *brd)
{
int i;
for (i = 0; i < brd->nasync; i++)
kfree(brd->channels[i]);
}
static int dgap_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int rc;
struct board_t *brd;
if (dgap_numboards >= MAXBOARDS)
return -EPERM;
rc = pci_enable_device(pdev);
if (rc)
return -EIO;
brd = dgap_found_board(pdev, ent->driver_data, dgap_numboards);
if (IS_ERR(brd))
return PTR_ERR(brd);
rc = dgap_firmware_load(pdev, ent->driver_data, brd);
if (rc)
goto cleanup_brd;
rc = dgap_alloc_flipbuf(brd);
if (rc)
goto cleanup_brd;
rc = dgap_tty_register(brd);
if (rc)
goto free_flipbuf;
rc = dgap_request_irq(brd);
if (rc)
goto unregister_tty;
/*
* Do tty device initialization.
*/
rc = dgap_tty_init(brd);
if (rc < 0)
goto free_irq;
rc = dgap_tty_register_ports(brd);
if (rc)
goto tty_free;
brd->state = BOARD_READY;
brd->dpastatus = BD_RUNNING;
dgap_board[dgap_numboards++] = brd;
return 0;
tty_free:
dgap_tty_free(brd);
free_irq:
dgap_free_irq(brd);
unregister_tty:
dgap_tty_unregister(brd);
free_flipbuf:
dgap_free_flipbuf(brd);
cleanup_brd:
dgap_cleanup_nodes();
dgap_unmap(brd);
kfree(brd);
return rc;
}
static void dgap_remove_one(struct pci_dev *dev)
{
/* Do Nothing */
}
static struct pci_driver dgap_driver = {
.name = "dgap",
.probe = dgap_init_one,
.id_table = dgap_pci_tbl,
.remove = dgap_remove_one,
};
/*
* Start of driver.
*/
static int dgap_start(void)
{
int rc;
unsigned long flags;
struct device *device;
dgap_numboards = 0;
pr_info("For the tools package please visit http://www.digi.com\n");
/*
* Register our base character device into the kernel.
*/
/*
* Register management/dpa devices
*/
rc = register_chrdev(DIGI_DGAP_MAJOR, "dgap", &dgap_board_fops);
if (rc < 0)
return rc;
dgap_class = class_create(THIS_MODULE, "dgap_mgmt");
if (IS_ERR(dgap_class)) {
rc = PTR_ERR(dgap_class);
goto failed_class;
}
device = device_create(dgap_class, NULL,
MKDEV(DIGI_DGAP_MAJOR, 0),
NULL, "dgap_mgmt");
if (IS_ERR(device)) {
rc = PTR_ERR(device);
goto failed_device;
}
/* Start the poller */
spin_lock_irqsave(&dgap_poll_lock, flags);
init_timer(&dgap_poll_timer);
dgap_poll_timer.function = dgap_poll_handler;
dgap_poll_timer.data = 0;
dgap_poll_time = jiffies + dgap_jiffies_from_ms(dgap_poll_tick);
dgap_poll_timer.expires = dgap_poll_time;
spin_unlock_irqrestore(&dgap_poll_lock, flags);
add_timer(&dgap_poll_timer);
return rc;
failed_device:
class_destroy(dgap_class);
failed_class:
unregister_chrdev(DIGI_DGAP_MAJOR, "dgap");
return rc;
}
static void dgap_stop(void)
{
unsigned long lock_flags;
spin_lock_irqsave(&dgap_poll_lock, lock_flags);
dgap_poll_stop = 1;
spin_unlock_irqrestore(&dgap_poll_lock, lock_flags);
del_timer_sync(&dgap_poll_timer);
device_destroy(dgap_class, MKDEV(DIGI_DGAP_MAJOR, 0));
class_destroy(dgap_class);
unregister_chrdev(DIGI_DGAP_MAJOR, "dgap");
}
/*
* dgap_cleanup_board()
*
* Free all the memory associated with a board
*/
static void dgap_cleanup_board(struct board_t *brd)
{
unsigned int i;
if (!brd || brd->magic != DGAP_BOARD_MAGIC)
return;
dgap_free_irq(brd);
tasklet_kill(&brd->helper_tasklet);
dgap_unmap(brd);
/* Free all allocated channels structs */
for (i = 0; i < MAXPORTS ; i++)
kfree(brd->channels[i]);
kfree(brd->flipbuf);
kfree(brd->flipflagbuf);
dgap_board[brd->boardnum] = NULL;
kfree(brd);
}
/************************************************************************
*
* Driver load/unload functions
*
************************************************************************/
/*
* init_module()
*
* Module load. This is where it all starts.
*/
static int dgap_init_module(void)
{
int rc;
pr_info("%s, Digi International Part Number %s\n", DG_NAME, DG_PART);
rc = dgap_start();
if (rc)
return rc;
rc = pci_register_driver(&dgap_driver);
if (rc)
goto err_stop;
rc = dgap_create_driver_sysfiles(&dgap_driver);
if (rc)
goto err_unregister;
dgap_driver_state = DRIVER_READY;
return 0;
err_unregister:
pci_unregister_driver(&dgap_driver);
err_stop:
dgap_stop();
return rc;
}
/*
* dgap_cleanup_module()
*
* Module unload. This is where it all ends.
*/
static void dgap_cleanup_module(void)
{
unsigned int i;
ulong lock_flags;
spin_lock_irqsave(&dgap_poll_lock, lock_flags);
dgap_poll_stop = 1;
spin_unlock_irqrestore(&dgap_poll_lock, lock_flags);
/* Turn off poller right away. */
del_timer_sync(&dgap_poll_timer);
dgap_remove_driver_sysfiles(&dgap_driver);
device_destroy(dgap_class, MKDEV(DIGI_DGAP_MAJOR, 0));
class_destroy(dgap_class);
unregister_chrdev(DIGI_DGAP_MAJOR, "dgap");
for (i = 0; i < dgap_numboards; ++i) {
dgap_remove_ports_sysfiles(dgap_board[i]);
dgap_cleanup_tty(dgap_board[i]);
dgap_cleanup_board(dgap_board[i]);
}
dgap_cleanup_nodes();
if (dgap_numboards)
pci_unregister_driver(&dgap_driver);
}
module_init(dgap_init_module);
module_exit(dgap_cleanup_module);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Digi International, http://www.digi.com");
MODULE_DESCRIPTION("Driver for the Digi International EPCA PCI based product line");
MODULE_SUPPORTED_DEVICE("dgap");
| gpl-2.0 |
aceofall/linux-kernel | drivers/input/touchscreen/cyttsp_core.c | 77 | 14346 | /*
* Core Source for:
* Cypress TrueTouch(TM) Standard Product (TTSP) touchscreen drivers.
* For use with Cypress Txx3xx parts.
* Supported parts include:
* CY8CTST341
* CY8CTMA340
*
* Copyright (C) 2009, 2010, 2011 Cypress Semiconductor, Inc.
* Copyright (C) 2012 Javier Martinez Canillas <javier@dowhile0.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, 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.
*
* 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.
*
* Contact Cypress Semiconductor at www.cypress.com <kev@cypress.com>
*
*/
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include "cyttsp_core.h"
/* Bootloader number of command keys */
#define CY_NUM_BL_KEYS 8
/* helpers */
#define GET_NUM_TOUCHES(x) ((x) & 0x0F)
#define IS_LARGE_AREA(x) (((x) & 0x10) >> 4)
#define IS_BAD_PKT(x) ((x) & 0x20)
#define IS_VALID_APP(x) ((x) & 0x01)
#define IS_OPERATIONAL_ERR(x) ((x) & 0x3F)
#define GET_HSTMODE(reg) (((reg) & 0x70) >> 4)
#define GET_BOOTLOADERMODE(reg) (((reg) & 0x10) >> 4)
#define CY_REG_BASE 0x00
#define CY_REG_ACT_DIST 0x1E
#define CY_REG_ACT_INTRVL 0x1D
#define CY_REG_TCH_TMOUT (CY_REG_ACT_INTRVL + 1)
#define CY_REG_LP_INTRVL (CY_REG_TCH_TMOUT + 1)
#define CY_MAXZ 255
#define CY_DELAY_DFLT 20 /* ms */
#define CY_DELAY_MAX 500
#define CY_ACT_DIST_DFLT 0xF8
#define CY_HNDSHK_BIT 0x80
/* device mode bits */
#define CY_OPERATE_MODE 0x00
#define CY_SYSINFO_MODE 0x10
/* power mode select bits */
#define CY_SOFT_RESET_MODE 0x01 /* return to Bootloader mode */
#define CY_DEEP_SLEEP_MODE 0x02
#define CY_LOW_POWER_MODE 0x04
/* Slots management */
#define CY_MAX_FINGER 4
#define CY_MAX_ID 16
static const u8 bl_command[] = {
0x00, /* file offset */
0xFF, /* command */
0xA5, /* exit bootloader command */
0, 1, 2, 3, 4, 5, 6, 7 /* default keys */
};
static int ttsp_read_block_data(struct cyttsp *ts, u8 command,
u8 length, void *buf)
{
int error;
int tries;
for (tries = 0; tries < CY_NUM_RETRY; tries++) {
error = ts->bus_ops->read(ts->dev, ts->xfer_buf, command,
length, buf);
if (!error)
return 0;
msleep(CY_DELAY_DFLT);
}
return -EIO;
}
static int ttsp_write_block_data(struct cyttsp *ts, u8 command,
u8 length, void *buf)
{
int error;
int tries;
for (tries = 0; tries < CY_NUM_RETRY; tries++) {
error = ts->bus_ops->write(ts->dev, ts->xfer_buf, command,
length, buf);
if (!error)
return 0;
msleep(CY_DELAY_DFLT);
}
return -EIO;
}
static int ttsp_send_command(struct cyttsp *ts, u8 cmd)
{
return ttsp_write_block_data(ts, CY_REG_BASE, sizeof(cmd), &cmd);
}
static int cyttsp_handshake(struct cyttsp *ts)
{
if (ts->pdata->use_hndshk)
return ttsp_send_command(ts,
ts->xy_data.hst_mode ^ CY_HNDSHK_BIT);
return 0;
}
static int cyttsp_load_bl_regs(struct cyttsp *ts)
{
memset(&ts->bl_data, 0, sizeof(ts->bl_data));
ts->bl_data.bl_status = 0x10;
return ttsp_read_block_data(ts, CY_REG_BASE,
sizeof(ts->bl_data), &ts->bl_data);
}
static int cyttsp_exit_bl_mode(struct cyttsp *ts)
{
int error;
u8 bl_cmd[sizeof(bl_command)];
memcpy(bl_cmd, bl_command, sizeof(bl_command));
if (ts->pdata->bl_keys)
memcpy(&bl_cmd[sizeof(bl_command) - CY_NUM_BL_KEYS],
ts->pdata->bl_keys, CY_NUM_BL_KEYS);
error = ttsp_write_block_data(ts, CY_REG_BASE,
sizeof(bl_cmd), bl_cmd);
if (error)
return error;
/* wait for TTSP Device to complete the operation */
msleep(CY_DELAY_DFLT);
error = cyttsp_load_bl_regs(ts);
if (error)
return error;
if (GET_BOOTLOADERMODE(ts->bl_data.bl_status))
return -EIO;
return 0;
}
static int cyttsp_set_operational_mode(struct cyttsp *ts)
{
int error;
error = ttsp_send_command(ts, CY_OPERATE_MODE);
if (error)
return error;
/* wait for TTSP Device to complete switch to Operational mode */
error = ttsp_read_block_data(ts, CY_REG_BASE,
sizeof(ts->xy_data), &ts->xy_data);
if (error)
return error;
error = cyttsp_handshake(ts);
if (error)
return error;
return ts->xy_data.act_dist == CY_ACT_DIST_DFLT ? -EIO : 0;
}
static int cyttsp_set_sysinfo_mode(struct cyttsp *ts)
{
int error;
memset(&ts->sysinfo_data, 0, sizeof(ts->sysinfo_data));
/* switch to sysinfo mode */
error = ttsp_send_command(ts, CY_SYSINFO_MODE);
if (error)
return error;
/* read sysinfo registers */
msleep(CY_DELAY_DFLT);
error = ttsp_read_block_data(ts, CY_REG_BASE, sizeof(ts->sysinfo_data),
&ts->sysinfo_data);
if (error)
return error;
error = cyttsp_handshake(ts);
if (error)
return error;
if (!ts->sysinfo_data.tts_verh && !ts->sysinfo_data.tts_verl)
return -EIO;
return 0;
}
static int cyttsp_set_sysinfo_regs(struct cyttsp *ts)
{
int retval = 0;
if (ts->pdata->act_intrvl != CY_ACT_INTRVL_DFLT ||
ts->pdata->tch_tmout != CY_TCH_TMOUT_DFLT ||
ts->pdata->lp_intrvl != CY_LP_INTRVL_DFLT) {
u8 intrvl_ray[] = {
ts->pdata->act_intrvl,
ts->pdata->tch_tmout,
ts->pdata->lp_intrvl
};
/* set intrvl registers */
retval = ttsp_write_block_data(ts, CY_REG_ACT_INTRVL,
sizeof(intrvl_ray), intrvl_ray);
msleep(CY_DELAY_DFLT);
}
return retval;
}
static int cyttsp_soft_reset(struct cyttsp *ts)
{
unsigned long timeout;
int retval;
/* wait for interrupt to set ready completion */
reinit_completion(&ts->bl_ready);
ts->state = CY_BL_STATE;
enable_irq(ts->irq);
retval = ttsp_send_command(ts, CY_SOFT_RESET_MODE);
if (retval)
goto out;
timeout = wait_for_completion_timeout(&ts->bl_ready,
msecs_to_jiffies(CY_DELAY_DFLT * CY_DELAY_MAX));
retval = timeout ? 0 : -EIO;
out:
ts->state = CY_IDLE_STATE;
disable_irq(ts->irq);
return retval;
}
static int cyttsp_act_dist_setup(struct cyttsp *ts)
{
u8 act_dist_setup = ts->pdata->act_dist;
/* Init gesture; active distance setup */
return ttsp_write_block_data(ts, CY_REG_ACT_DIST,
sizeof(act_dist_setup), &act_dist_setup);
}
static void cyttsp_extract_track_ids(struct cyttsp_xydata *xy_data, int *ids)
{
ids[0] = xy_data->touch12_id >> 4;
ids[1] = xy_data->touch12_id & 0xF;
ids[2] = xy_data->touch34_id >> 4;
ids[3] = xy_data->touch34_id & 0xF;
}
static const struct cyttsp_tch *cyttsp_get_tch(struct cyttsp_xydata *xy_data,
int idx)
{
switch (idx) {
case 0:
return &xy_data->tch1;
case 1:
return &xy_data->tch2;
case 2:
return &xy_data->tch3;
case 3:
return &xy_data->tch4;
default:
return NULL;
}
}
static void cyttsp_report_tchdata(struct cyttsp *ts)
{
struct cyttsp_xydata *xy_data = &ts->xy_data;
struct input_dev *input = ts->input;
int num_tch = GET_NUM_TOUCHES(xy_data->tt_stat);
const struct cyttsp_tch *tch;
int ids[CY_MAX_ID];
int i;
DECLARE_BITMAP(used, CY_MAX_ID);
if (IS_LARGE_AREA(xy_data->tt_stat) == 1) {
/* terminate all active tracks */
num_tch = 0;
dev_dbg(ts->dev, "%s: Large area detected\n", __func__);
} else if (num_tch > CY_MAX_FINGER) {
/* terminate all active tracks */
num_tch = 0;
dev_dbg(ts->dev, "%s: Num touch error detected\n", __func__);
} else if (IS_BAD_PKT(xy_data->tt_mode)) {
/* terminate all active tracks */
num_tch = 0;
dev_dbg(ts->dev, "%s: Invalid buffer detected\n", __func__);
}
cyttsp_extract_track_ids(xy_data, ids);
bitmap_zero(used, CY_MAX_ID);
for (i = 0; i < num_tch; i++) {
tch = cyttsp_get_tch(xy_data, i);
input_mt_slot(input, ids[i]);
input_mt_report_slot_state(input, MT_TOOL_FINGER, true);
input_report_abs(input, ABS_MT_POSITION_X, be16_to_cpu(tch->x));
input_report_abs(input, ABS_MT_POSITION_Y, be16_to_cpu(tch->y));
input_report_abs(input, ABS_MT_TOUCH_MAJOR, tch->z);
__set_bit(ids[i], used);
}
for (i = 0; i < CY_MAX_ID; i++) {
if (test_bit(i, used))
continue;
input_mt_slot(input, i);
input_mt_report_slot_state(input, MT_TOOL_FINGER, false);
}
input_sync(input);
}
static irqreturn_t cyttsp_irq(int irq, void *handle)
{
struct cyttsp *ts = handle;
int error;
if (unlikely(ts->state == CY_BL_STATE)) {
complete(&ts->bl_ready);
goto out;
}
/* Get touch data from CYTTSP device */
error = ttsp_read_block_data(ts, CY_REG_BASE,
sizeof(struct cyttsp_xydata), &ts->xy_data);
if (error)
goto out;
/* provide flow control handshake */
error = cyttsp_handshake(ts);
if (error)
goto out;
if (unlikely(ts->state == CY_IDLE_STATE))
goto out;
if (GET_BOOTLOADERMODE(ts->xy_data.tt_mode)) {
/*
* TTSP device has reset back to bootloader mode.
* Restore to operational mode.
*/
error = cyttsp_exit_bl_mode(ts);
if (error) {
dev_err(ts->dev,
"Could not return to operational mode, err: %d\n",
error);
ts->state = CY_IDLE_STATE;
}
} else {
cyttsp_report_tchdata(ts);
}
out:
return IRQ_HANDLED;
}
static int cyttsp_power_on(struct cyttsp *ts)
{
int error;
error = cyttsp_soft_reset(ts);
if (error)
return error;
error = cyttsp_load_bl_regs(ts);
if (error)
return error;
if (GET_BOOTLOADERMODE(ts->bl_data.bl_status) &&
IS_VALID_APP(ts->bl_data.bl_status)) {
error = cyttsp_exit_bl_mode(ts);
if (error)
return error;
}
if (GET_HSTMODE(ts->bl_data.bl_file) != CY_OPERATE_MODE ||
IS_OPERATIONAL_ERR(ts->bl_data.bl_status)) {
return -ENODEV;
}
error = cyttsp_set_sysinfo_mode(ts);
if (error)
return error;
error = cyttsp_set_sysinfo_regs(ts);
if (error)
return error;
error = cyttsp_set_operational_mode(ts);
if (error)
return error;
/* init active distance */
error = cyttsp_act_dist_setup(ts);
if (error)
return error;
ts->state = CY_ACTIVE_STATE;
return 0;
}
static int cyttsp_enable(struct cyttsp *ts)
{
int error;
/*
* The device firmware can wake on an I2C or SPI memory slave
* address match. So just reading a register is sufficient to
* wake up the device. The first read attempt will fail but it
* will wake it up making the second read attempt successful.
*/
error = ttsp_read_block_data(ts, CY_REG_BASE,
sizeof(ts->xy_data), &ts->xy_data);
if (error)
return error;
if (GET_HSTMODE(ts->xy_data.hst_mode))
return -EIO;
enable_irq(ts->irq);
return 0;
}
static int cyttsp_disable(struct cyttsp *ts)
{
int error;
error = ttsp_send_command(ts, CY_LOW_POWER_MODE);
if (error)
return error;
disable_irq(ts->irq);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int cyttsp_suspend(struct device *dev)
{
struct cyttsp *ts = dev_get_drvdata(dev);
int retval = 0;
mutex_lock(&ts->input->mutex);
if (ts->input->users) {
retval = cyttsp_disable(ts);
if (retval == 0)
ts->suspended = true;
}
mutex_unlock(&ts->input->mutex);
return retval;
}
static int cyttsp_resume(struct device *dev)
{
struct cyttsp *ts = dev_get_drvdata(dev);
mutex_lock(&ts->input->mutex);
if (ts->input->users)
cyttsp_enable(ts);
ts->suspended = false;
mutex_unlock(&ts->input->mutex);
return 0;
}
#endif
SIMPLE_DEV_PM_OPS(cyttsp_pm_ops, cyttsp_suspend, cyttsp_resume);
EXPORT_SYMBOL_GPL(cyttsp_pm_ops);
static int cyttsp_open(struct input_dev *dev)
{
struct cyttsp *ts = input_get_drvdata(dev);
int retval = 0;
if (!ts->suspended)
retval = cyttsp_enable(ts);
return retval;
}
static void cyttsp_close(struct input_dev *dev)
{
struct cyttsp *ts = input_get_drvdata(dev);
if (!ts->suspended)
cyttsp_disable(ts);
}
struct cyttsp *cyttsp_probe(const struct cyttsp_bus_ops *bus_ops,
struct device *dev, int irq, size_t xfer_buf_size)
{
const struct cyttsp_platform_data *pdata = dev->platform_data;
struct cyttsp *ts;
struct input_dev *input_dev;
int error;
if (!pdata || !pdata->name || irq <= 0) {
error = -EINVAL;
goto err_out;
}
ts = kzalloc(sizeof(*ts) + xfer_buf_size, GFP_KERNEL);
input_dev = input_allocate_device();
if (!ts || !input_dev) {
error = -ENOMEM;
goto err_free_mem;
}
ts->dev = dev;
ts->input = input_dev;
ts->pdata = dev->platform_data;
ts->bus_ops = bus_ops;
ts->irq = irq;
init_completion(&ts->bl_ready);
snprintf(ts->phys, sizeof(ts->phys), "%s/input0", dev_name(dev));
if (pdata->init) {
error = pdata->init();
if (error) {
dev_err(ts->dev, "platform init failed, err: %d\n",
error);
goto err_free_mem;
}
}
input_dev->name = pdata->name;
input_dev->phys = ts->phys;
input_dev->id.bustype = bus_ops->bustype;
input_dev->dev.parent = ts->dev;
input_dev->open = cyttsp_open;
input_dev->close = cyttsp_close;
input_set_drvdata(input_dev, ts);
__set_bit(EV_ABS, input_dev->evbit);
input_set_abs_params(input_dev, ABS_MT_POSITION_X,
0, pdata->maxx, 0, 0);
input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
0, pdata->maxy, 0, 0);
input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR,
0, CY_MAXZ, 0, 0);
input_mt_init_slots(input_dev, CY_MAX_ID, 0);
error = request_threaded_irq(ts->irq, NULL, cyttsp_irq,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
pdata->name, ts);
if (error) {
dev_err(ts->dev, "failed to request IRQ %d, err: %d\n",
ts->irq, error);
goto err_platform_exit;
}
disable_irq(ts->irq);
error = cyttsp_power_on(ts);
if (error)
goto err_free_irq;
error = input_register_device(input_dev);
if (error) {
dev_err(ts->dev, "failed to register input device: %d\n",
error);
goto err_free_irq;
}
return ts;
err_free_irq:
free_irq(ts->irq, ts);
err_platform_exit:
if (pdata->exit)
pdata->exit();
err_free_mem:
input_free_device(input_dev);
kfree(ts);
err_out:
return ERR_PTR(error);
}
EXPORT_SYMBOL_GPL(cyttsp_probe);
void cyttsp_remove(struct cyttsp *ts)
{
free_irq(ts->irq, ts);
input_unregister_device(ts->input);
if (ts->pdata->exit)
ts->pdata->exit();
kfree(ts);
}
EXPORT_SYMBOL_GPL(cyttsp_remove);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard touchscreen driver core");
MODULE_AUTHOR("Cypress");
| gpl-2.0 |
male-puppies/linux-3.18.pps | drivers/pinctrl/pinconf.c | 845 | 16148 | /*
* Core driver for the pin config portions of the pin control subsystem
*
* Copyright (C) 2011 ST-Ericsson SA
* Written on behalf of Linaro for ST-Ericsson
*
* Author: Linus Walleij <linus.walleij@linaro.org>
*
* License terms: GNU General Public License (GPL) version 2
*/
#define pr_fmt(fmt) "pinconfig core: " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/pinctrl/machine.h>
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinconf.h>
#include "core.h"
#include "pinconf.h"
int pinconf_check_ops(struct pinctrl_dev *pctldev)
{
const struct pinconf_ops *ops = pctldev->desc->confops;
/* We have to be able to config the pins in SOME way */
if (!ops->pin_config_set && !ops->pin_config_group_set) {
dev_err(pctldev->dev,
"pinconf has to be able to set a pins config\n");
return -EINVAL;
}
return 0;
}
int pinconf_validate_map(struct pinctrl_map const *map, int i)
{
if (!map->data.configs.group_or_pin) {
pr_err("failed to register map %s (%d): no group/pin given\n",
map->name, i);
return -EINVAL;
}
if (!map->data.configs.num_configs ||
!map->data.configs.configs) {
pr_err("failed to register map %s (%d): no configs given\n",
map->name, i);
return -EINVAL;
}
return 0;
}
int pin_config_get_for_pin(struct pinctrl_dev *pctldev, unsigned pin,
unsigned long *config)
{
const struct pinconf_ops *ops = pctldev->desc->confops;
if (!ops || !ops->pin_config_get) {
dev_dbg(pctldev->dev, "cannot get pin configuration, missing "
"pin_config_get() function in driver\n");
return -ENOTSUPP;
}
return ops->pin_config_get(pctldev, pin, config);
}
int pin_config_group_get(const char *dev_name, const char *pin_group,
unsigned long *config)
{
struct pinctrl_dev *pctldev;
const struct pinconf_ops *ops;
int selector, ret;
pctldev = get_pinctrl_dev_from_devname(dev_name);
if (!pctldev) {
ret = -EINVAL;
return ret;
}
mutex_lock(&pctldev->mutex);
ops = pctldev->desc->confops;
if (!ops || !ops->pin_config_group_get) {
dev_dbg(pctldev->dev, "cannot get configuration for pin "
"group, missing group config get function in "
"driver\n");
ret = -ENOTSUPP;
goto unlock;
}
selector = pinctrl_get_group_selector(pctldev, pin_group);
if (selector < 0) {
ret = selector;
goto unlock;
}
ret = ops->pin_config_group_get(pctldev, selector, config);
unlock:
mutex_unlock(&pctldev->mutex);
return ret;
}
int pinconf_map_to_setting(struct pinctrl_map const *map,
struct pinctrl_setting *setting)
{
struct pinctrl_dev *pctldev = setting->pctldev;
int pin;
switch (setting->type) {
case PIN_MAP_TYPE_CONFIGS_PIN:
pin = pin_get_from_name(pctldev,
map->data.configs.group_or_pin);
if (pin < 0) {
dev_err(pctldev->dev, "could not map pin config for \"%s\"",
map->data.configs.group_or_pin);
return pin;
}
setting->data.configs.group_or_pin = pin;
break;
case PIN_MAP_TYPE_CONFIGS_GROUP:
pin = pinctrl_get_group_selector(pctldev,
map->data.configs.group_or_pin);
if (pin < 0) {
dev_err(pctldev->dev, "could not map group config for \"%s\"",
map->data.configs.group_or_pin);
return pin;
}
setting->data.configs.group_or_pin = pin;
break;
default:
return -EINVAL;
}
setting->data.configs.num_configs = map->data.configs.num_configs;
setting->data.configs.configs = map->data.configs.configs;
return 0;
}
void pinconf_free_setting(struct pinctrl_setting const *setting)
{
}
int pinconf_apply_setting(struct pinctrl_setting const *setting)
{
struct pinctrl_dev *pctldev = setting->pctldev;
const struct pinconf_ops *ops = pctldev->desc->confops;
int ret;
if (!ops) {
dev_err(pctldev->dev, "missing confops\n");
return -EINVAL;
}
switch (setting->type) {
case PIN_MAP_TYPE_CONFIGS_PIN:
if (!ops->pin_config_set) {
dev_err(pctldev->dev, "missing pin_config_set op\n");
return -EINVAL;
}
ret = ops->pin_config_set(pctldev,
setting->data.configs.group_or_pin,
setting->data.configs.configs,
setting->data.configs.num_configs);
if (ret < 0) {
dev_err(pctldev->dev,
"pin_config_set op failed for pin %d\n",
setting->data.configs.group_or_pin);
return ret;
}
break;
case PIN_MAP_TYPE_CONFIGS_GROUP:
if (!ops->pin_config_group_set) {
dev_err(pctldev->dev,
"missing pin_config_group_set op\n");
return -EINVAL;
}
ret = ops->pin_config_group_set(pctldev,
setting->data.configs.group_or_pin,
setting->data.configs.configs,
setting->data.configs.num_configs);
if (ret < 0) {
dev_err(pctldev->dev,
"pin_config_group_set op failed for group %d\n",
setting->data.configs.group_or_pin);
return ret;
}
break;
default:
return -EINVAL;
}
return 0;
}
#ifdef CONFIG_DEBUG_FS
void pinconf_show_map(struct seq_file *s, struct pinctrl_map const *map)
{
struct pinctrl_dev *pctldev;
const struct pinconf_ops *confops;
int i;
pctldev = get_pinctrl_dev_from_devname(map->ctrl_dev_name);
if (pctldev)
confops = pctldev->desc->confops;
else
confops = NULL;
switch (map->type) {
case PIN_MAP_TYPE_CONFIGS_PIN:
seq_printf(s, "pin ");
break;
case PIN_MAP_TYPE_CONFIGS_GROUP:
seq_printf(s, "group ");
break;
default:
break;
}
seq_printf(s, "%s\n", map->data.configs.group_or_pin);
for (i = 0; i < map->data.configs.num_configs; i++) {
seq_printf(s, "config ");
if (confops && confops->pin_config_config_dbg_show)
confops->pin_config_config_dbg_show(pctldev, s,
map->data.configs.configs[i]);
else
seq_printf(s, "%08lx", map->data.configs.configs[i]);
seq_printf(s, "\n");
}
}
void pinconf_show_setting(struct seq_file *s,
struct pinctrl_setting const *setting)
{
struct pinctrl_dev *pctldev = setting->pctldev;
const struct pinctrl_ops *pctlops = pctldev->desc->pctlops;
const struct pinconf_ops *confops = pctldev->desc->confops;
struct pin_desc *desc;
int i;
switch (setting->type) {
case PIN_MAP_TYPE_CONFIGS_PIN:
desc = pin_desc_get(setting->pctldev,
setting->data.configs.group_or_pin);
seq_printf(s, "pin %s (%d)",
desc->name ? desc->name : "unnamed",
setting->data.configs.group_or_pin);
break;
case PIN_MAP_TYPE_CONFIGS_GROUP:
seq_printf(s, "group %s (%d)",
pctlops->get_group_name(pctldev,
setting->data.configs.group_or_pin),
setting->data.configs.group_or_pin);
break;
default:
break;
}
/*
* FIXME: We should really get the pin controler to dump the config
* values, so they can be decoded to something meaningful.
*/
for (i = 0; i < setting->data.configs.num_configs; i++) {
seq_printf(s, " ");
if (confops && confops->pin_config_config_dbg_show)
confops->pin_config_config_dbg_show(pctldev, s,
setting->data.configs.configs[i]);
else
seq_printf(s, "%08lx",
setting->data.configs.configs[i]);
}
seq_printf(s, "\n");
}
static void pinconf_dump_pin(struct pinctrl_dev *pctldev,
struct seq_file *s, int pin)
{
const struct pinconf_ops *ops = pctldev->desc->confops;
/* no-op when not using generic pin config */
pinconf_generic_dump_pin(pctldev, s, pin);
if (ops && ops->pin_config_dbg_show)
ops->pin_config_dbg_show(pctldev, s, pin);
}
static int pinconf_pins_show(struct seq_file *s, void *what)
{
struct pinctrl_dev *pctldev = s->private;
unsigned i, pin;
seq_puts(s, "Pin config settings per pin\n");
seq_puts(s, "Format: pin (name): configs\n");
mutex_lock(&pctldev->mutex);
/* The pin number can be retrived from the pin controller descriptor */
for (i = 0; i < pctldev->desc->npins; i++) {
struct pin_desc *desc;
pin = pctldev->desc->pins[i].number;
desc = pin_desc_get(pctldev, pin);
/* Skip if we cannot search the pin */
if (desc == NULL)
continue;
seq_printf(s, "pin %d (%s):", pin,
desc->name ? desc->name : "unnamed");
pinconf_dump_pin(pctldev, s, pin);
seq_printf(s, "\n");
}
mutex_unlock(&pctldev->mutex);
return 0;
}
static void pinconf_dump_group(struct pinctrl_dev *pctldev,
struct seq_file *s, unsigned selector,
const char *gname)
{
const struct pinconf_ops *ops = pctldev->desc->confops;
/* no-op when not using generic pin config */
pinconf_generic_dump_group(pctldev, s, gname);
if (ops && ops->pin_config_group_dbg_show)
ops->pin_config_group_dbg_show(pctldev, s, selector);
}
static int pinconf_groups_show(struct seq_file *s, void *what)
{
struct pinctrl_dev *pctldev = s->private;
const struct pinctrl_ops *pctlops = pctldev->desc->pctlops;
unsigned ngroups = pctlops->get_groups_count(pctldev);
unsigned selector = 0;
seq_puts(s, "Pin config settings per pin group\n");
seq_puts(s, "Format: group (name): configs\n");
while (selector < ngroups) {
const char *gname = pctlops->get_group_name(pctldev, selector);
seq_printf(s, "%u (%s):", selector, gname);
pinconf_dump_group(pctldev, s, selector, gname);
seq_printf(s, "\n");
selector++;
}
return 0;
}
static int pinconf_pins_open(struct inode *inode, struct file *file)
{
return single_open(file, pinconf_pins_show, inode->i_private);
}
static int pinconf_groups_open(struct inode *inode, struct file *file)
{
return single_open(file, pinconf_groups_show, inode->i_private);
}
static const struct file_operations pinconf_pins_ops = {
.open = pinconf_pins_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations pinconf_groups_ops = {
.open = pinconf_groups_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#define MAX_NAME_LEN 15
struct dbg_cfg {
enum pinctrl_map_type map_type;
char dev_name[MAX_NAME_LEN+1];
char state_name[MAX_NAME_LEN+1];
char pin_name[MAX_NAME_LEN+1];
};
/*
* Goal is to keep this structure as global in order to simply read the
* pinconf-config file after a write to check config is as expected
*/
static struct dbg_cfg pinconf_dbg_conf;
/**
* pinconf_dbg_config_print() - display the pinctrl config from the pinctrl
* map, of the dev/pin/state that was last written to pinconf-config file.
* @s: string filled in with config description
* @d: not used
*/
static int pinconf_dbg_config_print(struct seq_file *s, void *d)
{
struct pinctrl_maps *maps_node;
const struct pinctrl_map *map;
const struct pinctrl_map *found = NULL;
struct pinctrl_dev *pctldev;
const struct pinconf_ops *confops = NULL;
struct dbg_cfg *dbg = &pinconf_dbg_conf;
int i, j;
unsigned long config;
mutex_lock(&pinctrl_maps_mutex);
/* Parse the pinctrl map and look for the elected pin/state */
for_each_maps(maps_node, i, map) {
if (map->type != dbg->map_type)
continue;
if (strcmp(map->dev_name, dbg->dev_name))
continue;
if (strcmp(map->name, dbg->state_name))
continue;
for (j = 0; j < map->data.configs.num_configs; j++) {
if (!strcmp(map->data.configs.group_or_pin,
dbg->pin_name)) {
/* We found the right pin / state */
found = map;
break;
}
}
}
if (!found) {
seq_printf(s, "No config found for dev/state/pin, expected:\n");
seq_printf(s, "Searched dev:%s\n", dbg->dev_name);
seq_printf(s, "Searched state:%s\n", dbg->state_name);
seq_printf(s, "Searched pin:%s\n", dbg->pin_name);
seq_printf(s, "Use: modify config_pin <devname> "\
"<state> <pinname> <value>\n");
goto exit;
}
pctldev = get_pinctrl_dev_from_devname(found->ctrl_dev_name);
config = *found->data.configs.configs;
seq_printf(s, "Dev %s has config of %s in state %s: 0x%08lX\n",
dbg->dev_name, dbg->pin_name,
dbg->state_name, config);
if (pctldev)
confops = pctldev->desc->confops;
if (confops && confops->pin_config_config_dbg_show)
confops->pin_config_config_dbg_show(pctldev, s, config);
exit:
mutex_unlock(&pinctrl_maps_mutex);
return 0;
}
/**
* pinconf_dbg_config_write() - modify the pinctrl config in the pinctrl
* map, of a dev/pin/state entry based on user entries to pinconf-config
* @user_buf: contains the modification request with expected format:
* modify config_pin <devicename> <state> <pinname> <newvalue>
* modify is literal string, alternatives like add/delete not supported yet
* config_pin is literal, alternatives like config_mux not supported yet
* <devicename> <state> <pinname> are values that should match the pinctrl-maps
* <newvalue> reflects the new config and is driver dependant
*/
static ssize_t pinconf_dbg_config_write(struct file *file,
const char __user *user_buf, size_t count, loff_t *ppos)
{
struct pinctrl_maps *maps_node;
const struct pinctrl_map *map;
const struct pinctrl_map *found = NULL;
struct pinctrl_dev *pctldev;
const struct pinconf_ops *confops = NULL;
struct dbg_cfg *dbg = &pinconf_dbg_conf;
const struct pinctrl_map_configs *configs;
char config[MAX_NAME_LEN+1];
char buf[128];
char *b = &buf[0];
int buf_size;
char *token;
int i;
/* Get userspace string and assure termination */
buf_size = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, buf_size))
return -EFAULT;
buf[buf_size] = 0;
/*
* need to parse entry and extract parameters:
* modify configs_pin devicename state pinname newvalue
*/
/* Get arg: 'modify' */
token = strsep(&b, " ");
if (!token)
return -EINVAL;
if (strcmp(token, "modify"))
return -EINVAL;
/* Get arg type: "config_pin" type supported so far */
token = strsep(&b, " ");
if (!token)
return -EINVAL;
if (strcmp(token, "config_pin"))
return -EINVAL;
dbg->map_type = PIN_MAP_TYPE_CONFIGS_PIN;
/* get arg 'device_name' */
token = strsep(&b, " ");
if (token == NULL)
return -EINVAL;
if (strlen(token) >= MAX_NAME_LEN)
return -EINVAL;
strncpy(dbg->dev_name, token, MAX_NAME_LEN);
/* get arg 'state_name' */
token = strsep(&b, " ");
if (token == NULL)
return -EINVAL;
if (strlen(token) >= MAX_NAME_LEN)
return -EINVAL;
strncpy(dbg->state_name, token, MAX_NAME_LEN);
/* get arg 'pin_name' */
token = strsep(&b, " ");
if (token == NULL)
return -EINVAL;
if (strlen(token) >= MAX_NAME_LEN)
return -EINVAL;
strncpy(dbg->pin_name, token, MAX_NAME_LEN);
/* get new_value of config' */
token = strsep(&b, " ");
if (token == NULL)
return -EINVAL;
if (strlen(token) >= MAX_NAME_LEN)
return -EINVAL;
strncpy(config, token, MAX_NAME_LEN);
mutex_lock(&pinctrl_maps_mutex);
/* Parse the pinctrl map and look for the selected dev/state/pin */
for_each_maps(maps_node, i, map) {
if (strcmp(map->dev_name, dbg->dev_name))
continue;
if (map->type != dbg->map_type)
continue;
if (strcmp(map->name, dbg->state_name))
continue;
/* we found the right pin / state, so overwrite config */
if (!strcmp(map->data.configs.group_or_pin, dbg->pin_name)) {
found = map;
break;
}
}
if (!found) {
count = -EINVAL;
goto exit;
}
pctldev = get_pinctrl_dev_from_devname(found->ctrl_dev_name);
if (pctldev)
confops = pctldev->desc->confops;
if (confops && confops->pin_config_dbg_parse_modify) {
configs = &found->data.configs;
for (i = 0; i < configs->num_configs; i++) {
confops->pin_config_dbg_parse_modify(pctldev,
config,
&configs->configs[i]);
}
}
exit:
mutex_unlock(&pinctrl_maps_mutex);
return count;
}
static int pinconf_dbg_config_open(struct inode *inode, struct file *file)
{
return single_open(file, pinconf_dbg_config_print, inode->i_private);
}
static const struct file_operations pinconf_dbg_pinconfig_fops = {
.open = pinconf_dbg_config_open,
.write = pinconf_dbg_config_write,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.owner = THIS_MODULE,
};
void pinconf_init_device_debugfs(struct dentry *devroot,
struct pinctrl_dev *pctldev)
{
debugfs_create_file("pinconf-pins", S_IFREG | S_IRUGO,
devroot, pctldev, &pinconf_pins_ops);
debugfs_create_file("pinconf-groups", S_IFREG | S_IRUGO,
devroot, pctldev, &pinconf_groups_ops);
debugfs_create_file("pinconf-config", (S_IRUGO | S_IWUSR | S_IWGRP),
devroot, pctldev, &pinconf_dbg_pinconfig_fops);
}
#endif
| gpl-2.0 |
jiwanlimbu/ceph-client | arch/mips/oprofile/op_model_loongson3.c | 1101 | 5821 | /*
* 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/cpu.h>
#include <linux/smp.h>
#include <linux/proc_fs.h>
#include <linux/oprofile.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <asm/uaccess.h>
#include <irq.h>
#include <loongson.h>
#include "op_impl.h"
#define LOONGSON3_PERFCNT_OVERFLOW (1ULL << 63)
#define LOONGSON3_PERFCTRL_EXL (1UL << 0)
#define LOONGSON3_PERFCTRL_KERNEL (1UL << 1)
#define LOONGSON3_PERFCTRL_SUPERVISOR (1UL << 2)
#define LOONGSON3_PERFCTRL_USER (1UL << 3)
#define LOONGSON3_PERFCTRL_ENABLE (1UL << 4)
#define LOONGSON3_PERFCTRL_W (1UL << 30)
#define LOONGSON3_PERFCTRL_M (1UL << 31)
#define LOONGSON3_PERFCTRL_EVENT(idx, event) \
(((event) & (idx ? 0x0f : 0x3f)) << 5)
/* Loongson-3 PerfCount performance counter1 register */
#define read_c0_perflo1() __read_64bit_c0_register($25, 0)
#define write_c0_perflo1(val) __write_64bit_c0_register($25, 0, val)
#define read_c0_perfhi1() __read_64bit_c0_register($25, 1)
#define write_c0_perfhi1(val) __write_64bit_c0_register($25, 1, val)
/* Loongson-3 PerfCount performance counter2 register */
#define read_c0_perflo2() __read_64bit_c0_register($25, 2)
#define write_c0_perflo2(val) __write_64bit_c0_register($25, 2, val)
#define read_c0_perfhi2() __read_64bit_c0_register($25, 3)
#define write_c0_perfhi2(val) __write_64bit_c0_register($25, 3, val)
static int (*save_perf_irq)(void);
static struct loongson3_register_config {
unsigned int control1;
unsigned int control2;
unsigned long long reset_counter1;
unsigned long long reset_counter2;
int ctr1_enable, ctr2_enable;
} reg;
static void reset_counters(void *arg)
{
write_c0_perfhi1(0);
write_c0_perfhi2(0);
write_c0_perflo1(0xc0000000);
write_c0_perflo2(0x40000000);
}
/* Compute all of the registers in preparation for enabling profiling. */
static void loongson3_reg_setup(struct op_counter_config *ctr)
{
unsigned int control1 = 0;
unsigned int control2 = 0;
reg.reset_counter1 = 0;
reg.reset_counter2 = 0;
/* Compute the performance counter control word. */
/* For now count kernel and user mode */
if (ctr[0].enabled) {
control1 |= LOONGSON3_PERFCTRL_EVENT(0, ctr[0].event) |
LOONGSON3_PERFCTRL_ENABLE;
if (ctr[0].kernel)
control1 |= LOONGSON3_PERFCTRL_KERNEL;
if (ctr[0].user)
control1 |= LOONGSON3_PERFCTRL_USER;
reg.reset_counter1 = 0x8000000000000000ULL - ctr[0].count;
}
if (ctr[1].enabled) {
control2 |= LOONGSON3_PERFCTRL_EVENT(1, ctr[1].event) |
LOONGSON3_PERFCTRL_ENABLE;
if (ctr[1].kernel)
control2 |= LOONGSON3_PERFCTRL_KERNEL;
if (ctr[1].user)
control2 |= LOONGSON3_PERFCTRL_USER;
reg.reset_counter2 = 0x8000000000000000ULL - ctr[1].count;
}
if (ctr[0].enabled)
control1 |= LOONGSON3_PERFCTRL_EXL;
if (ctr[1].enabled)
control2 |= LOONGSON3_PERFCTRL_EXL;
reg.control1 = control1;
reg.control2 = control2;
reg.ctr1_enable = ctr[0].enabled;
reg.ctr2_enable = ctr[1].enabled;
}
/* Program all of the registers in preparation for enabling profiling. */
static void loongson3_cpu_setup(void *args)
{
uint64_t perfcount1, perfcount2;
perfcount1 = reg.reset_counter1;
perfcount2 = reg.reset_counter2;
write_c0_perfhi1(perfcount1);
write_c0_perfhi2(perfcount2);
}
static void loongson3_cpu_start(void *args)
{
/* Start all counters on current CPU */
reg.control1 |= (LOONGSON3_PERFCTRL_W|LOONGSON3_PERFCTRL_M);
reg.control2 |= (LOONGSON3_PERFCTRL_W|LOONGSON3_PERFCTRL_M);
if (reg.ctr1_enable)
write_c0_perflo1(reg.control1);
if (reg.ctr2_enable)
write_c0_perflo2(reg.control2);
}
static void loongson3_cpu_stop(void *args)
{
/* Stop all counters on current CPU */
write_c0_perflo1(0xc0000000);
write_c0_perflo2(0x40000000);
memset(®, 0, sizeof(reg));
}
static int loongson3_perfcount_handler(void)
{
unsigned long flags;
uint64_t counter1, counter2;
uint32_t cause, handled = IRQ_NONE;
struct pt_regs *regs = get_irq_regs();
cause = read_c0_cause();
if (!(cause & CAUSEF_PCI))
return handled;
counter1 = read_c0_perfhi1();
counter2 = read_c0_perfhi2();
local_irq_save(flags);
if (counter1 & LOONGSON3_PERFCNT_OVERFLOW) {
if (reg.ctr1_enable)
oprofile_add_sample(regs, 0);
counter1 = reg.reset_counter1;
}
if (counter2 & LOONGSON3_PERFCNT_OVERFLOW) {
if (reg.ctr2_enable)
oprofile_add_sample(regs, 1);
counter2 = reg.reset_counter2;
}
local_irq_restore(flags);
write_c0_perfhi1(counter1);
write_c0_perfhi2(counter2);
if (!(cause & CAUSEF_TI))
handled = IRQ_HANDLED;
return handled;
}
static int loongson3_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
switch (action) {
case CPU_STARTING:
case CPU_STARTING_FROZEN:
write_c0_perflo1(reg.control1);
write_c0_perflo2(reg.control2);
break;
case CPU_DYING:
case CPU_DYING_FROZEN:
write_c0_perflo1(0xc0000000);
write_c0_perflo2(0x40000000);
break;
}
return NOTIFY_OK;
}
static struct notifier_block loongson3_notifier_block = {
.notifier_call = loongson3_cpu_callback
};
static int __init loongson3_init(void)
{
on_each_cpu(reset_counters, NULL, 1);
register_hotcpu_notifier(&loongson3_notifier_block);
save_perf_irq = perf_irq;
perf_irq = loongson3_perfcount_handler;
return 0;
}
static void loongson3_exit(void)
{
on_each_cpu(reset_counters, NULL, 1);
unregister_hotcpu_notifier(&loongson3_notifier_block);
perf_irq = save_perf_irq;
}
struct op_mips_model op_model_loongson3_ops = {
.reg_setup = loongson3_reg_setup,
.cpu_setup = loongson3_cpu_setup,
.init = loongson3_init,
.exit = loongson3_exit,
.cpu_start = loongson3_cpu_start,
.cpu_stop = loongson3_cpu_stop,
.cpu_type = "mips/loongson3",
.num_counters = 2
};
| gpl-2.0 |
bbedward/ZenKernel_Shamu | fs/ocfs2/dlm/dlmmaster.c | 1357 | 96295 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* dlmmod.c
*
* standalone DLM module
*
* Copyright (C) 2004 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 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 021110-1307, USA.
*
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/highmem.h>
#include <linux/init.h>
#include <linux/sysctl.h>
#include <linux/random.h>
#include <linux/blkdev.h>
#include <linux/socket.h>
#include <linux/inet.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include "cluster/heartbeat.h"
#include "cluster/nodemanager.h"
#include "cluster/tcp.h"
#include "dlmapi.h"
#include "dlmcommon.h"
#include "dlmdomain.h"
#include "dlmdebug.h"
#define MLOG_MASK_PREFIX (ML_DLM|ML_DLM_MASTER)
#include "cluster/masklog.h"
static void dlm_mle_node_down(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle,
struct o2nm_node *node,
int idx);
static void dlm_mle_node_up(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle,
struct o2nm_node *node,
int idx);
static void dlm_assert_master_worker(struct dlm_work_item *item, void *data);
static int dlm_do_assert_master(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
void *nodemap, u32 flags);
static void dlm_deref_lockres_worker(struct dlm_work_item *item, void *data);
static inline int dlm_mle_equal(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle,
const char *name,
unsigned int namelen)
{
if (dlm != mle->dlm)
return 0;
if (namelen != mle->mnamelen ||
memcmp(name, mle->mname, namelen) != 0)
return 0;
return 1;
}
static struct kmem_cache *dlm_lockres_cache = NULL;
static struct kmem_cache *dlm_lockname_cache = NULL;
static struct kmem_cache *dlm_mle_cache = NULL;
static void dlm_mle_release(struct kref *kref);
static void dlm_init_mle(struct dlm_master_list_entry *mle,
enum dlm_mle_type type,
struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
const char *name,
unsigned int namelen);
static void dlm_put_mle(struct dlm_master_list_entry *mle);
static void __dlm_put_mle(struct dlm_master_list_entry *mle);
static int dlm_find_mle(struct dlm_ctxt *dlm,
struct dlm_master_list_entry **mle,
char *name, unsigned int namelen);
static int dlm_do_master_request(struct dlm_lock_resource *res,
struct dlm_master_list_entry *mle, int to);
static int dlm_wait_for_lock_mastery(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_master_list_entry *mle,
int *blocked);
static int dlm_restart_lock_mastery(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_master_list_entry *mle,
int blocked);
static int dlm_add_migration_mle(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_master_list_entry *mle,
struct dlm_master_list_entry **oldmle,
const char *name, unsigned int namelen,
u8 new_master, u8 master);
static u8 dlm_pick_migration_target(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res);
static void dlm_remove_nonlocal_locks(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res);
static int dlm_mark_lockres_migrating(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
u8 target);
static int dlm_pre_master_reco_lockres(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res);
int dlm_is_host_down(int errno)
{
switch (errno) {
case -EBADF:
case -ECONNREFUSED:
case -ENOTCONN:
case -ECONNRESET:
case -EPIPE:
case -EHOSTDOWN:
case -EHOSTUNREACH:
case -ETIMEDOUT:
case -ECONNABORTED:
case -ENETDOWN:
case -ENETUNREACH:
case -ENETRESET:
case -ESHUTDOWN:
case -ENOPROTOOPT:
case -EINVAL: /* if returned from our tcp code,
this means there is no socket */
return 1;
}
return 0;
}
/*
* MASTER LIST FUNCTIONS
*/
/*
* regarding master list entries and heartbeat callbacks:
*
* in order to avoid sleeping and allocation that occurs in
* heartbeat, master list entries are simply attached to the
* dlm's established heartbeat callbacks. the mle is attached
* when it is created, and since the dlm->spinlock is held at
* that time, any heartbeat event will be properly discovered
* by the mle. the mle needs to be detached from the
* dlm->mle_hb_events list as soon as heartbeat events are no
* longer useful to the mle, and before the mle is freed.
*
* as a general rule, heartbeat events are no longer needed by
* the mle once an "answer" regarding the lock master has been
* received.
*/
static inline void __dlm_mle_attach_hb_events(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle)
{
assert_spin_locked(&dlm->spinlock);
list_add_tail(&mle->hb_events, &dlm->mle_hb_events);
}
static inline void __dlm_mle_detach_hb_events(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle)
{
if (!list_empty(&mle->hb_events))
list_del_init(&mle->hb_events);
}
static inline void dlm_mle_detach_hb_events(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle)
{
spin_lock(&dlm->spinlock);
__dlm_mle_detach_hb_events(dlm, mle);
spin_unlock(&dlm->spinlock);
}
static void dlm_get_mle_inuse(struct dlm_master_list_entry *mle)
{
struct dlm_ctxt *dlm;
dlm = mle->dlm;
assert_spin_locked(&dlm->spinlock);
assert_spin_locked(&dlm->master_lock);
mle->inuse++;
kref_get(&mle->mle_refs);
}
static void dlm_put_mle_inuse(struct dlm_master_list_entry *mle)
{
struct dlm_ctxt *dlm;
dlm = mle->dlm;
spin_lock(&dlm->spinlock);
spin_lock(&dlm->master_lock);
mle->inuse--;
__dlm_put_mle(mle);
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
}
/* remove from list and free */
static void __dlm_put_mle(struct dlm_master_list_entry *mle)
{
struct dlm_ctxt *dlm;
dlm = mle->dlm;
assert_spin_locked(&dlm->spinlock);
assert_spin_locked(&dlm->master_lock);
if (!atomic_read(&mle->mle_refs.refcount)) {
/* this may or may not crash, but who cares.
* it's a BUG. */
mlog(ML_ERROR, "bad mle: %p\n", mle);
dlm_print_one_mle(mle);
BUG();
} else
kref_put(&mle->mle_refs, dlm_mle_release);
}
/* must not have any spinlocks coming in */
static void dlm_put_mle(struct dlm_master_list_entry *mle)
{
struct dlm_ctxt *dlm;
dlm = mle->dlm;
spin_lock(&dlm->spinlock);
spin_lock(&dlm->master_lock);
__dlm_put_mle(mle);
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
}
static inline void dlm_get_mle(struct dlm_master_list_entry *mle)
{
kref_get(&mle->mle_refs);
}
static void dlm_init_mle(struct dlm_master_list_entry *mle,
enum dlm_mle_type type,
struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
const char *name,
unsigned int namelen)
{
assert_spin_locked(&dlm->spinlock);
mle->dlm = dlm;
mle->type = type;
INIT_HLIST_NODE(&mle->master_hash_node);
INIT_LIST_HEAD(&mle->hb_events);
memset(mle->maybe_map, 0, sizeof(mle->maybe_map));
spin_lock_init(&mle->spinlock);
init_waitqueue_head(&mle->wq);
atomic_set(&mle->woken, 0);
kref_init(&mle->mle_refs);
memset(mle->response_map, 0, sizeof(mle->response_map));
mle->master = O2NM_MAX_NODES;
mle->new_master = O2NM_MAX_NODES;
mle->inuse = 0;
BUG_ON(mle->type != DLM_MLE_BLOCK &&
mle->type != DLM_MLE_MASTER &&
mle->type != DLM_MLE_MIGRATION);
if (mle->type == DLM_MLE_MASTER) {
BUG_ON(!res);
mle->mleres = res;
memcpy(mle->mname, res->lockname.name, res->lockname.len);
mle->mnamelen = res->lockname.len;
mle->mnamehash = res->lockname.hash;
} else {
BUG_ON(!name);
mle->mleres = NULL;
memcpy(mle->mname, name, namelen);
mle->mnamelen = namelen;
mle->mnamehash = dlm_lockid_hash(name, namelen);
}
atomic_inc(&dlm->mle_tot_count[mle->type]);
atomic_inc(&dlm->mle_cur_count[mle->type]);
/* copy off the node_map and register hb callbacks on our copy */
memcpy(mle->node_map, dlm->domain_map, sizeof(mle->node_map));
memcpy(mle->vote_map, dlm->domain_map, sizeof(mle->vote_map));
clear_bit(dlm->node_num, mle->vote_map);
clear_bit(dlm->node_num, mle->node_map);
/* attach the mle to the domain node up/down events */
__dlm_mle_attach_hb_events(dlm, mle);
}
void __dlm_unlink_mle(struct dlm_ctxt *dlm, struct dlm_master_list_entry *mle)
{
assert_spin_locked(&dlm->spinlock);
assert_spin_locked(&dlm->master_lock);
if (!hlist_unhashed(&mle->master_hash_node))
hlist_del_init(&mle->master_hash_node);
}
void __dlm_insert_mle(struct dlm_ctxt *dlm, struct dlm_master_list_entry *mle)
{
struct hlist_head *bucket;
assert_spin_locked(&dlm->master_lock);
bucket = dlm_master_hash(dlm, mle->mnamehash);
hlist_add_head(&mle->master_hash_node, bucket);
}
/* returns 1 if found, 0 if not */
static int dlm_find_mle(struct dlm_ctxt *dlm,
struct dlm_master_list_entry **mle,
char *name, unsigned int namelen)
{
struct dlm_master_list_entry *tmpmle;
struct hlist_head *bucket;
struct hlist_node *list;
unsigned int hash;
assert_spin_locked(&dlm->master_lock);
hash = dlm_lockid_hash(name, namelen);
bucket = dlm_master_hash(dlm, hash);
hlist_for_each(list, bucket) {
tmpmle = hlist_entry(list, struct dlm_master_list_entry,
master_hash_node);
if (!dlm_mle_equal(dlm, tmpmle, name, namelen))
continue;
dlm_get_mle(tmpmle);
*mle = tmpmle;
return 1;
}
return 0;
}
void dlm_hb_event_notify_attached(struct dlm_ctxt *dlm, int idx, int node_up)
{
struct dlm_master_list_entry *mle;
assert_spin_locked(&dlm->spinlock);
list_for_each_entry(mle, &dlm->mle_hb_events, hb_events) {
if (node_up)
dlm_mle_node_up(dlm, mle, NULL, idx);
else
dlm_mle_node_down(dlm, mle, NULL, idx);
}
}
static void dlm_mle_node_down(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle,
struct o2nm_node *node, int idx)
{
spin_lock(&mle->spinlock);
if (!test_bit(idx, mle->node_map))
mlog(0, "node %u already removed from nodemap!\n", idx);
else
clear_bit(idx, mle->node_map);
spin_unlock(&mle->spinlock);
}
static void dlm_mle_node_up(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle,
struct o2nm_node *node, int idx)
{
spin_lock(&mle->spinlock);
if (test_bit(idx, mle->node_map))
mlog(0, "node %u already in node map!\n", idx);
else
set_bit(idx, mle->node_map);
spin_unlock(&mle->spinlock);
}
int dlm_init_mle_cache(void)
{
dlm_mle_cache = kmem_cache_create("o2dlm_mle",
sizeof(struct dlm_master_list_entry),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (dlm_mle_cache == NULL)
return -ENOMEM;
return 0;
}
void dlm_destroy_mle_cache(void)
{
if (dlm_mle_cache)
kmem_cache_destroy(dlm_mle_cache);
}
static void dlm_mle_release(struct kref *kref)
{
struct dlm_master_list_entry *mle;
struct dlm_ctxt *dlm;
mle = container_of(kref, struct dlm_master_list_entry, mle_refs);
dlm = mle->dlm;
assert_spin_locked(&dlm->spinlock);
assert_spin_locked(&dlm->master_lock);
mlog(0, "Releasing mle for %.*s, type %d\n", mle->mnamelen, mle->mname,
mle->type);
/* remove from list if not already */
__dlm_unlink_mle(dlm, mle);
/* detach the mle from the domain node up/down events */
__dlm_mle_detach_hb_events(dlm, mle);
atomic_dec(&dlm->mle_cur_count[mle->type]);
/* NOTE: kfree under spinlock here.
* if this is bad, we can move this to a freelist. */
kmem_cache_free(dlm_mle_cache, mle);
}
/*
* LOCK RESOURCE FUNCTIONS
*/
int dlm_init_master_caches(void)
{
dlm_lockres_cache = kmem_cache_create("o2dlm_lockres",
sizeof(struct dlm_lock_resource),
0, SLAB_HWCACHE_ALIGN, NULL);
if (!dlm_lockres_cache)
goto bail;
dlm_lockname_cache = kmem_cache_create("o2dlm_lockname",
DLM_LOCKID_NAME_MAX, 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!dlm_lockname_cache)
goto bail;
return 0;
bail:
dlm_destroy_master_caches();
return -ENOMEM;
}
void dlm_destroy_master_caches(void)
{
if (dlm_lockname_cache)
kmem_cache_destroy(dlm_lockname_cache);
if (dlm_lockres_cache)
kmem_cache_destroy(dlm_lockres_cache);
}
static void dlm_lockres_release(struct kref *kref)
{
struct dlm_lock_resource *res;
struct dlm_ctxt *dlm;
res = container_of(kref, struct dlm_lock_resource, refs);
dlm = res->dlm;
/* This should not happen -- all lockres' have a name
* associated with them at init time. */
BUG_ON(!res->lockname.name);
mlog(0, "destroying lockres %.*s\n", res->lockname.len,
res->lockname.name);
spin_lock(&dlm->track_lock);
if (!list_empty(&res->tracking))
list_del_init(&res->tracking);
else {
mlog(ML_ERROR, "Resource %.*s not on the Tracking list\n",
res->lockname.len, res->lockname.name);
dlm_print_one_lock_resource(res);
}
spin_unlock(&dlm->track_lock);
atomic_dec(&dlm->res_cur_count);
if (!hlist_unhashed(&res->hash_node) ||
!list_empty(&res->granted) ||
!list_empty(&res->converting) ||
!list_empty(&res->blocked) ||
!list_empty(&res->dirty) ||
!list_empty(&res->recovering) ||
!list_empty(&res->purge)) {
mlog(ML_ERROR,
"Going to BUG for resource %.*s."
" We're on a list! [%c%c%c%c%c%c%c]\n",
res->lockname.len, res->lockname.name,
!hlist_unhashed(&res->hash_node) ? 'H' : ' ',
!list_empty(&res->granted) ? 'G' : ' ',
!list_empty(&res->converting) ? 'C' : ' ',
!list_empty(&res->blocked) ? 'B' : ' ',
!list_empty(&res->dirty) ? 'D' : ' ',
!list_empty(&res->recovering) ? 'R' : ' ',
!list_empty(&res->purge) ? 'P' : ' ');
dlm_print_one_lock_resource(res);
}
/* By the time we're ready to blow this guy away, we shouldn't
* be on any lists. */
BUG_ON(!hlist_unhashed(&res->hash_node));
BUG_ON(!list_empty(&res->granted));
BUG_ON(!list_empty(&res->converting));
BUG_ON(!list_empty(&res->blocked));
BUG_ON(!list_empty(&res->dirty));
BUG_ON(!list_empty(&res->recovering));
BUG_ON(!list_empty(&res->purge));
kmem_cache_free(dlm_lockname_cache, (void *)res->lockname.name);
kmem_cache_free(dlm_lockres_cache, res);
}
void dlm_lockres_put(struct dlm_lock_resource *res)
{
kref_put(&res->refs, dlm_lockres_release);
}
static void dlm_init_lockres(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
const char *name, unsigned int namelen)
{
char *qname;
/* If we memset here, we lose our reference to the kmalloc'd
* res->lockname.name, so be sure to init every field
* correctly! */
qname = (char *) res->lockname.name;
memcpy(qname, name, namelen);
res->lockname.len = namelen;
res->lockname.hash = dlm_lockid_hash(name, namelen);
init_waitqueue_head(&res->wq);
spin_lock_init(&res->spinlock);
INIT_HLIST_NODE(&res->hash_node);
INIT_LIST_HEAD(&res->granted);
INIT_LIST_HEAD(&res->converting);
INIT_LIST_HEAD(&res->blocked);
INIT_LIST_HEAD(&res->dirty);
INIT_LIST_HEAD(&res->recovering);
INIT_LIST_HEAD(&res->purge);
INIT_LIST_HEAD(&res->tracking);
atomic_set(&res->asts_reserved, 0);
res->migration_pending = 0;
res->inflight_locks = 0;
res->dlm = dlm;
kref_init(&res->refs);
atomic_inc(&dlm->res_tot_count);
atomic_inc(&dlm->res_cur_count);
/* just for consistency */
spin_lock(&res->spinlock);
dlm_set_lockres_owner(dlm, res, DLM_LOCK_RES_OWNER_UNKNOWN);
spin_unlock(&res->spinlock);
res->state = DLM_LOCK_RES_IN_PROGRESS;
res->last_used = 0;
spin_lock(&dlm->spinlock);
list_add_tail(&res->tracking, &dlm->tracking_list);
spin_unlock(&dlm->spinlock);
memset(res->lvb, 0, DLM_LVB_LEN);
memset(res->refmap, 0, sizeof(res->refmap));
}
struct dlm_lock_resource *dlm_new_lockres(struct dlm_ctxt *dlm,
const char *name,
unsigned int namelen)
{
struct dlm_lock_resource *res = NULL;
res = kmem_cache_zalloc(dlm_lockres_cache, GFP_NOFS);
if (!res)
goto error;
res->lockname.name = kmem_cache_zalloc(dlm_lockname_cache, GFP_NOFS);
if (!res->lockname.name)
goto error;
dlm_init_lockres(dlm, res, name, namelen);
return res;
error:
if (res && res->lockname.name)
kmem_cache_free(dlm_lockname_cache, (void *)res->lockname.name);
if (res)
kmem_cache_free(dlm_lockres_cache, res);
return NULL;
}
void dlm_lockres_set_refmap_bit(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res, int bit)
{
assert_spin_locked(&res->spinlock);
mlog(0, "res %.*s, set node %u, %ps()\n", res->lockname.len,
res->lockname.name, bit, __builtin_return_address(0));
set_bit(bit, res->refmap);
}
void dlm_lockres_clear_refmap_bit(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res, int bit)
{
assert_spin_locked(&res->spinlock);
mlog(0, "res %.*s, clr node %u, %ps()\n", res->lockname.len,
res->lockname.name, bit, __builtin_return_address(0));
clear_bit(bit, res->refmap);
}
void dlm_lockres_grab_inflight_ref(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res)
{
assert_spin_locked(&res->spinlock);
res->inflight_locks++;
mlog(0, "%s: res %.*s, inflight++: now %u, %ps()\n", dlm->name,
res->lockname.len, res->lockname.name, res->inflight_locks,
__builtin_return_address(0));
}
void dlm_lockres_drop_inflight_ref(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res)
{
assert_spin_locked(&res->spinlock);
BUG_ON(res->inflight_locks == 0);
res->inflight_locks--;
mlog(0, "%s: res %.*s, inflight--: now %u, %ps()\n", dlm->name,
res->lockname.len, res->lockname.name, res->inflight_locks,
__builtin_return_address(0));
wake_up(&res->wq);
}
/*
* lookup a lock resource by name.
* may already exist in the hashtable.
* lockid is null terminated
*
* if not, allocate enough for the lockres and for
* the temporary structure used in doing the mastering.
*
* also, do a lookup in the dlm->master_list to see
* if another node has begun mastering the same lock.
* if so, there should be a block entry in there
* for this name, and we should *not* attempt to master
* the lock here. need to wait around for that node
* to assert_master (or die).
*
*/
struct dlm_lock_resource * dlm_get_lock_resource(struct dlm_ctxt *dlm,
const char *lockid,
int namelen,
int flags)
{
struct dlm_lock_resource *tmpres=NULL, *res=NULL;
struct dlm_master_list_entry *mle = NULL;
struct dlm_master_list_entry *alloc_mle = NULL;
int blocked = 0;
int ret, nodenum;
struct dlm_node_iter iter;
unsigned int hash;
int tries = 0;
int bit, wait_on_recovery = 0;
BUG_ON(!lockid);
hash = dlm_lockid_hash(lockid, namelen);
mlog(0, "get lockres %s (len %d)\n", lockid, namelen);
lookup:
spin_lock(&dlm->spinlock);
tmpres = __dlm_lookup_lockres_full(dlm, lockid, namelen, hash);
if (tmpres) {
spin_unlock(&dlm->spinlock);
spin_lock(&tmpres->spinlock);
/* Wait on the thread that is mastering the resource */
if (tmpres->owner == DLM_LOCK_RES_OWNER_UNKNOWN) {
__dlm_wait_on_lockres(tmpres);
BUG_ON(tmpres->owner == DLM_LOCK_RES_OWNER_UNKNOWN);
spin_unlock(&tmpres->spinlock);
dlm_lockres_put(tmpres);
tmpres = NULL;
goto lookup;
}
/* Wait on the resource purge to complete before continuing */
if (tmpres->state & DLM_LOCK_RES_DROPPING_REF) {
BUG_ON(tmpres->owner == dlm->node_num);
__dlm_wait_on_lockres_flags(tmpres,
DLM_LOCK_RES_DROPPING_REF);
spin_unlock(&tmpres->spinlock);
dlm_lockres_put(tmpres);
tmpres = NULL;
goto lookup;
}
/* Grab inflight ref to pin the resource */
dlm_lockres_grab_inflight_ref(dlm, tmpres);
spin_unlock(&tmpres->spinlock);
if (res)
dlm_lockres_put(res);
res = tmpres;
goto leave;
}
if (!res) {
spin_unlock(&dlm->spinlock);
mlog(0, "allocating a new resource\n");
/* nothing found and we need to allocate one. */
alloc_mle = kmem_cache_alloc(dlm_mle_cache, GFP_NOFS);
if (!alloc_mle)
goto leave;
res = dlm_new_lockres(dlm, lockid, namelen);
if (!res)
goto leave;
goto lookup;
}
mlog(0, "no lockres found, allocated our own: %p\n", res);
if (flags & LKM_LOCAL) {
/* caller knows it's safe to assume it's not mastered elsewhere
* DONE! return right away */
spin_lock(&res->spinlock);
dlm_change_lockres_owner(dlm, res, dlm->node_num);
__dlm_insert_lockres(dlm, res);
dlm_lockres_grab_inflight_ref(dlm, res);
spin_unlock(&res->spinlock);
spin_unlock(&dlm->spinlock);
/* lockres still marked IN_PROGRESS */
goto wake_waiters;
}
/* check master list to see if another node has started mastering it */
spin_lock(&dlm->master_lock);
/* if we found a block, wait for lock to be mastered by another node */
blocked = dlm_find_mle(dlm, &mle, (char *)lockid, namelen);
if (blocked) {
int mig;
if (mle->type == DLM_MLE_MASTER) {
mlog(ML_ERROR, "master entry for nonexistent lock!\n");
BUG();
}
mig = (mle->type == DLM_MLE_MIGRATION);
/* if there is a migration in progress, let the migration
* finish before continuing. we can wait for the absence
* of the MIGRATION mle: either the migrate finished or
* one of the nodes died and the mle was cleaned up.
* if there is a BLOCK here, but it already has a master
* set, we are too late. the master does not have a ref
* for us in the refmap. detach the mle and drop it.
* either way, go back to the top and start over. */
if (mig || mle->master != O2NM_MAX_NODES) {
BUG_ON(mig && mle->master == dlm->node_num);
/* we arrived too late. the master does not
* have a ref for us. retry. */
mlog(0, "%s:%.*s: late on %s\n",
dlm->name, namelen, lockid,
mig ? "MIGRATION" : "BLOCK");
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
/* master is known, detach */
if (!mig)
dlm_mle_detach_hb_events(dlm, mle);
dlm_put_mle(mle);
mle = NULL;
/* this is lame, but we can't wait on either
* the mle or lockres waitqueue here */
if (mig)
msleep(100);
goto lookup;
}
} else {
/* go ahead and try to master lock on this node */
mle = alloc_mle;
/* make sure this does not get freed below */
alloc_mle = NULL;
dlm_init_mle(mle, DLM_MLE_MASTER, dlm, res, NULL, 0);
set_bit(dlm->node_num, mle->maybe_map);
__dlm_insert_mle(dlm, mle);
/* still holding the dlm spinlock, check the recovery map
* to see if there are any nodes that still need to be
* considered. these will not appear in the mle nodemap
* but they might own this lockres. wait on them. */
bit = find_next_bit(dlm->recovery_map, O2NM_MAX_NODES, 0);
if (bit < O2NM_MAX_NODES) {
mlog(0, "%s: res %.*s, At least one node (%d) "
"to recover before lock mastery can begin\n",
dlm->name, namelen, (char *)lockid, bit);
wait_on_recovery = 1;
}
}
/* at this point there is either a DLM_MLE_BLOCK or a
* DLM_MLE_MASTER on the master list, so it's safe to add the
* lockres to the hashtable. anyone who finds the lock will
* still have to wait on the IN_PROGRESS. */
/* finally add the lockres to its hash bucket */
__dlm_insert_lockres(dlm, res);
/* Grab inflight ref to pin the resource */
spin_lock(&res->spinlock);
dlm_lockres_grab_inflight_ref(dlm, res);
spin_unlock(&res->spinlock);
/* get an extra ref on the mle in case this is a BLOCK
* if so, the creator of the BLOCK may try to put the last
* ref at this time in the assert master handler, so we
* need an extra one to keep from a bad ptr deref. */
dlm_get_mle_inuse(mle);
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
redo_request:
while (wait_on_recovery) {
/* any cluster changes that occurred after dropping the
* dlm spinlock would be detectable be a change on the mle,
* so we only need to clear out the recovery map once. */
if (dlm_is_recovery_lock(lockid, namelen)) {
mlog(0, "%s: Recovery map is not empty, but must "
"master $RECOVERY lock now\n", dlm->name);
if (!dlm_pre_master_reco_lockres(dlm, res))
wait_on_recovery = 0;
else {
mlog(0, "%s: waiting 500ms for heartbeat state "
"change\n", dlm->name);
msleep(500);
}
continue;
}
dlm_kick_recovery_thread(dlm);
msleep(1000);
dlm_wait_for_recovery(dlm);
spin_lock(&dlm->spinlock);
bit = find_next_bit(dlm->recovery_map, O2NM_MAX_NODES, 0);
if (bit < O2NM_MAX_NODES) {
mlog(0, "%s: res %.*s, At least one node (%d) "
"to recover before lock mastery can begin\n",
dlm->name, namelen, (char *)lockid, bit);
wait_on_recovery = 1;
} else
wait_on_recovery = 0;
spin_unlock(&dlm->spinlock);
if (wait_on_recovery)
dlm_wait_for_node_recovery(dlm, bit, 10000);
}
/* must wait for lock to be mastered elsewhere */
if (blocked)
goto wait;
ret = -EINVAL;
dlm_node_iter_init(mle->vote_map, &iter);
while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
ret = dlm_do_master_request(res, mle, nodenum);
if (ret < 0)
mlog_errno(ret);
if (mle->master != O2NM_MAX_NODES) {
/* found a master ! */
if (mle->master <= nodenum)
break;
/* if our master request has not reached the master
* yet, keep going until it does. this is how the
* master will know that asserts are needed back to
* the lower nodes. */
mlog(0, "%s: res %.*s, Requests only up to %u but "
"master is %u, keep going\n", dlm->name, namelen,
lockid, nodenum, mle->master);
}
}
wait:
/* keep going until the response map includes all nodes */
ret = dlm_wait_for_lock_mastery(dlm, res, mle, &blocked);
if (ret < 0) {
wait_on_recovery = 1;
mlog(0, "%s: res %.*s, Node map changed, redo the master "
"request now, blocked=%d\n", dlm->name, res->lockname.len,
res->lockname.name, blocked);
if (++tries > 20) {
mlog(ML_ERROR, "%s: res %.*s, Spinning on "
"dlm_wait_for_lock_mastery, blocked = %d\n",
dlm->name, res->lockname.len,
res->lockname.name, blocked);
dlm_print_one_lock_resource(res);
dlm_print_one_mle(mle);
tries = 0;
}
goto redo_request;
}
mlog(0, "%s: res %.*s, Mastered by %u\n", dlm->name, res->lockname.len,
res->lockname.name, res->owner);
/* make sure we never continue without this */
BUG_ON(res->owner == O2NM_MAX_NODES);
/* master is known, detach if not already detached */
dlm_mle_detach_hb_events(dlm, mle);
dlm_put_mle(mle);
/* put the extra ref */
dlm_put_mle_inuse(mle);
wake_waiters:
spin_lock(&res->spinlock);
res->state &= ~DLM_LOCK_RES_IN_PROGRESS;
spin_unlock(&res->spinlock);
wake_up(&res->wq);
leave:
/* need to free the unused mle */
if (alloc_mle)
kmem_cache_free(dlm_mle_cache, alloc_mle);
return res;
}
#define DLM_MASTERY_TIMEOUT_MS 5000
static int dlm_wait_for_lock_mastery(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_master_list_entry *mle,
int *blocked)
{
u8 m;
int ret, bit;
int map_changed, voting_done;
int assert, sleep;
recheck:
ret = 0;
assert = 0;
/* check if another node has already become the owner */
spin_lock(&res->spinlock);
if (res->owner != DLM_LOCK_RES_OWNER_UNKNOWN) {
mlog(0, "%s:%.*s: owner is suddenly %u\n", dlm->name,
res->lockname.len, res->lockname.name, res->owner);
spin_unlock(&res->spinlock);
/* this will cause the master to re-assert across
* the whole cluster, freeing up mles */
if (res->owner != dlm->node_num) {
ret = dlm_do_master_request(res, mle, res->owner);
if (ret < 0) {
/* give recovery a chance to run */
mlog(ML_ERROR, "link to %u went down?: %d\n", res->owner, ret);
msleep(500);
goto recheck;
}
}
ret = 0;
goto leave;
}
spin_unlock(&res->spinlock);
spin_lock(&mle->spinlock);
m = mle->master;
map_changed = (memcmp(mle->vote_map, mle->node_map,
sizeof(mle->vote_map)) != 0);
voting_done = (memcmp(mle->vote_map, mle->response_map,
sizeof(mle->vote_map)) == 0);
/* restart if we hit any errors */
if (map_changed) {
int b;
mlog(0, "%s: %.*s: node map changed, restarting\n",
dlm->name, res->lockname.len, res->lockname.name);
ret = dlm_restart_lock_mastery(dlm, res, mle, *blocked);
b = (mle->type == DLM_MLE_BLOCK);
if ((*blocked && !b) || (!*blocked && b)) {
mlog(0, "%s:%.*s: status change: old=%d new=%d\n",
dlm->name, res->lockname.len, res->lockname.name,
*blocked, b);
*blocked = b;
}
spin_unlock(&mle->spinlock);
if (ret < 0) {
mlog_errno(ret);
goto leave;
}
mlog(0, "%s:%.*s: restart lock mastery succeeded, "
"rechecking now\n", dlm->name, res->lockname.len,
res->lockname.name);
goto recheck;
} else {
if (!voting_done) {
mlog(0, "map not changed and voting not done "
"for %s:%.*s\n", dlm->name, res->lockname.len,
res->lockname.name);
}
}
if (m != O2NM_MAX_NODES) {
/* another node has done an assert!
* all done! */
sleep = 0;
} else {
sleep = 1;
/* have all nodes responded? */
if (voting_done && !*blocked) {
bit = find_next_bit(mle->maybe_map, O2NM_MAX_NODES, 0);
if (dlm->node_num <= bit) {
/* my node number is lowest.
* now tell other nodes that I am
* mastering this. */
mle->master = dlm->node_num;
/* ref was grabbed in get_lock_resource
* will be dropped in dlmlock_master */
assert = 1;
sleep = 0;
}
/* if voting is done, but we have not received
* an assert master yet, we must sleep */
}
}
spin_unlock(&mle->spinlock);
/* sleep if we haven't finished voting yet */
if (sleep) {
unsigned long timeo = msecs_to_jiffies(DLM_MASTERY_TIMEOUT_MS);
/*
if (atomic_read(&mle->mle_refs.refcount) < 2)
mlog(ML_ERROR, "mle (%p) refs=%d, name=%.*s\n", mle,
atomic_read(&mle->mle_refs.refcount),
res->lockname.len, res->lockname.name);
*/
atomic_set(&mle->woken, 0);
(void)wait_event_timeout(mle->wq,
(atomic_read(&mle->woken) == 1),
timeo);
if (res->owner == O2NM_MAX_NODES) {
mlog(0, "%s:%.*s: waiting again\n", dlm->name,
res->lockname.len, res->lockname.name);
goto recheck;
}
mlog(0, "done waiting, master is %u\n", res->owner);
ret = 0;
goto leave;
}
ret = 0; /* done */
if (assert) {
m = dlm->node_num;
mlog(0, "about to master %.*s here, this=%u\n",
res->lockname.len, res->lockname.name, m);
ret = dlm_do_assert_master(dlm, res, mle->vote_map, 0);
if (ret) {
/* This is a failure in the network path,
* not in the response to the assert_master
* (any nonzero response is a BUG on this node).
* Most likely a socket just got disconnected
* due to node death. */
mlog_errno(ret);
}
/* no longer need to restart lock mastery.
* all living nodes have been contacted. */
ret = 0;
}
/* set the lockres owner */
spin_lock(&res->spinlock);
/* mastery reference obtained either during
* assert_master_handler or in get_lock_resource */
dlm_change_lockres_owner(dlm, res, m);
spin_unlock(&res->spinlock);
leave:
return ret;
}
struct dlm_bitmap_diff_iter
{
int curnode;
unsigned long *orig_bm;
unsigned long *cur_bm;
unsigned long diff_bm[BITS_TO_LONGS(O2NM_MAX_NODES)];
};
enum dlm_node_state_change
{
NODE_DOWN = -1,
NODE_NO_CHANGE = 0,
NODE_UP
};
static void dlm_bitmap_diff_iter_init(struct dlm_bitmap_diff_iter *iter,
unsigned long *orig_bm,
unsigned long *cur_bm)
{
unsigned long p1, p2;
int i;
iter->curnode = -1;
iter->orig_bm = orig_bm;
iter->cur_bm = cur_bm;
for (i = 0; i < BITS_TO_LONGS(O2NM_MAX_NODES); i++) {
p1 = *(iter->orig_bm + i);
p2 = *(iter->cur_bm + i);
iter->diff_bm[i] = (p1 & ~p2) | (p2 & ~p1);
}
}
static int dlm_bitmap_diff_iter_next(struct dlm_bitmap_diff_iter *iter,
enum dlm_node_state_change *state)
{
int bit;
if (iter->curnode >= O2NM_MAX_NODES)
return -ENOENT;
bit = find_next_bit(iter->diff_bm, O2NM_MAX_NODES,
iter->curnode+1);
if (bit >= O2NM_MAX_NODES) {
iter->curnode = O2NM_MAX_NODES;
return -ENOENT;
}
/* if it was there in the original then this node died */
if (test_bit(bit, iter->orig_bm))
*state = NODE_DOWN;
else
*state = NODE_UP;
iter->curnode = bit;
return bit;
}
static int dlm_restart_lock_mastery(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_master_list_entry *mle,
int blocked)
{
struct dlm_bitmap_diff_iter bdi;
enum dlm_node_state_change sc;
int node;
int ret = 0;
mlog(0, "something happened such that the "
"master process may need to be restarted!\n");
assert_spin_locked(&mle->spinlock);
dlm_bitmap_diff_iter_init(&bdi, mle->vote_map, mle->node_map);
node = dlm_bitmap_diff_iter_next(&bdi, &sc);
while (node >= 0) {
if (sc == NODE_UP) {
/* a node came up. clear any old vote from
* the response map and set it in the vote map
* then restart the mastery. */
mlog(ML_NOTICE, "node %d up while restarting\n", node);
/* redo the master request, but only for the new node */
mlog(0, "sending request to new node\n");
clear_bit(node, mle->response_map);
set_bit(node, mle->vote_map);
} else {
mlog(ML_ERROR, "node down! %d\n", node);
if (blocked) {
int lowest = find_next_bit(mle->maybe_map,
O2NM_MAX_NODES, 0);
/* act like it was never there */
clear_bit(node, mle->maybe_map);
if (node == lowest) {
mlog(0, "expected master %u died"
" while this node was blocked "
"waiting on it!\n", node);
lowest = find_next_bit(mle->maybe_map,
O2NM_MAX_NODES,
lowest+1);
if (lowest < O2NM_MAX_NODES) {
mlog(0, "%s:%.*s:still "
"blocked. waiting on %u "
"now\n", dlm->name,
res->lockname.len,
res->lockname.name,
lowest);
} else {
/* mle is an MLE_BLOCK, but
* there is now nothing left to
* block on. we need to return
* all the way back out and try
* again with an MLE_MASTER.
* dlm_do_local_recovery_cleanup
* has already run, so the mle
* refcount is ok */
mlog(0, "%s:%.*s: no "
"longer blocking. try to "
"master this here\n",
dlm->name,
res->lockname.len,
res->lockname.name);
mle->type = DLM_MLE_MASTER;
mle->mleres = res;
}
}
}
/* now blank out everything, as if we had never
* contacted anyone */
memset(mle->maybe_map, 0, sizeof(mle->maybe_map));
memset(mle->response_map, 0, sizeof(mle->response_map));
/* reset the vote_map to the current node_map */
memcpy(mle->vote_map, mle->node_map,
sizeof(mle->node_map));
/* put myself into the maybe map */
if (mle->type != DLM_MLE_BLOCK)
set_bit(dlm->node_num, mle->maybe_map);
}
ret = -EAGAIN;
node = dlm_bitmap_diff_iter_next(&bdi, &sc);
}
return ret;
}
/*
* DLM_MASTER_REQUEST_MSG
*
* returns: 0 on success,
* -errno on a network error
*
* on error, the caller should assume the target node is "dead"
*
*/
static int dlm_do_master_request(struct dlm_lock_resource *res,
struct dlm_master_list_entry *mle, int to)
{
struct dlm_ctxt *dlm = mle->dlm;
struct dlm_master_request request;
int ret, response=0, resend;
memset(&request, 0, sizeof(request));
request.node_idx = dlm->node_num;
BUG_ON(mle->type == DLM_MLE_MIGRATION);
request.namelen = (u8)mle->mnamelen;
memcpy(request.name, mle->mname, request.namelen);
again:
ret = o2net_send_message(DLM_MASTER_REQUEST_MSG, dlm->key, &request,
sizeof(request), to, &response);
if (ret < 0) {
if (ret == -ESRCH) {
/* should never happen */
mlog(ML_ERROR, "TCP stack not ready!\n");
BUG();
} else if (ret == -EINVAL) {
mlog(ML_ERROR, "bad args passed to o2net!\n");
BUG();
} else if (ret == -ENOMEM) {
mlog(ML_ERROR, "out of memory while trying to send "
"network message! retrying\n");
/* this is totally crude */
msleep(50);
goto again;
} else if (!dlm_is_host_down(ret)) {
/* not a network error. bad. */
mlog_errno(ret);
mlog(ML_ERROR, "unhandled error!");
BUG();
}
/* all other errors should be network errors,
* and likely indicate node death */
mlog(ML_ERROR, "link to %d went down!\n", to);
goto out;
}
ret = 0;
resend = 0;
spin_lock(&mle->spinlock);
switch (response) {
case DLM_MASTER_RESP_YES:
set_bit(to, mle->response_map);
mlog(0, "node %u is the master, response=YES\n", to);
mlog(0, "%s:%.*s: master node %u now knows I have a "
"reference\n", dlm->name, res->lockname.len,
res->lockname.name, to);
mle->master = to;
break;
case DLM_MASTER_RESP_NO:
mlog(0, "node %u not master, response=NO\n", to);
set_bit(to, mle->response_map);
break;
case DLM_MASTER_RESP_MAYBE:
mlog(0, "node %u not master, response=MAYBE\n", to);
set_bit(to, mle->response_map);
set_bit(to, mle->maybe_map);
break;
case DLM_MASTER_RESP_ERROR:
mlog(0, "node %u hit an error, resending\n", to);
resend = 1;
response = 0;
break;
default:
mlog(ML_ERROR, "bad response! %u\n", response);
BUG();
}
spin_unlock(&mle->spinlock);
if (resend) {
/* this is also totally crude */
msleep(50);
goto again;
}
out:
return ret;
}
/*
* locks that can be taken here:
* dlm->spinlock
* res->spinlock
* mle->spinlock
* dlm->master_list
*
* if possible, TRIM THIS DOWN!!!
*/
int dlm_master_request_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
u8 response = DLM_MASTER_RESP_MAYBE;
struct dlm_ctxt *dlm = data;
struct dlm_lock_resource *res = NULL;
struct dlm_master_request *request = (struct dlm_master_request *) msg->buf;
struct dlm_master_list_entry *mle = NULL, *tmpmle = NULL;
char *name;
unsigned int namelen, hash;
int found, ret;
int set_maybe;
int dispatch_assert = 0;
if (!dlm_grab(dlm))
return DLM_MASTER_RESP_NO;
if (!dlm_domain_fully_joined(dlm)) {
response = DLM_MASTER_RESP_NO;
goto send_response;
}
name = request->name;
namelen = request->namelen;
hash = dlm_lockid_hash(name, namelen);
if (namelen > DLM_LOCKID_NAME_MAX) {
response = DLM_IVBUFLEN;
goto send_response;
}
way_up_top:
spin_lock(&dlm->spinlock);
res = __dlm_lookup_lockres(dlm, name, namelen, hash);
if (res) {
spin_unlock(&dlm->spinlock);
/* take care of the easy cases up front */
spin_lock(&res->spinlock);
if (res->state & (DLM_LOCK_RES_RECOVERING|
DLM_LOCK_RES_MIGRATING)) {
spin_unlock(&res->spinlock);
mlog(0, "returning DLM_MASTER_RESP_ERROR since res is "
"being recovered/migrated\n");
response = DLM_MASTER_RESP_ERROR;
if (mle)
kmem_cache_free(dlm_mle_cache, mle);
goto send_response;
}
if (res->owner == dlm->node_num) {
dlm_lockres_set_refmap_bit(dlm, res, request->node_idx);
spin_unlock(&res->spinlock);
response = DLM_MASTER_RESP_YES;
if (mle)
kmem_cache_free(dlm_mle_cache, mle);
/* this node is the owner.
* there is some extra work that needs to
* happen now. the requesting node has
* caused all nodes up to this one to
* create mles. this node now needs to
* go back and clean those up. */
dispatch_assert = 1;
goto send_response;
} else if (res->owner != DLM_LOCK_RES_OWNER_UNKNOWN) {
spin_unlock(&res->spinlock);
// mlog(0, "node %u is the master\n", res->owner);
response = DLM_MASTER_RESP_NO;
if (mle)
kmem_cache_free(dlm_mle_cache, mle);
goto send_response;
}
/* ok, there is no owner. either this node is
* being blocked, or it is actively trying to
* master this lock. */
if (!(res->state & DLM_LOCK_RES_IN_PROGRESS)) {
mlog(ML_ERROR, "lock with no owner should be "
"in-progress!\n");
BUG();
}
// mlog(0, "lockres is in progress...\n");
spin_lock(&dlm->master_lock);
found = dlm_find_mle(dlm, &tmpmle, name, namelen);
if (!found) {
mlog(ML_ERROR, "no mle found for this lock!\n");
BUG();
}
set_maybe = 1;
spin_lock(&tmpmle->spinlock);
if (tmpmle->type == DLM_MLE_BLOCK) {
// mlog(0, "this node is waiting for "
// "lockres to be mastered\n");
response = DLM_MASTER_RESP_NO;
} else if (tmpmle->type == DLM_MLE_MIGRATION) {
mlog(0, "node %u is master, but trying to migrate to "
"node %u.\n", tmpmle->master, tmpmle->new_master);
if (tmpmle->master == dlm->node_num) {
mlog(ML_ERROR, "no owner on lockres, but this "
"node is trying to migrate it to %u?!\n",
tmpmle->new_master);
BUG();
} else {
/* the real master can respond on its own */
response = DLM_MASTER_RESP_NO;
}
} else if (tmpmle->master != DLM_LOCK_RES_OWNER_UNKNOWN) {
set_maybe = 0;
if (tmpmle->master == dlm->node_num) {
response = DLM_MASTER_RESP_YES;
/* this node will be the owner.
* go back and clean the mles on any
* other nodes */
dispatch_assert = 1;
dlm_lockres_set_refmap_bit(dlm, res,
request->node_idx);
} else
response = DLM_MASTER_RESP_NO;
} else {
// mlog(0, "this node is attempting to "
// "master lockres\n");
response = DLM_MASTER_RESP_MAYBE;
}
if (set_maybe)
set_bit(request->node_idx, tmpmle->maybe_map);
spin_unlock(&tmpmle->spinlock);
spin_unlock(&dlm->master_lock);
spin_unlock(&res->spinlock);
/* keep the mle attached to heartbeat events */
dlm_put_mle(tmpmle);
if (mle)
kmem_cache_free(dlm_mle_cache, mle);
goto send_response;
}
/*
* lockres doesn't exist on this node
* if there is an MLE_BLOCK, return NO
* if there is an MLE_MASTER, return MAYBE
* otherwise, add an MLE_BLOCK, return NO
*/
spin_lock(&dlm->master_lock);
found = dlm_find_mle(dlm, &tmpmle, name, namelen);
if (!found) {
/* this lockid has never been seen on this node yet */
// mlog(0, "no mle found\n");
if (!mle) {
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
mle = kmem_cache_alloc(dlm_mle_cache, GFP_NOFS);
if (!mle) {
response = DLM_MASTER_RESP_ERROR;
mlog_errno(-ENOMEM);
goto send_response;
}
goto way_up_top;
}
// mlog(0, "this is second time thru, already allocated, "
// "add the block.\n");
dlm_init_mle(mle, DLM_MLE_BLOCK, dlm, NULL, name, namelen);
set_bit(request->node_idx, mle->maybe_map);
__dlm_insert_mle(dlm, mle);
response = DLM_MASTER_RESP_NO;
} else {
// mlog(0, "mle was found\n");
set_maybe = 1;
spin_lock(&tmpmle->spinlock);
if (tmpmle->master == dlm->node_num) {
mlog(ML_ERROR, "no lockres, but an mle with this node as master!\n");
BUG();
}
if (tmpmle->type == DLM_MLE_BLOCK)
response = DLM_MASTER_RESP_NO;
else if (tmpmle->type == DLM_MLE_MIGRATION) {
mlog(0, "migration mle was found (%u->%u)\n",
tmpmle->master, tmpmle->new_master);
/* real master can respond on its own */
response = DLM_MASTER_RESP_NO;
} else
response = DLM_MASTER_RESP_MAYBE;
if (set_maybe)
set_bit(request->node_idx, tmpmle->maybe_map);
spin_unlock(&tmpmle->spinlock);
}
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
if (found) {
/* keep the mle attached to heartbeat events */
dlm_put_mle(tmpmle);
}
send_response:
/*
* __dlm_lookup_lockres() grabbed a reference to this lockres.
* The reference is released by dlm_assert_master_worker() under
* the call to dlm_dispatch_assert_master(). If
* dlm_assert_master_worker() isn't called, we drop it here.
*/
if (dispatch_assert) {
if (response != DLM_MASTER_RESP_YES)
mlog(ML_ERROR, "invalid response %d\n", response);
if (!res) {
mlog(ML_ERROR, "bad lockres while trying to assert!\n");
BUG();
}
mlog(0, "%u is the owner of %.*s, cleaning everyone else\n",
dlm->node_num, res->lockname.len, res->lockname.name);
ret = dlm_dispatch_assert_master(dlm, res, 0, request->node_idx,
DLM_ASSERT_MASTER_MLE_CLEANUP);
if (ret < 0) {
mlog(ML_ERROR, "failed to dispatch assert master work\n");
response = DLM_MASTER_RESP_ERROR;
dlm_lockres_put(res);
}
} else {
if (res)
dlm_lockres_put(res);
}
dlm_put(dlm);
return response;
}
/*
* DLM_ASSERT_MASTER_MSG
*/
/*
* NOTE: this can be used for debugging
* can periodically run all locks owned by this node
* and re-assert across the cluster...
*/
static int dlm_do_assert_master(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
void *nodemap, u32 flags)
{
struct dlm_assert_master assert;
int to, tmpret;
struct dlm_node_iter iter;
int ret = 0;
int reassert;
const char *lockname = res->lockname.name;
unsigned int namelen = res->lockname.len;
BUG_ON(namelen > O2NM_MAX_NAME_LEN);
spin_lock(&res->spinlock);
res->state |= DLM_LOCK_RES_SETREF_INPROG;
spin_unlock(&res->spinlock);
again:
reassert = 0;
/* note that if this nodemap is empty, it returns 0 */
dlm_node_iter_init(nodemap, &iter);
while ((to = dlm_node_iter_next(&iter)) >= 0) {
int r = 0;
struct dlm_master_list_entry *mle = NULL;
mlog(0, "sending assert master to %d (%.*s)\n", to,
namelen, lockname);
memset(&assert, 0, sizeof(assert));
assert.node_idx = dlm->node_num;
assert.namelen = namelen;
memcpy(assert.name, lockname, namelen);
assert.flags = cpu_to_be32(flags);
tmpret = o2net_send_message(DLM_ASSERT_MASTER_MSG, dlm->key,
&assert, sizeof(assert), to, &r);
if (tmpret < 0) {
mlog(ML_ERROR, "Error %d when sending message %u (key "
"0x%x) to node %u\n", tmpret,
DLM_ASSERT_MASTER_MSG, dlm->key, to);
if (!dlm_is_host_down(tmpret)) {
mlog(ML_ERROR, "unhandled error=%d!\n", tmpret);
BUG();
}
/* a node died. finish out the rest of the nodes. */
mlog(0, "link to %d went down!\n", to);
/* any nonzero status return will do */
ret = tmpret;
r = 0;
} else if (r < 0) {
/* ok, something horribly messed. kill thyself. */
mlog(ML_ERROR,"during assert master of %.*s to %u, "
"got %d.\n", namelen, lockname, to, r);
spin_lock(&dlm->spinlock);
spin_lock(&dlm->master_lock);
if (dlm_find_mle(dlm, &mle, (char *)lockname,
namelen)) {
dlm_print_one_mle(mle);
__dlm_put_mle(mle);
}
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
BUG();
}
if (r & DLM_ASSERT_RESPONSE_REASSERT &&
!(r & DLM_ASSERT_RESPONSE_MASTERY_REF)) {
mlog(ML_ERROR, "%.*s: very strange, "
"master MLE but no lockres on %u\n",
namelen, lockname, to);
}
if (r & DLM_ASSERT_RESPONSE_REASSERT) {
mlog(0, "%.*s: node %u create mles on other "
"nodes and requests a re-assert\n",
namelen, lockname, to);
reassert = 1;
}
if (r & DLM_ASSERT_RESPONSE_MASTERY_REF) {
mlog(0, "%.*s: node %u has a reference to this "
"lockres, set the bit in the refmap\n",
namelen, lockname, to);
spin_lock(&res->spinlock);
dlm_lockres_set_refmap_bit(dlm, res, to);
spin_unlock(&res->spinlock);
}
}
if (reassert)
goto again;
spin_lock(&res->spinlock);
res->state &= ~DLM_LOCK_RES_SETREF_INPROG;
spin_unlock(&res->spinlock);
wake_up(&res->wq);
return ret;
}
/*
* locks that can be taken here:
* dlm->spinlock
* res->spinlock
* mle->spinlock
* dlm->master_list
*
* if possible, TRIM THIS DOWN!!!
*/
int dlm_assert_master_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
struct dlm_ctxt *dlm = data;
struct dlm_master_list_entry *mle = NULL;
struct dlm_assert_master *assert = (struct dlm_assert_master *)msg->buf;
struct dlm_lock_resource *res = NULL;
char *name;
unsigned int namelen, hash;
u32 flags;
int master_request = 0, have_lockres_ref = 0;
int ret = 0;
if (!dlm_grab(dlm))
return 0;
name = assert->name;
namelen = assert->namelen;
hash = dlm_lockid_hash(name, namelen);
flags = be32_to_cpu(assert->flags);
if (namelen > DLM_LOCKID_NAME_MAX) {
mlog(ML_ERROR, "Invalid name length!");
goto done;
}
spin_lock(&dlm->spinlock);
if (flags)
mlog(0, "assert_master with flags: %u\n", flags);
/* find the MLE */
spin_lock(&dlm->master_lock);
if (!dlm_find_mle(dlm, &mle, name, namelen)) {
/* not an error, could be master just re-asserting */
mlog(0, "just got an assert_master from %u, but no "
"MLE for it! (%.*s)\n", assert->node_idx,
namelen, name);
} else {
int bit = find_next_bit (mle->maybe_map, O2NM_MAX_NODES, 0);
if (bit >= O2NM_MAX_NODES) {
/* not necessarily an error, though less likely.
* could be master just re-asserting. */
mlog(0, "no bits set in the maybe_map, but %u "
"is asserting! (%.*s)\n", assert->node_idx,
namelen, name);
} else if (bit != assert->node_idx) {
if (flags & DLM_ASSERT_MASTER_MLE_CLEANUP) {
mlog(0, "master %u was found, %u should "
"back off\n", assert->node_idx, bit);
} else {
/* with the fix for bug 569, a higher node
* number winning the mastery will respond
* YES to mastery requests, but this node
* had no way of knowing. let it pass. */
mlog(0, "%u is the lowest node, "
"%u is asserting. (%.*s) %u must "
"have begun after %u won.\n", bit,
assert->node_idx, namelen, name, bit,
assert->node_idx);
}
}
if (mle->type == DLM_MLE_MIGRATION) {
if (flags & DLM_ASSERT_MASTER_MLE_CLEANUP) {
mlog(0, "%s:%.*s: got cleanup assert"
" from %u for migration\n",
dlm->name, namelen, name,
assert->node_idx);
} else if (!(flags & DLM_ASSERT_MASTER_FINISH_MIGRATION)) {
mlog(0, "%s:%.*s: got unrelated assert"
" from %u for migration, ignoring\n",
dlm->name, namelen, name,
assert->node_idx);
__dlm_put_mle(mle);
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
goto done;
}
}
}
spin_unlock(&dlm->master_lock);
/* ok everything checks out with the MLE
* now check to see if there is a lockres */
res = __dlm_lookup_lockres(dlm, name, namelen, hash);
if (res) {
spin_lock(&res->spinlock);
if (res->state & DLM_LOCK_RES_RECOVERING) {
mlog(ML_ERROR, "%u asserting but %.*s is "
"RECOVERING!\n", assert->node_idx, namelen, name);
goto kill;
}
if (!mle) {
if (res->owner != DLM_LOCK_RES_OWNER_UNKNOWN &&
res->owner != assert->node_idx) {
mlog(ML_ERROR, "DIE! Mastery assert from %u, "
"but current owner is %u! (%.*s)\n",
assert->node_idx, res->owner, namelen,
name);
__dlm_print_one_lock_resource(res);
BUG();
}
} else if (mle->type != DLM_MLE_MIGRATION) {
if (res->owner != DLM_LOCK_RES_OWNER_UNKNOWN) {
/* owner is just re-asserting */
if (res->owner == assert->node_idx) {
mlog(0, "owner %u re-asserting on "
"lock %.*s\n", assert->node_idx,
namelen, name);
goto ok;
}
mlog(ML_ERROR, "got assert_master from "
"node %u, but %u is the owner! "
"(%.*s)\n", assert->node_idx,
res->owner, namelen, name);
goto kill;
}
if (!(res->state & DLM_LOCK_RES_IN_PROGRESS)) {
mlog(ML_ERROR, "got assert from %u, but lock "
"with no owner should be "
"in-progress! (%.*s)\n",
assert->node_idx,
namelen, name);
goto kill;
}
} else /* mle->type == DLM_MLE_MIGRATION */ {
/* should only be getting an assert from new master */
if (assert->node_idx != mle->new_master) {
mlog(ML_ERROR, "got assert from %u, but "
"new master is %u, and old master "
"was %u (%.*s)\n",
assert->node_idx, mle->new_master,
mle->master, namelen, name);
goto kill;
}
}
ok:
spin_unlock(&res->spinlock);
}
// mlog(0, "woo! got an assert_master from node %u!\n",
// assert->node_idx);
if (mle) {
int extra_ref = 0;
int nn = -1;
int rr, err = 0;
spin_lock(&mle->spinlock);
if (mle->type == DLM_MLE_BLOCK || mle->type == DLM_MLE_MIGRATION)
extra_ref = 1;
else {
/* MASTER mle: if any bits set in the response map
* then the calling node needs to re-assert to clear
* up nodes that this node contacted */
while ((nn = find_next_bit (mle->response_map, O2NM_MAX_NODES,
nn+1)) < O2NM_MAX_NODES) {
if (nn != dlm->node_num && nn != assert->node_idx)
master_request = 1;
}
}
mle->master = assert->node_idx;
atomic_set(&mle->woken, 1);
wake_up(&mle->wq);
spin_unlock(&mle->spinlock);
if (res) {
int wake = 0;
spin_lock(&res->spinlock);
if (mle->type == DLM_MLE_MIGRATION) {
mlog(0, "finishing off migration of lockres %.*s, "
"from %u to %u\n",
res->lockname.len, res->lockname.name,
dlm->node_num, mle->new_master);
res->state &= ~DLM_LOCK_RES_MIGRATING;
wake = 1;
dlm_change_lockres_owner(dlm, res, mle->new_master);
BUG_ON(res->state & DLM_LOCK_RES_DIRTY);
} else {
dlm_change_lockres_owner(dlm, res, mle->master);
}
spin_unlock(&res->spinlock);
have_lockres_ref = 1;
if (wake)
wake_up(&res->wq);
}
/* master is known, detach if not already detached.
* ensures that only one assert_master call will happen
* on this mle. */
spin_lock(&dlm->master_lock);
rr = atomic_read(&mle->mle_refs.refcount);
if (mle->inuse > 0) {
if (extra_ref && rr < 3)
err = 1;
else if (!extra_ref && rr < 2)
err = 1;
} else {
if (extra_ref && rr < 2)
err = 1;
else if (!extra_ref && rr < 1)
err = 1;
}
if (err) {
mlog(ML_ERROR, "%s:%.*s: got assert master from %u "
"that will mess up this node, refs=%d, extra=%d, "
"inuse=%d\n", dlm->name, namelen, name,
assert->node_idx, rr, extra_ref, mle->inuse);
dlm_print_one_mle(mle);
}
__dlm_unlink_mle(dlm, mle);
__dlm_mle_detach_hb_events(dlm, mle);
__dlm_put_mle(mle);
if (extra_ref) {
/* the assert master message now balances the extra
* ref given by the master / migration request message.
* if this is the last put, it will be removed
* from the list. */
__dlm_put_mle(mle);
}
spin_unlock(&dlm->master_lock);
} else if (res) {
if (res->owner != assert->node_idx) {
mlog(0, "assert_master from %u, but current "
"owner is %u (%.*s), no mle\n", assert->node_idx,
res->owner, namelen, name);
}
}
spin_unlock(&dlm->spinlock);
done:
ret = 0;
if (res) {
spin_lock(&res->spinlock);
res->state |= DLM_LOCK_RES_SETREF_INPROG;
spin_unlock(&res->spinlock);
*ret_data = (void *)res;
}
dlm_put(dlm);
if (master_request) {
mlog(0, "need to tell master to reassert\n");
/* positive. negative would shoot down the node. */
ret |= DLM_ASSERT_RESPONSE_REASSERT;
if (!have_lockres_ref) {
mlog(ML_ERROR, "strange, got assert from %u, MASTER "
"mle present here for %s:%.*s, but no lockres!\n",
assert->node_idx, dlm->name, namelen, name);
}
}
if (have_lockres_ref) {
/* let the master know we have a reference to the lockres */
ret |= DLM_ASSERT_RESPONSE_MASTERY_REF;
mlog(0, "%s:%.*s: got assert from %u, need a ref\n",
dlm->name, namelen, name, assert->node_idx);
}
return ret;
kill:
/* kill the caller! */
mlog(ML_ERROR, "Bad message received from another node. Dumping state "
"and killing the other node now! This node is OK and can continue.\n");
__dlm_print_one_lock_resource(res);
spin_unlock(&res->spinlock);
spin_unlock(&dlm->spinlock);
*ret_data = (void *)res;
dlm_put(dlm);
return -EINVAL;
}
void dlm_assert_master_post_handler(int status, void *data, void *ret_data)
{
struct dlm_lock_resource *res = (struct dlm_lock_resource *)ret_data;
if (ret_data) {
spin_lock(&res->spinlock);
res->state &= ~DLM_LOCK_RES_SETREF_INPROG;
spin_unlock(&res->spinlock);
wake_up(&res->wq);
dlm_lockres_put(res);
}
return;
}
int dlm_dispatch_assert_master(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
int ignore_higher, u8 request_from, u32 flags)
{
struct dlm_work_item *item;
item = kzalloc(sizeof(*item), GFP_ATOMIC);
if (!item)
return -ENOMEM;
/* queue up work for dlm_assert_master_worker */
dlm_grab(dlm); /* get an extra ref for the work item */
dlm_init_work_item(dlm, item, dlm_assert_master_worker, NULL);
item->u.am.lockres = res; /* already have a ref */
/* can optionally ignore node numbers higher than this node */
item->u.am.ignore_higher = ignore_higher;
item->u.am.request_from = request_from;
item->u.am.flags = flags;
if (ignore_higher)
mlog(0, "IGNORE HIGHER: %.*s\n", res->lockname.len,
res->lockname.name);
spin_lock(&dlm->work_lock);
list_add_tail(&item->list, &dlm->work_list);
spin_unlock(&dlm->work_lock);
queue_work(dlm->dlm_worker, &dlm->dispatched_work);
return 0;
}
static void dlm_assert_master_worker(struct dlm_work_item *item, void *data)
{
struct dlm_ctxt *dlm = data;
int ret = 0;
struct dlm_lock_resource *res;
unsigned long nodemap[BITS_TO_LONGS(O2NM_MAX_NODES)];
int ignore_higher;
int bit;
u8 request_from;
u32 flags;
dlm = item->dlm;
res = item->u.am.lockres;
ignore_higher = item->u.am.ignore_higher;
request_from = item->u.am.request_from;
flags = item->u.am.flags;
spin_lock(&dlm->spinlock);
memcpy(nodemap, dlm->domain_map, sizeof(nodemap));
spin_unlock(&dlm->spinlock);
clear_bit(dlm->node_num, nodemap);
if (ignore_higher) {
/* if is this just to clear up mles for nodes below
* this node, do not send the message to the original
* caller or any node number higher than this */
clear_bit(request_from, nodemap);
bit = dlm->node_num;
while (1) {
bit = find_next_bit(nodemap, O2NM_MAX_NODES,
bit+1);
if (bit >= O2NM_MAX_NODES)
break;
clear_bit(bit, nodemap);
}
}
/*
* If we're migrating this lock to someone else, we are no
* longer allowed to assert out own mastery. OTOH, we need to
* prevent migration from starting while we're still asserting
* our dominance. The reserved ast delays migration.
*/
spin_lock(&res->spinlock);
if (res->state & DLM_LOCK_RES_MIGRATING) {
mlog(0, "Someone asked us to assert mastery, but we're "
"in the middle of migration. Skipping assert, "
"the new master will handle that.\n");
spin_unlock(&res->spinlock);
goto put;
} else
__dlm_lockres_reserve_ast(res);
spin_unlock(&res->spinlock);
/* this call now finishes out the nodemap
* even if one or more nodes die */
mlog(0, "worker about to master %.*s here, this=%u\n",
res->lockname.len, res->lockname.name, dlm->node_num);
ret = dlm_do_assert_master(dlm, res, nodemap, flags);
if (ret < 0) {
/* no need to restart, we are done */
if (!dlm_is_host_down(ret))
mlog_errno(ret);
}
/* Ok, we've asserted ourselves. Let's let migration start. */
dlm_lockres_release_ast(dlm, res);
put:
dlm_lockres_put(res);
mlog(0, "finished with dlm_assert_master_worker\n");
}
/* SPECIAL CASE for the $RECOVERY lock used by the recovery thread.
* We cannot wait for node recovery to complete to begin mastering this
* lockres because this lockres is used to kick off recovery! ;-)
* So, do a pre-check on all living nodes to see if any of those nodes
* think that $RECOVERY is currently mastered by a dead node. If so,
* we wait a short time to allow that node to get notified by its own
* heartbeat stack, then check again. All $RECOVERY lock resources
* mastered by dead nodes are purged when the hearbeat callback is
* fired, so we can know for sure that it is safe to continue once
* the node returns a live node or no node. */
static int dlm_pre_master_reco_lockres(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res)
{
struct dlm_node_iter iter;
int nodenum;
int ret = 0;
u8 master = DLM_LOCK_RES_OWNER_UNKNOWN;
spin_lock(&dlm->spinlock);
dlm_node_iter_init(dlm->domain_map, &iter);
spin_unlock(&dlm->spinlock);
while ((nodenum = dlm_node_iter_next(&iter)) >= 0) {
/* do not send to self */
if (nodenum == dlm->node_num)
continue;
ret = dlm_do_master_requery(dlm, res, nodenum, &master);
if (ret < 0) {
mlog_errno(ret);
if (!dlm_is_host_down(ret))
BUG();
/* host is down, so answer for that node would be
* DLM_LOCK_RES_OWNER_UNKNOWN. continue. */
ret = 0;
}
if (master != DLM_LOCK_RES_OWNER_UNKNOWN) {
/* check to see if this master is in the recovery map */
spin_lock(&dlm->spinlock);
if (test_bit(master, dlm->recovery_map)) {
mlog(ML_NOTICE, "%s: node %u has not seen "
"node %u go down yet, and thinks the "
"dead node is mastering the recovery "
"lock. must wait.\n", dlm->name,
nodenum, master);
ret = -EAGAIN;
}
spin_unlock(&dlm->spinlock);
mlog(0, "%s: reco lock master is %u\n", dlm->name,
master);
break;
}
}
return ret;
}
/*
* DLM_DEREF_LOCKRES_MSG
*/
int dlm_drop_lockres_ref(struct dlm_ctxt *dlm, struct dlm_lock_resource *res)
{
struct dlm_deref_lockres deref;
int ret = 0, r;
const char *lockname;
unsigned int namelen;
lockname = res->lockname.name;
namelen = res->lockname.len;
BUG_ON(namelen > O2NM_MAX_NAME_LEN);
memset(&deref, 0, sizeof(deref));
deref.node_idx = dlm->node_num;
deref.namelen = namelen;
memcpy(deref.name, lockname, namelen);
ret = o2net_send_message(DLM_DEREF_LOCKRES_MSG, dlm->key,
&deref, sizeof(deref), res->owner, &r);
if (ret < 0)
mlog(ML_ERROR, "%s: res %.*s, error %d send DEREF to node %u\n",
dlm->name, namelen, lockname, ret, res->owner);
else if (r < 0) {
/* BAD. other node says I did not have a ref. */
mlog(ML_ERROR, "%s: res %.*s, DEREF to node %u got %d\n",
dlm->name, namelen, lockname, res->owner, r);
dlm_print_one_lock_resource(res);
BUG();
}
return ret;
}
int dlm_deref_lockres_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
struct dlm_ctxt *dlm = data;
struct dlm_deref_lockres *deref = (struct dlm_deref_lockres *)msg->buf;
struct dlm_lock_resource *res = NULL;
char *name;
unsigned int namelen;
int ret = -EINVAL;
u8 node;
unsigned int hash;
struct dlm_work_item *item;
int cleared = 0;
int dispatch = 0;
if (!dlm_grab(dlm))
return 0;
name = deref->name;
namelen = deref->namelen;
node = deref->node_idx;
if (namelen > DLM_LOCKID_NAME_MAX) {
mlog(ML_ERROR, "Invalid name length!");
goto done;
}
if (deref->node_idx >= O2NM_MAX_NODES) {
mlog(ML_ERROR, "Invalid node number: %u\n", node);
goto done;
}
hash = dlm_lockid_hash(name, namelen);
spin_lock(&dlm->spinlock);
res = __dlm_lookup_lockres_full(dlm, name, namelen, hash);
if (!res) {
spin_unlock(&dlm->spinlock);
mlog(ML_ERROR, "%s:%.*s: bad lockres name\n",
dlm->name, namelen, name);
goto done;
}
spin_unlock(&dlm->spinlock);
spin_lock(&res->spinlock);
if (res->state & DLM_LOCK_RES_SETREF_INPROG)
dispatch = 1;
else {
BUG_ON(res->state & DLM_LOCK_RES_DROPPING_REF);
if (test_bit(node, res->refmap)) {
dlm_lockres_clear_refmap_bit(dlm, res, node);
cleared = 1;
}
}
spin_unlock(&res->spinlock);
if (!dispatch) {
if (cleared)
dlm_lockres_calc_usage(dlm, res);
else {
mlog(ML_ERROR, "%s:%.*s: node %u trying to drop ref "
"but it is already dropped!\n", dlm->name,
res->lockname.len, res->lockname.name, node);
dlm_print_one_lock_resource(res);
}
ret = 0;
goto done;
}
item = kzalloc(sizeof(*item), GFP_NOFS);
if (!item) {
ret = -ENOMEM;
mlog_errno(ret);
goto done;
}
dlm_init_work_item(dlm, item, dlm_deref_lockres_worker, NULL);
item->u.dl.deref_res = res;
item->u.dl.deref_node = node;
spin_lock(&dlm->work_lock);
list_add_tail(&item->list, &dlm->work_list);
spin_unlock(&dlm->work_lock);
queue_work(dlm->dlm_worker, &dlm->dispatched_work);
return 0;
done:
if (res)
dlm_lockres_put(res);
dlm_put(dlm);
return ret;
}
static void dlm_deref_lockres_worker(struct dlm_work_item *item, void *data)
{
struct dlm_ctxt *dlm;
struct dlm_lock_resource *res;
u8 node;
u8 cleared = 0;
dlm = item->dlm;
res = item->u.dl.deref_res;
node = item->u.dl.deref_node;
spin_lock(&res->spinlock);
BUG_ON(res->state & DLM_LOCK_RES_DROPPING_REF);
if (test_bit(node, res->refmap)) {
__dlm_wait_on_lockres_flags(res, DLM_LOCK_RES_SETREF_INPROG);
dlm_lockres_clear_refmap_bit(dlm, res, node);
cleared = 1;
}
spin_unlock(&res->spinlock);
if (cleared) {
mlog(0, "%s:%.*s node %u ref dropped in dispatch\n",
dlm->name, res->lockname.len, res->lockname.name, node);
dlm_lockres_calc_usage(dlm, res);
} else {
mlog(ML_ERROR, "%s:%.*s: node %u trying to drop ref "
"but it is already dropped!\n", dlm->name,
res->lockname.len, res->lockname.name, node);
dlm_print_one_lock_resource(res);
}
dlm_lockres_put(res);
}
/*
* A migrateable resource is one that is :
* 1. locally mastered, and,
* 2. zero local locks, and,
* 3. one or more non-local locks, or, one or more references
* Returns 1 if yes, 0 if not.
*/
static int dlm_is_lockres_migrateable(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res)
{
enum dlm_lockres_list idx;
int nonlocal = 0, node_ref;
struct list_head *queue;
struct dlm_lock *lock;
u64 cookie;
assert_spin_locked(&res->spinlock);
if (res->owner != dlm->node_num)
return 0;
for (idx = DLM_GRANTED_LIST; idx <= DLM_BLOCKED_LIST; idx++) {
queue = dlm_list_idx_to_ptr(res, idx);
list_for_each_entry(lock, queue, list) {
if (lock->ml.node != dlm->node_num) {
nonlocal++;
continue;
}
cookie = be64_to_cpu(lock->ml.cookie);
mlog(0, "%s: Not migrateable res %.*s, lock %u:%llu on "
"%s list\n", dlm->name, res->lockname.len,
res->lockname.name,
dlm_get_lock_cookie_node(cookie),
dlm_get_lock_cookie_seq(cookie),
dlm_list_in_text(idx));
return 0;
}
}
if (!nonlocal) {
node_ref = find_next_bit(res->refmap, O2NM_MAX_NODES, 0);
if (node_ref >= O2NM_MAX_NODES)
return 0;
}
mlog(0, "%s: res %.*s, Migrateable\n", dlm->name, res->lockname.len,
res->lockname.name);
return 1;
}
/*
* DLM_MIGRATE_LOCKRES
*/
static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res, u8 target)
{
struct dlm_master_list_entry *mle = NULL;
struct dlm_master_list_entry *oldmle = NULL;
struct dlm_migratable_lockres *mres = NULL;
int ret = 0;
const char *name;
unsigned int namelen;
int mle_added = 0;
int wake = 0;
if (!dlm_grab(dlm))
return -EINVAL;
BUG_ON(target == O2NM_MAX_NODES);
name = res->lockname.name;
namelen = res->lockname.len;
mlog(0, "%s: Migrating %.*s to node %u\n", dlm->name, namelen, name,
target);
/* preallocate up front. if this fails, abort */
ret = -ENOMEM;
mres = (struct dlm_migratable_lockres *) __get_free_page(GFP_NOFS);
if (!mres) {
mlog_errno(ret);
goto leave;
}
mle = kmem_cache_alloc(dlm_mle_cache, GFP_NOFS);
if (!mle) {
mlog_errno(ret);
goto leave;
}
ret = 0;
/*
* clear any existing master requests and
* add the migration mle to the list
*/
spin_lock(&dlm->spinlock);
spin_lock(&dlm->master_lock);
ret = dlm_add_migration_mle(dlm, res, mle, &oldmle, name,
namelen, target, dlm->node_num);
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
if (ret == -EEXIST) {
mlog(0, "another process is already migrating it\n");
goto fail;
}
mle_added = 1;
/*
* set the MIGRATING flag and flush asts
* if we fail after this we need to re-dirty the lockres
*/
if (dlm_mark_lockres_migrating(dlm, res, target) < 0) {
mlog(ML_ERROR, "tried to migrate %.*s to %u, but "
"the target went down.\n", res->lockname.len,
res->lockname.name, target);
spin_lock(&res->spinlock);
res->state &= ~DLM_LOCK_RES_MIGRATING;
wake = 1;
spin_unlock(&res->spinlock);
ret = -EINVAL;
}
fail:
if (oldmle) {
/* master is known, detach if not already detached */
dlm_mle_detach_hb_events(dlm, oldmle);
dlm_put_mle(oldmle);
}
if (ret < 0) {
if (mle_added) {
dlm_mle_detach_hb_events(dlm, mle);
dlm_put_mle(mle);
} else if (mle) {
kmem_cache_free(dlm_mle_cache, mle);
mle = NULL;
}
goto leave;
}
/*
* at this point, we have a migration target, an mle
* in the master list, and the MIGRATING flag set on
* the lockres
*/
/* now that remote nodes are spinning on the MIGRATING flag,
* ensure that all assert_master work is flushed. */
flush_workqueue(dlm->dlm_worker);
/* get an extra reference on the mle.
* otherwise the assert_master from the new
* master will destroy this.
* also, make sure that all callers of dlm_get_mle
* take both dlm->spinlock and dlm->master_lock */
spin_lock(&dlm->spinlock);
spin_lock(&dlm->master_lock);
dlm_get_mle_inuse(mle);
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
/* notify new node and send all lock state */
/* call send_one_lockres with migration flag.
* this serves as notice to the target node that a
* migration is starting. */
ret = dlm_send_one_lockres(dlm, res, mres, target,
DLM_MRES_MIGRATION);
if (ret < 0) {
mlog(0, "migration to node %u failed with %d\n",
target, ret);
/* migration failed, detach and clean up mle */
dlm_mle_detach_hb_events(dlm, mle);
dlm_put_mle(mle);
dlm_put_mle_inuse(mle);
spin_lock(&res->spinlock);
res->state &= ~DLM_LOCK_RES_MIGRATING;
wake = 1;
spin_unlock(&res->spinlock);
if (dlm_is_host_down(ret))
dlm_wait_for_node_death(dlm, target,
DLM_NODE_DEATH_WAIT_MAX);
goto leave;
}
/* at this point, the target sends a message to all nodes,
* (using dlm_do_migrate_request). this node is skipped since
* we had to put an mle in the list to begin the process. this
* node now waits for target to do an assert master. this node
* will be the last one notified, ensuring that the migration
* is complete everywhere. if the target dies while this is
* going on, some nodes could potentially see the target as the
* master, so it is important that my recovery finds the migration
* mle and sets the master to UNKNOWN. */
/* wait for new node to assert master */
while (1) {
ret = wait_event_interruptible_timeout(mle->wq,
(atomic_read(&mle->woken) == 1),
msecs_to_jiffies(5000));
if (ret >= 0) {
if (atomic_read(&mle->woken) == 1 ||
res->owner == target)
break;
mlog(0, "%s:%.*s: timed out during migration\n",
dlm->name, res->lockname.len, res->lockname.name);
/* avoid hang during shutdown when migrating lockres
* to a node which also goes down */
if (dlm_is_node_dead(dlm, target)) {
mlog(0, "%s:%.*s: expected migration "
"target %u is no longer up, restarting\n",
dlm->name, res->lockname.len,
res->lockname.name, target);
ret = -EINVAL;
/* migration failed, detach and clean up mle */
dlm_mle_detach_hb_events(dlm, mle);
dlm_put_mle(mle);
dlm_put_mle_inuse(mle);
spin_lock(&res->spinlock);
res->state &= ~DLM_LOCK_RES_MIGRATING;
wake = 1;
spin_unlock(&res->spinlock);
goto leave;
}
} else
mlog(0, "%s:%.*s: caught signal during migration\n",
dlm->name, res->lockname.len, res->lockname.name);
}
/* all done, set the owner, clear the flag */
spin_lock(&res->spinlock);
dlm_set_lockres_owner(dlm, res, target);
res->state &= ~DLM_LOCK_RES_MIGRATING;
dlm_remove_nonlocal_locks(dlm, res);
spin_unlock(&res->spinlock);
wake_up(&res->wq);
/* master is known, detach if not already detached */
dlm_mle_detach_hb_events(dlm, mle);
dlm_put_mle_inuse(mle);
ret = 0;
dlm_lockres_calc_usage(dlm, res);
leave:
/* re-dirty the lockres if we failed */
if (ret < 0)
dlm_kick_thread(dlm, res);
/* wake up waiters if the MIGRATING flag got set
* but migration failed */
if (wake)
wake_up(&res->wq);
if (mres)
free_page((unsigned long)mres);
dlm_put(dlm);
mlog(0, "%s: Migrating %.*s to %u, returns %d\n", dlm->name, namelen,
name, target, ret);
return ret;
}
#define DLM_MIGRATION_RETRY_MS 100
/*
* Should be called only after beginning the domain leave process.
* There should not be any remaining locks on nonlocal lock resources,
* and there should be no local locks left on locally mastered resources.
*
* Called with the dlm spinlock held, may drop it to do migration, but
* will re-acquire before exit.
*
* Returns: 1 if dlm->spinlock was dropped/retaken, 0 if never dropped
*/
int dlm_empty_lockres(struct dlm_ctxt *dlm, struct dlm_lock_resource *res)
{
int ret;
int lock_dropped = 0;
u8 target = O2NM_MAX_NODES;
assert_spin_locked(&dlm->spinlock);
spin_lock(&res->spinlock);
if (dlm_is_lockres_migrateable(dlm, res))
target = dlm_pick_migration_target(dlm, res);
spin_unlock(&res->spinlock);
if (target == O2NM_MAX_NODES)
goto leave;
/* Wheee! Migrate lockres here! Will sleep so drop spinlock. */
spin_unlock(&dlm->spinlock);
lock_dropped = 1;
ret = dlm_migrate_lockres(dlm, res, target);
if (ret)
mlog(0, "%s: res %.*s, Migrate to node %u failed with %d\n",
dlm->name, res->lockname.len, res->lockname.name,
target, ret);
spin_lock(&dlm->spinlock);
leave:
return lock_dropped;
}
int dlm_lock_basts_flushed(struct dlm_ctxt *dlm, struct dlm_lock *lock)
{
int ret;
spin_lock(&dlm->ast_lock);
spin_lock(&lock->spinlock);
ret = (list_empty(&lock->bast_list) && !lock->bast_pending);
spin_unlock(&lock->spinlock);
spin_unlock(&dlm->ast_lock);
return ret;
}
static int dlm_migration_can_proceed(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
u8 mig_target)
{
int can_proceed;
spin_lock(&res->spinlock);
can_proceed = !!(res->state & DLM_LOCK_RES_MIGRATING);
spin_unlock(&res->spinlock);
/* target has died, so make the caller break out of the
* wait_event, but caller must recheck the domain_map */
spin_lock(&dlm->spinlock);
if (!test_bit(mig_target, dlm->domain_map))
can_proceed = 1;
spin_unlock(&dlm->spinlock);
return can_proceed;
}
static int dlm_lockres_is_dirty(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res)
{
int ret;
spin_lock(&res->spinlock);
ret = !!(res->state & DLM_LOCK_RES_DIRTY);
spin_unlock(&res->spinlock);
return ret;
}
static int dlm_mark_lockres_migrating(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
u8 target)
{
int ret = 0;
mlog(0, "dlm_mark_lockres_migrating: %.*s, from %u to %u\n",
res->lockname.len, res->lockname.name, dlm->node_num,
target);
/* need to set MIGRATING flag on lockres. this is done by
* ensuring that all asts have been flushed for this lockres. */
spin_lock(&res->spinlock);
BUG_ON(res->migration_pending);
res->migration_pending = 1;
/* strategy is to reserve an extra ast then release
* it below, letting the release do all of the work */
__dlm_lockres_reserve_ast(res);
spin_unlock(&res->spinlock);
/* now flush all the pending asts */
dlm_kick_thread(dlm, res);
/* before waiting on DIRTY, block processes which may
* try to dirty the lockres before MIGRATING is set */
spin_lock(&res->spinlock);
BUG_ON(res->state & DLM_LOCK_RES_BLOCK_DIRTY);
res->state |= DLM_LOCK_RES_BLOCK_DIRTY;
spin_unlock(&res->spinlock);
/* now wait on any pending asts and the DIRTY state */
wait_event(dlm->ast_wq, !dlm_lockres_is_dirty(dlm, res));
dlm_lockres_release_ast(dlm, res);
mlog(0, "about to wait on migration_wq, dirty=%s\n",
res->state & DLM_LOCK_RES_DIRTY ? "yes" : "no");
/* if the extra ref we just put was the final one, this
* will pass thru immediately. otherwise, we need to wait
* for the last ast to finish. */
again:
ret = wait_event_interruptible_timeout(dlm->migration_wq,
dlm_migration_can_proceed(dlm, res, target),
msecs_to_jiffies(1000));
if (ret < 0) {
mlog(0, "woken again: migrating? %s, dead? %s\n",
res->state & DLM_LOCK_RES_MIGRATING ? "yes":"no",
test_bit(target, dlm->domain_map) ? "no":"yes");
} else {
mlog(0, "all is well: migrating? %s, dead? %s\n",
res->state & DLM_LOCK_RES_MIGRATING ? "yes":"no",
test_bit(target, dlm->domain_map) ? "no":"yes");
}
if (!dlm_migration_can_proceed(dlm, res, target)) {
mlog(0, "trying again...\n");
goto again;
}
ret = 0;
/* did the target go down or die? */
spin_lock(&dlm->spinlock);
if (!test_bit(target, dlm->domain_map)) {
mlog(ML_ERROR, "aha. migration target %u just went down\n",
target);
ret = -EHOSTDOWN;
}
spin_unlock(&dlm->spinlock);
/*
* if target is down, we need to clear DLM_LOCK_RES_BLOCK_DIRTY for
* another try; otherwise, we are sure the MIGRATING state is there,
* drop the unneded state which blocked threads trying to DIRTY
*/
spin_lock(&res->spinlock);
BUG_ON(!(res->state & DLM_LOCK_RES_BLOCK_DIRTY));
res->state &= ~DLM_LOCK_RES_BLOCK_DIRTY;
if (!ret)
BUG_ON(!(res->state & DLM_LOCK_RES_MIGRATING));
spin_unlock(&res->spinlock);
/*
* at this point:
*
* o the DLM_LOCK_RES_MIGRATING flag is set if target not down
* o there are no pending asts on this lockres
* o all processes trying to reserve an ast on this
* lockres must wait for the MIGRATING flag to clear
*/
return ret;
}
/* last step in the migration process.
* original master calls this to free all of the dlm_lock
* structures that used to be for other nodes. */
static void dlm_remove_nonlocal_locks(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res)
{
struct list_head *queue = &res->granted;
int i, bit;
struct dlm_lock *lock, *next;
assert_spin_locked(&res->spinlock);
BUG_ON(res->owner == dlm->node_num);
for (i=0; i<3; i++) {
list_for_each_entry_safe(lock, next, queue, list) {
if (lock->ml.node != dlm->node_num) {
mlog(0, "putting lock for node %u\n",
lock->ml.node);
/* be extra careful */
BUG_ON(!list_empty(&lock->ast_list));
BUG_ON(!list_empty(&lock->bast_list));
BUG_ON(lock->ast_pending);
BUG_ON(lock->bast_pending);
dlm_lockres_clear_refmap_bit(dlm, res,
lock->ml.node);
list_del_init(&lock->list);
dlm_lock_put(lock);
/* In a normal unlock, we would have added a
* DLM_UNLOCK_FREE_LOCK action. Force it. */
dlm_lock_put(lock);
}
}
queue++;
}
bit = 0;
while (1) {
bit = find_next_bit(res->refmap, O2NM_MAX_NODES, bit);
if (bit >= O2NM_MAX_NODES)
break;
/* do not clear the local node reference, if there is a
* process holding this, let it drop the ref itself */
if (bit != dlm->node_num) {
mlog(0, "%s:%.*s: node %u had a ref to this "
"migrating lockres, clearing\n", dlm->name,
res->lockname.len, res->lockname.name, bit);
dlm_lockres_clear_refmap_bit(dlm, res, bit);
}
bit++;
}
}
/*
* Pick a node to migrate the lock resource to. This function selects a
* potential target based first on the locks and then on refmap. It skips
* nodes that are in the process of exiting the domain.
*/
static u8 dlm_pick_migration_target(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res)
{
enum dlm_lockres_list idx;
struct list_head *queue = &res->granted;
struct dlm_lock *lock;
int noderef;
u8 nodenum = O2NM_MAX_NODES;
assert_spin_locked(&dlm->spinlock);
assert_spin_locked(&res->spinlock);
/* Go through all the locks */
for (idx = DLM_GRANTED_LIST; idx <= DLM_BLOCKED_LIST; idx++) {
queue = dlm_list_idx_to_ptr(res, idx);
list_for_each_entry(lock, queue, list) {
if (lock->ml.node == dlm->node_num)
continue;
if (test_bit(lock->ml.node, dlm->exit_domain_map))
continue;
nodenum = lock->ml.node;
goto bail;
}
}
/* Go thru the refmap */
noderef = -1;
while (1) {
noderef = find_next_bit(res->refmap, O2NM_MAX_NODES,
noderef + 1);
if (noderef >= O2NM_MAX_NODES)
break;
if (noderef == dlm->node_num)
continue;
if (test_bit(noderef, dlm->exit_domain_map))
continue;
nodenum = noderef;
goto bail;
}
bail:
return nodenum;
}
/* this is called by the new master once all lockres
* data has been received */
static int dlm_do_migrate_request(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
u8 master, u8 new_master,
struct dlm_node_iter *iter)
{
struct dlm_migrate_request migrate;
int ret, skip, status = 0;
int nodenum;
memset(&migrate, 0, sizeof(migrate));
migrate.namelen = res->lockname.len;
memcpy(migrate.name, res->lockname.name, migrate.namelen);
migrate.new_master = new_master;
migrate.master = master;
ret = 0;
/* send message to all nodes, except the master and myself */
while ((nodenum = dlm_node_iter_next(iter)) >= 0) {
if (nodenum == master ||
nodenum == new_master)
continue;
/* We could race exit domain. If exited, skip. */
spin_lock(&dlm->spinlock);
skip = (!test_bit(nodenum, dlm->domain_map));
spin_unlock(&dlm->spinlock);
if (skip) {
clear_bit(nodenum, iter->node_map);
continue;
}
ret = o2net_send_message(DLM_MIGRATE_REQUEST_MSG, dlm->key,
&migrate, sizeof(migrate), nodenum,
&status);
if (ret < 0) {
mlog(ML_ERROR, "%s: res %.*s, Error %d send "
"MIGRATE_REQUEST to node %u\n", dlm->name,
migrate.namelen, migrate.name, ret, nodenum);
if (!dlm_is_host_down(ret)) {
mlog(ML_ERROR, "unhandled error=%d!\n", ret);
BUG();
}
clear_bit(nodenum, iter->node_map);
ret = 0;
} else if (status < 0) {
mlog(0, "migrate request (node %u) returned %d!\n",
nodenum, status);
ret = status;
} else if (status == DLM_MIGRATE_RESPONSE_MASTERY_REF) {
/* during the migration request we short-circuited
* the mastery of the lockres. make sure we have
* a mastery ref for nodenum */
mlog(0, "%s:%.*s: need ref for node %u\n",
dlm->name, res->lockname.len, res->lockname.name,
nodenum);
spin_lock(&res->spinlock);
dlm_lockres_set_refmap_bit(dlm, res, nodenum);
spin_unlock(&res->spinlock);
}
}
if (ret < 0)
mlog_errno(ret);
mlog(0, "returning ret=%d\n", ret);
return ret;
}
/* if there is an existing mle for this lockres, we now know who the master is.
* (the one who sent us *this* message) we can clear it up right away.
* since the process that put the mle on the list still has a reference to it,
* we can unhash it now, set the master and wake the process. as a result,
* we will have no mle in the list to start with. now we can add an mle for
* the migration and this should be the only one found for those scanning the
* list. */
int dlm_migrate_request_handler(struct o2net_msg *msg, u32 len, void *data,
void **ret_data)
{
struct dlm_ctxt *dlm = data;
struct dlm_lock_resource *res = NULL;
struct dlm_migrate_request *migrate = (struct dlm_migrate_request *) msg->buf;
struct dlm_master_list_entry *mle = NULL, *oldmle = NULL;
const char *name;
unsigned int namelen, hash;
int ret = 0;
if (!dlm_grab(dlm))
return -EINVAL;
name = migrate->name;
namelen = migrate->namelen;
hash = dlm_lockid_hash(name, namelen);
/* preallocate.. if this fails, abort */
mle = kmem_cache_alloc(dlm_mle_cache, GFP_NOFS);
if (!mle) {
ret = -ENOMEM;
goto leave;
}
/* check for pre-existing lock */
spin_lock(&dlm->spinlock);
res = __dlm_lookup_lockres(dlm, name, namelen, hash);
if (res) {
spin_lock(&res->spinlock);
if (res->state & DLM_LOCK_RES_RECOVERING) {
/* if all is working ok, this can only mean that we got
* a migrate request from a node that we now see as
* dead. what can we do here? drop it to the floor? */
spin_unlock(&res->spinlock);
mlog(ML_ERROR, "Got a migrate request, but the "
"lockres is marked as recovering!");
kmem_cache_free(dlm_mle_cache, mle);
ret = -EINVAL; /* need a better solution */
goto unlock;
}
res->state |= DLM_LOCK_RES_MIGRATING;
spin_unlock(&res->spinlock);
}
spin_lock(&dlm->master_lock);
/* ignore status. only nonzero status would BUG. */
ret = dlm_add_migration_mle(dlm, res, mle, &oldmle,
name, namelen,
migrate->new_master,
migrate->master);
spin_unlock(&dlm->master_lock);
unlock:
spin_unlock(&dlm->spinlock);
if (oldmle) {
/* master is known, detach if not already detached */
dlm_mle_detach_hb_events(dlm, oldmle);
dlm_put_mle(oldmle);
}
if (res)
dlm_lockres_put(res);
leave:
dlm_put(dlm);
return ret;
}
/* must be holding dlm->spinlock and dlm->master_lock
* when adding a migration mle, we can clear any other mles
* in the master list because we know with certainty that
* the master is "master". so we remove any old mle from
* the list after setting it's master field, and then add
* the new migration mle. this way we can hold with the rule
* of having only one mle for a given lock name at all times. */
static int dlm_add_migration_mle(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res,
struct dlm_master_list_entry *mle,
struct dlm_master_list_entry **oldmle,
const char *name, unsigned int namelen,
u8 new_master, u8 master)
{
int found;
int ret = 0;
*oldmle = NULL;
assert_spin_locked(&dlm->spinlock);
assert_spin_locked(&dlm->master_lock);
/* caller is responsible for any ref taken here on oldmle */
found = dlm_find_mle(dlm, oldmle, (char *)name, namelen);
if (found) {
struct dlm_master_list_entry *tmp = *oldmle;
spin_lock(&tmp->spinlock);
if (tmp->type == DLM_MLE_MIGRATION) {
if (master == dlm->node_num) {
/* ah another process raced me to it */
mlog(0, "tried to migrate %.*s, but some "
"process beat me to it\n",
namelen, name);
ret = -EEXIST;
} else {
/* bad. 2 NODES are trying to migrate! */
mlog(ML_ERROR, "migration error mle: "
"master=%u new_master=%u // request: "
"master=%u new_master=%u // "
"lockres=%.*s\n",
tmp->master, tmp->new_master,
master, new_master,
namelen, name);
BUG();
}
} else {
/* this is essentially what assert_master does */
tmp->master = master;
atomic_set(&tmp->woken, 1);
wake_up(&tmp->wq);
/* remove it so that only one mle will be found */
__dlm_unlink_mle(dlm, tmp);
__dlm_mle_detach_hb_events(dlm, tmp);
ret = DLM_MIGRATE_RESPONSE_MASTERY_REF;
mlog(0, "%s:%.*s: master=%u, newmaster=%u, "
"telling master to get ref for cleared out mle "
"during migration\n", dlm->name, namelen, name,
master, new_master);
}
spin_unlock(&tmp->spinlock);
}
/* now add a migration mle to the tail of the list */
dlm_init_mle(mle, DLM_MLE_MIGRATION, dlm, res, name, namelen);
mle->new_master = new_master;
/* the new master will be sending an assert master for this.
* at that point we will get the refmap reference */
mle->master = master;
/* do this for consistency with other mle types */
set_bit(new_master, mle->maybe_map);
__dlm_insert_mle(dlm, mle);
return ret;
}
/*
* Sets the owner of the lockres, associated to the mle, to UNKNOWN
*/
static struct dlm_lock_resource *dlm_reset_mleres_owner(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle)
{
struct dlm_lock_resource *res;
/* Find the lockres associated to the mle and set its owner to UNK */
res = __dlm_lookup_lockres(dlm, mle->mname, mle->mnamelen,
mle->mnamehash);
if (res) {
spin_unlock(&dlm->master_lock);
/* move lockres onto recovery list */
spin_lock(&res->spinlock);
dlm_set_lockres_owner(dlm, res, DLM_LOCK_RES_OWNER_UNKNOWN);
dlm_move_lockres_to_recovery_list(dlm, res);
spin_unlock(&res->spinlock);
dlm_lockres_put(res);
/* about to get rid of mle, detach from heartbeat */
__dlm_mle_detach_hb_events(dlm, mle);
/* dump the mle */
spin_lock(&dlm->master_lock);
__dlm_put_mle(mle);
spin_unlock(&dlm->master_lock);
}
return res;
}
static void dlm_clean_migration_mle(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle)
{
__dlm_mle_detach_hb_events(dlm, mle);
spin_lock(&mle->spinlock);
__dlm_unlink_mle(dlm, mle);
atomic_set(&mle->woken, 1);
spin_unlock(&mle->spinlock);
wake_up(&mle->wq);
}
static void dlm_clean_block_mle(struct dlm_ctxt *dlm,
struct dlm_master_list_entry *mle, u8 dead_node)
{
int bit;
BUG_ON(mle->type != DLM_MLE_BLOCK);
spin_lock(&mle->spinlock);
bit = find_next_bit(mle->maybe_map, O2NM_MAX_NODES, 0);
if (bit != dead_node) {
mlog(0, "mle found, but dead node %u would not have been "
"master\n", dead_node);
spin_unlock(&mle->spinlock);
} else {
/* Must drop the refcount by one since the assert_master will
* never arrive. This may result in the mle being unlinked and
* freed, but there may still be a process waiting in the
* dlmlock path which is fine. */
mlog(0, "node %u was expected master\n", dead_node);
atomic_set(&mle->woken, 1);
spin_unlock(&mle->spinlock);
wake_up(&mle->wq);
/* Do not need events any longer, so detach from heartbeat */
__dlm_mle_detach_hb_events(dlm, mle);
__dlm_put_mle(mle);
}
}
void dlm_clean_master_list(struct dlm_ctxt *dlm, u8 dead_node)
{
struct dlm_master_list_entry *mle;
struct dlm_lock_resource *res;
struct hlist_head *bucket;
struct hlist_node *list;
unsigned int i;
mlog(0, "dlm=%s, dead node=%u\n", dlm->name, dead_node);
top:
assert_spin_locked(&dlm->spinlock);
/* clean the master list */
spin_lock(&dlm->master_lock);
for (i = 0; i < DLM_HASH_BUCKETS; i++) {
bucket = dlm_master_hash(dlm, i);
hlist_for_each(list, bucket) {
mle = hlist_entry(list, struct dlm_master_list_entry,
master_hash_node);
BUG_ON(mle->type != DLM_MLE_BLOCK &&
mle->type != DLM_MLE_MASTER &&
mle->type != DLM_MLE_MIGRATION);
/* MASTER mles are initiated locally. The waiting
* process will notice the node map change shortly.
* Let that happen as normal. */
if (mle->type == DLM_MLE_MASTER)
continue;
/* BLOCK mles are initiated by other nodes. Need to
* clean up if the dead node would have been the
* master. */
if (mle->type == DLM_MLE_BLOCK) {
dlm_clean_block_mle(dlm, mle, dead_node);
continue;
}
/* Everything else is a MIGRATION mle */
/* The rule for MIGRATION mles is that the master
* becomes UNKNOWN if *either* the original or the new
* master dies. All UNKNOWN lockres' are sent to
* whichever node becomes the recovery master. The new
* master is responsible for determining if there is
* still a master for this lockres, or if he needs to
* take over mastery. Either way, this node should
* expect another message to resolve this. */
if (mle->master != dead_node &&
mle->new_master != dead_node)
continue;
/* If we have reached this point, this mle needs to be
* removed from the list and freed. */
dlm_clean_migration_mle(dlm, mle);
mlog(0, "%s: node %u died during migration from "
"%u to %u!\n", dlm->name, dead_node, mle->master,
mle->new_master);
/* If we find a lockres associated with the mle, we've
* hit this rare case that messes up our lock ordering.
* If so, we need to drop the master lock so that we can
* take the lockres lock, meaning that we will have to
* restart from the head of list. */
res = dlm_reset_mleres_owner(dlm, mle);
if (res)
/* restart */
goto top;
/* This may be the last reference */
__dlm_put_mle(mle);
}
}
spin_unlock(&dlm->master_lock);
}
int dlm_finish_migration(struct dlm_ctxt *dlm, struct dlm_lock_resource *res,
u8 old_master)
{
struct dlm_node_iter iter;
int ret = 0;
spin_lock(&dlm->spinlock);
dlm_node_iter_init(dlm->domain_map, &iter);
clear_bit(old_master, iter.node_map);
clear_bit(dlm->node_num, iter.node_map);
spin_unlock(&dlm->spinlock);
/* ownership of the lockres is changing. account for the
* mastery reference here since old_master will briefly have
* a reference after the migration completes */
spin_lock(&res->spinlock);
dlm_lockres_set_refmap_bit(dlm, res, old_master);
spin_unlock(&res->spinlock);
mlog(0, "now time to do a migrate request to other nodes\n");
ret = dlm_do_migrate_request(dlm, res, old_master,
dlm->node_num, &iter);
if (ret < 0) {
mlog_errno(ret);
goto leave;
}
mlog(0, "doing assert master of %.*s to all except the original node\n",
res->lockname.len, res->lockname.name);
/* this call now finishes out the nodemap
* even if one or more nodes die */
ret = dlm_do_assert_master(dlm, res, iter.node_map,
DLM_ASSERT_MASTER_FINISH_MIGRATION);
if (ret < 0) {
/* no longer need to retry. all living nodes contacted. */
mlog_errno(ret);
ret = 0;
}
memset(iter.node_map, 0, sizeof(iter.node_map));
set_bit(old_master, iter.node_map);
mlog(0, "doing assert master of %.*s back to %u\n",
res->lockname.len, res->lockname.name, old_master);
ret = dlm_do_assert_master(dlm, res, iter.node_map,
DLM_ASSERT_MASTER_FINISH_MIGRATION);
if (ret < 0) {
mlog(0, "assert master to original master failed "
"with %d.\n", ret);
/* the only nonzero status here would be because of
* a dead original node. we're done. */
ret = 0;
}
/* all done, set the owner, clear the flag */
spin_lock(&res->spinlock);
dlm_set_lockres_owner(dlm, res, dlm->node_num);
res->state &= ~DLM_LOCK_RES_MIGRATING;
spin_unlock(&res->spinlock);
/* re-dirty it on the new master */
dlm_kick_thread(dlm, res);
wake_up(&res->wq);
leave:
return ret;
}
/*
* LOCKRES AST REFCOUNT
* this is integral to migration
*/
/* for future intent to call an ast, reserve one ahead of time.
* this should be called only after waiting on the lockres
* with dlm_wait_on_lockres, and while still holding the
* spinlock after the call. */
void __dlm_lockres_reserve_ast(struct dlm_lock_resource *res)
{
assert_spin_locked(&res->spinlock);
if (res->state & DLM_LOCK_RES_MIGRATING) {
__dlm_print_one_lock_resource(res);
}
BUG_ON(res->state & DLM_LOCK_RES_MIGRATING);
atomic_inc(&res->asts_reserved);
}
/*
* used to drop the reserved ast, either because it went unused,
* or because the ast/bast was actually called.
*
* also, if there is a pending migration on this lockres,
* and this was the last pending ast on the lockres,
* atomically set the MIGRATING flag before we drop the lock.
* this is how we ensure that migration can proceed with no
* asts in progress. note that it is ok if the state of the
* queues is such that a lock should be granted in the future
* or that a bast should be fired, because the new master will
* shuffle the lists on this lockres as soon as it is migrated.
*/
void dlm_lockres_release_ast(struct dlm_ctxt *dlm,
struct dlm_lock_resource *res)
{
if (!atomic_dec_and_lock(&res->asts_reserved, &res->spinlock))
return;
if (!res->migration_pending) {
spin_unlock(&res->spinlock);
return;
}
BUG_ON(res->state & DLM_LOCK_RES_MIGRATING);
res->migration_pending = 0;
res->state |= DLM_LOCK_RES_MIGRATING;
spin_unlock(&res->spinlock);
wake_up(&res->wq);
wake_up(&dlm->migration_wq);
}
void dlm_force_free_mles(struct dlm_ctxt *dlm)
{
int i;
struct hlist_head *bucket;
struct dlm_master_list_entry *mle;
struct hlist_node *tmp, *list;
/*
* We notified all other nodes that we are exiting the domain and
* marked the dlm state to DLM_CTXT_LEAVING. If any mles are still
* around we force free them and wake any processes that are waiting
* on the mles
*/
spin_lock(&dlm->spinlock);
spin_lock(&dlm->master_lock);
BUG_ON(dlm->dlm_state != DLM_CTXT_LEAVING);
BUG_ON((find_next_bit(dlm->domain_map, O2NM_MAX_NODES, 0) < O2NM_MAX_NODES));
for (i = 0; i < DLM_HASH_BUCKETS; i++) {
bucket = dlm_master_hash(dlm, i);
hlist_for_each_safe(list, tmp, bucket) {
mle = hlist_entry(list, struct dlm_master_list_entry,
master_hash_node);
if (mle->type != DLM_MLE_BLOCK) {
mlog(ML_ERROR, "bad mle: %p\n", mle);
dlm_print_one_mle(mle);
}
atomic_set(&mle->woken, 1);
wake_up(&mle->wq);
__dlm_unlink_mle(dlm, mle);
__dlm_mle_detach_hb_events(dlm, mle);
__dlm_put_mle(mle);
}
}
spin_unlock(&dlm->master_lock);
spin_unlock(&dlm->spinlock);
}
| gpl-2.0 |
doadin/samsung-kernel-msm7x30 | net/sctp/objcnt.c | 1357 | 4336 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
*
* This file is part of the SCTP kernel implementation
*
* Support for memory object debugging. This allows one to monitor the
* object allocations/deallocations for types instrumented for this
* via the proc fs.
*
* This SCTP implementation 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 SCTP implementation 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 GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* Jon Grimm <jgrimm@us.ibm.com>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <net/sctp/sctp.h>
/*
* Global counters to count raw object allocation counts.
* To add new counters, choose a unique suffix for the variable
* name as the helper macros key off this suffix to make
* life easier for the programmer.
*/
SCTP_DBG_OBJCNT(sock);
SCTP_DBG_OBJCNT(ep);
SCTP_DBG_OBJCNT(transport);
SCTP_DBG_OBJCNT(assoc);
SCTP_DBG_OBJCNT(bind_addr);
SCTP_DBG_OBJCNT(bind_bucket);
SCTP_DBG_OBJCNT(chunk);
SCTP_DBG_OBJCNT(addr);
SCTP_DBG_OBJCNT(ssnmap);
SCTP_DBG_OBJCNT(datamsg);
SCTP_DBG_OBJCNT(keys);
/* An array to make it easy to pretty print the debug information
* to the proc fs.
*/
static sctp_dbg_objcnt_entry_t sctp_dbg_objcnt[] = {
SCTP_DBG_OBJCNT_ENTRY(sock),
SCTP_DBG_OBJCNT_ENTRY(ep),
SCTP_DBG_OBJCNT_ENTRY(assoc),
SCTP_DBG_OBJCNT_ENTRY(transport),
SCTP_DBG_OBJCNT_ENTRY(chunk),
SCTP_DBG_OBJCNT_ENTRY(bind_addr),
SCTP_DBG_OBJCNT_ENTRY(bind_bucket),
SCTP_DBG_OBJCNT_ENTRY(addr),
SCTP_DBG_OBJCNT_ENTRY(ssnmap),
SCTP_DBG_OBJCNT_ENTRY(datamsg),
SCTP_DBG_OBJCNT_ENTRY(keys),
};
/* Callback from procfs to read out objcount information.
* Walk through the entries in the sctp_dbg_objcnt array, dumping
* the raw object counts for each monitored type.
*/
static int sctp_objcnt_seq_show(struct seq_file *seq, void *v)
{
int i;
i = (int)*(loff_t *)v;
seq_setwidth(seq, 127);
seq_printf(seq, "%s: %d", sctp_dbg_objcnt[i].label,
atomic_read(sctp_dbg_objcnt[i].counter));
seq_pad(seq, '\n');
return 0;
}
static void *sctp_objcnt_seq_start(struct seq_file *seq, loff_t *pos)
{
return (*pos >= ARRAY_SIZE(sctp_dbg_objcnt)) ? NULL : (void *)pos;
}
static void sctp_objcnt_seq_stop(struct seq_file *seq, void *v)
{
}
static void * sctp_objcnt_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return (*pos >= ARRAY_SIZE(sctp_dbg_objcnt)) ? NULL : (void *)pos;
}
static const struct seq_operations sctp_objcnt_seq_ops = {
.start = sctp_objcnt_seq_start,
.next = sctp_objcnt_seq_next,
.stop = sctp_objcnt_seq_stop,
.show = sctp_objcnt_seq_show,
};
static int sctp_objcnt_seq_open(struct inode *inode, struct file *file)
{
return seq_open(file, &sctp_objcnt_seq_ops);
}
static const struct file_operations sctp_objcnt_ops = {
.open = sctp_objcnt_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
/* Initialize the objcount in the proc filesystem. */
void sctp_dbg_objcnt_init(void)
{
struct proc_dir_entry *ent;
ent = proc_create("sctp_dbg_objcnt", 0,
proc_net_sctp, &sctp_objcnt_ops);
if (!ent)
pr_warn("sctp_dbg_objcnt: Unable to create /proc entry.\n");
}
/* Cleanup the objcount entry in the proc filesystem. */
void sctp_dbg_objcnt_exit(void)
{
remove_proc_entry("sctp_dbg_objcnt", proc_net_sctp);
}
| gpl-2.0 |
fefifofum/android_kernel_bq_maxwell2plus_3.0.8 | drivers/net/qlcnic/qlcnic_hw.c | 2381 | 45799 | /*
* QLogic qlcnic NIC Driver
* Copyright (c) 2009-2010 QLogic Corporation
*
* See LICENSE.qlcnic for copyright and licensing details.
*/
#include "qlcnic.h"
#include <linux/slab.h>
#include <net/ip.h>
#include <linux/bitops.h>
#define MASK(n) ((1ULL<<(n))-1)
#define OCM_WIN_P3P(addr) (addr & 0xffc0000)
#define GET_MEM_OFFS_2M(addr) (addr & MASK(18))
#define CRB_BLK(off) ((off >> 20) & 0x3f)
#define CRB_SUBBLK(off) ((off >> 16) & 0xf)
#define CRB_WINDOW_2M (0x130060)
#define CRB_HI(off) ((crb_hub_agt[CRB_BLK(off)] << 20) | ((off) & 0xf0000))
#define CRB_INDIRECT_2M (0x1e0000UL)
#ifndef readq
static inline u64 readq(void __iomem *addr)
{
return readl(addr) | (((u64) readl(addr + 4)) << 32LL);
}
#endif
#ifndef writeq
static inline void writeq(u64 val, void __iomem *addr)
{
writel(((u32) (val)), (addr));
writel(((u32) (val >> 32)), (addr + 4));
}
#endif
static const struct crb_128M_2M_block_map
crb_128M_2M_map[64] __cacheline_aligned_in_smp = {
{{{0, 0, 0, 0} } }, /* 0: PCI */
{{{1, 0x0100000, 0x0102000, 0x120000}, /* 1: PCIE */
{1, 0x0110000, 0x0120000, 0x130000},
{1, 0x0120000, 0x0122000, 0x124000},
{1, 0x0130000, 0x0132000, 0x126000},
{1, 0x0140000, 0x0142000, 0x128000},
{1, 0x0150000, 0x0152000, 0x12a000},
{1, 0x0160000, 0x0170000, 0x110000},
{1, 0x0170000, 0x0172000, 0x12e000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x01e0000, 0x01e0800, 0x122000},
{0, 0x0000000, 0x0000000, 0x000000} } },
{{{1, 0x0200000, 0x0210000, 0x180000} } },/* 2: MN */
{{{0, 0, 0, 0} } }, /* 3: */
{{{1, 0x0400000, 0x0401000, 0x169000} } },/* 4: P2NR1 */
{{{1, 0x0500000, 0x0510000, 0x140000} } },/* 5: SRE */
{{{1, 0x0600000, 0x0610000, 0x1c0000} } },/* 6: NIU */
{{{1, 0x0700000, 0x0704000, 0x1b8000} } },/* 7: QM */
{{{1, 0x0800000, 0x0802000, 0x170000}, /* 8: SQM0 */
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x08f0000, 0x08f2000, 0x172000} } },
{{{1, 0x0900000, 0x0902000, 0x174000}, /* 9: SQM1*/
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x09f0000, 0x09f2000, 0x176000} } },
{{{0, 0x0a00000, 0x0a02000, 0x178000}, /* 10: SQM2*/
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x0af0000, 0x0af2000, 0x17a000} } },
{{{0, 0x0b00000, 0x0b02000, 0x17c000}, /* 11: SQM3*/
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{1, 0x0bf0000, 0x0bf2000, 0x17e000} } },
{{{1, 0x0c00000, 0x0c04000, 0x1d4000} } },/* 12: I2Q */
{{{1, 0x0d00000, 0x0d04000, 0x1a4000} } },/* 13: TMR */
{{{1, 0x0e00000, 0x0e04000, 0x1a0000} } },/* 14: ROMUSB */
{{{1, 0x0f00000, 0x0f01000, 0x164000} } },/* 15: PEG4 */
{{{0, 0x1000000, 0x1004000, 0x1a8000} } },/* 16: XDMA */
{{{1, 0x1100000, 0x1101000, 0x160000} } },/* 17: PEG0 */
{{{1, 0x1200000, 0x1201000, 0x161000} } },/* 18: PEG1 */
{{{1, 0x1300000, 0x1301000, 0x162000} } },/* 19: PEG2 */
{{{1, 0x1400000, 0x1401000, 0x163000} } },/* 20: PEG3 */
{{{1, 0x1500000, 0x1501000, 0x165000} } },/* 21: P2ND */
{{{1, 0x1600000, 0x1601000, 0x166000} } },/* 22: P2NI */
{{{0, 0, 0, 0} } }, /* 23: */
{{{0, 0, 0, 0} } }, /* 24: */
{{{0, 0, 0, 0} } }, /* 25: */
{{{0, 0, 0, 0} } }, /* 26: */
{{{0, 0, 0, 0} } }, /* 27: */
{{{0, 0, 0, 0} } }, /* 28: */
{{{1, 0x1d00000, 0x1d10000, 0x190000} } },/* 29: MS */
{{{1, 0x1e00000, 0x1e01000, 0x16a000} } },/* 30: P2NR2 */
{{{1, 0x1f00000, 0x1f10000, 0x150000} } },/* 31: EPG */
{{{0} } }, /* 32: PCI */
{{{1, 0x2100000, 0x2102000, 0x120000}, /* 33: PCIE */
{1, 0x2110000, 0x2120000, 0x130000},
{1, 0x2120000, 0x2122000, 0x124000},
{1, 0x2130000, 0x2132000, 0x126000},
{1, 0x2140000, 0x2142000, 0x128000},
{1, 0x2150000, 0x2152000, 0x12a000},
{1, 0x2160000, 0x2170000, 0x110000},
{1, 0x2170000, 0x2172000, 0x12e000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000},
{0, 0x0000000, 0x0000000, 0x000000} } },
{{{1, 0x2200000, 0x2204000, 0x1b0000} } },/* 34: CAM */
{{{0} } }, /* 35: */
{{{0} } }, /* 36: */
{{{0} } }, /* 37: */
{{{0} } }, /* 38: */
{{{0} } }, /* 39: */
{{{1, 0x2800000, 0x2804000, 0x1a4000} } },/* 40: TMR */
{{{1, 0x2900000, 0x2901000, 0x16b000} } },/* 41: P2NR3 */
{{{1, 0x2a00000, 0x2a00400, 0x1ac400} } },/* 42: RPMX1 */
{{{1, 0x2b00000, 0x2b00400, 0x1ac800} } },/* 43: RPMX2 */
{{{1, 0x2c00000, 0x2c00400, 0x1acc00} } },/* 44: RPMX3 */
{{{1, 0x2d00000, 0x2d00400, 0x1ad000} } },/* 45: RPMX4 */
{{{1, 0x2e00000, 0x2e00400, 0x1ad400} } },/* 46: RPMX5 */
{{{1, 0x2f00000, 0x2f00400, 0x1ad800} } },/* 47: RPMX6 */
{{{1, 0x3000000, 0x3000400, 0x1adc00} } },/* 48: RPMX7 */
{{{0, 0x3100000, 0x3104000, 0x1a8000} } },/* 49: XDMA */
{{{1, 0x3200000, 0x3204000, 0x1d4000} } },/* 50: I2Q */
{{{1, 0x3300000, 0x3304000, 0x1a0000} } },/* 51: ROMUSB */
{{{0} } }, /* 52: */
{{{1, 0x3500000, 0x3500400, 0x1ac000} } },/* 53: RPMX0 */
{{{1, 0x3600000, 0x3600400, 0x1ae000} } },/* 54: RPMX8 */
{{{1, 0x3700000, 0x3700400, 0x1ae400} } },/* 55: RPMX9 */
{{{1, 0x3800000, 0x3804000, 0x1d0000} } },/* 56: OCM0 */
{{{1, 0x3900000, 0x3904000, 0x1b4000} } },/* 57: CRYPTO */
{{{1, 0x3a00000, 0x3a04000, 0x1d8000} } },/* 58: SMB */
{{{0} } }, /* 59: I2C0 */
{{{0} } }, /* 60: I2C1 */
{{{1, 0x3d00000, 0x3d04000, 0x1d8000} } },/* 61: LPC */
{{{1, 0x3e00000, 0x3e01000, 0x167000} } },/* 62: P2NC */
{{{1, 0x3f00000, 0x3f01000, 0x168000} } } /* 63: P2NR0 */
};
/*
* top 12 bits of crb internal address (hub, agent)
*/
static const unsigned crb_hub_agt[64] = {
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PS,
QLCNIC_HW_CRB_HUB_AGT_ADR_MN,
QLCNIC_HW_CRB_HUB_AGT_ADR_MS,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_SRE,
QLCNIC_HW_CRB_HUB_AGT_ADR_NIU,
QLCNIC_HW_CRB_HUB_AGT_ADR_QMN,
QLCNIC_HW_CRB_HUB_AGT_ADR_SQN0,
QLCNIC_HW_CRB_HUB_AGT_ADR_SQN1,
QLCNIC_HW_CRB_HUB_AGT_ADR_SQN2,
QLCNIC_HW_CRB_HUB_AGT_ADR_SQN3,
QLCNIC_HW_CRB_HUB_AGT_ADR_I2Q,
QLCNIC_HW_CRB_HUB_AGT_ADR_TIMR,
QLCNIC_HW_CRB_HUB_AGT_ADR_ROMUSB,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN4,
QLCNIC_HW_CRB_HUB_AGT_ADR_XDMA,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN1,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN2,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGN3,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGND,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGNI,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGS0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGS1,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGS2,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGS3,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGSI,
QLCNIC_HW_CRB_HUB_AGT_ADR_SN,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_EG,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PS,
QLCNIC_HW_CRB_HUB_AGT_ADR_CAM,
0,
0,
0,
0,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_TIMR,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX1,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX2,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX3,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX4,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX5,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX6,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX7,
QLCNIC_HW_CRB_HUB_AGT_ADR_XDMA,
QLCNIC_HW_CRB_HUB_AGT_ADR_I2Q,
QLCNIC_HW_CRB_HUB_AGT_ADR_ROMUSB,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX0,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX8,
QLCNIC_HW_CRB_HUB_AGT_ADR_RPMX9,
QLCNIC_HW_CRB_HUB_AGT_ADR_OCM0,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_SMB,
QLCNIC_HW_CRB_HUB_AGT_ADR_I2C0,
QLCNIC_HW_CRB_HUB_AGT_ADR_I2C1,
0,
QLCNIC_HW_CRB_HUB_AGT_ADR_PGNC,
0,
};
/* PCI Windowing for DDR regions. */
#define QLCNIC_PCIE_SEM_TIMEOUT 10000
int
qlcnic_pcie_sem_lock(struct qlcnic_adapter *adapter, int sem, u32 id_reg)
{
int done = 0, timeout = 0;
while (!done) {
done = QLCRD32(adapter, QLCNIC_PCIE_REG(PCIE_SEM_LOCK(sem)));
if (done == 1)
break;
if (++timeout >= QLCNIC_PCIE_SEM_TIMEOUT) {
dev_err(&adapter->pdev->dev,
"Failed to acquire sem=%d lock; holdby=%d\n",
sem, id_reg ? QLCRD32(adapter, id_reg) : -1);
return -EIO;
}
msleep(1);
}
if (id_reg)
QLCWR32(adapter, id_reg, adapter->portnum);
return 0;
}
void
qlcnic_pcie_sem_unlock(struct qlcnic_adapter *adapter, int sem)
{
QLCRD32(adapter, QLCNIC_PCIE_REG(PCIE_SEM_UNLOCK(sem)));
}
static int
qlcnic_send_cmd_descs(struct qlcnic_adapter *adapter,
struct cmd_desc_type0 *cmd_desc_arr, int nr_desc)
{
u32 i, producer, consumer;
struct qlcnic_cmd_buffer *pbuf;
struct cmd_desc_type0 *cmd_desc;
struct qlcnic_host_tx_ring *tx_ring;
i = 0;
if (!test_bit(__QLCNIC_FW_ATTACHED, &adapter->state))
return -EIO;
tx_ring = adapter->tx_ring;
__netif_tx_lock_bh(tx_ring->txq);
producer = tx_ring->producer;
consumer = tx_ring->sw_consumer;
if (nr_desc >= qlcnic_tx_avail(tx_ring)) {
netif_tx_stop_queue(tx_ring->txq);
smp_mb();
if (qlcnic_tx_avail(tx_ring) > nr_desc) {
if (qlcnic_tx_avail(tx_ring) > TX_STOP_THRESH)
netif_tx_wake_queue(tx_ring->txq);
} else {
adapter->stats.xmit_off++;
__netif_tx_unlock_bh(tx_ring->txq);
return -EBUSY;
}
}
do {
cmd_desc = &cmd_desc_arr[i];
pbuf = &tx_ring->cmd_buf_arr[producer];
pbuf->skb = NULL;
pbuf->frag_count = 0;
memcpy(&tx_ring->desc_head[producer],
&cmd_desc_arr[i], sizeof(struct cmd_desc_type0));
producer = get_next_index(producer, tx_ring->num_desc);
i++;
} while (i != nr_desc);
tx_ring->producer = producer;
qlcnic_update_cmd_producer(adapter, tx_ring);
__netif_tx_unlock_bh(tx_ring->txq);
return 0;
}
static int
qlcnic_sre_macaddr_change(struct qlcnic_adapter *adapter, u8 *addr,
__le16 vlan_id, unsigned op)
{
struct qlcnic_nic_req req;
struct qlcnic_mac_req *mac_req;
struct qlcnic_vlan_req *vlan_req;
u64 word;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_REQUEST << 23);
word = QLCNIC_MAC_EVENT | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
mac_req = (struct qlcnic_mac_req *)&req.words[0];
mac_req->op = op;
memcpy(mac_req->mac_addr, addr, 6);
vlan_req = (struct qlcnic_vlan_req *)&req.words[1];
vlan_req->vlan_id = vlan_id;
return qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
}
static int qlcnic_nic_add_mac(struct qlcnic_adapter *adapter, const u8 *addr)
{
struct list_head *head;
struct qlcnic_mac_list_s *cur;
/* look up if already exists */
list_for_each(head, &adapter->mac_list) {
cur = list_entry(head, struct qlcnic_mac_list_s, list);
if (memcmp(addr, cur->mac_addr, ETH_ALEN) == 0)
return 0;
}
cur = kzalloc(sizeof(struct qlcnic_mac_list_s), GFP_ATOMIC);
if (cur == NULL) {
dev_err(&adapter->netdev->dev,
"failed to add mac address filter\n");
return -ENOMEM;
}
memcpy(cur->mac_addr, addr, ETH_ALEN);
if (qlcnic_sre_macaddr_change(adapter,
cur->mac_addr, 0, QLCNIC_MAC_ADD)) {
kfree(cur);
return -EIO;
}
list_add_tail(&cur->list, &adapter->mac_list);
return 0;
}
void qlcnic_set_multi(struct net_device *netdev)
{
struct qlcnic_adapter *adapter = netdev_priv(netdev);
struct netdev_hw_addr *ha;
static const u8 bcast_addr[ETH_ALEN] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff
};
u32 mode = VPORT_MISS_MODE_DROP;
if (!test_bit(__QLCNIC_FW_ATTACHED, &adapter->state))
return;
qlcnic_nic_add_mac(adapter, adapter->mac_addr);
qlcnic_nic_add_mac(adapter, bcast_addr);
if (netdev->flags & IFF_PROMISC) {
if (!(adapter->flags & QLCNIC_PROMISC_DISABLED))
mode = VPORT_MISS_MODE_ACCEPT_ALL;
goto send_fw_cmd;
}
if ((netdev->flags & IFF_ALLMULTI) ||
(netdev_mc_count(netdev) > adapter->max_mc_count)) {
mode = VPORT_MISS_MODE_ACCEPT_MULTI;
goto send_fw_cmd;
}
if (!netdev_mc_empty(netdev)) {
netdev_for_each_mc_addr(ha, netdev) {
qlcnic_nic_add_mac(adapter, ha->addr);
}
}
send_fw_cmd:
qlcnic_nic_set_promisc(adapter, mode);
}
int qlcnic_nic_set_promisc(struct qlcnic_adapter *adapter, u32 mode)
{
struct qlcnic_nic_req req;
u64 word;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_SET_MAC_RECEIVE_MODE |
((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(mode);
return qlcnic_send_cmd_descs(adapter,
(struct cmd_desc_type0 *)&req, 1);
}
void qlcnic_free_mac_list(struct qlcnic_adapter *adapter)
{
struct qlcnic_mac_list_s *cur;
struct list_head *head = &adapter->mac_list;
while (!list_empty(head)) {
cur = list_entry(head->next, struct qlcnic_mac_list_s, list);
qlcnic_sre_macaddr_change(adapter,
cur->mac_addr, 0, QLCNIC_MAC_DEL);
list_del(&cur->list);
kfree(cur);
}
}
void qlcnic_prune_lb_filters(struct qlcnic_adapter *adapter)
{
struct qlcnic_filter *tmp_fil;
struct hlist_node *tmp_hnode, *n;
struct hlist_head *head;
int i;
for (i = 0; i < adapter->fhash.fmax; i++) {
head = &(adapter->fhash.fhead[i]);
hlist_for_each_entry_safe(tmp_fil, tmp_hnode, n, head, fnode)
{
if (jiffies >
(QLCNIC_FILTER_AGE * HZ + tmp_fil->ftime)) {
qlcnic_sre_macaddr_change(adapter,
tmp_fil->faddr, tmp_fil->vlan_id,
tmp_fil->vlan_id ? QLCNIC_MAC_VLAN_DEL :
QLCNIC_MAC_DEL);
spin_lock_bh(&adapter->mac_learn_lock);
adapter->fhash.fnum--;
hlist_del(&tmp_fil->fnode);
spin_unlock_bh(&adapter->mac_learn_lock);
kfree(tmp_fil);
}
}
}
}
void qlcnic_delete_lb_filters(struct qlcnic_adapter *adapter)
{
struct qlcnic_filter *tmp_fil;
struct hlist_node *tmp_hnode, *n;
struct hlist_head *head;
int i;
for (i = 0; i < adapter->fhash.fmax; i++) {
head = &(adapter->fhash.fhead[i]);
hlist_for_each_entry_safe(tmp_fil, tmp_hnode, n, head, fnode) {
qlcnic_sre_macaddr_change(adapter, tmp_fil->faddr,
tmp_fil->vlan_id, tmp_fil->vlan_id ?
QLCNIC_MAC_VLAN_DEL : QLCNIC_MAC_DEL);
spin_lock_bh(&adapter->mac_learn_lock);
adapter->fhash.fnum--;
hlist_del(&tmp_fil->fnode);
spin_unlock_bh(&adapter->mac_learn_lock);
kfree(tmp_fil);
}
}
}
/*
* Send the interrupt coalescing parameter set by ethtool to the card.
*/
int qlcnic_config_intr_coalesce(struct qlcnic_adapter *adapter)
{
struct qlcnic_nic_req req;
int rv;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
req.req_hdr = cpu_to_le64(QLCNIC_CONFIG_INTR_COALESCE |
((u64) adapter->portnum << 16));
req.words[0] = cpu_to_le64(((u64) adapter->ahw->coal.flag) << 32);
req.words[2] = cpu_to_le64(adapter->ahw->coal.rx_packets |
((u64) adapter->ahw->coal.rx_time_us) << 16);
req.words[5] = cpu_to_le64(adapter->ahw->coal.timer_out |
((u64) adapter->ahw->coal.type) << 32 |
((u64) adapter->ahw->coal.sts_ring_mask) << 40);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"Could not send interrupt coalescing parameters\n");
return rv;
}
int qlcnic_config_hw_lro(struct qlcnic_adapter *adapter, int enable)
{
struct qlcnic_nic_req req;
u64 word;
int rv;
if (!test_bit(__QLCNIC_FW_ATTACHED, &adapter->state))
return 0;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_HW_LRO | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(enable);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"Could not send configure hw lro request\n");
return rv;
}
int qlcnic_config_bridged_mode(struct qlcnic_adapter *adapter, u32 enable)
{
struct qlcnic_nic_req req;
u64 word;
int rv;
if (!!(adapter->flags & QLCNIC_BRIDGE_ENABLED) == enable)
return 0;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_BRIDGING |
((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(enable);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"Could not send configure bridge mode request\n");
adapter->flags ^= QLCNIC_BRIDGE_ENABLED;
return rv;
}
#define RSS_HASHTYPE_IP_TCP 0x3
int qlcnic_config_rss(struct qlcnic_adapter *adapter, int enable)
{
struct qlcnic_nic_req req;
u64 word;
int i, rv;
static const u64 key[] = {
0xbeac01fa6a42b73bULL, 0x8030f20c77cb2da3ULL,
0xae7b30b4d0ca2bcbULL, 0x43a38fb04167253dULL,
0x255b0ec26d5a56daULL
};
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_RSS | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
/*
* RSS request:
* bits 3-0: hash_method
* 5-4: hash_type_ipv4
* 7-6: hash_type_ipv6
* 8: enable
* 9: use indirection table
* 47-10: reserved
* 63-48: indirection table mask
*/
word = ((u64)(RSS_HASHTYPE_IP_TCP & 0x3) << 4) |
((u64)(RSS_HASHTYPE_IP_TCP & 0x3) << 6) |
((u64)(enable & 0x1) << 8) |
((0x7ULL) << 48);
req.words[0] = cpu_to_le64(word);
for (i = 0; i < 5; i++)
req.words[i+1] = cpu_to_le64(key[i]);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev, "could not configure RSS\n");
return rv;
}
int qlcnic_config_ipaddr(struct qlcnic_adapter *adapter, __be32 ip, int cmd)
{
struct qlcnic_nic_req req;
struct qlcnic_ipaddr *ipa;
u64 word;
int rv;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_IPADDR | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(cmd);
ipa = (struct qlcnic_ipaddr *)&req.words[1];
ipa->ipv4 = ip;
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"could not notify %s IP 0x%x reuqest\n",
(cmd == QLCNIC_IP_UP) ? "Add" : "Remove", ip);
return rv;
}
int qlcnic_linkevent_request(struct qlcnic_adapter *adapter, int enable)
{
struct qlcnic_nic_req req;
u64 word;
int rv;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_GET_LINKEVENT | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64(enable | (enable << 8));
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"could not configure link notification\n");
return rv;
}
int qlcnic_send_lro_cleanup(struct qlcnic_adapter *adapter)
{
struct qlcnic_nic_req req;
u64 word;
int rv;
if (!test_bit(__QLCNIC_FW_ATTACHED, &adapter->state))
return 0;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_LRO_REQUEST |
((u64)adapter->portnum << 16) |
((u64)QLCNIC_LRO_REQUEST_CLEANUP << 56) ;
req.req_hdr = cpu_to_le64(word);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv != 0)
dev_err(&adapter->netdev->dev,
"could not cleanup lro flows\n");
return rv;
}
/*
* qlcnic_change_mtu - Change the Maximum Transfer Unit
* @returns 0 on success, negative on failure
*/
int qlcnic_change_mtu(struct net_device *netdev, int mtu)
{
struct qlcnic_adapter *adapter = netdev_priv(netdev);
int rc = 0;
if (mtu < P3P_MIN_MTU || mtu > P3P_MAX_MTU) {
dev_err(&adapter->netdev->dev, "%d bytes < mtu < %d bytes"
" not supported\n", P3P_MAX_MTU, P3P_MIN_MTU);
return -EINVAL;
}
rc = qlcnic_fw_cmd_set_mtu(adapter, mtu);
if (!rc)
netdev->mtu = mtu;
return rc;
}
u32 qlcnic_fix_features(struct net_device *netdev, u32 features)
{
struct qlcnic_adapter *adapter = netdev_priv(netdev);
if ((adapter->flags & QLCNIC_ESWITCH_ENABLED)) {
u32 changed = features ^ netdev->features;
features ^= changed & (NETIF_F_ALL_CSUM | NETIF_F_RXCSUM);
}
if (!(features & NETIF_F_RXCSUM))
features &= ~NETIF_F_LRO;
return features;
}
int qlcnic_set_features(struct net_device *netdev, u32 features)
{
struct qlcnic_adapter *adapter = netdev_priv(netdev);
u32 changed = netdev->features ^ features;
int hw_lro = (features & NETIF_F_LRO) ? QLCNIC_LRO_ENABLED : 0;
if (!(changed & NETIF_F_LRO))
return 0;
netdev->features = features ^ NETIF_F_LRO;
if (qlcnic_config_hw_lro(adapter, hw_lro))
return -EIO;
if ((hw_lro == 0) && qlcnic_send_lro_cleanup(adapter))
return -EIO;
return 0;
}
/*
* Changes the CRB window to the specified window.
*/
/* Returns < 0 if off is not valid,
* 1 if window access is needed. 'off' is set to offset from
* CRB space in 128M pci map
* 0 if no window access is needed. 'off' is set to 2M addr
* In: 'off' is offset from base in 128M pci map
*/
static int
qlcnic_pci_get_crb_addr_2M(struct qlcnic_adapter *adapter,
ulong off, void __iomem **addr)
{
const struct crb_128M_2M_sub_block_map *m;
if ((off >= QLCNIC_CRB_MAX) || (off < QLCNIC_PCI_CRBSPACE))
return -EINVAL;
off -= QLCNIC_PCI_CRBSPACE;
/*
* Try direct map
*/
m = &crb_128M_2M_map[CRB_BLK(off)].sub_block[CRB_SUBBLK(off)];
if (m->valid && (m->start_128M <= off) && (m->end_128M > off)) {
*addr = adapter->ahw->pci_base0 + m->start_2M +
(off - m->start_128M);
return 0;
}
/*
* Not in direct map, use crb window
*/
*addr = adapter->ahw->pci_base0 + CRB_INDIRECT_2M + (off & MASK(16));
return 1;
}
/*
* In: 'off' is offset from CRB space in 128M pci map
* Out: 'off' is 2M pci map addr
* side effect: lock crb window
*/
static int
qlcnic_pci_set_crbwindow_2M(struct qlcnic_adapter *adapter, ulong off)
{
u32 window;
void __iomem *addr = adapter->ahw->pci_base0 + CRB_WINDOW_2M;
off -= QLCNIC_PCI_CRBSPACE;
window = CRB_HI(off);
if (window == 0) {
dev_err(&adapter->pdev->dev, "Invalid offset 0x%lx\n", off);
return -EIO;
}
writel(window, addr);
if (readl(addr) != window) {
if (printk_ratelimit())
dev_warn(&adapter->pdev->dev,
"failed to set CRB window to %d off 0x%lx\n",
window, off);
return -EIO;
}
return 0;
}
int
qlcnic_hw_write_wx_2M(struct qlcnic_adapter *adapter, ulong off, u32 data)
{
unsigned long flags;
int rv;
void __iomem *addr = NULL;
rv = qlcnic_pci_get_crb_addr_2M(adapter, off, &addr);
if (rv == 0) {
writel(data, addr);
return 0;
}
if (rv > 0) {
/* indirect access */
write_lock_irqsave(&adapter->ahw->crb_lock, flags);
crb_win_lock(adapter);
rv = qlcnic_pci_set_crbwindow_2M(adapter, off);
if (!rv)
writel(data, addr);
crb_win_unlock(adapter);
write_unlock_irqrestore(&adapter->ahw->crb_lock, flags);
return rv;
}
dev_err(&adapter->pdev->dev,
"%s: invalid offset: 0x%016lx\n", __func__, off);
dump_stack();
return -EIO;
}
u32
qlcnic_hw_read_wx_2M(struct qlcnic_adapter *adapter, ulong off)
{
unsigned long flags;
int rv;
u32 data = -1;
void __iomem *addr = NULL;
rv = qlcnic_pci_get_crb_addr_2M(adapter, off, &addr);
if (rv == 0)
return readl(addr);
if (rv > 0) {
/* indirect access */
write_lock_irqsave(&adapter->ahw->crb_lock, flags);
crb_win_lock(adapter);
if (!qlcnic_pci_set_crbwindow_2M(adapter, off))
data = readl(addr);
crb_win_unlock(adapter);
write_unlock_irqrestore(&adapter->ahw->crb_lock, flags);
return data;
}
dev_err(&adapter->pdev->dev,
"%s: invalid offset: 0x%016lx\n", __func__, off);
dump_stack();
return -1;
}
void __iomem *
qlcnic_get_ioaddr(struct qlcnic_adapter *adapter, u32 offset)
{
void __iomem *addr = NULL;
WARN_ON(qlcnic_pci_get_crb_addr_2M(adapter, offset, &addr));
return addr;
}
static int
qlcnic_pci_set_window_2M(struct qlcnic_adapter *adapter,
u64 addr, u32 *start)
{
u32 window;
window = OCM_WIN_P3P(addr);
writel(window, adapter->ahw->ocm_win_crb);
/* read back to flush */
readl(adapter->ahw->ocm_win_crb);
*start = QLCNIC_PCI_OCM0_2M + GET_MEM_OFFS_2M(addr);
return 0;
}
static int
qlcnic_pci_mem_access_direct(struct qlcnic_adapter *adapter, u64 off,
u64 *data, int op)
{
void __iomem *addr;
int ret;
u32 start;
mutex_lock(&adapter->ahw->mem_lock);
ret = qlcnic_pci_set_window_2M(adapter, off, &start);
if (ret != 0)
goto unlock;
addr = adapter->ahw->pci_base0 + start;
if (op == 0) /* read */
*data = readq(addr);
else /* write */
writeq(*data, addr);
unlock:
mutex_unlock(&adapter->ahw->mem_lock);
return ret;
}
void
qlcnic_pci_camqm_read_2M(struct qlcnic_adapter *adapter, u64 off, u64 *data)
{
void __iomem *addr = adapter->ahw->pci_base0 +
QLCNIC_PCI_CAMQM_2M_BASE + (off - QLCNIC_PCI_CAMQM);
mutex_lock(&adapter->ahw->mem_lock);
*data = readq(addr);
mutex_unlock(&adapter->ahw->mem_lock);
}
void
qlcnic_pci_camqm_write_2M(struct qlcnic_adapter *adapter, u64 off, u64 data)
{
void __iomem *addr = adapter->ahw->pci_base0 +
QLCNIC_PCI_CAMQM_2M_BASE + (off - QLCNIC_PCI_CAMQM);
mutex_lock(&adapter->ahw->mem_lock);
writeq(data, addr);
mutex_unlock(&adapter->ahw->mem_lock);
}
#define MAX_CTL_CHECK 1000
int
qlcnic_pci_mem_write_2M(struct qlcnic_adapter *adapter,
u64 off, u64 data)
{
int i, j, ret;
u32 temp, off8;
void __iomem *mem_crb;
/* Only 64-bit aligned access */
if (off & 7)
return -EIO;
/* P3 onward, test agent base for MIU and SIU is same */
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_QDR_NET,
QLCNIC_ADDR_QDR_NET_MAX)) {
mem_crb = qlcnic_get_ioaddr(adapter,
QLCNIC_CRB_QDR_NET+MIU_TEST_AGT_BASE);
goto correct;
}
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_DDR_NET, QLCNIC_ADDR_DDR_NET_MAX)) {
mem_crb = qlcnic_get_ioaddr(adapter,
QLCNIC_CRB_DDR_NET+MIU_TEST_AGT_BASE);
goto correct;
}
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_OCM0, QLCNIC_ADDR_OCM0_MAX))
return qlcnic_pci_mem_access_direct(adapter, off, &data, 1);
return -EIO;
correct:
off8 = off & ~0xf;
mutex_lock(&adapter->ahw->mem_lock);
writel(off8, (mem_crb + MIU_TEST_AGT_ADDR_LO));
writel(0, (mem_crb + MIU_TEST_AGT_ADDR_HI));
i = 0;
writel(TA_CTL_ENABLE, (mem_crb + TEST_AGT_CTRL));
writel((TA_CTL_START | TA_CTL_ENABLE),
(mem_crb + TEST_AGT_CTRL));
for (j = 0; j < MAX_CTL_CHECK; j++) {
temp = readl(mem_crb + TEST_AGT_CTRL);
if ((temp & TA_CTL_BUSY) == 0)
break;
}
if (j >= MAX_CTL_CHECK) {
ret = -EIO;
goto done;
}
i = (off & 0xf) ? 0 : 2;
writel(readl(mem_crb + MIU_TEST_AGT_RDDATA(i)),
mem_crb + MIU_TEST_AGT_WRDATA(i));
writel(readl(mem_crb + MIU_TEST_AGT_RDDATA(i+1)),
mem_crb + MIU_TEST_AGT_WRDATA(i+1));
i = (off & 0xf) ? 2 : 0;
writel(data & 0xffffffff,
mem_crb + MIU_TEST_AGT_WRDATA(i));
writel((data >> 32) & 0xffffffff,
mem_crb + MIU_TEST_AGT_WRDATA(i+1));
writel((TA_CTL_ENABLE | TA_CTL_WRITE), (mem_crb + TEST_AGT_CTRL));
writel((TA_CTL_START | TA_CTL_ENABLE | TA_CTL_WRITE),
(mem_crb + TEST_AGT_CTRL));
for (j = 0; j < MAX_CTL_CHECK; j++) {
temp = readl(mem_crb + TEST_AGT_CTRL);
if ((temp & TA_CTL_BUSY) == 0)
break;
}
if (j >= MAX_CTL_CHECK) {
if (printk_ratelimit())
dev_err(&adapter->pdev->dev,
"failed to write through agent\n");
ret = -EIO;
} else
ret = 0;
done:
mutex_unlock(&adapter->ahw->mem_lock);
return ret;
}
int
qlcnic_pci_mem_read_2M(struct qlcnic_adapter *adapter,
u64 off, u64 *data)
{
int j, ret;
u32 temp, off8;
u64 val;
void __iomem *mem_crb;
/* Only 64-bit aligned access */
if (off & 7)
return -EIO;
/* P3 onward, test agent base for MIU and SIU is same */
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_QDR_NET,
QLCNIC_ADDR_QDR_NET_MAX)) {
mem_crb = qlcnic_get_ioaddr(adapter,
QLCNIC_CRB_QDR_NET+MIU_TEST_AGT_BASE);
goto correct;
}
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_DDR_NET, QLCNIC_ADDR_DDR_NET_MAX)) {
mem_crb = qlcnic_get_ioaddr(adapter,
QLCNIC_CRB_DDR_NET+MIU_TEST_AGT_BASE);
goto correct;
}
if (ADDR_IN_RANGE(off, QLCNIC_ADDR_OCM0, QLCNIC_ADDR_OCM0_MAX)) {
return qlcnic_pci_mem_access_direct(adapter,
off, data, 0);
}
return -EIO;
correct:
off8 = off & ~0xf;
mutex_lock(&adapter->ahw->mem_lock);
writel(off8, (mem_crb + MIU_TEST_AGT_ADDR_LO));
writel(0, (mem_crb + MIU_TEST_AGT_ADDR_HI));
writel(TA_CTL_ENABLE, (mem_crb + TEST_AGT_CTRL));
writel((TA_CTL_START | TA_CTL_ENABLE), (mem_crb + TEST_AGT_CTRL));
for (j = 0; j < MAX_CTL_CHECK; j++) {
temp = readl(mem_crb + TEST_AGT_CTRL);
if ((temp & TA_CTL_BUSY) == 0)
break;
}
if (j >= MAX_CTL_CHECK) {
if (printk_ratelimit())
dev_err(&adapter->pdev->dev,
"failed to read through agent\n");
ret = -EIO;
} else {
off8 = MIU_TEST_AGT_RDDATA_LO;
if (off & 0xf)
off8 = MIU_TEST_AGT_RDDATA_UPPER_LO;
temp = readl(mem_crb + off8 + 4);
val = (u64)temp << 32;
val |= readl(mem_crb + off8);
*data = val;
ret = 0;
}
mutex_unlock(&adapter->ahw->mem_lock);
return ret;
}
int qlcnic_get_board_info(struct qlcnic_adapter *adapter)
{
int offset, board_type, magic;
struct pci_dev *pdev = adapter->pdev;
offset = QLCNIC_FW_MAGIC_OFFSET;
if (qlcnic_rom_fast_read(adapter, offset, &magic))
return -EIO;
if (magic != QLCNIC_BDINFO_MAGIC) {
dev_err(&pdev->dev, "invalid board config, magic=%08x\n",
magic);
return -EIO;
}
offset = QLCNIC_BRDTYPE_OFFSET;
if (qlcnic_rom_fast_read(adapter, offset, &board_type))
return -EIO;
adapter->ahw->board_type = board_type;
if (board_type == QLCNIC_BRDTYPE_P3P_4_GB_MM) {
u32 gpio = QLCRD32(adapter, QLCNIC_ROMUSB_GLB_PAD_GPIO_I);
if ((gpio & 0x8000) == 0)
board_type = QLCNIC_BRDTYPE_P3P_10G_TP;
}
switch (board_type) {
case QLCNIC_BRDTYPE_P3P_HMEZ:
case QLCNIC_BRDTYPE_P3P_XG_LOM:
case QLCNIC_BRDTYPE_P3P_10G_CX4:
case QLCNIC_BRDTYPE_P3P_10G_CX4_LP:
case QLCNIC_BRDTYPE_P3P_IMEZ:
case QLCNIC_BRDTYPE_P3P_10G_SFP_PLUS:
case QLCNIC_BRDTYPE_P3P_10G_SFP_CT:
case QLCNIC_BRDTYPE_P3P_10G_SFP_QT:
case QLCNIC_BRDTYPE_P3P_10G_XFP:
case QLCNIC_BRDTYPE_P3P_10000_BASE_T:
adapter->ahw->port_type = QLCNIC_XGBE;
break;
case QLCNIC_BRDTYPE_P3P_REF_QG:
case QLCNIC_BRDTYPE_P3P_4_GB:
case QLCNIC_BRDTYPE_P3P_4_GB_MM:
adapter->ahw->port_type = QLCNIC_GBE;
break;
case QLCNIC_BRDTYPE_P3P_10G_TP:
adapter->ahw->port_type = (adapter->portnum < 2) ?
QLCNIC_XGBE : QLCNIC_GBE;
break;
default:
dev_err(&pdev->dev, "unknown board type %x\n", board_type);
adapter->ahw->port_type = QLCNIC_XGBE;
break;
}
return 0;
}
int
qlcnic_wol_supported(struct qlcnic_adapter *adapter)
{
u32 wol_cfg;
wol_cfg = QLCRD32(adapter, QLCNIC_WOL_CONFIG_NV);
if (wol_cfg & (1UL << adapter->portnum)) {
wol_cfg = QLCRD32(adapter, QLCNIC_WOL_CONFIG);
if (wol_cfg & (1 << adapter->portnum))
return 1;
}
return 0;
}
int qlcnic_config_led(struct qlcnic_adapter *adapter, u32 state, u32 rate)
{
struct qlcnic_nic_req req;
int rv;
u64 word;
memset(&req, 0, sizeof(struct qlcnic_nic_req));
req.qhdr = cpu_to_le64(QLCNIC_HOST_REQUEST << 23);
word = QLCNIC_H2C_OPCODE_CONFIG_LED | ((u64)adapter->portnum << 16);
req.req_hdr = cpu_to_le64(word);
req.words[0] = cpu_to_le64((u64)rate << 32);
req.words[1] = cpu_to_le64(state);
rv = qlcnic_send_cmd_descs(adapter, (struct cmd_desc_type0 *)&req, 1);
if (rv)
dev_err(&adapter->pdev->dev, "LED configuration failed.\n");
return rv;
}
/* FW dump related functions */
static u32
qlcnic_dump_crb(struct qlcnic_adapter *adapter, struct qlcnic_dump_entry *entry,
u32 *buffer)
{
int i;
u32 addr, data;
struct __crb *crb = &entry->region.crb;
void __iomem *base = adapter->ahw->pci_base0;
addr = crb->addr;
for (i = 0; i < crb->no_ops; i++) {
QLCNIC_RD_DUMP_REG(addr, base, &data);
*buffer++ = cpu_to_le32(addr);
*buffer++ = cpu_to_le32(data);
addr += crb->stride;
}
return crb->no_ops * 2 * sizeof(u32);
}
static u32
qlcnic_dump_ctrl(struct qlcnic_adapter *adapter,
struct qlcnic_dump_entry *entry, u32 *buffer)
{
int i, k, timeout = 0;
void __iomem *base = adapter->ahw->pci_base0;
u32 addr, data;
u8 opcode, no_ops;
struct __ctrl *ctr = &entry->region.ctrl;
struct qlcnic_dump_template_hdr *t_hdr = adapter->ahw->fw_dump.tmpl_hdr;
addr = ctr->addr;
no_ops = ctr->no_ops;
for (i = 0; i < no_ops; i++) {
k = 0;
opcode = 0;
for (k = 0; k < 8; k++) {
if (!(ctr->opcode & (1 << k)))
continue;
switch (1 << k) {
case QLCNIC_DUMP_WCRB:
QLCNIC_WR_DUMP_REG(addr, base, ctr->val1);
break;
case QLCNIC_DUMP_RWCRB:
QLCNIC_RD_DUMP_REG(addr, base, &data);
QLCNIC_WR_DUMP_REG(addr, base, data);
break;
case QLCNIC_DUMP_ANDCRB:
QLCNIC_RD_DUMP_REG(addr, base, &data);
QLCNIC_WR_DUMP_REG(addr, base,
(data & ctr->val2));
break;
case QLCNIC_DUMP_ORCRB:
QLCNIC_RD_DUMP_REG(addr, base, &data);
QLCNIC_WR_DUMP_REG(addr, base,
(data | ctr->val3));
break;
case QLCNIC_DUMP_POLLCRB:
while (timeout <= ctr->timeout) {
QLCNIC_RD_DUMP_REG(addr, base, &data);
if ((data & ctr->val2) == ctr->val1)
break;
msleep(1);
timeout++;
}
if (timeout > ctr->timeout) {
dev_info(&adapter->pdev->dev,
"Timed out, aborting poll CRB\n");
return -EINVAL;
}
break;
case QLCNIC_DUMP_RD_SAVE:
if (ctr->index_a)
addr = t_hdr->saved_state[ctr->index_a];
QLCNIC_RD_DUMP_REG(addr, base, &data);
t_hdr->saved_state[ctr->index_v] = data;
break;
case QLCNIC_DUMP_WRT_SAVED:
if (ctr->index_v)
data = t_hdr->saved_state[ctr->index_v];
else
data = ctr->val1;
if (ctr->index_a)
addr = t_hdr->saved_state[ctr->index_a];
QLCNIC_WR_DUMP_REG(addr, base, data);
break;
case QLCNIC_DUMP_MOD_SAVE_ST:
data = t_hdr->saved_state[ctr->index_v];
data <<= ctr->shl_val;
data >>= ctr->shr_val;
if (ctr->val2)
data &= ctr->val2;
data |= ctr->val3;
data += ctr->val1;
t_hdr->saved_state[ctr->index_v] = data;
break;
default:
dev_info(&adapter->pdev->dev,
"Unknown opcode\n");
break;
}
}
addr += ctr->stride;
}
return 0;
}
static u32
qlcnic_dump_mux(struct qlcnic_adapter *adapter, struct qlcnic_dump_entry *entry,
u32 *buffer)
{
int loop;
u32 val, data = 0;
struct __mux *mux = &entry->region.mux;
void __iomem *base = adapter->ahw->pci_base0;
val = mux->val;
for (loop = 0; loop < mux->no_ops; loop++) {
QLCNIC_WR_DUMP_REG(mux->addr, base, val);
QLCNIC_RD_DUMP_REG(mux->read_addr, base, &data);
*buffer++ = cpu_to_le32(val);
*buffer++ = cpu_to_le32(data);
val += mux->val_stride;
}
return 2 * mux->no_ops * sizeof(u32);
}
static u32
qlcnic_dump_que(struct qlcnic_adapter *adapter, struct qlcnic_dump_entry *entry,
u32 *buffer)
{
int i, loop;
u32 cnt, addr, data, que_id = 0;
void __iomem *base = adapter->ahw->pci_base0;
struct __queue *que = &entry->region.que;
addr = que->read_addr;
cnt = que->read_addr_cnt;
for (loop = 0; loop < que->no_ops; loop++) {
QLCNIC_WR_DUMP_REG(que->sel_addr, base, que_id);
addr = que->read_addr;
for (i = 0; i < cnt; i++) {
QLCNIC_RD_DUMP_REG(addr, base, &data);
*buffer++ = cpu_to_le32(data);
addr += que->read_addr_stride;
}
que_id += que->stride;
}
return que->no_ops * cnt * sizeof(u32);
}
static u32
qlcnic_dump_ocm(struct qlcnic_adapter *adapter, struct qlcnic_dump_entry *entry,
u32 *buffer)
{
int i;
u32 data;
void __iomem *addr;
struct __ocm *ocm = &entry->region.ocm;
addr = adapter->ahw->pci_base0 + ocm->read_addr;
for (i = 0; i < ocm->no_ops; i++) {
data = readl(addr);
*buffer++ = cpu_to_le32(data);
addr += ocm->read_addr_stride;
}
return ocm->no_ops * sizeof(u32);
}
static u32
qlcnic_read_rom(struct qlcnic_adapter *adapter, struct qlcnic_dump_entry *entry,
u32 *buffer)
{
int i, count = 0;
u32 fl_addr, size, val, lck_val, addr;
struct __mem *rom = &entry->region.mem;
void __iomem *base = adapter->ahw->pci_base0;
fl_addr = rom->addr;
size = rom->size/4;
lock_try:
lck_val = readl(base + QLCNIC_FLASH_SEM2_LK);
if (!lck_val && count < MAX_CTL_CHECK) {
msleep(10);
count++;
goto lock_try;
}
writel(adapter->ahw->pci_func, (base + QLCNIC_FLASH_LOCK_ID));
for (i = 0; i < size; i++) {
addr = fl_addr & 0xFFFF0000;
QLCNIC_WR_DUMP_REG(FLASH_ROM_WINDOW, base, addr);
addr = LSW(fl_addr) + FLASH_ROM_DATA;
QLCNIC_RD_DUMP_REG(addr, base, &val);
fl_addr += 4;
*buffer++ = cpu_to_le32(val);
}
readl(base + QLCNIC_FLASH_SEM2_ULK);
return rom->size;
}
static u32
qlcnic_dump_l1_cache(struct qlcnic_adapter *adapter,
struct qlcnic_dump_entry *entry, u32 *buffer)
{
int i;
u32 cnt, val, data, addr;
void __iomem *base = adapter->ahw->pci_base0;
struct __cache *l1 = &entry->region.cache;
val = l1->init_tag_val;
for (i = 0; i < l1->no_ops; i++) {
QLCNIC_WR_DUMP_REG(l1->addr, base, val);
QLCNIC_WR_DUMP_REG(l1->ctrl_addr, base, LSW(l1->ctrl_val));
addr = l1->read_addr;
cnt = l1->read_addr_num;
while (cnt) {
QLCNIC_RD_DUMP_REG(addr, base, &data);
*buffer++ = cpu_to_le32(data);
addr += l1->read_addr_stride;
cnt--;
}
val += l1->stride;
}
return l1->no_ops * l1->read_addr_num * sizeof(u32);
}
static u32
qlcnic_dump_l2_cache(struct qlcnic_adapter *adapter,
struct qlcnic_dump_entry *entry, u32 *buffer)
{
int i;
u32 cnt, val, data, addr;
u8 poll_mask, poll_to, time_out = 0;
void __iomem *base = adapter->ahw->pci_base0;
struct __cache *l2 = &entry->region.cache;
val = l2->init_tag_val;
poll_mask = LSB(MSW(l2->ctrl_val));
poll_to = MSB(MSW(l2->ctrl_val));
for (i = 0; i < l2->no_ops; i++) {
QLCNIC_WR_DUMP_REG(l2->addr, base, val);
do {
QLCNIC_WR_DUMP_REG(l2->ctrl_addr, base,
LSW(l2->ctrl_val));
QLCNIC_RD_DUMP_REG(l2->ctrl_addr, base, &data);
if (!(data & poll_mask))
break;
msleep(1);
time_out++;
} while (time_out <= poll_to);
if (time_out > poll_to)
return -EINVAL;
addr = l2->read_addr;
cnt = l2->read_addr_num;
while (cnt) {
QLCNIC_RD_DUMP_REG(addr, base, &data);
*buffer++ = cpu_to_le32(data);
addr += l2->read_addr_stride;
cnt--;
}
val += l2->stride;
}
return l2->no_ops * l2->read_addr_num * sizeof(u32);
}
static u32
qlcnic_read_memory(struct qlcnic_adapter *adapter,
struct qlcnic_dump_entry *entry, u32 *buffer)
{
u32 addr, data, test, ret = 0;
int i, reg_read;
struct __mem *mem = &entry->region.mem;
void __iomem *base = adapter->ahw->pci_base0;
reg_read = mem->size;
addr = mem->addr;
/* check for data size of multiple of 16 and 16 byte alignment */
if ((addr & 0xf) || (reg_read%16)) {
dev_info(&adapter->pdev->dev,
"Unaligned memory addr:0x%x size:0x%x\n",
addr, reg_read);
return -EINVAL;
}
mutex_lock(&adapter->ahw->mem_lock);
while (reg_read != 0) {
QLCNIC_WR_DUMP_REG(MIU_TEST_ADDR_LO, base, addr);
QLCNIC_WR_DUMP_REG(MIU_TEST_ADDR_HI, base, 0);
QLCNIC_WR_DUMP_REG(MIU_TEST_CTR, base,
TA_CTL_ENABLE | TA_CTL_START);
for (i = 0; i < MAX_CTL_CHECK; i++) {
QLCNIC_RD_DUMP_REG(MIU_TEST_CTR, base, &test);
if (!(test & TA_CTL_BUSY))
break;
}
if (i == MAX_CTL_CHECK) {
if (printk_ratelimit()) {
dev_err(&adapter->pdev->dev,
"failed to read through agent\n");
ret = -EINVAL;
goto out;
}
}
for (i = 0; i < 4; i++) {
QLCNIC_RD_DUMP_REG(MIU_TEST_READ_DATA[i], base, &data);
*buffer++ = cpu_to_le32(data);
}
addr += 16;
reg_read -= 16;
ret += 16;
}
out:
mutex_unlock(&adapter->ahw->mem_lock);
return mem->size;
}
static u32
qlcnic_dump_nop(struct qlcnic_adapter *adapter,
struct qlcnic_dump_entry *entry, u32 *buffer)
{
entry->hdr.flags |= QLCNIC_DUMP_SKIP;
return 0;
}
struct qlcnic_dump_operations fw_dump_ops[] = {
{ QLCNIC_DUMP_NOP, qlcnic_dump_nop },
{ QLCNIC_DUMP_READ_CRB, qlcnic_dump_crb },
{ QLCNIC_DUMP_READ_MUX, qlcnic_dump_mux },
{ QLCNIC_DUMP_QUEUE, qlcnic_dump_que },
{ QLCNIC_DUMP_BRD_CONFIG, qlcnic_read_rom },
{ QLCNIC_DUMP_READ_OCM, qlcnic_dump_ocm },
{ QLCNIC_DUMP_PEG_REG, qlcnic_dump_ctrl },
{ QLCNIC_DUMP_L1_DTAG, qlcnic_dump_l1_cache },
{ QLCNIC_DUMP_L1_ITAG, qlcnic_dump_l1_cache },
{ QLCNIC_DUMP_L1_DATA, qlcnic_dump_l1_cache },
{ QLCNIC_DUMP_L1_INST, qlcnic_dump_l1_cache },
{ QLCNIC_DUMP_L2_DTAG, qlcnic_dump_l2_cache },
{ QLCNIC_DUMP_L2_ITAG, qlcnic_dump_l2_cache },
{ QLCNIC_DUMP_L2_DATA, qlcnic_dump_l2_cache },
{ QLCNIC_DUMP_L2_INST, qlcnic_dump_l2_cache },
{ QLCNIC_DUMP_READ_ROM, qlcnic_read_rom },
{ QLCNIC_DUMP_READ_MEM, qlcnic_read_memory },
{ QLCNIC_DUMP_READ_CTRL, qlcnic_dump_ctrl },
{ QLCNIC_DUMP_TLHDR, qlcnic_dump_nop },
{ QLCNIC_DUMP_RDEND, qlcnic_dump_nop },
};
/* Walk the template and collect dump for each entry in the dump template */
static int
qlcnic_valid_dump_entry(struct device *dev, struct qlcnic_dump_entry *entry,
u32 size)
{
int ret = 1;
if (size != entry->hdr.cap_size) {
dev_info(dev,
"Invalidate dump, Type:%d\tMask:%d\tSize:%dCap_size:%d\n",
entry->hdr.type, entry->hdr.mask, size, entry->hdr.cap_size);
dev_info(dev, "Aborting further dump capture\n");
ret = 0;
}
return ret;
}
int qlcnic_dump_fw(struct qlcnic_adapter *adapter)
{
u32 *buffer;
char mesg[64];
char *msg[] = {mesg, NULL};
int i, k, ops_cnt, ops_index, dump_size = 0;
u32 entry_offset, dump, no_entries, buf_offset = 0;
struct qlcnic_dump_entry *entry;
struct qlcnic_fw_dump *fw_dump = &adapter->ahw->fw_dump;
struct qlcnic_dump_template_hdr *tmpl_hdr = fw_dump->tmpl_hdr;
if (fw_dump->clr) {
dev_info(&adapter->pdev->dev,
"Previous dump not cleared, not capturing dump\n");
return -EIO;
}
/* Calculate the size for dump data area only */
for (i = 2, k = 1; (i & QLCNIC_DUMP_MASK_MAX); i <<= 1, k++)
if (i & tmpl_hdr->drv_cap_mask)
dump_size += tmpl_hdr->cap_sizes[k];
if (!dump_size)
return -EIO;
fw_dump->data = vzalloc(dump_size);
if (!fw_dump->data) {
dev_info(&adapter->pdev->dev,
"Unable to allocate (%d KB) for fw dump\n",
dump_size/1024);
return -ENOMEM;
}
buffer = fw_dump->data;
fw_dump->size = dump_size;
no_entries = tmpl_hdr->num_entries;
ops_cnt = ARRAY_SIZE(fw_dump_ops);
entry_offset = tmpl_hdr->offset;
tmpl_hdr->sys_info[0] = QLCNIC_DRIVER_VERSION;
tmpl_hdr->sys_info[1] = adapter->fw_version;
for (i = 0; i < no_entries; i++) {
entry = (struct qlcnic_dump_entry *) ((void *) tmpl_hdr +
entry_offset);
if (!(entry->hdr.mask & tmpl_hdr->drv_cap_mask)) {
entry->hdr.flags |= QLCNIC_DUMP_SKIP;
entry_offset += entry->hdr.offset;
continue;
}
/* Find the handler for this entry */
ops_index = 0;
while (ops_index < ops_cnt) {
if (entry->hdr.type == fw_dump_ops[ops_index].opcode)
break;
ops_index++;
}
if (ops_index == ops_cnt) {
dev_info(&adapter->pdev->dev,
"Invalid entry type %d, exiting dump\n",
entry->hdr.type);
goto error;
}
/* Collect dump for this entry */
dump = fw_dump_ops[ops_index].handler(adapter, entry, buffer);
if (dump && !qlcnic_valid_dump_entry(&adapter->pdev->dev, entry,
dump))
entry->hdr.flags |= QLCNIC_DUMP_SKIP;
buf_offset += entry->hdr.cap_size;
entry_offset += entry->hdr.offset;
buffer = fw_dump->data + buf_offset;
}
if (dump_size != buf_offset) {
dev_info(&adapter->pdev->dev,
"Captured(%d) and expected size(%d) do not match\n",
buf_offset, dump_size);
goto error;
} else {
fw_dump->clr = 1;
snprintf(mesg, sizeof(mesg), "FW dump for device: %d\n",
adapter->pdev->devfn);
dev_info(&adapter->pdev->dev, "Dump data, %d bytes captured\n",
fw_dump->size);
/* Send a udev event to notify availability of FW dump */
kobject_uevent_env(&adapter->pdev->dev.kobj, KOBJ_CHANGE, msg);
return 0;
}
error:
vfree(fw_dump->data);
return -EINVAL;
}
| gpl-2.0 |
hallovveen31/smooth | drivers/usb/musb/am35x.c | 2381 | 16701 | /*
* Texas Instruments AM35x "glue layer"
*
* Copyright (c) 2010, by Texas Instruments
*
* Based on the DA8xx "glue layer" code.
* Copyright (c) 2008-2009, MontaVista Software, Inc. <source@mvista.com>
*
* This file is part of the Inventra Controller Driver for Linux.
*
* The Inventra Controller Driver for Linux 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.
*
* The Inventra Controller Driver for Linux 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 The Inventra Controller Driver for Linux ; 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/clk.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <plat/usb.h>
#include "musb_core.h"
/*
* AM35x specific definitions
*/
/* USB 2.0 OTG module registers */
#define USB_REVISION_REG 0x00
#define USB_CTRL_REG 0x04
#define USB_STAT_REG 0x08
#define USB_EMULATION_REG 0x0c
/* 0x10 Reserved */
#define USB_AUTOREQ_REG 0x14
#define USB_SRP_FIX_TIME_REG 0x18
#define USB_TEARDOWN_REG 0x1c
#define EP_INTR_SRC_REG 0x20
#define EP_INTR_SRC_SET_REG 0x24
#define EP_INTR_SRC_CLEAR_REG 0x28
#define EP_INTR_MASK_REG 0x2c
#define EP_INTR_MASK_SET_REG 0x30
#define EP_INTR_MASK_CLEAR_REG 0x34
#define EP_INTR_SRC_MASKED_REG 0x38
#define CORE_INTR_SRC_REG 0x40
#define CORE_INTR_SRC_SET_REG 0x44
#define CORE_INTR_SRC_CLEAR_REG 0x48
#define CORE_INTR_MASK_REG 0x4c
#define CORE_INTR_MASK_SET_REG 0x50
#define CORE_INTR_MASK_CLEAR_REG 0x54
#define CORE_INTR_SRC_MASKED_REG 0x58
/* 0x5c Reserved */
#define USB_END_OF_INTR_REG 0x60
/* Control register bits */
#define AM35X_SOFT_RESET_MASK 1
/* USB interrupt register bits */
#define AM35X_INTR_USB_SHIFT 16
#define AM35X_INTR_USB_MASK (0x1ff << AM35X_INTR_USB_SHIFT)
#define AM35X_INTR_DRVVBUS 0x100
#define AM35X_INTR_RX_SHIFT 16
#define AM35X_INTR_TX_SHIFT 0
#define AM35X_TX_EP_MASK 0xffff /* EP0 + 15 Tx EPs */
#define AM35X_RX_EP_MASK 0xfffe /* 15 Rx EPs */
#define AM35X_TX_INTR_MASK (AM35X_TX_EP_MASK << AM35X_INTR_TX_SHIFT)
#define AM35X_RX_INTR_MASK (AM35X_RX_EP_MASK << AM35X_INTR_RX_SHIFT)
#define USB_MENTOR_CORE_OFFSET 0x400
struct am35x_glue {
struct device *dev;
struct platform_device *musb;
struct clk *phy_clk;
struct clk *clk;
};
#define glue_to_musb(g) platform_get_drvdata(g->musb)
/*
* am35x_musb_enable - enable interrupts
*/
static void am35x_musb_enable(struct musb *musb)
{
void __iomem *reg_base = musb->ctrl_base;
u32 epmask;
/* Workaround: setup IRQs through both register sets. */
epmask = ((musb->epmask & AM35X_TX_EP_MASK) << AM35X_INTR_TX_SHIFT) |
((musb->epmask & AM35X_RX_EP_MASK) << AM35X_INTR_RX_SHIFT);
musb_writel(reg_base, EP_INTR_MASK_SET_REG, epmask);
musb_writel(reg_base, CORE_INTR_MASK_SET_REG, AM35X_INTR_USB_MASK);
/* Force the DRVVBUS IRQ so we can start polling for ID change. */
if (is_otg_enabled(musb))
musb_writel(reg_base, CORE_INTR_SRC_SET_REG,
AM35X_INTR_DRVVBUS << AM35X_INTR_USB_SHIFT);
}
/*
* am35x_musb_disable - disable HDRC and flush interrupts
*/
static void am35x_musb_disable(struct musb *musb)
{
void __iomem *reg_base = musb->ctrl_base;
musb_writel(reg_base, CORE_INTR_MASK_CLEAR_REG, AM35X_INTR_USB_MASK);
musb_writel(reg_base, EP_INTR_MASK_CLEAR_REG,
AM35X_TX_INTR_MASK | AM35X_RX_INTR_MASK);
musb_writeb(musb->mregs, MUSB_DEVCTL, 0);
musb_writel(reg_base, USB_END_OF_INTR_REG, 0);
}
#ifdef CONFIG_USB_MUSB_HDRC_HCD
#define portstate(stmt) stmt
#else
#define portstate(stmt)
#endif
static void am35x_musb_set_vbus(struct musb *musb, int is_on)
{
WARN_ON(is_on && is_peripheral_active(musb));
}
#define POLL_SECONDS 2
static struct timer_list otg_workaround;
static void otg_timer(unsigned long _musb)
{
struct musb *musb = (void *)_musb;
void __iomem *mregs = musb->mregs;
u8 devctl;
unsigned long flags;
/*
* We poll because AM35x's won't expose several OTG-critical
* status change events (from the transceiver) otherwise.
*/
devctl = musb_readb(mregs, MUSB_DEVCTL);
dev_dbg(musb->controller, "Poll devctl %02x (%s)\n", devctl,
otg_state_string(musb->xceiv->state));
spin_lock_irqsave(&musb->lock, flags);
switch (musb->xceiv->state) {
case OTG_STATE_A_WAIT_BCON:
devctl &= ~MUSB_DEVCTL_SESSION;
musb_writeb(musb->mregs, MUSB_DEVCTL, devctl);
devctl = musb_readb(musb->mregs, MUSB_DEVCTL);
if (devctl & MUSB_DEVCTL_BDEVICE) {
musb->xceiv->state = OTG_STATE_B_IDLE;
MUSB_DEV_MODE(musb);
} else {
musb->xceiv->state = OTG_STATE_A_IDLE;
MUSB_HST_MODE(musb);
}
break;
case OTG_STATE_A_WAIT_VFALL:
musb->xceiv->state = OTG_STATE_A_WAIT_VRISE;
musb_writel(musb->ctrl_base, CORE_INTR_SRC_SET_REG,
MUSB_INTR_VBUSERROR << AM35X_INTR_USB_SHIFT);
break;
case OTG_STATE_B_IDLE:
if (!is_peripheral_enabled(musb))
break;
devctl = musb_readb(mregs, MUSB_DEVCTL);
if (devctl & MUSB_DEVCTL_BDEVICE)
mod_timer(&otg_workaround, jiffies + POLL_SECONDS * HZ);
else
musb->xceiv->state = OTG_STATE_A_IDLE;
break;
default:
break;
}
spin_unlock_irqrestore(&musb->lock, flags);
}
static void am35x_musb_try_idle(struct musb *musb, unsigned long timeout)
{
static unsigned long last_timer;
if (!is_otg_enabled(musb))
return;
if (timeout == 0)
timeout = jiffies + msecs_to_jiffies(3);
/* Never idle if active, or when VBUS timeout is not set as host */
if (musb->is_active || (musb->a_wait_bcon == 0 &&
musb->xceiv->state == OTG_STATE_A_WAIT_BCON)) {
dev_dbg(musb->controller, "%s active, deleting timer\n",
otg_state_string(musb->xceiv->state));
del_timer(&otg_workaround);
last_timer = jiffies;
return;
}
if (time_after(last_timer, timeout) && timer_pending(&otg_workaround)) {
dev_dbg(musb->controller, "Longer idle timer already pending, ignoring...\n");
return;
}
last_timer = timeout;
dev_dbg(musb->controller, "%s inactive, starting idle timer for %u ms\n",
otg_state_string(musb->xceiv->state),
jiffies_to_msecs(timeout - jiffies));
mod_timer(&otg_workaround, timeout);
}
static irqreturn_t am35x_musb_interrupt(int irq, void *hci)
{
struct musb *musb = hci;
void __iomem *reg_base = musb->ctrl_base;
struct device *dev = musb->controller;
struct musb_hdrc_platform_data *plat = dev->platform_data;
struct omap_musb_board_data *data = plat->board_data;
unsigned long flags;
irqreturn_t ret = IRQ_NONE;
u32 epintr, usbintr;
spin_lock_irqsave(&musb->lock, flags);
/* Get endpoint interrupts */
epintr = musb_readl(reg_base, EP_INTR_SRC_MASKED_REG);
if (epintr) {
musb_writel(reg_base, EP_INTR_SRC_CLEAR_REG, epintr);
musb->int_rx =
(epintr & AM35X_RX_INTR_MASK) >> AM35X_INTR_RX_SHIFT;
musb->int_tx =
(epintr & AM35X_TX_INTR_MASK) >> AM35X_INTR_TX_SHIFT;
}
/* Get usb core interrupts */
usbintr = musb_readl(reg_base, CORE_INTR_SRC_MASKED_REG);
if (!usbintr && !epintr)
goto eoi;
if (usbintr) {
musb_writel(reg_base, CORE_INTR_SRC_CLEAR_REG, usbintr);
musb->int_usb =
(usbintr & AM35X_INTR_USB_MASK) >> AM35X_INTR_USB_SHIFT;
}
/*
* DRVVBUS IRQs are the only proxy we have (a very poor one!) for
* AM35x's missing ID change IRQ. We need an ID change IRQ to
* switch appropriately between halves of the OTG state machine.
* Managing DEVCTL.SESSION per Mentor docs requires that we know its
* value but DEVCTL.BDEVICE is invalid without DEVCTL.SESSION set.
* Also, DRVVBUS pulses for SRP (but not at 5V) ...
*/
if (usbintr & (AM35X_INTR_DRVVBUS << AM35X_INTR_USB_SHIFT)) {
int drvvbus = musb_readl(reg_base, USB_STAT_REG);
void __iomem *mregs = musb->mregs;
u8 devctl = musb_readb(mregs, MUSB_DEVCTL);
int err;
err = is_host_enabled(musb) && (musb->int_usb &
MUSB_INTR_VBUSERROR);
if (err) {
/*
* The Mentor core doesn't debounce VBUS as needed
* to cope with device connect current spikes. This
* means it's not uncommon for bus-powered devices
* to get VBUS errors during enumeration.
*
* This is a workaround, but newer RTL from Mentor
* seems to allow a better one: "re"-starting sessions
* without waiting for VBUS to stop registering in
* devctl.
*/
musb->int_usb &= ~MUSB_INTR_VBUSERROR;
musb->xceiv->state = OTG_STATE_A_WAIT_VFALL;
mod_timer(&otg_workaround, jiffies + POLL_SECONDS * HZ);
WARNING("VBUS error workaround (delay coming)\n");
} else if (is_host_enabled(musb) && drvvbus) {
MUSB_HST_MODE(musb);
musb->xceiv->default_a = 1;
musb->xceiv->state = OTG_STATE_A_WAIT_VRISE;
portstate(musb->port1_status |= USB_PORT_STAT_POWER);
del_timer(&otg_workaround);
} else {
musb->is_active = 0;
MUSB_DEV_MODE(musb);
musb->xceiv->default_a = 0;
musb->xceiv->state = OTG_STATE_B_IDLE;
portstate(musb->port1_status &= ~USB_PORT_STAT_POWER);
}
/* NOTE: this must complete power-on within 100 ms. */
dev_dbg(musb->controller, "VBUS %s (%s)%s, devctl %02x\n",
drvvbus ? "on" : "off",
otg_state_string(musb->xceiv->state),
err ? " ERROR" : "",
devctl);
ret = IRQ_HANDLED;
}
if (musb->int_tx || musb->int_rx || musb->int_usb)
ret |= musb_interrupt(musb);
eoi:
/* EOI needs to be written for the IRQ to be re-asserted. */
if (ret == IRQ_HANDLED || epintr || usbintr) {
/* clear level interrupt */
if (data->clear_irq)
data->clear_irq();
/* write EOI */
musb_writel(reg_base, USB_END_OF_INTR_REG, 0);
}
/* Poll for ID change */
if (is_otg_enabled(musb) && musb->xceiv->state == OTG_STATE_B_IDLE)
mod_timer(&otg_workaround, jiffies + POLL_SECONDS * HZ);
spin_unlock_irqrestore(&musb->lock, flags);
return ret;
}
static int am35x_musb_set_mode(struct musb *musb, u8 musb_mode)
{
struct device *dev = musb->controller;
struct musb_hdrc_platform_data *plat = dev->platform_data;
struct omap_musb_board_data *data = plat->board_data;
int retval = 0;
if (data->set_mode)
data->set_mode(musb_mode);
else
retval = -EIO;
return retval;
}
static int am35x_musb_init(struct musb *musb)
{
struct device *dev = musb->controller;
struct musb_hdrc_platform_data *plat = dev->platform_data;
struct omap_musb_board_data *data = plat->board_data;
void __iomem *reg_base = musb->ctrl_base;
u32 rev;
musb->mregs += USB_MENTOR_CORE_OFFSET;
/* Returns zero if e.g. not clocked */
rev = musb_readl(reg_base, USB_REVISION_REG);
if (!rev)
return -ENODEV;
usb_nop_xceiv_register();
musb->xceiv = otg_get_transceiver();
if (!musb->xceiv)
return -ENODEV;
if (is_host_enabled(musb))
setup_timer(&otg_workaround, otg_timer, (unsigned long) musb);
/* Reset the musb */
if (data->reset)
data->reset();
/* Reset the controller */
musb_writel(reg_base, USB_CTRL_REG, AM35X_SOFT_RESET_MASK);
/* Start the on-chip PHY and its PLL. */
if (data->set_phy_power)
data->set_phy_power(1);
msleep(5);
musb->isr = am35x_musb_interrupt;
/* clear level interrupt */
if (data->clear_irq)
data->clear_irq();
return 0;
}
static int am35x_musb_exit(struct musb *musb)
{
struct device *dev = musb->controller;
struct musb_hdrc_platform_data *plat = dev->platform_data;
struct omap_musb_board_data *data = plat->board_data;
if (is_host_enabled(musb))
del_timer_sync(&otg_workaround);
/* Shutdown the on-chip PHY and its PLL. */
if (data->set_phy_power)
data->set_phy_power(0);
otg_put_transceiver(musb->xceiv);
usb_nop_xceiv_unregister();
return 0;
}
/* AM35x supports only 32bit read operation */
void musb_read_fifo(struct musb_hw_ep *hw_ep, u16 len, u8 *dst)
{
void __iomem *fifo = hw_ep->fifo;
u32 val;
int i;
/* Read for 32bit-aligned destination address */
if (likely((0x03 & (unsigned long) dst) == 0) && len >= 4) {
readsl(fifo, dst, len >> 2);
dst += len & ~0x03;
len &= 0x03;
}
/*
* Now read the remaining 1 to 3 byte or complete length if
* unaligned address.
*/
if (len > 4) {
for (i = 0; i < (len >> 2); i++) {
*(u32 *) dst = musb_readl(fifo, 0);
dst += 4;
}
len &= 0x03;
}
if (len > 0) {
val = musb_readl(fifo, 0);
memcpy(dst, &val, len);
}
}
static const struct musb_platform_ops am35x_ops = {
.init = am35x_musb_init,
.exit = am35x_musb_exit,
.enable = am35x_musb_enable,
.disable = am35x_musb_disable,
.set_mode = am35x_musb_set_mode,
.try_idle = am35x_musb_try_idle,
.set_vbus = am35x_musb_set_vbus,
};
static u64 am35x_dmamask = DMA_BIT_MASK(32);
static int __init am35x_probe(struct platform_device *pdev)
{
struct musb_hdrc_platform_data *pdata = pdev->dev.platform_data;
struct platform_device *musb;
struct am35x_glue *glue;
struct clk *phy_clk;
struct clk *clk;
int ret = -ENOMEM;
glue = kzalloc(sizeof(*glue), GFP_KERNEL);
if (!glue) {
dev_err(&pdev->dev, "failed to allocate glue context\n");
goto err0;
}
musb = platform_device_alloc("musb-hdrc", -1);
if (!musb) {
dev_err(&pdev->dev, "failed to allocate musb device\n");
goto err1;
}
phy_clk = clk_get(&pdev->dev, "fck");
if (IS_ERR(phy_clk)) {
dev_err(&pdev->dev, "failed to get PHY clock\n");
ret = PTR_ERR(phy_clk);
goto err2;
}
clk = clk_get(&pdev->dev, "ick");
if (IS_ERR(clk)) {
dev_err(&pdev->dev, "failed to get clock\n");
ret = PTR_ERR(clk);
goto err3;
}
ret = clk_enable(phy_clk);
if (ret) {
dev_err(&pdev->dev, "failed to enable PHY clock\n");
goto err4;
}
ret = clk_enable(clk);
if (ret) {
dev_err(&pdev->dev, "failed to enable clock\n");
goto err5;
}
musb->dev.parent = &pdev->dev;
musb->dev.dma_mask = &am35x_dmamask;
musb->dev.coherent_dma_mask = am35x_dmamask;
glue->dev = &pdev->dev;
glue->musb = musb;
glue->phy_clk = phy_clk;
glue->clk = clk;
pdata->platform_ops = &am35x_ops;
platform_set_drvdata(pdev, glue);
ret = platform_device_add_resources(musb, pdev->resource,
pdev->num_resources);
if (ret) {
dev_err(&pdev->dev, "failed to add resources\n");
goto err6;
}
ret = platform_device_add_data(musb, pdata, sizeof(*pdata));
if (ret) {
dev_err(&pdev->dev, "failed to add platform_data\n");
goto err6;
}
ret = platform_device_add(musb);
if (ret) {
dev_err(&pdev->dev, "failed to register musb device\n");
goto err6;
}
return 0;
err6:
clk_disable(clk);
err5:
clk_disable(phy_clk);
err4:
clk_put(clk);
err3:
clk_put(phy_clk);
err2:
platform_device_put(musb);
err1:
kfree(glue);
err0:
return ret;
}
static int __exit am35x_remove(struct platform_device *pdev)
{
struct am35x_glue *glue = platform_get_drvdata(pdev);
platform_device_del(glue->musb);
platform_device_put(glue->musb);
clk_disable(glue->clk);
clk_disable(glue->phy_clk);
clk_put(glue->clk);
clk_put(glue->phy_clk);
kfree(glue);
return 0;
}
#ifdef CONFIG_PM
static int am35x_suspend(struct device *dev)
{
struct am35x_glue *glue = dev_get_drvdata(dev);
struct musb_hdrc_platform_data *plat = dev->platform_data;
struct omap_musb_board_data *data = plat->board_data;
/* Shutdown the on-chip PHY and its PLL. */
if (data->set_phy_power)
data->set_phy_power(0);
clk_disable(glue->phy_clk);
clk_disable(glue->clk);
return 0;
}
static int am35x_resume(struct device *dev)
{
struct am35x_glue *glue = dev_get_drvdata(dev);
struct musb_hdrc_platform_data *plat = dev->platform_data;
struct omap_musb_board_data *data = plat->board_data;
int ret;
/* Start the on-chip PHY and its PLL. */
if (data->set_phy_power)
data->set_phy_power(1);
ret = clk_enable(glue->phy_clk);
if (ret) {
dev_err(dev, "failed to enable PHY clock\n");
return ret;
}
ret = clk_enable(glue->clk);
if (ret) {
dev_err(dev, "failed to enable clock\n");
return ret;
}
return 0;
}
static struct dev_pm_ops am35x_pm_ops = {
.suspend = am35x_suspend,
.resume = am35x_resume,
};
#define DEV_PM_OPS &am35x_pm_ops
#else
#define DEV_PM_OPS NULL
#endif
static struct platform_driver am35x_driver = {
.remove = __exit_p(am35x_remove),
.driver = {
.name = "musb-am35x",
.pm = DEV_PM_OPS,
},
};
MODULE_DESCRIPTION("AM35x MUSB Glue Layer");
MODULE_AUTHOR("Ajay Kumar Gupta <ajay.gupta@ti.com>");
MODULE_LICENSE("GPL v2");
static int __init am35x_init(void)
{
return platform_driver_probe(&am35x_driver, am35x_probe);
}
subsys_initcall(am35x_init);
static void __exit am35x_exit(void)
{
platform_driver_unregister(&am35x_driver);
}
module_exit(am35x_exit);
| gpl-2.0 |
RealVNC/android-kernel-omap | drivers/edac/cell_edac.c | 2637 | 7392 | /*
* Cell MIC driver for ECC counting
*
* Copyright 2007 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* This file may be distributed under the terms of the
* GNU General Public License.
*/
#undef DEBUG
#include <linux/edac.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/stop_machine.h>
#include <linux/io.h>
#include <asm/machdep.h>
#include <asm/cell-regs.h>
#include "edac_core.h"
struct cell_edac_priv
{
struct cbe_mic_tm_regs __iomem *regs;
int node;
int chanmask;
#ifdef DEBUG
u64 prev_fir;
#endif
};
static void cell_edac_count_ce(struct mem_ctl_info *mci, int chan, u64 ar)
{
struct cell_edac_priv *priv = mci->pvt_info;
struct csrow_info *csrow = &mci->csrows[0];
unsigned long address, pfn, offset, syndrome;
dev_dbg(mci->dev, "ECC CE err on node %d, channel %d, ar = 0x%016llx\n",
priv->node, chan, ar);
/* Address decoding is likely a bit bogus, to dbl check */
address = (ar & 0xffffffffe0000000ul) >> 29;
if (priv->chanmask == 0x3)
address = (address << 1) | chan;
pfn = address >> PAGE_SHIFT;
offset = address & ~PAGE_MASK;
syndrome = (ar & 0x000000001fe00000ul) >> 21;
/* TODO: Decoding of the error address */
edac_mc_handle_ce(mci, csrow->first_page + pfn, offset,
syndrome, 0, chan, "");
}
static void cell_edac_count_ue(struct mem_ctl_info *mci, int chan, u64 ar)
{
struct cell_edac_priv *priv = mci->pvt_info;
struct csrow_info *csrow = &mci->csrows[0];
unsigned long address, pfn, offset;
dev_dbg(mci->dev, "ECC UE err on node %d, channel %d, ar = 0x%016llx\n",
priv->node, chan, ar);
/* Address decoding is likely a bit bogus, to dbl check */
address = (ar & 0xffffffffe0000000ul) >> 29;
if (priv->chanmask == 0x3)
address = (address << 1) | chan;
pfn = address >> PAGE_SHIFT;
offset = address & ~PAGE_MASK;
/* TODO: Decoding of the error address */
edac_mc_handle_ue(mci, csrow->first_page + pfn, offset, 0, "");
}
static void cell_edac_check(struct mem_ctl_info *mci)
{
struct cell_edac_priv *priv = mci->pvt_info;
u64 fir, addreg, clear = 0;
fir = in_be64(&priv->regs->mic_fir);
#ifdef DEBUG
if (fir != priv->prev_fir) {
dev_dbg(mci->dev, "fir change : 0x%016lx\n", fir);
priv->prev_fir = fir;
}
#endif
if ((priv->chanmask & 0x1) && (fir & CBE_MIC_FIR_ECC_SINGLE_0_ERR)) {
addreg = in_be64(&priv->regs->mic_df_ecc_address_0);
clear |= CBE_MIC_FIR_ECC_SINGLE_0_RESET;
cell_edac_count_ce(mci, 0, addreg);
}
if ((priv->chanmask & 0x2) && (fir & CBE_MIC_FIR_ECC_SINGLE_1_ERR)) {
addreg = in_be64(&priv->regs->mic_df_ecc_address_1);
clear |= CBE_MIC_FIR_ECC_SINGLE_1_RESET;
cell_edac_count_ce(mci, 1, addreg);
}
if ((priv->chanmask & 0x1) && (fir & CBE_MIC_FIR_ECC_MULTI_0_ERR)) {
addreg = in_be64(&priv->regs->mic_df_ecc_address_0);
clear |= CBE_MIC_FIR_ECC_MULTI_0_RESET;
cell_edac_count_ue(mci, 0, addreg);
}
if ((priv->chanmask & 0x2) && (fir & CBE_MIC_FIR_ECC_MULTI_1_ERR)) {
addreg = in_be64(&priv->regs->mic_df_ecc_address_1);
clear |= CBE_MIC_FIR_ECC_MULTI_1_RESET;
cell_edac_count_ue(mci, 1, addreg);
}
/* The procedure for clearing FIR bits is a bit ... weird */
if (clear) {
fir &= ~(CBE_MIC_FIR_ECC_ERR_MASK | CBE_MIC_FIR_ECC_SET_MASK);
fir |= CBE_MIC_FIR_ECC_RESET_MASK;
fir &= ~clear;
out_be64(&priv->regs->mic_fir, fir);
(void)in_be64(&priv->regs->mic_fir);
mb(); /* sync up */
#ifdef DEBUG
fir = in_be64(&priv->regs->mic_fir);
dev_dbg(mci->dev, "fir clear : 0x%016lx\n", fir);
#endif
}
}
static void __devinit cell_edac_init_csrows(struct mem_ctl_info *mci)
{
struct csrow_info *csrow = &mci->csrows[0];
struct cell_edac_priv *priv = mci->pvt_info;
struct device_node *np;
for (np = NULL;
(np = of_find_node_by_name(np, "memory")) != NULL;) {
struct resource r;
/* We "know" that the Cell firmware only creates one entry
* in the "memory" nodes. If that changes, this code will
* need to be adapted.
*/
if (of_address_to_resource(np, 0, &r))
continue;
if (of_node_to_nid(np) != priv->node)
continue;
csrow->first_page = r.start >> PAGE_SHIFT;
csrow->nr_pages = (r.end - r.start + 1) >> PAGE_SHIFT;
csrow->last_page = csrow->first_page + csrow->nr_pages - 1;
csrow->mtype = MEM_XDR;
csrow->edac_mode = EDAC_SECDED;
dev_dbg(mci->dev,
"Initialized on node %d, chanmask=0x%x,"
" first_page=0x%lx, nr_pages=0x%x\n",
priv->node, priv->chanmask,
csrow->first_page, csrow->nr_pages);
break;
}
}
static int __devinit cell_edac_probe(struct platform_device *pdev)
{
struct cbe_mic_tm_regs __iomem *regs;
struct mem_ctl_info *mci;
struct cell_edac_priv *priv;
u64 reg;
int rc, chanmask;
regs = cbe_get_cpu_mic_tm_regs(cbe_node_to_cpu(pdev->id));
if (regs == NULL)
return -ENODEV;
edac_op_state = EDAC_OPSTATE_POLL;
/* Get channel population */
reg = in_be64(®s->mic_mnt_cfg);
dev_dbg(&pdev->dev, "MIC_MNT_CFG = 0x%016llx\n", reg);
chanmask = 0;
if (reg & CBE_MIC_MNT_CFG_CHAN_0_POP)
chanmask |= 0x1;
if (reg & CBE_MIC_MNT_CFG_CHAN_1_POP)
chanmask |= 0x2;
if (chanmask == 0) {
dev_warn(&pdev->dev,
"Yuck ! No channel populated ? Aborting !\n");
return -ENODEV;
}
dev_dbg(&pdev->dev, "Initial FIR = 0x%016llx\n",
in_be64(®s->mic_fir));
/* Allocate & init EDAC MC data structure */
mci = edac_mc_alloc(sizeof(struct cell_edac_priv), 1,
chanmask == 3 ? 2 : 1, pdev->id);
if (mci == NULL)
return -ENOMEM;
priv = mci->pvt_info;
priv->regs = regs;
priv->node = pdev->id;
priv->chanmask = chanmask;
mci->dev = &pdev->dev;
mci->mtype_cap = MEM_FLAG_XDR;
mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_EC | EDAC_FLAG_SECDED;
mci->edac_cap = EDAC_FLAG_EC | EDAC_FLAG_SECDED;
mci->mod_name = "cell_edac";
mci->ctl_name = "MIC";
mci->dev_name = dev_name(&pdev->dev);
mci->edac_check = cell_edac_check;
cell_edac_init_csrows(mci);
/* Register with EDAC core */
rc = edac_mc_add_mc(mci);
if (rc) {
dev_err(&pdev->dev, "failed to register with EDAC core\n");
edac_mc_free(mci);
return rc;
}
return 0;
}
static int __devexit cell_edac_remove(struct platform_device *pdev)
{
struct mem_ctl_info *mci = edac_mc_del_mc(&pdev->dev);
if (mci)
edac_mc_free(mci);
return 0;
}
static struct platform_driver cell_edac_driver = {
.driver = {
.name = "cbe-mic",
.owner = THIS_MODULE,
},
.probe = cell_edac_probe,
.remove = __devexit_p(cell_edac_remove),
};
static int __init cell_edac_init(void)
{
/* Sanity check registers data structure */
BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs,
mic_df_ecc_address_0) != 0xf8);
BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs,
mic_df_ecc_address_1) != 0x1b8);
BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs,
mic_df_config) != 0x218);
BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs,
mic_fir) != 0x230);
BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs,
mic_mnt_cfg) != 0x210);
BUILD_BUG_ON(offsetof(struct cbe_mic_tm_regs,
mic_exc) != 0x208);
return platform_driver_register(&cell_edac_driver);
}
static void __exit cell_edac_exit(void)
{
platform_driver_unregister(&cell_edac_driver);
}
module_init(cell_edac_init);
module_exit(cell_edac_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Benjamin Herrenschmidt <benh@kernel.crashing.org>");
MODULE_DESCRIPTION("ECC counting for Cell MIC");
| gpl-2.0 |
Kalashnikitty/Aurora_D802 | arch/x86/tools/relocs.c | 2637 | 19228 | #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <elf.h>
#include <byteswap.h>
#define USE_BSD
#include <endian.h>
#include <regex.h>
#include <tools/le_byteshift.h>
static void die(char *fmt, ...);
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
static Elf32_Ehdr ehdr;
static unsigned long reloc_count, reloc_idx;
static unsigned long *relocs;
static unsigned long reloc16_count, reloc16_idx;
static unsigned long *relocs16;
struct section {
Elf32_Shdr shdr;
struct section *link;
Elf32_Sym *symtab;
Elf32_Rel *reltab;
char *strtab;
};
static struct section *secs;
enum symtype {
S_ABS,
S_REL,
S_SEG,
S_LIN,
S_NSYMTYPES
};
static const char * const sym_regex_kernel[S_NSYMTYPES] = {
/*
* Following symbols have been audited. There values are constant and do
* not change if bzImage is loaded at a different physical address than
* the address for which it has been compiled. Don't warn user about
* absolute relocations present w.r.t these symbols.
*/
[S_ABS] =
"^(xen_irq_disable_direct_reloc$|"
"xen_save_fl_direct_reloc$|"
"VDSO|"
"__crc_)",
/*
* These symbols are known to be relative, even if the linker marks them
* as absolute (typically defined outside any section in the linker script.)
*/
[S_REL] =
"^(__init_(begin|end)|"
"__x86_cpu_dev_(start|end)|"
"(__parainstructions|__alt_instructions)(|_end)|"
"(__iommu_table|__apicdrivers|__smp_locks)(|_end)|"
"_end)$"
};
static const char * const sym_regex_realmode[S_NSYMTYPES] = {
/*
* These are 16-bit segment symbols when compiling 16-bit code.
*/
[S_SEG] =
"^real_mode_seg$",
/*
* These are offsets belonging to segments, as opposed to linear addresses,
* when compiling 16-bit code.
*/
[S_LIN] =
"^pa_",
};
static const char * const *sym_regex;
static regex_t sym_regex_c[S_NSYMTYPES];
static int is_reloc(enum symtype type, const char *sym_name)
{
return sym_regex[type] &&
!regexec(&sym_regex_c[type], sym_name, 0, NULL, 0);
}
static void regex_init(int use_real_mode)
{
char errbuf[128];
int err;
int i;
if (use_real_mode)
sym_regex = sym_regex_realmode;
else
sym_regex = sym_regex_kernel;
for (i = 0; i < S_NSYMTYPES; i++) {
if (!sym_regex[i])
continue;
err = regcomp(&sym_regex_c[i], sym_regex[i],
REG_EXTENDED|REG_NOSUB);
if (err) {
regerror(err, &sym_regex_c[i], errbuf, sizeof errbuf);
die("%s", errbuf);
}
}
}
static void die(char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
exit(1);
}
static const char *sym_type(unsigned type)
{
static const char *type_name[] = {
#define SYM_TYPE(X) [X] = #X
SYM_TYPE(STT_NOTYPE),
SYM_TYPE(STT_OBJECT),
SYM_TYPE(STT_FUNC),
SYM_TYPE(STT_SECTION),
SYM_TYPE(STT_FILE),
SYM_TYPE(STT_COMMON),
SYM_TYPE(STT_TLS),
#undef SYM_TYPE
};
const char *name = "unknown sym type name";
if (type < ARRAY_SIZE(type_name)) {
name = type_name[type];
}
return name;
}
static const char *sym_bind(unsigned bind)
{
static const char *bind_name[] = {
#define SYM_BIND(X) [X] = #X
SYM_BIND(STB_LOCAL),
SYM_BIND(STB_GLOBAL),
SYM_BIND(STB_WEAK),
#undef SYM_BIND
};
const char *name = "unknown sym bind name";
if (bind < ARRAY_SIZE(bind_name)) {
name = bind_name[bind];
}
return name;
}
static const char *sym_visibility(unsigned visibility)
{
static const char *visibility_name[] = {
#define SYM_VISIBILITY(X) [X] = #X
SYM_VISIBILITY(STV_DEFAULT),
SYM_VISIBILITY(STV_INTERNAL),
SYM_VISIBILITY(STV_HIDDEN),
SYM_VISIBILITY(STV_PROTECTED),
#undef SYM_VISIBILITY
};
const char *name = "unknown sym visibility name";
if (visibility < ARRAY_SIZE(visibility_name)) {
name = visibility_name[visibility];
}
return name;
}
static const char *rel_type(unsigned type)
{
static const char *type_name[] = {
#define REL_TYPE(X) [X] = #X
REL_TYPE(R_386_NONE),
REL_TYPE(R_386_32),
REL_TYPE(R_386_PC32),
REL_TYPE(R_386_GOT32),
REL_TYPE(R_386_PLT32),
REL_TYPE(R_386_COPY),
REL_TYPE(R_386_GLOB_DAT),
REL_TYPE(R_386_JMP_SLOT),
REL_TYPE(R_386_RELATIVE),
REL_TYPE(R_386_GOTOFF),
REL_TYPE(R_386_GOTPC),
REL_TYPE(R_386_8),
REL_TYPE(R_386_PC8),
REL_TYPE(R_386_16),
REL_TYPE(R_386_PC16),
#undef REL_TYPE
};
const char *name = "unknown type rel type name";
if (type < ARRAY_SIZE(type_name) && type_name[type]) {
name = type_name[type];
}
return name;
}
static const char *sec_name(unsigned shndx)
{
const char *sec_strtab;
const char *name;
sec_strtab = secs[ehdr.e_shstrndx].strtab;
name = "<noname>";
if (shndx < ehdr.e_shnum) {
name = sec_strtab + secs[shndx].shdr.sh_name;
}
else if (shndx == SHN_ABS) {
name = "ABSOLUTE";
}
else if (shndx == SHN_COMMON) {
name = "COMMON";
}
return name;
}
static const char *sym_name(const char *sym_strtab, Elf32_Sym *sym)
{
const char *name;
name = "<noname>";
if (sym->st_name) {
name = sym_strtab + sym->st_name;
}
else {
name = sec_name(sym->st_shndx);
}
return name;
}
#if BYTE_ORDER == LITTLE_ENDIAN
#define le16_to_cpu(val) (val)
#define le32_to_cpu(val) (val)
#endif
#if BYTE_ORDER == BIG_ENDIAN
#define le16_to_cpu(val) bswap_16(val)
#define le32_to_cpu(val) bswap_32(val)
#endif
static uint16_t elf16_to_cpu(uint16_t val)
{
return le16_to_cpu(val);
}
static uint32_t elf32_to_cpu(uint32_t val)
{
return le32_to_cpu(val);
}
static void read_ehdr(FILE *fp)
{
if (fread(&ehdr, sizeof(ehdr), 1, fp) != 1) {
die("Cannot read ELF header: %s\n",
strerror(errno));
}
if (memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0) {
die("No ELF magic\n");
}
if (ehdr.e_ident[EI_CLASS] != ELFCLASS32) {
die("Not a 32 bit executable\n");
}
if (ehdr.e_ident[EI_DATA] != ELFDATA2LSB) {
die("Not a LSB ELF executable\n");
}
if (ehdr.e_ident[EI_VERSION] != EV_CURRENT) {
die("Unknown ELF version\n");
}
/* Convert the fields to native endian */
ehdr.e_type = elf16_to_cpu(ehdr.e_type);
ehdr.e_machine = elf16_to_cpu(ehdr.e_machine);
ehdr.e_version = elf32_to_cpu(ehdr.e_version);
ehdr.e_entry = elf32_to_cpu(ehdr.e_entry);
ehdr.e_phoff = elf32_to_cpu(ehdr.e_phoff);
ehdr.e_shoff = elf32_to_cpu(ehdr.e_shoff);
ehdr.e_flags = elf32_to_cpu(ehdr.e_flags);
ehdr.e_ehsize = elf16_to_cpu(ehdr.e_ehsize);
ehdr.e_phentsize = elf16_to_cpu(ehdr.e_phentsize);
ehdr.e_phnum = elf16_to_cpu(ehdr.e_phnum);
ehdr.e_shentsize = elf16_to_cpu(ehdr.e_shentsize);
ehdr.e_shnum = elf16_to_cpu(ehdr.e_shnum);
ehdr.e_shstrndx = elf16_to_cpu(ehdr.e_shstrndx);
if ((ehdr.e_type != ET_EXEC) && (ehdr.e_type != ET_DYN)) {
die("Unsupported ELF header type\n");
}
if (ehdr.e_machine != EM_386) {
die("Not for x86\n");
}
if (ehdr.e_version != EV_CURRENT) {
die("Unknown ELF version\n");
}
if (ehdr.e_ehsize != sizeof(Elf32_Ehdr)) {
die("Bad Elf header size\n");
}
if (ehdr.e_phentsize != sizeof(Elf32_Phdr)) {
die("Bad program header entry\n");
}
if (ehdr.e_shentsize != sizeof(Elf32_Shdr)) {
die("Bad section header entry\n");
}
if (ehdr.e_shstrndx >= ehdr.e_shnum) {
die("String table index out of bounds\n");
}
}
static void read_shdrs(FILE *fp)
{
int i;
Elf32_Shdr shdr;
secs = calloc(ehdr.e_shnum, sizeof(struct section));
if (!secs) {
die("Unable to allocate %d section headers\n",
ehdr.e_shnum);
}
if (fseek(fp, ehdr.e_shoff, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
ehdr.e_shoff, strerror(errno));
}
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (fread(&shdr, sizeof shdr, 1, fp) != 1)
die("Cannot read ELF section headers %d/%d: %s\n",
i, ehdr.e_shnum, strerror(errno));
sec->shdr.sh_name = elf32_to_cpu(shdr.sh_name);
sec->shdr.sh_type = elf32_to_cpu(shdr.sh_type);
sec->shdr.sh_flags = elf32_to_cpu(shdr.sh_flags);
sec->shdr.sh_addr = elf32_to_cpu(shdr.sh_addr);
sec->shdr.sh_offset = elf32_to_cpu(shdr.sh_offset);
sec->shdr.sh_size = elf32_to_cpu(shdr.sh_size);
sec->shdr.sh_link = elf32_to_cpu(shdr.sh_link);
sec->shdr.sh_info = elf32_to_cpu(shdr.sh_info);
sec->shdr.sh_addralign = elf32_to_cpu(shdr.sh_addralign);
sec->shdr.sh_entsize = elf32_to_cpu(shdr.sh_entsize);
if (sec->shdr.sh_link < ehdr.e_shnum)
sec->link = &secs[sec->shdr.sh_link];
}
}
static void read_strtabs(FILE *fp)
{
int i;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_STRTAB) {
continue;
}
sec->strtab = malloc(sec->shdr.sh_size);
if (!sec->strtab) {
die("malloc of %d bytes for strtab failed\n",
sec->shdr.sh_size);
}
if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
sec->shdr.sh_offset, strerror(errno));
}
if (fread(sec->strtab, 1, sec->shdr.sh_size, fp)
!= sec->shdr.sh_size) {
die("Cannot read symbol table: %s\n",
strerror(errno));
}
}
}
static void read_symtabs(FILE *fp)
{
int i,j;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_SYMTAB) {
continue;
}
sec->symtab = malloc(sec->shdr.sh_size);
if (!sec->symtab) {
die("malloc of %d bytes for symtab failed\n",
sec->shdr.sh_size);
}
if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
sec->shdr.sh_offset, strerror(errno));
}
if (fread(sec->symtab, 1, sec->shdr.sh_size, fp)
!= sec->shdr.sh_size) {
die("Cannot read symbol table: %s\n",
strerror(errno));
}
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Sym); j++) {
Elf32_Sym *sym = &sec->symtab[j];
sym->st_name = elf32_to_cpu(sym->st_name);
sym->st_value = elf32_to_cpu(sym->st_value);
sym->st_size = elf32_to_cpu(sym->st_size);
sym->st_shndx = elf16_to_cpu(sym->st_shndx);
}
}
}
static void read_relocs(FILE *fp)
{
int i,j;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_REL) {
continue;
}
sec->reltab = malloc(sec->shdr.sh_size);
if (!sec->reltab) {
die("malloc of %d bytes for relocs failed\n",
sec->shdr.sh_size);
}
if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
sec->shdr.sh_offset, strerror(errno));
}
if (fread(sec->reltab, 1, sec->shdr.sh_size, fp)
!= sec->shdr.sh_size) {
die("Cannot read symbol table: %s\n",
strerror(errno));
}
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Rel); j++) {
Elf32_Rel *rel = &sec->reltab[j];
rel->r_offset = elf32_to_cpu(rel->r_offset);
rel->r_info = elf32_to_cpu(rel->r_info);
}
}
}
static void print_absolute_symbols(void)
{
int i;
printf("Absolute symbols\n");
printf(" Num: Value Size Type Bind Visibility Name\n");
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
char *sym_strtab;
int j;
if (sec->shdr.sh_type != SHT_SYMTAB) {
continue;
}
sym_strtab = sec->link->strtab;
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Sym); j++) {
Elf32_Sym *sym;
const char *name;
sym = &sec->symtab[j];
name = sym_name(sym_strtab, sym);
if (sym->st_shndx != SHN_ABS) {
continue;
}
printf("%5d %08x %5d %10s %10s %12s %s\n",
j, sym->st_value, sym->st_size,
sym_type(ELF32_ST_TYPE(sym->st_info)),
sym_bind(ELF32_ST_BIND(sym->st_info)),
sym_visibility(ELF32_ST_VISIBILITY(sym->st_other)),
name);
}
}
printf("\n");
}
static void print_absolute_relocs(void)
{
int i, printed = 0;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
struct section *sec_applies, *sec_symtab;
char *sym_strtab;
Elf32_Sym *sh_symtab;
int j;
if (sec->shdr.sh_type != SHT_REL) {
continue;
}
sec_symtab = sec->link;
sec_applies = &secs[sec->shdr.sh_info];
if (!(sec_applies->shdr.sh_flags & SHF_ALLOC)) {
continue;
}
sh_symtab = sec_symtab->symtab;
sym_strtab = sec_symtab->link->strtab;
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Rel); j++) {
Elf32_Rel *rel;
Elf32_Sym *sym;
const char *name;
rel = &sec->reltab[j];
sym = &sh_symtab[ELF32_R_SYM(rel->r_info)];
name = sym_name(sym_strtab, sym);
if (sym->st_shndx != SHN_ABS) {
continue;
}
/* Absolute symbols are not relocated if bzImage is
* loaded at a non-compiled address. Display a warning
* to user at compile time about the absolute
* relocations present.
*
* User need to audit the code to make sure
* some symbols which should have been section
* relative have not become absolute because of some
* linker optimization or wrong programming usage.
*
* Before warning check if this absolute symbol
* relocation is harmless.
*/
if (is_reloc(S_ABS, name) || is_reloc(S_REL, name))
continue;
if (!printed) {
printf("WARNING: Absolute relocations"
" present\n");
printf("Offset Info Type Sym.Value "
"Sym.Name\n");
printed = 1;
}
printf("%08x %08x %10s %08x %s\n",
rel->r_offset,
rel->r_info,
rel_type(ELF32_R_TYPE(rel->r_info)),
sym->st_value,
name);
}
}
if (printed)
printf("\n");
}
static void walk_relocs(void (*visit)(Elf32_Rel *rel, Elf32_Sym *sym),
int use_real_mode)
{
int i;
/* Walk through the relocations */
for (i = 0; i < ehdr.e_shnum; i++) {
char *sym_strtab;
Elf32_Sym *sh_symtab;
struct section *sec_applies, *sec_symtab;
int j;
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_REL) {
continue;
}
sec_symtab = sec->link;
sec_applies = &secs[sec->shdr.sh_info];
if (!(sec_applies->shdr.sh_flags & SHF_ALLOC)) {
continue;
}
sh_symtab = sec_symtab->symtab;
sym_strtab = sec_symtab->link->strtab;
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Rel); j++) {
Elf32_Rel *rel;
Elf32_Sym *sym;
unsigned r_type;
const char *symname;
int shn_abs;
rel = &sec->reltab[j];
sym = &sh_symtab[ELF32_R_SYM(rel->r_info)];
r_type = ELF32_R_TYPE(rel->r_info);
shn_abs = sym->st_shndx == SHN_ABS;
switch (r_type) {
case R_386_NONE:
case R_386_PC32:
case R_386_PC16:
case R_386_PC8:
/*
* NONE can be ignored and and PC relative
* relocations don't need to be adjusted.
*/
break;
case R_386_16:
symname = sym_name(sym_strtab, sym);
if (!use_real_mode)
goto bad;
if (shn_abs) {
if (is_reloc(S_ABS, symname))
break;
else if (!is_reloc(S_SEG, symname))
goto bad;
} else {
if (is_reloc(S_LIN, symname))
goto bad;
else
break;
}
visit(rel, sym);
break;
case R_386_32:
symname = sym_name(sym_strtab, sym);
if (shn_abs) {
if (is_reloc(S_ABS, symname))
break;
else if (!is_reloc(S_REL, symname))
goto bad;
} else {
if (use_real_mode &&
!is_reloc(S_LIN, symname))
break;
}
visit(rel, sym);
break;
default:
die("Unsupported relocation type: %s (%d)\n",
rel_type(r_type), r_type);
break;
bad:
symname = sym_name(sym_strtab, sym);
die("Invalid %s %s relocation: %s\n",
shn_abs ? "absolute" : "relative",
rel_type(r_type), symname);
}
}
}
}
static void count_reloc(Elf32_Rel *rel, Elf32_Sym *sym)
{
if (ELF32_R_TYPE(rel->r_info) == R_386_16)
reloc16_count++;
else
reloc_count++;
}
static void collect_reloc(Elf32_Rel *rel, Elf32_Sym *sym)
{
/* Remember the address that needs to be adjusted. */
if (ELF32_R_TYPE(rel->r_info) == R_386_16)
relocs16[reloc16_idx++] = rel->r_offset;
else
relocs[reloc_idx++] = rel->r_offset;
}
static int cmp_relocs(const void *va, const void *vb)
{
const unsigned long *a, *b;
a = va; b = vb;
return (*a == *b)? 0 : (*a > *b)? 1 : -1;
}
static int write32(unsigned int v, FILE *f)
{
unsigned char buf[4];
put_unaligned_le32(v, buf);
return fwrite(buf, 1, 4, f) == 4 ? 0 : -1;
}
static void emit_relocs(int as_text, int use_real_mode)
{
int i;
/* Count how many relocations I have and allocate space for them. */
reloc_count = 0;
walk_relocs(count_reloc, use_real_mode);
relocs = malloc(reloc_count * sizeof(relocs[0]));
if (!relocs) {
die("malloc of %d entries for relocs failed\n",
reloc_count);
}
relocs16 = malloc(reloc16_count * sizeof(relocs[0]));
if (!relocs16) {
die("malloc of %d entries for relocs16 failed\n",
reloc16_count);
}
/* Collect up the relocations */
reloc_idx = 0;
walk_relocs(collect_reloc, use_real_mode);
if (reloc16_count && !use_real_mode)
die("Segment relocations found but --realmode not specified\n");
/* Order the relocations for more efficient processing */
qsort(relocs, reloc_count, sizeof(relocs[0]), cmp_relocs);
qsort(relocs16, reloc16_count, sizeof(relocs16[0]), cmp_relocs);
/* Print the relocations */
if (as_text) {
/* Print the relocations in a form suitable that
* gas will like.
*/
printf(".section \".data.reloc\",\"a\"\n");
printf(".balign 4\n");
if (use_real_mode) {
printf("\t.long %lu\n", reloc16_count);
for (i = 0; i < reloc16_count; i++)
printf("\t.long 0x%08lx\n", relocs16[i]);
printf("\t.long %lu\n", reloc_count);
for (i = 0; i < reloc_count; i++) {
printf("\t.long 0x%08lx\n", relocs[i]);
}
} else {
/* Print a stop */
printf("\t.long 0x%08lx\n", (unsigned long)0);
for (i = 0; i < reloc_count; i++) {
printf("\t.long 0x%08lx\n", relocs[i]);
}
}
printf("\n");
}
else {
if (use_real_mode) {
write32(reloc16_count, stdout);
for (i = 0; i < reloc16_count; i++)
write32(relocs16[i], stdout);
write32(reloc_count, stdout);
/* Now print each relocation */
for (i = 0; i < reloc_count; i++)
write32(relocs[i], stdout);
} else {
/* Print a stop */
write32(0, stdout);
/* Now print each relocation */
for (i = 0; i < reloc_count; i++) {
write32(relocs[i], stdout);
}
}
}
}
static void usage(void)
{
die("relocs [--abs-syms|--abs-relocs|--text|--realmode] vmlinux\n");
}
int main(int argc, char **argv)
{
int show_absolute_syms, show_absolute_relocs;
int as_text, use_real_mode;
const char *fname;
FILE *fp;
int i;
show_absolute_syms = 0;
show_absolute_relocs = 0;
as_text = 0;
use_real_mode = 0;
fname = NULL;
for (i = 1; i < argc; i++) {
char *arg = argv[i];
if (*arg == '-') {
if (strcmp(arg, "--abs-syms") == 0) {
show_absolute_syms = 1;
continue;
}
if (strcmp(arg, "--abs-relocs") == 0) {
show_absolute_relocs = 1;
continue;
}
if (strcmp(arg, "--text") == 0) {
as_text = 1;
continue;
}
if (strcmp(arg, "--realmode") == 0) {
use_real_mode = 1;
continue;
}
}
else if (!fname) {
fname = arg;
continue;
}
usage();
}
if (!fname) {
usage();
}
regex_init(use_real_mode);
fp = fopen(fname, "r");
if (!fp) {
die("Cannot open %s: %s\n",
fname, strerror(errno));
}
read_ehdr(fp);
read_shdrs(fp);
read_strtabs(fp);
read_symtabs(fp);
read_relocs(fp);
if (show_absolute_syms) {
print_absolute_symbols();
return 0;
}
if (show_absolute_relocs) {
print_absolute_relocs();
return 0;
}
emit_relocs(as_text, use_real_mode);
return 0;
}
| gpl-2.0 |
sub77/test_kernel_samsung_matissewifi | arch/x86/tools/relocs.c | 2637 | 19228 | #include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <elf.h>
#include <byteswap.h>
#define USE_BSD
#include <endian.h>
#include <regex.h>
#include <tools/le_byteshift.h>
static void die(char *fmt, ...);
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
static Elf32_Ehdr ehdr;
static unsigned long reloc_count, reloc_idx;
static unsigned long *relocs;
static unsigned long reloc16_count, reloc16_idx;
static unsigned long *relocs16;
struct section {
Elf32_Shdr shdr;
struct section *link;
Elf32_Sym *symtab;
Elf32_Rel *reltab;
char *strtab;
};
static struct section *secs;
enum symtype {
S_ABS,
S_REL,
S_SEG,
S_LIN,
S_NSYMTYPES
};
static const char * const sym_regex_kernel[S_NSYMTYPES] = {
/*
* Following symbols have been audited. There values are constant and do
* not change if bzImage is loaded at a different physical address than
* the address for which it has been compiled. Don't warn user about
* absolute relocations present w.r.t these symbols.
*/
[S_ABS] =
"^(xen_irq_disable_direct_reloc$|"
"xen_save_fl_direct_reloc$|"
"VDSO|"
"__crc_)",
/*
* These symbols are known to be relative, even if the linker marks them
* as absolute (typically defined outside any section in the linker script.)
*/
[S_REL] =
"^(__init_(begin|end)|"
"__x86_cpu_dev_(start|end)|"
"(__parainstructions|__alt_instructions)(|_end)|"
"(__iommu_table|__apicdrivers|__smp_locks)(|_end)|"
"_end)$"
};
static const char * const sym_regex_realmode[S_NSYMTYPES] = {
/*
* These are 16-bit segment symbols when compiling 16-bit code.
*/
[S_SEG] =
"^real_mode_seg$",
/*
* These are offsets belonging to segments, as opposed to linear addresses,
* when compiling 16-bit code.
*/
[S_LIN] =
"^pa_",
};
static const char * const *sym_regex;
static regex_t sym_regex_c[S_NSYMTYPES];
static int is_reloc(enum symtype type, const char *sym_name)
{
return sym_regex[type] &&
!regexec(&sym_regex_c[type], sym_name, 0, NULL, 0);
}
static void regex_init(int use_real_mode)
{
char errbuf[128];
int err;
int i;
if (use_real_mode)
sym_regex = sym_regex_realmode;
else
sym_regex = sym_regex_kernel;
for (i = 0; i < S_NSYMTYPES; i++) {
if (!sym_regex[i])
continue;
err = regcomp(&sym_regex_c[i], sym_regex[i],
REG_EXTENDED|REG_NOSUB);
if (err) {
regerror(err, &sym_regex_c[i], errbuf, sizeof errbuf);
die("%s", errbuf);
}
}
}
static void die(char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
exit(1);
}
static const char *sym_type(unsigned type)
{
static const char *type_name[] = {
#define SYM_TYPE(X) [X] = #X
SYM_TYPE(STT_NOTYPE),
SYM_TYPE(STT_OBJECT),
SYM_TYPE(STT_FUNC),
SYM_TYPE(STT_SECTION),
SYM_TYPE(STT_FILE),
SYM_TYPE(STT_COMMON),
SYM_TYPE(STT_TLS),
#undef SYM_TYPE
};
const char *name = "unknown sym type name";
if (type < ARRAY_SIZE(type_name)) {
name = type_name[type];
}
return name;
}
static const char *sym_bind(unsigned bind)
{
static const char *bind_name[] = {
#define SYM_BIND(X) [X] = #X
SYM_BIND(STB_LOCAL),
SYM_BIND(STB_GLOBAL),
SYM_BIND(STB_WEAK),
#undef SYM_BIND
};
const char *name = "unknown sym bind name";
if (bind < ARRAY_SIZE(bind_name)) {
name = bind_name[bind];
}
return name;
}
static const char *sym_visibility(unsigned visibility)
{
static const char *visibility_name[] = {
#define SYM_VISIBILITY(X) [X] = #X
SYM_VISIBILITY(STV_DEFAULT),
SYM_VISIBILITY(STV_INTERNAL),
SYM_VISIBILITY(STV_HIDDEN),
SYM_VISIBILITY(STV_PROTECTED),
#undef SYM_VISIBILITY
};
const char *name = "unknown sym visibility name";
if (visibility < ARRAY_SIZE(visibility_name)) {
name = visibility_name[visibility];
}
return name;
}
static const char *rel_type(unsigned type)
{
static const char *type_name[] = {
#define REL_TYPE(X) [X] = #X
REL_TYPE(R_386_NONE),
REL_TYPE(R_386_32),
REL_TYPE(R_386_PC32),
REL_TYPE(R_386_GOT32),
REL_TYPE(R_386_PLT32),
REL_TYPE(R_386_COPY),
REL_TYPE(R_386_GLOB_DAT),
REL_TYPE(R_386_JMP_SLOT),
REL_TYPE(R_386_RELATIVE),
REL_TYPE(R_386_GOTOFF),
REL_TYPE(R_386_GOTPC),
REL_TYPE(R_386_8),
REL_TYPE(R_386_PC8),
REL_TYPE(R_386_16),
REL_TYPE(R_386_PC16),
#undef REL_TYPE
};
const char *name = "unknown type rel type name";
if (type < ARRAY_SIZE(type_name) && type_name[type]) {
name = type_name[type];
}
return name;
}
static const char *sec_name(unsigned shndx)
{
const char *sec_strtab;
const char *name;
sec_strtab = secs[ehdr.e_shstrndx].strtab;
name = "<noname>";
if (shndx < ehdr.e_shnum) {
name = sec_strtab + secs[shndx].shdr.sh_name;
}
else if (shndx == SHN_ABS) {
name = "ABSOLUTE";
}
else if (shndx == SHN_COMMON) {
name = "COMMON";
}
return name;
}
static const char *sym_name(const char *sym_strtab, Elf32_Sym *sym)
{
const char *name;
name = "<noname>";
if (sym->st_name) {
name = sym_strtab + sym->st_name;
}
else {
name = sec_name(sym->st_shndx);
}
return name;
}
#if BYTE_ORDER == LITTLE_ENDIAN
#define le16_to_cpu(val) (val)
#define le32_to_cpu(val) (val)
#endif
#if BYTE_ORDER == BIG_ENDIAN
#define le16_to_cpu(val) bswap_16(val)
#define le32_to_cpu(val) bswap_32(val)
#endif
static uint16_t elf16_to_cpu(uint16_t val)
{
return le16_to_cpu(val);
}
static uint32_t elf32_to_cpu(uint32_t val)
{
return le32_to_cpu(val);
}
static void read_ehdr(FILE *fp)
{
if (fread(&ehdr, sizeof(ehdr), 1, fp) != 1) {
die("Cannot read ELF header: %s\n",
strerror(errno));
}
if (memcmp(ehdr.e_ident, ELFMAG, SELFMAG) != 0) {
die("No ELF magic\n");
}
if (ehdr.e_ident[EI_CLASS] != ELFCLASS32) {
die("Not a 32 bit executable\n");
}
if (ehdr.e_ident[EI_DATA] != ELFDATA2LSB) {
die("Not a LSB ELF executable\n");
}
if (ehdr.e_ident[EI_VERSION] != EV_CURRENT) {
die("Unknown ELF version\n");
}
/* Convert the fields to native endian */
ehdr.e_type = elf16_to_cpu(ehdr.e_type);
ehdr.e_machine = elf16_to_cpu(ehdr.e_machine);
ehdr.e_version = elf32_to_cpu(ehdr.e_version);
ehdr.e_entry = elf32_to_cpu(ehdr.e_entry);
ehdr.e_phoff = elf32_to_cpu(ehdr.e_phoff);
ehdr.e_shoff = elf32_to_cpu(ehdr.e_shoff);
ehdr.e_flags = elf32_to_cpu(ehdr.e_flags);
ehdr.e_ehsize = elf16_to_cpu(ehdr.e_ehsize);
ehdr.e_phentsize = elf16_to_cpu(ehdr.e_phentsize);
ehdr.e_phnum = elf16_to_cpu(ehdr.e_phnum);
ehdr.e_shentsize = elf16_to_cpu(ehdr.e_shentsize);
ehdr.e_shnum = elf16_to_cpu(ehdr.e_shnum);
ehdr.e_shstrndx = elf16_to_cpu(ehdr.e_shstrndx);
if ((ehdr.e_type != ET_EXEC) && (ehdr.e_type != ET_DYN)) {
die("Unsupported ELF header type\n");
}
if (ehdr.e_machine != EM_386) {
die("Not for x86\n");
}
if (ehdr.e_version != EV_CURRENT) {
die("Unknown ELF version\n");
}
if (ehdr.e_ehsize != sizeof(Elf32_Ehdr)) {
die("Bad Elf header size\n");
}
if (ehdr.e_phentsize != sizeof(Elf32_Phdr)) {
die("Bad program header entry\n");
}
if (ehdr.e_shentsize != sizeof(Elf32_Shdr)) {
die("Bad section header entry\n");
}
if (ehdr.e_shstrndx >= ehdr.e_shnum) {
die("String table index out of bounds\n");
}
}
static void read_shdrs(FILE *fp)
{
int i;
Elf32_Shdr shdr;
secs = calloc(ehdr.e_shnum, sizeof(struct section));
if (!secs) {
die("Unable to allocate %d section headers\n",
ehdr.e_shnum);
}
if (fseek(fp, ehdr.e_shoff, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
ehdr.e_shoff, strerror(errno));
}
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (fread(&shdr, sizeof shdr, 1, fp) != 1)
die("Cannot read ELF section headers %d/%d: %s\n",
i, ehdr.e_shnum, strerror(errno));
sec->shdr.sh_name = elf32_to_cpu(shdr.sh_name);
sec->shdr.sh_type = elf32_to_cpu(shdr.sh_type);
sec->shdr.sh_flags = elf32_to_cpu(shdr.sh_flags);
sec->shdr.sh_addr = elf32_to_cpu(shdr.sh_addr);
sec->shdr.sh_offset = elf32_to_cpu(shdr.sh_offset);
sec->shdr.sh_size = elf32_to_cpu(shdr.sh_size);
sec->shdr.sh_link = elf32_to_cpu(shdr.sh_link);
sec->shdr.sh_info = elf32_to_cpu(shdr.sh_info);
sec->shdr.sh_addralign = elf32_to_cpu(shdr.sh_addralign);
sec->shdr.sh_entsize = elf32_to_cpu(shdr.sh_entsize);
if (sec->shdr.sh_link < ehdr.e_shnum)
sec->link = &secs[sec->shdr.sh_link];
}
}
static void read_strtabs(FILE *fp)
{
int i;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_STRTAB) {
continue;
}
sec->strtab = malloc(sec->shdr.sh_size);
if (!sec->strtab) {
die("malloc of %d bytes for strtab failed\n",
sec->shdr.sh_size);
}
if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
sec->shdr.sh_offset, strerror(errno));
}
if (fread(sec->strtab, 1, sec->shdr.sh_size, fp)
!= sec->shdr.sh_size) {
die("Cannot read symbol table: %s\n",
strerror(errno));
}
}
}
static void read_symtabs(FILE *fp)
{
int i,j;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_SYMTAB) {
continue;
}
sec->symtab = malloc(sec->shdr.sh_size);
if (!sec->symtab) {
die("malloc of %d bytes for symtab failed\n",
sec->shdr.sh_size);
}
if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
sec->shdr.sh_offset, strerror(errno));
}
if (fread(sec->symtab, 1, sec->shdr.sh_size, fp)
!= sec->shdr.sh_size) {
die("Cannot read symbol table: %s\n",
strerror(errno));
}
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Sym); j++) {
Elf32_Sym *sym = &sec->symtab[j];
sym->st_name = elf32_to_cpu(sym->st_name);
sym->st_value = elf32_to_cpu(sym->st_value);
sym->st_size = elf32_to_cpu(sym->st_size);
sym->st_shndx = elf16_to_cpu(sym->st_shndx);
}
}
}
static void read_relocs(FILE *fp)
{
int i,j;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_REL) {
continue;
}
sec->reltab = malloc(sec->shdr.sh_size);
if (!sec->reltab) {
die("malloc of %d bytes for relocs failed\n",
sec->shdr.sh_size);
}
if (fseek(fp, sec->shdr.sh_offset, SEEK_SET) < 0) {
die("Seek to %d failed: %s\n",
sec->shdr.sh_offset, strerror(errno));
}
if (fread(sec->reltab, 1, sec->shdr.sh_size, fp)
!= sec->shdr.sh_size) {
die("Cannot read symbol table: %s\n",
strerror(errno));
}
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Rel); j++) {
Elf32_Rel *rel = &sec->reltab[j];
rel->r_offset = elf32_to_cpu(rel->r_offset);
rel->r_info = elf32_to_cpu(rel->r_info);
}
}
}
static void print_absolute_symbols(void)
{
int i;
printf("Absolute symbols\n");
printf(" Num: Value Size Type Bind Visibility Name\n");
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
char *sym_strtab;
int j;
if (sec->shdr.sh_type != SHT_SYMTAB) {
continue;
}
sym_strtab = sec->link->strtab;
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Sym); j++) {
Elf32_Sym *sym;
const char *name;
sym = &sec->symtab[j];
name = sym_name(sym_strtab, sym);
if (sym->st_shndx != SHN_ABS) {
continue;
}
printf("%5d %08x %5d %10s %10s %12s %s\n",
j, sym->st_value, sym->st_size,
sym_type(ELF32_ST_TYPE(sym->st_info)),
sym_bind(ELF32_ST_BIND(sym->st_info)),
sym_visibility(ELF32_ST_VISIBILITY(sym->st_other)),
name);
}
}
printf("\n");
}
static void print_absolute_relocs(void)
{
int i, printed = 0;
for (i = 0; i < ehdr.e_shnum; i++) {
struct section *sec = &secs[i];
struct section *sec_applies, *sec_symtab;
char *sym_strtab;
Elf32_Sym *sh_symtab;
int j;
if (sec->shdr.sh_type != SHT_REL) {
continue;
}
sec_symtab = sec->link;
sec_applies = &secs[sec->shdr.sh_info];
if (!(sec_applies->shdr.sh_flags & SHF_ALLOC)) {
continue;
}
sh_symtab = sec_symtab->symtab;
sym_strtab = sec_symtab->link->strtab;
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Rel); j++) {
Elf32_Rel *rel;
Elf32_Sym *sym;
const char *name;
rel = &sec->reltab[j];
sym = &sh_symtab[ELF32_R_SYM(rel->r_info)];
name = sym_name(sym_strtab, sym);
if (sym->st_shndx != SHN_ABS) {
continue;
}
/* Absolute symbols are not relocated if bzImage is
* loaded at a non-compiled address. Display a warning
* to user at compile time about the absolute
* relocations present.
*
* User need to audit the code to make sure
* some symbols which should have been section
* relative have not become absolute because of some
* linker optimization or wrong programming usage.
*
* Before warning check if this absolute symbol
* relocation is harmless.
*/
if (is_reloc(S_ABS, name) || is_reloc(S_REL, name))
continue;
if (!printed) {
printf("WARNING: Absolute relocations"
" present\n");
printf("Offset Info Type Sym.Value "
"Sym.Name\n");
printed = 1;
}
printf("%08x %08x %10s %08x %s\n",
rel->r_offset,
rel->r_info,
rel_type(ELF32_R_TYPE(rel->r_info)),
sym->st_value,
name);
}
}
if (printed)
printf("\n");
}
static void walk_relocs(void (*visit)(Elf32_Rel *rel, Elf32_Sym *sym),
int use_real_mode)
{
int i;
/* Walk through the relocations */
for (i = 0; i < ehdr.e_shnum; i++) {
char *sym_strtab;
Elf32_Sym *sh_symtab;
struct section *sec_applies, *sec_symtab;
int j;
struct section *sec = &secs[i];
if (sec->shdr.sh_type != SHT_REL) {
continue;
}
sec_symtab = sec->link;
sec_applies = &secs[sec->shdr.sh_info];
if (!(sec_applies->shdr.sh_flags & SHF_ALLOC)) {
continue;
}
sh_symtab = sec_symtab->symtab;
sym_strtab = sec_symtab->link->strtab;
for (j = 0; j < sec->shdr.sh_size/sizeof(Elf32_Rel); j++) {
Elf32_Rel *rel;
Elf32_Sym *sym;
unsigned r_type;
const char *symname;
int shn_abs;
rel = &sec->reltab[j];
sym = &sh_symtab[ELF32_R_SYM(rel->r_info)];
r_type = ELF32_R_TYPE(rel->r_info);
shn_abs = sym->st_shndx == SHN_ABS;
switch (r_type) {
case R_386_NONE:
case R_386_PC32:
case R_386_PC16:
case R_386_PC8:
/*
* NONE can be ignored and and PC relative
* relocations don't need to be adjusted.
*/
break;
case R_386_16:
symname = sym_name(sym_strtab, sym);
if (!use_real_mode)
goto bad;
if (shn_abs) {
if (is_reloc(S_ABS, symname))
break;
else if (!is_reloc(S_SEG, symname))
goto bad;
} else {
if (is_reloc(S_LIN, symname))
goto bad;
else
break;
}
visit(rel, sym);
break;
case R_386_32:
symname = sym_name(sym_strtab, sym);
if (shn_abs) {
if (is_reloc(S_ABS, symname))
break;
else if (!is_reloc(S_REL, symname))
goto bad;
} else {
if (use_real_mode &&
!is_reloc(S_LIN, symname))
break;
}
visit(rel, sym);
break;
default:
die("Unsupported relocation type: %s (%d)\n",
rel_type(r_type), r_type);
break;
bad:
symname = sym_name(sym_strtab, sym);
die("Invalid %s %s relocation: %s\n",
shn_abs ? "absolute" : "relative",
rel_type(r_type), symname);
}
}
}
}
static void count_reloc(Elf32_Rel *rel, Elf32_Sym *sym)
{
if (ELF32_R_TYPE(rel->r_info) == R_386_16)
reloc16_count++;
else
reloc_count++;
}
static void collect_reloc(Elf32_Rel *rel, Elf32_Sym *sym)
{
/* Remember the address that needs to be adjusted. */
if (ELF32_R_TYPE(rel->r_info) == R_386_16)
relocs16[reloc16_idx++] = rel->r_offset;
else
relocs[reloc_idx++] = rel->r_offset;
}
static int cmp_relocs(const void *va, const void *vb)
{
const unsigned long *a, *b;
a = va; b = vb;
return (*a == *b)? 0 : (*a > *b)? 1 : -1;
}
static int write32(unsigned int v, FILE *f)
{
unsigned char buf[4];
put_unaligned_le32(v, buf);
return fwrite(buf, 1, 4, f) == 4 ? 0 : -1;
}
static void emit_relocs(int as_text, int use_real_mode)
{
int i;
/* Count how many relocations I have and allocate space for them. */
reloc_count = 0;
walk_relocs(count_reloc, use_real_mode);
relocs = malloc(reloc_count * sizeof(relocs[0]));
if (!relocs) {
die("malloc of %d entries for relocs failed\n",
reloc_count);
}
relocs16 = malloc(reloc16_count * sizeof(relocs[0]));
if (!relocs16) {
die("malloc of %d entries for relocs16 failed\n",
reloc16_count);
}
/* Collect up the relocations */
reloc_idx = 0;
walk_relocs(collect_reloc, use_real_mode);
if (reloc16_count && !use_real_mode)
die("Segment relocations found but --realmode not specified\n");
/* Order the relocations for more efficient processing */
qsort(relocs, reloc_count, sizeof(relocs[0]), cmp_relocs);
qsort(relocs16, reloc16_count, sizeof(relocs16[0]), cmp_relocs);
/* Print the relocations */
if (as_text) {
/* Print the relocations in a form suitable that
* gas will like.
*/
printf(".section \".data.reloc\",\"a\"\n");
printf(".balign 4\n");
if (use_real_mode) {
printf("\t.long %lu\n", reloc16_count);
for (i = 0; i < reloc16_count; i++)
printf("\t.long 0x%08lx\n", relocs16[i]);
printf("\t.long %lu\n", reloc_count);
for (i = 0; i < reloc_count; i++) {
printf("\t.long 0x%08lx\n", relocs[i]);
}
} else {
/* Print a stop */
printf("\t.long 0x%08lx\n", (unsigned long)0);
for (i = 0; i < reloc_count; i++) {
printf("\t.long 0x%08lx\n", relocs[i]);
}
}
printf("\n");
}
else {
if (use_real_mode) {
write32(reloc16_count, stdout);
for (i = 0; i < reloc16_count; i++)
write32(relocs16[i], stdout);
write32(reloc_count, stdout);
/* Now print each relocation */
for (i = 0; i < reloc_count; i++)
write32(relocs[i], stdout);
} else {
/* Print a stop */
write32(0, stdout);
/* Now print each relocation */
for (i = 0; i < reloc_count; i++) {
write32(relocs[i], stdout);
}
}
}
}
static void usage(void)
{
die("relocs [--abs-syms|--abs-relocs|--text|--realmode] vmlinux\n");
}
int main(int argc, char **argv)
{
int show_absolute_syms, show_absolute_relocs;
int as_text, use_real_mode;
const char *fname;
FILE *fp;
int i;
show_absolute_syms = 0;
show_absolute_relocs = 0;
as_text = 0;
use_real_mode = 0;
fname = NULL;
for (i = 1; i < argc; i++) {
char *arg = argv[i];
if (*arg == '-') {
if (strcmp(arg, "--abs-syms") == 0) {
show_absolute_syms = 1;
continue;
}
if (strcmp(arg, "--abs-relocs") == 0) {
show_absolute_relocs = 1;
continue;
}
if (strcmp(arg, "--text") == 0) {
as_text = 1;
continue;
}
if (strcmp(arg, "--realmode") == 0) {
use_real_mode = 1;
continue;
}
}
else if (!fname) {
fname = arg;
continue;
}
usage();
}
if (!fname) {
usage();
}
regex_init(use_real_mode);
fp = fopen(fname, "r");
if (!fp) {
die("Cannot open %s: %s\n",
fname, strerror(errno));
}
read_ehdr(fp);
read_shdrs(fp);
read_strtabs(fp);
read_symtabs(fp);
read_relocs(fp);
if (show_absolute_syms) {
print_absolute_symbols();
return 0;
}
if (show_absolute_relocs) {
print_absolute_relocs();
return 0;
}
emit_relocs(as_text, use_real_mode);
return 0;
}
| gpl-2.0 |
avisconti/prova | arch/arm/mm/highmem.c | 2893 | 4372 | /*
* arch/arm/mm/highmem.c -- ARM highmem support
*
* Author: Nicolas Pitre
* Created: september 8, 2008
* Copyright: Marvell Semiconductors 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.
*/
#include <linux/cpu.h>
#include <linux/module.h>
#include <linux/highmem.h>
#include <linux/interrupt.h>
#include <asm/fixmap.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include "mm.h"
void *kmap(struct page *page)
{
might_sleep();
if (!PageHighMem(page))
return page_address(page);
return kmap_high(page);
}
EXPORT_SYMBOL(kmap);
void kunmap(struct page *page)
{
BUG_ON(in_interrupt());
if (!PageHighMem(page))
return;
kunmap_high(page);
}
EXPORT_SYMBOL(kunmap);
void *kmap_atomic(struct page *page)
{
unsigned int idx;
unsigned long vaddr;
void *kmap;
int type;
pagefault_disable();
if (!PageHighMem(page))
return page_address(page);
#ifdef CONFIG_DEBUG_HIGHMEM
/*
* There is no cache coherency issue when non VIVT, so force the
* dedicated kmap usage for better debugging purposes in that case.
*/
if (!cache_is_vivt())
kmap = NULL;
else
#endif
kmap = kmap_high_get(page);
if (kmap)
return kmap;
type = kmap_atomic_idx_push();
idx = type + KM_TYPE_NR * smp_processor_id();
vaddr = __fix_to_virt(FIX_KMAP_BEGIN + idx);
#ifdef CONFIG_DEBUG_HIGHMEM
/*
* With debugging enabled, kunmap_atomic forces that entry to 0.
* Make sure it was indeed properly unmapped.
*/
BUG_ON(!pte_none(get_top_pte(vaddr)));
#endif
/*
* When debugging is off, kunmap_atomic leaves the previous mapping
* in place, so the contained TLB flush ensures the TLB is updated
* with the new mapping.
*/
set_top_pte(vaddr, mk_pte(page, kmap_prot));
return (void *)vaddr;
}
EXPORT_SYMBOL(kmap_atomic);
void __kunmap_atomic(void *kvaddr)
{
unsigned long vaddr = (unsigned long) kvaddr & PAGE_MASK;
int idx, type;
if (kvaddr >= (void *)FIXADDR_START) {
type = kmap_atomic_idx();
idx = type + KM_TYPE_NR * smp_processor_id();
if (cache_is_vivt())
__cpuc_flush_dcache_area((void *)vaddr, PAGE_SIZE);
#ifdef CONFIG_DEBUG_HIGHMEM
BUG_ON(vaddr != __fix_to_virt(FIX_KMAP_BEGIN + idx));
set_top_pte(vaddr, __pte(0));
#else
(void) idx; /* to kill a warning */
#endif
kmap_atomic_idx_pop();
} else if (vaddr >= PKMAP_ADDR(0) && vaddr < PKMAP_ADDR(LAST_PKMAP)) {
/* this address was obtained through kmap_high_get() */
kunmap_high(pte_page(pkmap_page_table[PKMAP_NR(vaddr)]));
}
pagefault_enable();
}
EXPORT_SYMBOL(__kunmap_atomic);
void *kmap_atomic_pfn(unsigned long pfn)
{
unsigned long vaddr;
int idx, type;
pagefault_disable();
type = kmap_atomic_idx_push();
idx = type + KM_TYPE_NR * smp_processor_id();
vaddr = __fix_to_virt(FIX_KMAP_BEGIN + idx);
#ifdef CONFIG_DEBUG_HIGHMEM
BUG_ON(!pte_none(get_top_pte(vaddr)));
#endif
set_top_pte(vaddr, pfn_pte(pfn, kmap_prot));
return (void *)vaddr;
}
struct page *kmap_atomic_to_page(const void *ptr)
{
unsigned long vaddr = (unsigned long)ptr;
if (vaddr < FIXADDR_START)
return virt_to_page(ptr);
return pte_page(get_top_pte(vaddr));
}
#ifdef CONFIG_ARCH_WANT_KMAP_ATOMIC_FLUSH
static void kmap_remove_unused_cpu(int cpu)
{
int start_idx, idx, type;
pagefault_disable();
type = kmap_atomic_idx();
start_idx = type + 1 + KM_TYPE_NR * cpu;
for (idx = start_idx; idx < KM_TYPE_NR + KM_TYPE_NR * cpu; idx++) {
unsigned long vaddr = __fix_to_virt(FIX_KMAP_BEGIN + idx);
pte_t ptep;
ptep = get_top_pte(vaddr);
if (ptep)
set_top_pte(vaddr, __pte(0));
}
pagefault_enable();
}
static void kmap_remove_unused(void *unused)
{
kmap_remove_unused_cpu(smp_processor_id());
}
void kmap_atomic_flush_unused(void)
{
on_each_cpu(kmap_remove_unused, NULL, 1);
}
static int hotplug_kmap_atomic_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
switch (action & (~CPU_TASKS_FROZEN)) {
case CPU_DYING:
kmap_remove_unused_cpu((int)hcpu);
break;
default:
break;
}
return NOTIFY_OK;
}
static struct notifier_block hotplug_kmap_atomic_notifier = {
.notifier_call = hotplug_kmap_atomic_callback,
};
static int __init init_kmap_atomic(void)
{
return register_hotcpu_notifier(&hotplug_kmap_atomic_notifier);
}
early_initcall(init_kmap_atomic);
#endif
| gpl-2.0 |
AOSP-JF/platform_kernel_samsung_jf | drivers/rtc/rtc-rs5c372.c | 4941 | 17973 | /*
* An I2C driver for Ricoh RS5C372, R2025S/D and RV5C38[67] RTCs
*
* Copyright (C) 2005 Pavel Mironchik <pmironchik@optifacio.net>
* Copyright (C) 2006 Tower Technologies
* Copyright (C) 2008 Paul Mundt
*
* 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/i2c.h>
#include <linux/rtc.h>
#include <linux/bcd.h>
#include <linux/slab.h>
#include <linux/module.h>
#define DRV_VERSION "0.6"
/*
* Ricoh has a family of I2C based RTCs, which differ only slightly from
* each other. Differences center on pinout (e.g. how many interrupts,
* output clock, etc) and how the control registers are used. The '372
* is significant only because that's the one this driver first supported.
*/
#define RS5C372_REG_SECS 0
#define RS5C372_REG_MINS 1
#define RS5C372_REG_HOURS 2
#define RS5C372_REG_WDAY 3
#define RS5C372_REG_DAY 4
#define RS5C372_REG_MONTH 5
#define RS5C372_REG_YEAR 6
#define RS5C372_REG_TRIM 7
# define RS5C372_TRIM_XSL 0x80
# define RS5C372_TRIM_MASK 0x7F
#define RS5C_REG_ALARM_A_MIN 8 /* or ALARM_W */
#define RS5C_REG_ALARM_A_HOURS 9
#define RS5C_REG_ALARM_A_WDAY 10
#define RS5C_REG_ALARM_B_MIN 11 /* or ALARM_D */
#define RS5C_REG_ALARM_B_HOURS 12
#define RS5C_REG_ALARM_B_WDAY 13 /* (ALARM_B only) */
#define RS5C_REG_CTRL1 14
# define RS5C_CTRL1_AALE (1 << 7) /* or WALE */
# define RS5C_CTRL1_BALE (1 << 6) /* or DALE */
# define RV5C387_CTRL1_24 (1 << 5)
# define RS5C372A_CTRL1_SL1 (1 << 5)
# define RS5C_CTRL1_CT_MASK (7 << 0)
# define RS5C_CTRL1_CT0 (0 << 0) /* no periodic irq */
# define RS5C_CTRL1_CT4 (4 << 0) /* 1 Hz level irq */
#define RS5C_REG_CTRL2 15
# define RS5C372_CTRL2_24 (1 << 5)
# define R2025_CTRL2_XST (1 << 5)
# define RS5C_CTRL2_XSTP (1 << 4) /* only if !R2025S/D */
# define RS5C_CTRL2_CTFG (1 << 2)
# define RS5C_CTRL2_AAFG (1 << 1) /* or WAFG */
# define RS5C_CTRL2_BAFG (1 << 0) /* or DAFG */
/* to read (style 1) or write registers starting at R */
#define RS5C_ADDR(R) (((R) << 4) | 0)
enum rtc_type {
rtc_undef = 0,
rtc_r2025sd,
rtc_rs5c372a,
rtc_rs5c372b,
rtc_rv5c386,
rtc_rv5c387a,
};
static const struct i2c_device_id rs5c372_id[] = {
{ "r2025sd", rtc_r2025sd },
{ "rs5c372a", rtc_rs5c372a },
{ "rs5c372b", rtc_rs5c372b },
{ "rv5c386", rtc_rv5c386 },
{ "rv5c387a", rtc_rv5c387a },
{ }
};
MODULE_DEVICE_TABLE(i2c, rs5c372_id);
/* REVISIT: this assumes that:
* - we're in the 21st century, so it's safe to ignore the century
* bit for rv5c38[67] (REG_MONTH bit 7);
* - we should use ALARM_A not ALARM_B (may be wrong on some boards)
*/
struct rs5c372 {
struct i2c_client *client;
struct rtc_device *rtc;
enum rtc_type type;
unsigned time24:1;
unsigned has_irq:1;
unsigned smbus:1;
char buf[17];
char *regs;
};
static int rs5c_get_regs(struct rs5c372 *rs5c)
{
struct i2c_client *client = rs5c->client;
struct i2c_msg msgs[] = {
{ client->addr, I2C_M_RD, sizeof rs5c->buf, rs5c->buf },
};
/* This implements the third reading method from the datasheet, using
* an internal address that's reset after each transaction (by STOP)
* to 0x0f ... so we read extra registers, and skip the first one.
*
* The first method doesn't work with the iop3xx adapter driver, on at
* least 80219 chips; this works around that bug.
*
* The third method on the other hand doesn't work for the SMBus-only
* configurations, so we use the the first method there, stripping off
* the extra register in the process.
*/
if (rs5c->smbus) {
int addr = RS5C_ADDR(RS5C372_REG_SECS);
int size = sizeof(rs5c->buf) - 1;
if (i2c_smbus_read_i2c_block_data(client, addr, size,
rs5c->buf + 1) != size) {
dev_warn(&client->dev, "can't read registers\n");
return -EIO;
}
} else {
if ((i2c_transfer(client->adapter, msgs, 1)) != 1) {
dev_warn(&client->dev, "can't read registers\n");
return -EIO;
}
}
dev_dbg(&client->dev,
"%02x %02x %02x (%02x) %02x %02x %02x (%02x), "
"%02x %02x %02x, %02x %02x %02x; %02x %02x\n",
rs5c->regs[0], rs5c->regs[1], rs5c->regs[2], rs5c->regs[3],
rs5c->regs[4], rs5c->regs[5], rs5c->regs[6], rs5c->regs[7],
rs5c->regs[8], rs5c->regs[9], rs5c->regs[10], rs5c->regs[11],
rs5c->regs[12], rs5c->regs[13], rs5c->regs[14], rs5c->regs[15]);
return 0;
}
static unsigned rs5c_reg2hr(struct rs5c372 *rs5c, unsigned reg)
{
unsigned hour;
if (rs5c->time24)
return bcd2bin(reg & 0x3f);
hour = bcd2bin(reg & 0x1f);
if (hour == 12)
hour = 0;
if (reg & 0x20)
hour += 12;
return hour;
}
static unsigned rs5c_hr2reg(struct rs5c372 *rs5c, unsigned hour)
{
if (rs5c->time24)
return bin2bcd(hour);
if (hour > 12)
return 0x20 | bin2bcd(hour - 12);
if (hour == 12)
return 0x20 | bin2bcd(12);
if (hour == 0)
return bin2bcd(12);
return bin2bcd(hour);
}
static int rs5c372_get_datetime(struct i2c_client *client, struct rtc_time *tm)
{
struct rs5c372 *rs5c = i2c_get_clientdata(client);
int status = rs5c_get_regs(rs5c);
if (status < 0)
return status;
tm->tm_sec = bcd2bin(rs5c->regs[RS5C372_REG_SECS] & 0x7f);
tm->tm_min = bcd2bin(rs5c->regs[RS5C372_REG_MINS] & 0x7f);
tm->tm_hour = rs5c_reg2hr(rs5c, rs5c->regs[RS5C372_REG_HOURS]);
tm->tm_wday = bcd2bin(rs5c->regs[RS5C372_REG_WDAY] & 0x07);
tm->tm_mday = bcd2bin(rs5c->regs[RS5C372_REG_DAY] & 0x3f);
/* tm->tm_mon is zero-based */
tm->tm_mon = bcd2bin(rs5c->regs[RS5C372_REG_MONTH] & 0x1f) - 1;
/* year is 1900 + tm->tm_year */
tm->tm_year = bcd2bin(rs5c->regs[RS5C372_REG_YEAR]) + 100;
dev_dbg(&client->dev, "%s: tm is secs=%d, mins=%d, hours=%d, "
"mday=%d, mon=%d, year=%d, wday=%d\n",
__func__,
tm->tm_sec, tm->tm_min, tm->tm_hour,
tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday);
/* rtc might need initialization */
return rtc_valid_tm(tm);
}
static int rs5c372_set_datetime(struct i2c_client *client, struct rtc_time *tm)
{
struct rs5c372 *rs5c = i2c_get_clientdata(client);
unsigned char buf[7];
int addr;
dev_dbg(&client->dev, "%s: tm is secs=%d, mins=%d, hours=%d "
"mday=%d, mon=%d, year=%d, wday=%d\n",
__func__,
tm->tm_sec, tm->tm_min, tm->tm_hour,
tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday);
addr = RS5C_ADDR(RS5C372_REG_SECS);
buf[0] = bin2bcd(tm->tm_sec);
buf[1] = bin2bcd(tm->tm_min);
buf[2] = rs5c_hr2reg(rs5c, tm->tm_hour);
buf[3] = bin2bcd(tm->tm_wday);
buf[4] = bin2bcd(tm->tm_mday);
buf[5] = bin2bcd(tm->tm_mon + 1);
buf[6] = bin2bcd(tm->tm_year - 100);
if (i2c_smbus_write_i2c_block_data(client, addr, sizeof(buf), buf) < 0) {
dev_err(&client->dev, "%s: write error\n", __func__);
return -EIO;
}
return 0;
}
#if defined(CONFIG_RTC_INTF_PROC) || defined(CONFIG_RTC_INTF_PROC_MODULE)
#define NEED_TRIM
#endif
#if defined(CONFIG_RTC_INTF_SYSFS) || defined(CONFIG_RTC_INTF_SYSFS_MODULE)
#define NEED_TRIM
#endif
#ifdef NEED_TRIM
static int rs5c372_get_trim(struct i2c_client *client, int *osc, int *trim)
{
struct rs5c372 *rs5c372 = i2c_get_clientdata(client);
u8 tmp = rs5c372->regs[RS5C372_REG_TRIM];
if (osc)
*osc = (tmp & RS5C372_TRIM_XSL) ? 32000 : 32768;
if (trim) {
dev_dbg(&client->dev, "%s: raw trim=%x\n", __func__, tmp);
tmp &= RS5C372_TRIM_MASK;
if (tmp & 0x3e) {
int t = tmp & 0x3f;
if (tmp & 0x40)
t = (~t | (s8)0xc0) + 1;
else
t = t - 1;
tmp = t * 2;
} else
tmp = 0;
*trim = tmp;
}
return 0;
}
#endif
static int rs5c372_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
return rs5c372_get_datetime(to_i2c_client(dev), tm);
}
static int rs5c372_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
return rs5c372_set_datetime(to_i2c_client(dev), tm);
}
static int rs5c_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
struct i2c_client *client = to_i2c_client(dev);
struct rs5c372 *rs5c = i2c_get_clientdata(client);
unsigned char buf;
int status, addr;
buf = rs5c->regs[RS5C_REG_CTRL1];
if (!rs5c->has_irq)
return -EINVAL;
status = rs5c_get_regs(rs5c);
if (status < 0)
return status;
addr = RS5C_ADDR(RS5C_REG_CTRL1);
if (enabled)
buf |= RS5C_CTRL1_AALE;
else
buf &= ~RS5C_CTRL1_AALE;
if (i2c_smbus_write_byte_data(client, addr, buf) < 0) {
printk(KERN_WARNING "%s: can't update alarm\n",
rs5c->rtc->name);
status = -EIO;
} else
rs5c->regs[RS5C_REG_CTRL1] = buf;
return status;
}
/* NOTE: Since RTC_WKALM_{RD,SET} were originally defined for EFI,
* which only exposes a polled programming interface; and since
* these calls map directly to those EFI requests; we don't demand
* we have an IRQ for this chip when we go through this API.
*
* The older x86_pc derived RTC_ALM_{READ,SET} calls require irqs
* though, managed through RTC_AIE_{ON,OFF} requests.
*/
static int rs5c_read_alarm(struct device *dev, struct rtc_wkalrm *t)
{
struct i2c_client *client = to_i2c_client(dev);
struct rs5c372 *rs5c = i2c_get_clientdata(client);
int status;
status = rs5c_get_regs(rs5c);
if (status < 0)
return status;
/* report alarm time */
t->time.tm_sec = 0;
t->time.tm_min = bcd2bin(rs5c->regs[RS5C_REG_ALARM_A_MIN] & 0x7f);
t->time.tm_hour = rs5c_reg2hr(rs5c, rs5c->regs[RS5C_REG_ALARM_A_HOURS]);
t->time.tm_mday = -1;
t->time.tm_mon = -1;
t->time.tm_year = -1;
t->time.tm_wday = -1;
t->time.tm_yday = -1;
t->time.tm_isdst = -1;
/* ... and status */
t->enabled = !!(rs5c->regs[RS5C_REG_CTRL1] & RS5C_CTRL1_AALE);
t->pending = !!(rs5c->regs[RS5C_REG_CTRL2] & RS5C_CTRL2_AAFG);
return 0;
}
static int rs5c_set_alarm(struct device *dev, struct rtc_wkalrm *t)
{
struct i2c_client *client = to_i2c_client(dev);
struct rs5c372 *rs5c = i2c_get_clientdata(client);
int status, addr, i;
unsigned char buf[3];
/* only handle up to 24 hours in the future, like RTC_ALM_SET */
if (t->time.tm_mday != -1
|| t->time.tm_mon != -1
|| t->time.tm_year != -1)
return -EINVAL;
/* REVISIT: round up tm_sec */
/* if needed, disable irq (clears pending status) */
status = rs5c_get_regs(rs5c);
if (status < 0)
return status;
if (rs5c->regs[RS5C_REG_CTRL1] & RS5C_CTRL1_AALE) {
addr = RS5C_ADDR(RS5C_REG_CTRL1);
buf[0] = rs5c->regs[RS5C_REG_CTRL1] & ~RS5C_CTRL1_AALE;
if (i2c_smbus_write_byte_data(client, addr, buf[0]) < 0) {
pr_debug("%s: can't disable alarm\n", rs5c->rtc->name);
return -EIO;
}
rs5c->regs[RS5C_REG_CTRL1] = buf[0];
}
/* set alarm */
buf[0] = bin2bcd(t->time.tm_min);
buf[1] = rs5c_hr2reg(rs5c, t->time.tm_hour);
buf[2] = 0x7f; /* any/all days */
for (i = 0; i < sizeof(buf); i++) {
addr = RS5C_ADDR(RS5C_REG_ALARM_A_MIN + i);
if (i2c_smbus_write_byte_data(client, addr, buf[i]) < 0) {
pr_debug("%s: can't set alarm time\n", rs5c->rtc->name);
return -EIO;
}
}
/* ... and maybe enable its irq */
if (t->enabled) {
addr = RS5C_ADDR(RS5C_REG_CTRL1);
buf[0] = rs5c->regs[RS5C_REG_CTRL1] | RS5C_CTRL1_AALE;
if (i2c_smbus_write_byte_data(client, addr, buf[0]) < 0)
printk(KERN_WARNING "%s: can't enable alarm\n",
rs5c->rtc->name);
rs5c->regs[RS5C_REG_CTRL1] = buf[0];
}
return 0;
}
#if defined(CONFIG_RTC_INTF_PROC) || defined(CONFIG_RTC_INTF_PROC_MODULE)
static int rs5c372_rtc_proc(struct device *dev, struct seq_file *seq)
{
int err, osc, trim;
err = rs5c372_get_trim(to_i2c_client(dev), &osc, &trim);
if (err == 0) {
seq_printf(seq, "crystal\t\t: %d.%03d KHz\n",
osc / 1000, osc % 1000);
seq_printf(seq, "trim\t\t: %d\n", trim);
}
return 0;
}
#else
#define rs5c372_rtc_proc NULL
#endif
static const struct rtc_class_ops rs5c372_rtc_ops = {
.proc = rs5c372_rtc_proc,
.read_time = rs5c372_rtc_read_time,
.set_time = rs5c372_rtc_set_time,
.read_alarm = rs5c_read_alarm,
.set_alarm = rs5c_set_alarm,
.alarm_irq_enable = rs5c_rtc_alarm_irq_enable,
};
#if defined(CONFIG_RTC_INTF_SYSFS) || defined(CONFIG_RTC_INTF_SYSFS_MODULE)
static ssize_t rs5c372_sysfs_show_trim(struct device *dev,
struct device_attribute *attr, char *buf)
{
int err, trim;
err = rs5c372_get_trim(to_i2c_client(dev), NULL, &trim);
if (err)
return err;
return sprintf(buf, "%d\n", trim);
}
static DEVICE_ATTR(trim, S_IRUGO, rs5c372_sysfs_show_trim, NULL);
static ssize_t rs5c372_sysfs_show_osc(struct device *dev,
struct device_attribute *attr, char *buf)
{
int err, osc;
err = rs5c372_get_trim(to_i2c_client(dev), &osc, NULL);
if (err)
return err;
return sprintf(buf, "%d.%03d KHz\n", osc / 1000, osc % 1000);
}
static DEVICE_ATTR(osc, S_IRUGO, rs5c372_sysfs_show_osc, NULL);
static int rs5c_sysfs_register(struct device *dev)
{
int err;
err = device_create_file(dev, &dev_attr_trim);
if (err)
return err;
err = device_create_file(dev, &dev_attr_osc);
if (err)
device_remove_file(dev, &dev_attr_trim);
return err;
}
static void rs5c_sysfs_unregister(struct device *dev)
{
device_remove_file(dev, &dev_attr_trim);
device_remove_file(dev, &dev_attr_osc);
}
#else
static int rs5c_sysfs_register(struct device *dev)
{
return 0;
}
static void rs5c_sysfs_unregister(struct device *dev)
{
/* nothing */
}
#endif /* SYSFS */
static struct i2c_driver rs5c372_driver;
static int rs5c_oscillator_setup(struct rs5c372 *rs5c372)
{
unsigned char buf[2];
int addr, i, ret = 0;
if (rs5c372->type == rtc_r2025sd) {
if (!(rs5c372->regs[RS5C_REG_CTRL2] & R2025_CTRL2_XST))
return ret;
rs5c372->regs[RS5C_REG_CTRL2] &= ~R2025_CTRL2_XST;
} else {
if (!(rs5c372->regs[RS5C_REG_CTRL2] & RS5C_CTRL2_XSTP))
return ret;
rs5c372->regs[RS5C_REG_CTRL2] &= ~RS5C_CTRL2_XSTP;
}
addr = RS5C_ADDR(RS5C_REG_CTRL1);
buf[0] = rs5c372->regs[RS5C_REG_CTRL1];
buf[1] = rs5c372->regs[RS5C_REG_CTRL2];
/* use 24hr mode */
switch (rs5c372->type) {
case rtc_rs5c372a:
case rtc_rs5c372b:
buf[1] |= RS5C372_CTRL2_24;
rs5c372->time24 = 1;
break;
case rtc_r2025sd:
case rtc_rv5c386:
case rtc_rv5c387a:
buf[0] |= RV5C387_CTRL1_24;
rs5c372->time24 = 1;
break;
default:
/* impossible */
break;
}
for (i = 0; i < sizeof(buf); i++) {
addr = RS5C_ADDR(RS5C_REG_CTRL1 + i);
ret = i2c_smbus_write_byte_data(rs5c372->client, addr, buf[i]);
if (unlikely(ret < 0))
return ret;
}
rs5c372->regs[RS5C_REG_CTRL1] = buf[0];
rs5c372->regs[RS5C_REG_CTRL2] = buf[1];
return 0;
}
static int rs5c372_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int err = 0;
int smbus_mode = 0;
struct rs5c372 *rs5c372;
struct rtc_time tm;
dev_dbg(&client->dev, "%s\n", __func__);
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C |
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_I2C_BLOCK)) {
/*
* If we don't have any master mode adapter, try breaking
* it down in to the barest of capabilities.
*/
if (i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_I2C_BLOCK))
smbus_mode = 1;
else {
/* Still no good, give up */
err = -ENODEV;
goto exit;
}
}
if (!(rs5c372 = kzalloc(sizeof(struct rs5c372), GFP_KERNEL))) {
err = -ENOMEM;
goto exit;
}
rs5c372->client = client;
i2c_set_clientdata(client, rs5c372);
rs5c372->type = id->driver_data;
/* we read registers 0x0f then 0x00-0x0f; skip the first one */
rs5c372->regs = &rs5c372->buf[1];
rs5c372->smbus = smbus_mode;
err = rs5c_get_regs(rs5c372);
if (err < 0)
goto exit_kfree;
/* clock may be set for am/pm or 24 hr time */
switch (rs5c372->type) {
case rtc_rs5c372a:
case rtc_rs5c372b:
/* alarm uses ALARM_A; and nINTRA on 372a, nINTR on 372b.
* so does periodic irq, except some 327a modes.
*/
if (rs5c372->regs[RS5C_REG_CTRL2] & RS5C372_CTRL2_24)
rs5c372->time24 = 1;
break;
case rtc_r2025sd:
case rtc_rv5c386:
case rtc_rv5c387a:
if (rs5c372->regs[RS5C_REG_CTRL1] & RV5C387_CTRL1_24)
rs5c372->time24 = 1;
/* alarm uses ALARM_W; and nINTRB for alarm and periodic
* irq, on both 386 and 387
*/
break;
default:
dev_err(&client->dev, "unknown RTC type\n");
goto exit_kfree;
}
/* if the oscillator lost power and no other software (like
* the bootloader) set it up, do it here.
*
* The R2025S/D does this a little differently than the other
* parts, so we special case that..
*/
err = rs5c_oscillator_setup(rs5c372);
if (unlikely(err < 0)) {
dev_err(&client->dev, "setup error\n");
goto exit_kfree;
}
if (rs5c372_get_datetime(client, &tm) < 0)
dev_warn(&client->dev, "clock needs to be set\n");
dev_info(&client->dev, "%s found, %s, driver version " DRV_VERSION "\n",
({ char *s; switch (rs5c372->type) {
case rtc_r2025sd: s = "r2025sd"; break;
case rtc_rs5c372a: s = "rs5c372a"; break;
case rtc_rs5c372b: s = "rs5c372b"; break;
case rtc_rv5c386: s = "rv5c386"; break;
case rtc_rv5c387a: s = "rv5c387a"; break;
default: s = "chip"; break;
}; s;}),
rs5c372->time24 ? "24hr" : "am/pm"
);
/* REVISIT use client->irq to register alarm irq ... */
rs5c372->rtc = rtc_device_register(rs5c372_driver.driver.name,
&client->dev, &rs5c372_rtc_ops, THIS_MODULE);
if (IS_ERR(rs5c372->rtc)) {
err = PTR_ERR(rs5c372->rtc);
goto exit_kfree;
}
err = rs5c_sysfs_register(&client->dev);
if (err)
goto exit_devreg;
return 0;
exit_devreg:
rtc_device_unregister(rs5c372->rtc);
exit_kfree:
kfree(rs5c372);
exit:
return err;
}
static int rs5c372_remove(struct i2c_client *client)
{
struct rs5c372 *rs5c372 = i2c_get_clientdata(client);
rtc_device_unregister(rs5c372->rtc);
rs5c_sysfs_unregister(&client->dev);
kfree(rs5c372);
return 0;
}
static struct i2c_driver rs5c372_driver = {
.driver = {
.name = "rtc-rs5c372",
},
.probe = rs5c372_probe,
.remove = rs5c372_remove,
.id_table = rs5c372_id,
};
module_i2c_driver(rs5c372_driver);
MODULE_AUTHOR(
"Pavel Mironchik <pmironchik@optifacio.net>, "
"Alessandro Zummo <a.zummo@towertech.it>, "
"Paul Mundt <lethal@linux-sh.org>");
MODULE_DESCRIPTION("Ricoh RS5C372 RTC driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
TI-OpenLink/wl18xx | drivers/clocksource/dw_apb_timer.c | 7501 | 11521 | /*
* (C) Copyright 2009 Intel Corporation
* Author: Jacob Pan (jacob.jun.pan@intel.com)
*
* Shared with ARM platforms, Jamie Iles, Picochip 2011
*
* 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.
*
* Support for the Synopsys DesignWare APB Timers.
*/
#include <linux/dw_apb_timer.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/slab.h>
#define APBT_MIN_PERIOD 4
#define APBT_MIN_DELTA_USEC 200
#define APBTMR_N_LOAD_COUNT 0x00
#define APBTMR_N_CURRENT_VALUE 0x04
#define APBTMR_N_CONTROL 0x08
#define APBTMR_N_EOI 0x0c
#define APBTMR_N_INT_STATUS 0x10
#define APBTMRS_INT_STATUS 0xa0
#define APBTMRS_EOI 0xa4
#define APBTMRS_RAW_INT_STATUS 0xa8
#define APBTMRS_COMP_VERSION 0xac
#define APBTMR_CONTROL_ENABLE (1 << 0)
/* 1: periodic, 0:free running. */
#define APBTMR_CONTROL_MODE_PERIODIC (1 << 1)
#define APBTMR_CONTROL_INT (1 << 2)
static inline struct dw_apb_clock_event_device *
ced_to_dw_apb_ced(struct clock_event_device *evt)
{
return container_of(evt, struct dw_apb_clock_event_device, ced);
}
static inline struct dw_apb_clocksource *
clocksource_to_dw_apb_clocksource(struct clocksource *cs)
{
return container_of(cs, struct dw_apb_clocksource, cs);
}
static unsigned long apbt_readl(struct dw_apb_timer *timer, unsigned long offs)
{
return readl(timer->base + offs);
}
static void apbt_writel(struct dw_apb_timer *timer, unsigned long val,
unsigned long offs)
{
writel(val, timer->base + offs);
}
static void apbt_disable_int(struct dw_apb_timer *timer)
{
unsigned long ctrl = apbt_readl(timer, APBTMR_N_CONTROL);
ctrl |= APBTMR_CONTROL_INT;
apbt_writel(timer, ctrl, APBTMR_N_CONTROL);
}
/**
* dw_apb_clockevent_pause() - stop the clock_event_device from running
*
* @dw_ced: The APB clock to stop generating events.
*/
void dw_apb_clockevent_pause(struct dw_apb_clock_event_device *dw_ced)
{
disable_irq(dw_ced->timer.irq);
apbt_disable_int(&dw_ced->timer);
}
static void apbt_eoi(struct dw_apb_timer *timer)
{
apbt_readl(timer, APBTMR_N_EOI);
}
static irqreturn_t dw_apb_clockevent_irq(int irq, void *data)
{
struct clock_event_device *evt = data;
struct dw_apb_clock_event_device *dw_ced = ced_to_dw_apb_ced(evt);
if (!evt->event_handler) {
pr_info("Spurious APBT timer interrupt %d", irq);
return IRQ_NONE;
}
if (dw_ced->eoi)
dw_ced->eoi(&dw_ced->timer);
evt->event_handler(evt);
return IRQ_HANDLED;
}
static void apbt_enable_int(struct dw_apb_timer *timer)
{
unsigned long ctrl = apbt_readl(timer, APBTMR_N_CONTROL);
/* clear pending intr */
apbt_readl(timer, APBTMR_N_EOI);
ctrl &= ~APBTMR_CONTROL_INT;
apbt_writel(timer, ctrl, APBTMR_N_CONTROL);
}
static void apbt_set_mode(enum clock_event_mode mode,
struct clock_event_device *evt)
{
unsigned long ctrl;
unsigned long period;
struct dw_apb_clock_event_device *dw_ced = ced_to_dw_apb_ced(evt);
pr_debug("%s CPU %d mode=%d\n", __func__, first_cpu(*evt->cpumask),
mode);
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
period = DIV_ROUND_UP(dw_ced->timer.freq, HZ);
ctrl = apbt_readl(&dw_ced->timer, APBTMR_N_CONTROL);
ctrl |= APBTMR_CONTROL_MODE_PERIODIC;
apbt_writel(&dw_ced->timer, ctrl, APBTMR_N_CONTROL);
/*
* DW APB p. 46, have to disable timer before load counter,
* may cause sync problem.
*/
ctrl &= ~APBTMR_CONTROL_ENABLE;
apbt_writel(&dw_ced->timer, ctrl, APBTMR_N_CONTROL);
udelay(1);
pr_debug("Setting clock period %lu for HZ %d\n", period, HZ);
apbt_writel(&dw_ced->timer, period, APBTMR_N_LOAD_COUNT);
ctrl |= APBTMR_CONTROL_ENABLE;
apbt_writel(&dw_ced->timer, ctrl, APBTMR_N_CONTROL);
break;
case CLOCK_EVT_MODE_ONESHOT:
ctrl = apbt_readl(&dw_ced->timer, APBTMR_N_CONTROL);
/*
* set free running mode, this mode will let timer reload max
* timeout which will give time (3min on 25MHz clock) to rearm
* the next event, therefore emulate the one-shot mode.
*/
ctrl &= ~APBTMR_CONTROL_ENABLE;
ctrl &= ~APBTMR_CONTROL_MODE_PERIODIC;
apbt_writel(&dw_ced->timer, ctrl, APBTMR_N_CONTROL);
/* write again to set free running mode */
apbt_writel(&dw_ced->timer, ctrl, APBTMR_N_CONTROL);
/*
* DW APB p. 46, load counter with all 1s before starting free
* running mode.
*/
apbt_writel(&dw_ced->timer, ~0, APBTMR_N_LOAD_COUNT);
ctrl &= ~APBTMR_CONTROL_INT;
ctrl |= APBTMR_CONTROL_ENABLE;
apbt_writel(&dw_ced->timer, ctrl, APBTMR_N_CONTROL);
break;
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
ctrl = apbt_readl(&dw_ced->timer, APBTMR_N_CONTROL);
ctrl &= ~APBTMR_CONTROL_ENABLE;
apbt_writel(&dw_ced->timer, ctrl, APBTMR_N_CONTROL);
break;
case CLOCK_EVT_MODE_RESUME:
apbt_enable_int(&dw_ced->timer);
break;
}
}
static int apbt_next_event(unsigned long delta,
struct clock_event_device *evt)
{
unsigned long ctrl;
struct dw_apb_clock_event_device *dw_ced = ced_to_dw_apb_ced(evt);
/* Disable timer */
ctrl = apbt_readl(&dw_ced->timer, APBTMR_N_CONTROL);
ctrl &= ~APBTMR_CONTROL_ENABLE;
apbt_writel(&dw_ced->timer, ctrl, APBTMR_N_CONTROL);
/* write new count */
apbt_writel(&dw_ced->timer, delta, APBTMR_N_LOAD_COUNT);
ctrl |= APBTMR_CONTROL_ENABLE;
apbt_writel(&dw_ced->timer, ctrl, APBTMR_N_CONTROL);
return 0;
}
/**
* dw_apb_clockevent_init() - use an APB timer as a clock_event_device
*
* @cpu: The CPU the events will be targeted at.
* @name: The name used for the timer and the IRQ for it.
* @rating: The rating to give the timer.
* @base: I/O base for the timer registers.
* @irq: The interrupt number to use for the timer.
* @freq: The frequency that the timer counts at.
*
* This creates a clock_event_device for using with the generic clock layer
* but does not start and register it. This should be done with
* dw_apb_clockevent_register() as the next step. If this is the first time
* it has been called for a timer then the IRQ will be requested, if not it
* just be enabled to allow CPU hotplug to avoid repeatedly requesting and
* releasing the IRQ.
*/
struct dw_apb_clock_event_device *
dw_apb_clockevent_init(int cpu, const char *name, unsigned rating,
void __iomem *base, int irq, unsigned long freq)
{
struct dw_apb_clock_event_device *dw_ced =
kzalloc(sizeof(*dw_ced), GFP_KERNEL);
int err;
if (!dw_ced)
return NULL;
dw_ced->timer.base = base;
dw_ced->timer.irq = irq;
dw_ced->timer.freq = freq;
clockevents_calc_mult_shift(&dw_ced->ced, freq, APBT_MIN_PERIOD);
dw_ced->ced.max_delta_ns = clockevent_delta2ns(0x7fffffff,
&dw_ced->ced);
dw_ced->ced.min_delta_ns = clockevent_delta2ns(5000, &dw_ced->ced);
dw_ced->ced.cpumask = cpumask_of(cpu);
dw_ced->ced.features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT;
dw_ced->ced.set_mode = apbt_set_mode;
dw_ced->ced.set_next_event = apbt_next_event;
dw_ced->ced.irq = dw_ced->timer.irq;
dw_ced->ced.rating = rating;
dw_ced->ced.name = name;
dw_ced->irqaction.name = dw_ced->ced.name;
dw_ced->irqaction.handler = dw_apb_clockevent_irq;
dw_ced->irqaction.dev_id = &dw_ced->ced;
dw_ced->irqaction.irq = irq;
dw_ced->irqaction.flags = IRQF_TIMER | IRQF_IRQPOLL |
IRQF_NOBALANCING |
IRQF_DISABLED;
dw_ced->eoi = apbt_eoi;
err = setup_irq(irq, &dw_ced->irqaction);
if (err) {
pr_err("failed to request timer irq\n");
kfree(dw_ced);
dw_ced = NULL;
}
return dw_ced;
}
/**
* dw_apb_clockevent_resume() - resume a clock that has been paused.
*
* @dw_ced: The APB clock to resume.
*/
void dw_apb_clockevent_resume(struct dw_apb_clock_event_device *dw_ced)
{
enable_irq(dw_ced->timer.irq);
}
/**
* dw_apb_clockevent_stop() - stop the clock_event_device and release the IRQ.
*
* @dw_ced: The APB clock to stop generating the events.
*/
void dw_apb_clockevent_stop(struct dw_apb_clock_event_device *dw_ced)
{
free_irq(dw_ced->timer.irq, &dw_ced->ced);
}
/**
* dw_apb_clockevent_register() - register the clock with the generic layer
*
* @dw_ced: The APB clock to register as a clock_event_device.
*/
void dw_apb_clockevent_register(struct dw_apb_clock_event_device *dw_ced)
{
apbt_writel(&dw_ced->timer, 0, APBTMR_N_CONTROL);
clockevents_register_device(&dw_ced->ced);
apbt_enable_int(&dw_ced->timer);
}
/**
* dw_apb_clocksource_start() - start the clocksource counting.
*
* @dw_cs: The clocksource to start.
*
* This is used to start the clocksource before registration and can be used
* to enable calibration of timers.
*/
void dw_apb_clocksource_start(struct dw_apb_clocksource *dw_cs)
{
/*
* start count down from 0xffff_ffff. this is done by toggling the
* enable bit then load initial load count to ~0.
*/
unsigned long ctrl = apbt_readl(&dw_cs->timer, APBTMR_N_CONTROL);
ctrl &= ~APBTMR_CONTROL_ENABLE;
apbt_writel(&dw_cs->timer, ctrl, APBTMR_N_CONTROL);
apbt_writel(&dw_cs->timer, ~0, APBTMR_N_LOAD_COUNT);
/* enable, mask interrupt */
ctrl &= ~APBTMR_CONTROL_MODE_PERIODIC;
ctrl |= (APBTMR_CONTROL_ENABLE | APBTMR_CONTROL_INT);
apbt_writel(&dw_cs->timer, ctrl, APBTMR_N_CONTROL);
/* read it once to get cached counter value initialized */
dw_apb_clocksource_read(dw_cs);
}
static cycle_t __apbt_read_clocksource(struct clocksource *cs)
{
unsigned long current_count;
struct dw_apb_clocksource *dw_cs =
clocksource_to_dw_apb_clocksource(cs);
current_count = apbt_readl(&dw_cs->timer, APBTMR_N_CURRENT_VALUE);
return (cycle_t)~current_count;
}
static void apbt_restart_clocksource(struct clocksource *cs)
{
struct dw_apb_clocksource *dw_cs =
clocksource_to_dw_apb_clocksource(cs);
dw_apb_clocksource_start(dw_cs);
}
/**
* dw_apb_clocksource_init() - use an APB timer as a clocksource.
*
* @rating: The rating to give the clocksource.
* @name: The name for the clocksource.
* @base: The I/O base for the timer registers.
* @freq: The frequency that the timer counts at.
*
* This creates a clocksource using an APB timer but does not yet register it
* with the clocksource system. This should be done with
* dw_apb_clocksource_register() as the next step.
*/
struct dw_apb_clocksource *
dw_apb_clocksource_init(unsigned rating, const char *name, void __iomem *base,
unsigned long freq)
{
struct dw_apb_clocksource *dw_cs = kzalloc(sizeof(*dw_cs), GFP_KERNEL);
if (!dw_cs)
return NULL;
dw_cs->timer.base = base;
dw_cs->timer.freq = freq;
dw_cs->cs.name = name;
dw_cs->cs.rating = rating;
dw_cs->cs.read = __apbt_read_clocksource;
dw_cs->cs.mask = CLOCKSOURCE_MASK(32);
dw_cs->cs.flags = CLOCK_SOURCE_IS_CONTINUOUS;
dw_cs->cs.resume = apbt_restart_clocksource;
return dw_cs;
}
/**
* dw_apb_clocksource_register() - register the APB clocksource.
*
* @dw_cs: The clocksource to register.
*/
void dw_apb_clocksource_register(struct dw_apb_clocksource *dw_cs)
{
clocksource_register_hz(&dw_cs->cs, dw_cs->timer.freq);
}
/**
* dw_apb_clocksource_read() - read the current value of a clocksource.
*
* @dw_cs: The clocksource to read.
*/
cycle_t dw_apb_clocksource_read(struct dw_apb_clocksource *dw_cs)
{
return (cycle_t)~apbt_readl(&dw_cs->timer, APBTMR_N_CURRENT_VALUE);
}
/**
* dw_apb_clocksource_unregister() - unregister and free a clocksource.
*
* @dw_cs: The clocksource to unregister/free.
*/
void dw_apb_clocksource_unregister(struct dw_apb_clocksource *dw_cs)
{
clocksource_unregister(&dw_cs->cs);
kfree(dw_cs);
}
| gpl-2.0 |
Slim80/Imperium_Kernel_TW_4.4.2_new | drivers/staging/comedi/drivers/addi-data/hwdrv_apci16xx.c | 8013 | 29161 | /**
@verbatim
Copyright (C) 2004,2005 ADDI-DATA GmbH for the source code of this module.
ADDI-DATA GmbH
Dieselstrasse 3
D-77833 Ottersweier
Tel: +19(0)7223/9493-0
Fax: +49(0)7223/9493-92
http://www.addi-data.com
info@addi-data.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
You should also find the complete GPL in the COPYING file accompanying this source code.
@endverbatim
*/
/*
+-----------------------------------------------------------------------+
| (C) ADDI-DATA GmbH Dieselstraße 3 D-77833 Ottersweier |
+-----------------------------------------------------------------------+
| Tel : +49 (0) 7223/9493-0 | email : info@addi-data.com |
| Fax : +49 (0) 7223/9493-92 | Internet : http://www.addi-data.com |
+-----------------------------------------------------------------------+
| Project : API APCI1648 | Compiler : gcc |
| Module name : TTL.C | Version : 2.96 |
+-------------------------------+---------------------------------------+
| Project manager: S. Weber | Date : 25/05/2005 |
+-----------------------------------------------------------------------+
| Description : APCI-16XX TTL I/O module |
| |
| |
+-----------------------------------------------------------------------+
| UPDATES |
+-----------------------------------------------------------------------+
| Date | Author | Description of updates |
+----------+-----------+------------------------------------------------+
|25.05.2005| S.Weber | Creation |
| | | |
+-----------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------------+
| Included files |
+----------------------------------------------------------------------------+
*/
#include "hwdrv_apci16xx.h"
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI16XX_InsnConfigInitTTLIO |
| (struct comedi_device *dev, |
| struct comedi_subdevice *s, |
| struct comedi_insn *insn, |
| unsigned int *data) |
+----------------------------------------------------------------------------+
| Task APCI16XX_TTL_INIT (using defaults) : |
| Configure the TTL I/O operating mode from all ports |
| You must calling this function be |
| for you call any other function witch access of TTL. |
| APCI16XX_TTL_INITDIRECTION(user inputs for direction) |
+----------------------------------------------------------------------------+
| Input Parameters : b_InitType = (unsigned char) data[0]; |
| b_Port0Mode = (unsigned char) data[1]; |
| b_Port1Mode = (unsigned char) data[2]; |
| b_Port2Mode = (unsigned char) data[3]; |
| b_Port3Mode = (unsigned char) data[4]; |
| ........ |
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value :>0: No error |
| -1: Port 0 mode selection is wrong |
| -2: Port 1 mode selection is wrong |
| -3: Port 2 mode selection is wrong |
| -4: Port 3 mode selection is wrong |
| -X: Port X-1 mode selection is wrong |
| .... |
| -100 : Config command error |
| -101 : Data size error |
+----------------------------------------------------------------------------+
*/
int i_APCI16XX_InsnConfigInitTTLIO(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = insn->n;
unsigned char b_Command = 0;
unsigned char b_Cpt = 0;
unsigned char b_NumberOfPort =
(unsigned char) (this_board->i_NbrTTLChannel / 8);
/************************/
/* Test the buffer size */
/************************/
if (insn->n >= 1) {
/*******************/
/* Get the command */
/* **************** */
b_Command = (unsigned char) data[0];
/********************/
/* Test the command */
/********************/
if ((b_Command == APCI16XX_TTL_INIT) ||
(b_Command == APCI16XX_TTL_INITDIRECTION) ||
(b_Command == APCI16XX_TTL_OUTPUTMEMORY)) {
/***************************************/
/* Test the initialisation buffer size */
/***************************************/
if ((b_Command == APCI16XX_TTL_INITDIRECTION)
&& ((unsigned char) (insn->n - 1) != b_NumberOfPort)) {
/*******************/
/* Data size error */
/*******************/
printk("\nBuffer size error");
i_ReturnValue = -101;
}
if ((b_Command == APCI16XX_TTL_OUTPUTMEMORY)
&& ((unsigned char) (insn->n) != 2)) {
/*******************/
/* Data size error */
/*******************/
printk("\nBuffer size error");
i_ReturnValue = -101;
}
} else {
/************************/
/* Config command error */
/************************/
printk("\nCommand selection error");
i_ReturnValue = -100;
}
} else {
/*******************/
/* Data size error */
/*******************/
printk("\nBuffer size error");
i_ReturnValue = -101;
}
/**************************************************************************/
/* Test if no error occur and APCI16XX_TTL_INITDIRECTION command selected */
/**************************************************************************/
if ((i_ReturnValue >= 0) && (b_Command == APCI16XX_TTL_INITDIRECTION)) {
memset(devpriv->ul_TTLPortConfiguration, 0,
sizeof(devpriv->ul_TTLPortConfiguration));
/*************************************/
/* Test the port direction selection */
/*************************************/
for (b_Cpt = 1;
(b_Cpt <= b_NumberOfPort) && (i_ReturnValue >= 0);
b_Cpt++) {
/**********************/
/* Test the direction */
/**********************/
if ((data[b_Cpt] != 0) && (data[b_Cpt] != 0xFF)) {
/************************/
/* Port direction error */
/************************/
printk("\nPort %d direction selection error",
(int) b_Cpt);
i_ReturnValue = -(int) b_Cpt;
}
/**************************/
/* Save the configuration */
/**************************/
devpriv->ul_TTLPortConfiguration[(b_Cpt - 1) / 4] =
devpriv->ul_TTLPortConfiguration[(b_Cpt -
1) / 4] | (data[b_Cpt] << (8 * ((b_Cpt -
1) % 4)));
}
}
/**************************/
/* Test if no error occur */
/**************************/
if (i_ReturnValue >= 0) {
/***********************************/
/* Test if TTL port initilaisation */
/***********************************/
if ((b_Command == APCI16XX_TTL_INIT)
|| (b_Command == APCI16XX_TTL_INITDIRECTION)) {
/******************************/
/* Set all port configuration */
/******************************/
for (b_Cpt = 0; b_Cpt <= b_NumberOfPort; b_Cpt++) {
if ((b_Cpt % 4) == 0) {
/*************************/
/* Set the configuration */
/*************************/
outl(devpriv->
ul_TTLPortConfiguration[b_Cpt /
4],
devpriv->iobase + 32 + b_Cpt);
}
}
}
}
/************************************************/
/* Test if output memory initialisation command */
/************************************************/
if (b_Command == APCI16XX_TTL_OUTPUTMEMORY) {
if (data[1]) {
devpriv->b_OutputMemoryStatus = ADDIDATA_ENABLE;
} else {
devpriv->b_OutputMemoryStatus = ADDIDATA_DISABLE;
}
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| INPUT FUNCTIONS |
+----------------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI16XX_InsnBitsReadTTLIO |
| (struct comedi_device *dev, |
| struct comedi_subdevice *s, |
| struct comedi_insn *insn, |
| unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Read the status from selected TTL digital input |
| (b_InputChannel) |
+----------------------------------------------------------------------------+
| Task : Read the status from digital input port |
| (b_SelectedPort) |
+----------------------------------------------------------------------------+
| Input Parameters : |
| APCI16XX_TTL_READCHANNEL |
| b_SelectedPort= CR_RANGE(insn->chanspec); |
| b_InputChannel= CR_CHAN(insn->chanspec); |
| b_ReadType = (unsigned char) data[0]; |
| |
| APCI16XX_TTL_READPORT |
| b_SelectedPort= CR_RANGE(insn->chanspec); |
| b_ReadType = (unsigned char) data[0]; |
+----------------------------------------------------------------------------+
| Output Parameters : data[0] 0 : Channle is not active |
| 1 : Channle is active |
+----------------------------------------------------------------------------+
| Return Value : >0 : No error |
| -100 : Config command error |
| -101 : Data size error |
| -102 : The selected TTL input port is wrong |
| -103 : The selected TTL digital input is wrong |
+----------------------------------------------------------------------------+
*/
int i_APCI16XX_InsnBitsReadTTLIO(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = insn->n;
unsigned char b_Command = 0;
unsigned char b_NumberOfPort =
(unsigned char) (this_board->i_NbrTTLChannel / 8);
unsigned char b_SelectedPort = CR_RANGE(insn->chanspec);
unsigned char b_InputChannel = CR_CHAN(insn->chanspec);
unsigned char *pb_Status;
unsigned int dw_Status;
/************************/
/* Test the buffer size */
/************************/
if (insn->n >= 1) {
/*******************/
/* Get the command */
/* **************** */
b_Command = (unsigned char) data[0];
/********************/
/* Test the command */
/********************/
if ((b_Command == APCI16XX_TTL_READCHANNEL)
|| (b_Command == APCI16XX_TTL_READPORT)) {
/**************************/
/* Test the selected port */
/**************************/
if (b_SelectedPort < b_NumberOfPort) {
/**********************/
/* Test if input port */
/**********************/
if (((devpriv->ul_TTLPortConfiguration
[b_SelectedPort /
4] >> (8 *
(b_SelectedPort
%
4))) &
0xFF) == 0) {
/***************************/
/* Test the channel number */
/***************************/
if ((b_Command ==
APCI16XX_TTL_READCHANNEL)
&& (b_InputChannel > 7)) {
/*******************************************/
/* The selected TTL digital input is wrong */
/*******************************************/
printk("\nChannel selection error");
i_ReturnValue = -103;
}
} else {
/****************************************/
/* The selected TTL input port is wrong */
/****************************************/
printk("\nPort selection error");
i_ReturnValue = -102;
}
} else {
/****************************************/
/* The selected TTL input port is wrong */
/****************************************/
printk("\nPort selection error");
i_ReturnValue = -102;
}
} else {
/************************/
/* Config command error */
/************************/
printk("\nCommand selection error");
i_ReturnValue = -100;
}
} else {
/*******************/
/* Data size error */
/*******************/
printk("\nBuffer size error");
i_ReturnValue = -101;
}
/**************************/
/* Test if no error occur */
/**************************/
if (i_ReturnValue >= 0) {
pb_Status = (unsigned char *) &data[0];
/*******************************/
/* Get the digital inpu status */
/*******************************/
dw_Status =
inl(devpriv->iobase + 8 + ((b_SelectedPort / 4) * 4));
dw_Status = (dw_Status >> (8 * (b_SelectedPort % 4))) & 0xFF;
/***********************/
/* Save the port value */
/***********************/
*pb_Status = (unsigned char) dw_Status;
/***************************************/
/* Test if read channel status command */
/***************************************/
if (b_Command == APCI16XX_TTL_READCHANNEL) {
*pb_Status = (*pb_Status >> b_InputChannel) & 1;
}
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI16XX_InsnReadTTLIOAllPortValue |
| (struct comedi_device *dev, |
| struct comedi_subdevice *s, |
| struct comedi_insn *insn, |
| unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Read the status from all digital input ports |
+----------------------------------------------------------------------------+
| Input Parameters : - |
+----------------------------------------------------------------------------+
| Output Parameters : data[0] : Port 0 to 3 data |
| data[1] : Port 4 to 7 data |
| .... |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -100 : Read command error |
| -101 : Data size error |
+----------------------------------------------------------------------------+
*/
int i_APCI16XX_InsnReadTTLIOAllPortValue(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
unsigned char b_Command = (unsigned char) CR_AREF(insn->chanspec);
int i_ReturnValue = insn->n;
unsigned char b_Cpt = 0;
unsigned char b_NumberOfPort = 0;
unsigned int *pls_ReadData = data;
/********************/
/* Test the command */
/********************/
if ((b_Command == APCI16XX_TTL_READ_ALL_INPUTS)
|| (b_Command == APCI16XX_TTL_READ_ALL_OUTPUTS)) {
/**********************************/
/* Get the number of 32-Bit ports */
/**********************************/
b_NumberOfPort =
(unsigned char) (this_board->i_NbrTTLChannel / 32);
if ((b_NumberOfPort * 32) <
this_board->i_NbrTTLChannel) {
b_NumberOfPort = b_NumberOfPort + 1;
}
/************************/
/* Test the buffer size */
/************************/
if (insn->n >= b_NumberOfPort) {
if (b_Command == APCI16XX_TTL_READ_ALL_INPUTS) {
/**************************/
/* Read all digital input */
/**************************/
for (b_Cpt = 0; b_Cpt < b_NumberOfPort; b_Cpt++) {
/************************/
/* Read the 32-Bit port */
/************************/
pls_ReadData[b_Cpt] =
inl(devpriv->iobase + 8 +
(b_Cpt * 4));
/**************************************/
/* Mask all channels used als outputs */
/**************************************/
pls_ReadData[b_Cpt] =
pls_ReadData[b_Cpt] &
(~devpriv->
ul_TTLPortConfiguration[b_Cpt]);
}
} else {
/****************************/
/* Read all digital outputs */
/****************************/
for (b_Cpt = 0; b_Cpt < b_NumberOfPort; b_Cpt++) {
/************************/
/* Read the 32-Bit port */
/************************/
pls_ReadData[b_Cpt] =
inl(devpriv->iobase + 20 +
(b_Cpt * 4));
/**************************************/
/* Mask all channels used als outputs */
/**************************************/
pls_ReadData[b_Cpt] =
pls_ReadData[b_Cpt] & devpriv->
ul_TTLPortConfiguration[b_Cpt];
}
}
} else {
/*******************/
/* Data size error */
/*******************/
printk("\nBuffer size error");
i_ReturnValue = -101;
}
} else {
/*****************/
/* Command error */
/*****************/
printk("\nCommand selection error");
i_ReturnValue = -100;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| OUTPUT FUNCTIONS |
+----------------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI16XX_InsnBitsWriteTTLIO |
| (struct comedi_device *dev, |
| struct comedi_subdevice *s, |
| struct comedi_insn *insn, |
| unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Set the state from selected TTL digital output |
| (b_OutputChannel) |
+----------------------------------------------------------------------------+
| Task : Set the state from digital output port |
| (b_SelectedPort) |
+----------------------------------------------------------------------------+
| Input Parameters : |
| APCI16XX_TTL_WRITECHANNEL_ON | APCI16XX_TTL_WRITECHANNEL_OFF |
| b_SelectedPort = CR_RANGE(insn->chanspec); |
| b_OutputChannel= CR_CHAN(insn->chanspec); |
| b_Command = (unsigned char) data[0]; |
| |
| APCI16XX_TTL_WRITEPORT_ON | APCI16XX_TTL_WRITEPORT_OFF |
| b_SelectedPort = CR_RANGE(insn->chanspec); |
| b_Command = (unsigned char) data[0]; |
+----------------------------------------------------------------------------+
| Output Parameters : data[0] : TTL output port 0 to 3 data |
| data[1] : TTL output port 4 to 7 data |
| .... |
+----------------------------------------------------------------------------+
| Return Value : >0 : No error |
| -100 : Command error |
| -101 : Data size error |
| -102 : The selected TTL output port is wrong |
| -103 : The selected TTL digital output is wrong |
| -104 : Output memory disabled |
+----------------------------------------------------------------------------+
*/
int i_APCI16XX_InsnBitsWriteTTLIO(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = insn->n;
unsigned char b_Command = 0;
unsigned char b_NumberOfPort =
(unsigned char) (this_board->i_NbrTTLChannel / 8);
unsigned char b_SelectedPort = CR_RANGE(insn->chanspec);
unsigned char b_OutputChannel = CR_CHAN(insn->chanspec);
unsigned int dw_Status = 0;
/************************/
/* Test the buffer size */
/************************/
if (insn->n >= 1) {
/*******************/
/* Get the command */
/* **************** */
b_Command = (unsigned char) data[0];
/********************/
/* Test the command */
/********************/
if ((b_Command == APCI16XX_TTL_WRITECHANNEL_ON) ||
(b_Command == APCI16XX_TTL_WRITEPORT_ON) ||
(b_Command == APCI16XX_TTL_WRITECHANNEL_OFF) ||
(b_Command == APCI16XX_TTL_WRITEPORT_OFF)) {
/**************************/
/* Test the selected port */
/**************************/
if (b_SelectedPort < b_NumberOfPort) {
/***********************/
/* Test if output port */
/***********************/
if (((devpriv->ul_TTLPortConfiguration
[b_SelectedPort /
4] >> (8 *
(b_SelectedPort
%
4))) &
0xFF) == 0xFF) {
/***************************/
/* Test the channel number */
/***************************/
if (((b_Command == APCI16XX_TTL_WRITECHANNEL_ON) || (b_Command == APCI16XX_TTL_WRITECHANNEL_OFF)) && (b_OutputChannel > 7)) {
/********************************************/
/* The selected TTL digital output is wrong */
/********************************************/
printk("\nChannel selection error");
i_ReturnValue = -103;
}
if (((b_Command == APCI16XX_TTL_WRITECHANNEL_OFF) || (b_Command == APCI16XX_TTL_WRITEPORT_OFF)) && (devpriv->b_OutputMemoryStatus == ADDIDATA_DISABLE)) {
/********************************************/
/* The selected TTL digital output is wrong */
/********************************************/
printk("\nOutput memory disabled");
i_ReturnValue = -104;
}
/************************/
/* Test the buffer size */
/************************/
if (((b_Command == APCI16XX_TTL_WRITEPORT_ON) || (b_Command == APCI16XX_TTL_WRITEPORT_OFF)) && (insn->n < 2)) {
/*******************/
/* Data size error */
/*******************/
printk("\nBuffer size error");
i_ReturnValue = -101;
}
} else {
/*****************************************/
/* The selected TTL output port is wrong */
/*****************************************/
printk("\nPort selection error %lX",
(unsigned long)devpriv->
ul_TTLPortConfiguration[0]);
i_ReturnValue = -102;
}
} else {
/****************************************/
/* The selected TTL output port is wrong */
/****************************************/
printk("\nPort selection error %d %d",
b_SelectedPort, b_NumberOfPort);
i_ReturnValue = -102;
}
} else {
/************************/
/* Config command error */
/************************/
printk("\nCommand selection error");
i_ReturnValue = -100;
}
} else {
/*******************/
/* Data size error */
/*******************/
printk("\nBuffer size error");
i_ReturnValue = -101;
}
/**************************/
/* Test if no error occur */
/**************************/
if (i_ReturnValue >= 0) {
/********************************/
/* Get the digital output state */
/********************************/
dw_Status =
inl(devpriv->iobase + 20 + ((b_SelectedPort / 4) * 4));
/**********************************/
/* Test if output memory not used */
/**********************************/
if (devpriv->b_OutputMemoryStatus == ADDIDATA_DISABLE) {
/*********************************/
/* Clear the selected port value */
/*********************************/
dw_Status =
dw_Status & (0xFFFFFFFFUL -
(0xFFUL << (8 * (b_SelectedPort % 4))));
}
/******************************/
/* Test if setting channel ON */
/******************************/
if (b_Command == APCI16XX_TTL_WRITECHANNEL_ON) {
dw_Status =
dw_Status | (1UL << ((8 * (b_SelectedPort %
4)) + b_OutputChannel));
}
/***************************/
/* Test if setting port ON */
/***************************/
if (b_Command == APCI16XX_TTL_WRITEPORT_ON) {
dw_Status =
dw_Status | ((data[1] & 0xFF) << (8 *
(b_SelectedPort % 4)));
}
/*******************************/
/* Test if setting channel OFF */
/*******************************/
if (b_Command == APCI16XX_TTL_WRITECHANNEL_OFF) {
dw_Status =
dw_Status & (0xFFFFFFFFUL -
(1UL << ((8 * (b_SelectedPort % 4)) +
b_OutputChannel)));
}
/****************************/
/* Test if setting port OFF */
/****************************/
if (b_Command == APCI16XX_TTL_WRITEPORT_OFF) {
dw_Status =
dw_Status & (0xFFFFFFFFUL -
((data[1] & 0xFF) << (8 * (b_SelectedPort %
4))));
}
outl(dw_Status,
devpriv->iobase + 20 + ((b_SelectedPort / 4) * 4));
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI2200_Reset(struct comedi_device *dev) | +----------------------------------------------------------------------------+
| Task :resets all the registers |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev |
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value : - |
+----------------------------------------------------------------------------+
*/
int i_APCI16XX_Reset(struct comedi_device *dev)
{
return 0;
}
| gpl-2.0 |
v-superuser/android_kernel_htc_a5 | net/sctp/ulpqueue.c | 8013 | 28422 | /* SCTP kernel implementation
* (C) Copyright IBM Corp. 2001, 2004
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2001 Intel Corp.
* Copyright (c) 2001 Nokia, Inc.
* Copyright (c) 2001 La Monte H.P. Yarroll
*
* This abstraction carries sctp events to the ULP (sockets).
*
* This SCTP implementation 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 SCTP implementation 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 GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* Jon Grimm <jgrimm@us.ibm.com>
* La Monte H.P. Yarroll <piggy@acm.org>
* Sridhar Samudrala <sri@us.ibm.com>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/sctp/structs.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
/* Forward declarations for internal helpers. */
static struct sctp_ulpevent * sctp_ulpq_reasm(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *);
static struct sctp_ulpevent * sctp_ulpq_order(struct sctp_ulpq *,
struct sctp_ulpevent *);
static void sctp_ulpq_reasm_drain(struct sctp_ulpq *ulpq);
/* 1st Level Abstractions */
/* Initialize a ULP queue from a block of memory. */
struct sctp_ulpq *sctp_ulpq_init(struct sctp_ulpq *ulpq,
struct sctp_association *asoc)
{
memset(ulpq, 0, sizeof(struct sctp_ulpq));
ulpq->asoc = asoc;
skb_queue_head_init(&ulpq->reasm);
skb_queue_head_init(&ulpq->lobby);
ulpq->pd_mode = 0;
ulpq->malloced = 0;
return ulpq;
}
/* Flush the reassembly and ordering queues. */
void sctp_ulpq_flush(struct sctp_ulpq *ulpq)
{
struct sk_buff *skb;
struct sctp_ulpevent *event;
while ((skb = __skb_dequeue(&ulpq->lobby)) != NULL) {
event = sctp_skb2event(skb);
sctp_ulpevent_free(event);
}
while ((skb = __skb_dequeue(&ulpq->reasm)) != NULL) {
event = sctp_skb2event(skb);
sctp_ulpevent_free(event);
}
}
/* Dispose of a ulpqueue. */
void sctp_ulpq_free(struct sctp_ulpq *ulpq)
{
sctp_ulpq_flush(ulpq);
if (ulpq->malloced)
kfree(ulpq);
}
/* Process an incoming DATA chunk. */
int sctp_ulpq_tail_data(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sk_buff_head temp;
struct sctp_ulpevent *event;
/* Create an event from the incoming chunk. */
event = sctp_ulpevent_make_rcvmsg(chunk->asoc, chunk, gfp);
if (!event)
return -ENOMEM;
/* Do reassembly if needed. */
event = sctp_ulpq_reasm(ulpq, event);
/* Do ordering if needed. */
if ((event) && (event->msg_flags & MSG_EOR)){
/* Create a temporary list to collect chunks on. */
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
event = sctp_ulpq_order(ulpq, event);
}
/* Send event to the ULP. 'event' is the sctp_ulpevent for
* very first SKB on the 'temp' list.
*/
if (event)
sctp_ulpq_tail_event(ulpq, event);
return 0;
}
/* Add a new event for propagation to the ULP. */
/* Clear the partial delivery mode for this socket. Note: This
* assumes that no association is currently in partial delivery mode.
*/
int sctp_clear_pd(struct sock *sk, struct sctp_association *asoc)
{
struct sctp_sock *sp = sctp_sk(sk);
if (atomic_dec_and_test(&sp->pd_mode)) {
/* This means there are no other associations in PD, so
* we can go ahead and clear out the lobby in one shot
*/
if (!skb_queue_empty(&sp->pd_lobby)) {
struct list_head *list;
sctp_skb_list_tail(&sp->pd_lobby, &sk->sk_receive_queue);
list = (struct list_head *)&sctp_sk(sk)->pd_lobby;
INIT_LIST_HEAD(list);
return 1;
}
} else {
/* There are other associations in PD, so we only need to
* pull stuff out of the lobby that belongs to the
* associations that is exiting PD (all of its notifications
* are posted here).
*/
if (!skb_queue_empty(&sp->pd_lobby) && asoc) {
struct sk_buff *skb, *tmp;
struct sctp_ulpevent *event;
sctp_skb_for_each(skb, &sp->pd_lobby, tmp) {
event = sctp_skb2event(skb);
if (event->asoc == asoc) {
__skb_unlink(skb, &sp->pd_lobby);
__skb_queue_tail(&sk->sk_receive_queue,
skb);
}
}
}
}
return 0;
}
/* Set the pd_mode on the socket and ulpq */
static void sctp_ulpq_set_pd(struct sctp_ulpq *ulpq)
{
struct sctp_sock *sp = sctp_sk(ulpq->asoc->base.sk);
atomic_inc(&sp->pd_mode);
ulpq->pd_mode = 1;
}
/* Clear the pd_mode and restart any pending messages waiting for delivery. */
static int sctp_ulpq_clear_pd(struct sctp_ulpq *ulpq)
{
ulpq->pd_mode = 0;
sctp_ulpq_reasm_drain(ulpq);
return sctp_clear_pd(ulpq->asoc->base.sk, ulpq->asoc);
}
/* If the SKB of 'event' is on a list, it is the first such member
* of that list.
*/
int sctp_ulpq_tail_event(struct sctp_ulpq *ulpq, struct sctp_ulpevent *event)
{
struct sock *sk = ulpq->asoc->base.sk;
struct sk_buff_head *queue, *skb_list;
struct sk_buff *skb = sctp_event2skb(event);
int clear_pd = 0;
skb_list = (struct sk_buff_head *) skb->prev;
/* If the socket is just going to throw this away, do not
* even try to deliver it.
*/
if (sock_flag(sk, SOCK_DEAD) || (sk->sk_shutdown & RCV_SHUTDOWN))
goto out_free;
/* Check if the user wishes to receive this event. */
if (!sctp_ulpevent_is_enabled(event, &sctp_sk(sk)->subscribe))
goto out_free;
/* If we are in partial delivery mode, post to the lobby until
* partial delivery is cleared, unless, of course _this_ is
* the association the cause of the partial delivery.
*/
if (atomic_read(&sctp_sk(sk)->pd_mode) == 0) {
queue = &sk->sk_receive_queue;
} else {
if (ulpq->pd_mode) {
/* If the association is in partial delivery, we
* need to finish delivering the partially processed
* packet before passing any other data. This is
* because we don't truly support stream interleaving.
*/
if ((event->msg_flags & MSG_NOTIFICATION) ||
(SCTP_DATA_NOT_FRAG ==
(event->msg_flags & SCTP_DATA_FRAG_MASK)))
queue = &sctp_sk(sk)->pd_lobby;
else {
clear_pd = event->msg_flags & MSG_EOR;
queue = &sk->sk_receive_queue;
}
} else {
/*
* If fragment interleave is enabled, we
* can queue this to the receive queue instead
* of the lobby.
*/
if (sctp_sk(sk)->frag_interleave)
queue = &sk->sk_receive_queue;
else
queue = &sctp_sk(sk)->pd_lobby;
}
}
/* If we are harvesting multiple skbs they will be
* collected on a list.
*/
if (skb_list)
sctp_skb_list_tail(skb_list, queue);
else
__skb_queue_tail(queue, skb);
/* Did we just complete partial delivery and need to get
* rolling again? Move pending data to the receive
* queue.
*/
if (clear_pd)
sctp_ulpq_clear_pd(ulpq);
if (queue == &sk->sk_receive_queue)
sk->sk_data_ready(sk, 0);
return 1;
out_free:
if (skb_list)
sctp_queue_purge_ulpevents(skb_list);
else
sctp_ulpevent_free(event);
return 0;
}
/* 2nd Level Abstractions */
/* Helper function to store chunks that need to be reassembled. */
static void sctp_ulpq_store_reasm(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff *pos;
struct sctp_ulpevent *cevent;
__u32 tsn, ctsn;
tsn = event->tsn;
/* See if it belongs at the end. */
pos = skb_peek_tail(&ulpq->reasm);
if (!pos) {
__skb_queue_tail(&ulpq->reasm, sctp_event2skb(event));
return;
}
/* Short circuit just dropping it at the end. */
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
if (TSN_lt(ctsn, tsn)) {
__skb_queue_tail(&ulpq->reasm, sctp_event2skb(event));
return;
}
/* Find the right place in this list. We store them by TSN. */
skb_queue_walk(&ulpq->reasm, pos) {
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
if (TSN_lt(tsn, ctsn))
break;
}
/* Insert before pos. */
__skb_queue_before(&ulpq->reasm, pos, sctp_event2skb(event));
}
/* Helper function to return an event corresponding to the reassembled
* datagram.
* This routine creates a re-assembled skb given the first and last skb's
* as stored in the reassembly queue. The skb's may be non-linear if the sctp
* payload was fragmented on the way and ip had to reassemble them.
* We add the rest of skb's to the first skb's fraglist.
*/
static struct sctp_ulpevent *sctp_make_reassembled_event(struct sk_buff_head *queue, struct sk_buff *f_frag, struct sk_buff *l_frag)
{
struct sk_buff *pos;
struct sk_buff *new = NULL;
struct sctp_ulpevent *event;
struct sk_buff *pnext, *last;
struct sk_buff *list = skb_shinfo(f_frag)->frag_list;
/* Store the pointer to the 2nd skb */
if (f_frag == l_frag)
pos = NULL;
else
pos = f_frag->next;
/* Get the last skb in the f_frag's frag_list if present. */
for (last = list; list; last = list, list = list->next);
/* Add the list of remaining fragments to the first fragments
* frag_list.
*/
if (last)
last->next = pos;
else {
if (skb_cloned(f_frag)) {
/* This is a cloned skb, we can't just modify
* the frag_list. We need a new skb to do that.
* Instead of calling skb_unshare(), we'll do it
* ourselves since we need to delay the free.
*/
new = skb_copy(f_frag, GFP_ATOMIC);
if (!new)
return NULL; /* try again later */
sctp_skb_set_owner_r(new, f_frag->sk);
skb_shinfo(new)->frag_list = pos;
} else
skb_shinfo(f_frag)->frag_list = pos;
}
/* Remove the first fragment from the reassembly queue. */
__skb_unlink(f_frag, queue);
/* if we did unshare, then free the old skb and re-assign */
if (new) {
kfree_skb(f_frag);
f_frag = new;
}
while (pos) {
pnext = pos->next;
/* Update the len and data_len fields of the first fragment. */
f_frag->len += pos->len;
f_frag->data_len += pos->len;
/* Remove the fragment from the reassembly queue. */
__skb_unlink(pos, queue);
/* Break if we have reached the last fragment. */
if (pos == l_frag)
break;
pos->next = pnext;
pos = pnext;
}
event = sctp_skb2event(f_frag);
SCTP_INC_STATS(SCTP_MIB_REASMUSRMSGS);
return event;
}
/* Helper function to check if an incoming chunk has filled up the last
* missing fragment in a SCTP datagram and return the corresponding event.
*/
static struct sctp_ulpevent *sctp_ulpq_retrieve_reassembled(struct sctp_ulpq *ulpq)
{
struct sk_buff *pos;
struct sctp_ulpevent *cevent;
struct sk_buff *first_frag = NULL;
__u32 ctsn, next_tsn;
struct sctp_ulpevent *retval = NULL;
struct sk_buff *pd_first = NULL;
struct sk_buff *pd_last = NULL;
size_t pd_len = 0;
struct sctp_association *asoc;
u32 pd_point;
/* Initialized to 0 just to avoid compiler warning message. Will
* never be used with this value. It is referenced only after it
* is set when we find the first fragment of a message.
*/
next_tsn = 0;
/* The chunks are held in the reasm queue sorted by TSN.
* Walk through the queue sequentially and look for a sequence of
* fragmented chunks that complete a datagram.
* 'first_frag' and next_tsn are reset when we find a chunk which
* is the first fragment of a datagram. Once these 2 fields are set
* we expect to find the remaining middle fragments and the last
* fragment in order. If not, first_frag is reset to NULL and we
* start the next pass when we find another first fragment.
*
* There is a potential to do partial delivery if user sets
* SCTP_PARTIAL_DELIVERY_POINT option. Lets count some things here
* to see if can do PD.
*/
skb_queue_walk(&ulpq->reasm, pos) {
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
/* If this "FIRST_FRAG" is the first
* element in the queue, then count it towards
* possible PD.
*/
if (pos == ulpq->reasm.next) {
pd_first = pos;
pd_last = pos;
pd_len = pos->len;
} else {
pd_first = NULL;
pd_last = NULL;
pd_len = 0;
}
first_frag = pos;
next_tsn = ctsn + 1;
break;
case SCTP_DATA_MIDDLE_FRAG:
if ((first_frag) && (ctsn == next_tsn)) {
next_tsn++;
if (pd_first) {
pd_last = pos;
pd_len += pos->len;
}
} else
first_frag = NULL;
break;
case SCTP_DATA_LAST_FRAG:
if (first_frag && (ctsn == next_tsn))
goto found;
else
first_frag = NULL;
break;
}
}
asoc = ulpq->asoc;
if (pd_first) {
/* Make sure we can enter partial deliver.
* We can trigger partial delivery only if framgent
* interleave is set, or the socket is not already
* in partial delivery.
*/
if (!sctp_sk(asoc->base.sk)->frag_interleave &&
atomic_read(&sctp_sk(asoc->base.sk)->pd_mode))
goto done;
cevent = sctp_skb2event(pd_first);
pd_point = sctp_sk(asoc->base.sk)->pd_point;
if (pd_point && pd_point <= pd_len) {
retval = sctp_make_reassembled_event(&ulpq->reasm,
pd_first,
pd_last);
if (retval)
sctp_ulpq_set_pd(ulpq);
}
}
done:
return retval;
found:
retval = sctp_make_reassembled_event(&ulpq->reasm, first_frag, pos);
if (retval)
retval->msg_flags |= MSG_EOR;
goto done;
}
/* Retrieve the next set of fragments of a partial message. */
static struct sctp_ulpevent *sctp_ulpq_retrieve_partial(struct sctp_ulpq *ulpq)
{
struct sk_buff *pos, *last_frag, *first_frag;
struct sctp_ulpevent *cevent;
__u32 ctsn, next_tsn;
int is_last;
struct sctp_ulpevent *retval;
/* The chunks are held in the reasm queue sorted by TSN.
* Walk through the queue sequentially and look for the first
* sequence of fragmented chunks.
*/
if (skb_queue_empty(&ulpq->reasm))
return NULL;
last_frag = first_frag = NULL;
retval = NULL;
next_tsn = 0;
is_last = 0;
skb_queue_walk(&ulpq->reasm, pos) {
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_MIDDLE_FRAG:
if (!first_frag) {
first_frag = pos;
next_tsn = ctsn + 1;
last_frag = pos;
} else if (next_tsn == ctsn)
next_tsn++;
else
goto done;
break;
case SCTP_DATA_LAST_FRAG:
if (!first_frag)
first_frag = pos;
else if (ctsn != next_tsn)
goto done;
last_frag = pos;
is_last = 1;
goto done;
default:
return NULL;
}
}
/* We have the reassembled event. There is no need to look
* further.
*/
done:
retval = sctp_make_reassembled_event(&ulpq->reasm, first_frag, last_frag);
if (retval && is_last)
retval->msg_flags |= MSG_EOR;
return retval;
}
/* Helper function to reassemble chunks. Hold chunks on the reasm queue that
* need reassembling.
*/
static struct sctp_ulpevent *sctp_ulpq_reasm(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sctp_ulpevent *retval = NULL;
/* Check if this is part of a fragmented message. */
if (SCTP_DATA_NOT_FRAG == (event->msg_flags & SCTP_DATA_FRAG_MASK)) {
event->msg_flags |= MSG_EOR;
return event;
}
sctp_ulpq_store_reasm(ulpq, event);
if (!ulpq->pd_mode)
retval = sctp_ulpq_retrieve_reassembled(ulpq);
else {
__u32 ctsn, ctsnap;
/* Do not even bother unless this is the next tsn to
* be delivered.
*/
ctsn = event->tsn;
ctsnap = sctp_tsnmap_get_ctsn(&ulpq->asoc->peer.tsn_map);
if (TSN_lte(ctsn, ctsnap))
retval = sctp_ulpq_retrieve_partial(ulpq);
}
return retval;
}
/* Retrieve the first part (sequential fragments) for partial delivery. */
static struct sctp_ulpevent *sctp_ulpq_retrieve_first(struct sctp_ulpq *ulpq)
{
struct sk_buff *pos, *last_frag, *first_frag;
struct sctp_ulpevent *cevent;
__u32 ctsn, next_tsn;
struct sctp_ulpevent *retval;
/* The chunks are held in the reasm queue sorted by TSN.
* Walk through the queue sequentially and look for a sequence of
* fragmented chunks that start a datagram.
*/
if (skb_queue_empty(&ulpq->reasm))
return NULL;
last_frag = first_frag = NULL;
retval = NULL;
next_tsn = 0;
skb_queue_walk(&ulpq->reasm, pos) {
cevent = sctp_skb2event(pos);
ctsn = cevent->tsn;
switch (cevent->msg_flags & SCTP_DATA_FRAG_MASK) {
case SCTP_DATA_FIRST_FRAG:
if (!first_frag) {
first_frag = pos;
next_tsn = ctsn + 1;
last_frag = pos;
} else
goto done;
break;
case SCTP_DATA_MIDDLE_FRAG:
if (!first_frag)
return NULL;
if (ctsn == next_tsn) {
next_tsn++;
last_frag = pos;
} else
goto done;
break;
default:
return NULL;
}
}
/* We have the reassembled event. There is no need to look
* further.
*/
done:
retval = sctp_make_reassembled_event(&ulpq->reasm, first_frag, last_frag);
return retval;
}
/*
* Flush out stale fragments from the reassembly queue when processing
* a Forward TSN.
*
* RFC 3758, Section 3.6
*
* After receiving and processing a FORWARD TSN, the data receiver MUST
* take cautions in updating its re-assembly queue. The receiver MUST
* remove any partially reassembled message, which is still missing one
* or more TSNs earlier than or equal to the new cumulative TSN point.
* In the event that the receiver has invoked the partial delivery API,
* a notification SHOULD also be generated to inform the upper layer API
* that the message being partially delivered will NOT be completed.
*/
void sctp_ulpq_reasm_flushtsn(struct sctp_ulpq *ulpq, __u32 fwd_tsn)
{
struct sk_buff *pos, *tmp;
struct sctp_ulpevent *event;
__u32 tsn;
if (skb_queue_empty(&ulpq->reasm))
return;
skb_queue_walk_safe(&ulpq->reasm, pos, tmp) {
event = sctp_skb2event(pos);
tsn = event->tsn;
/* Since the entire message must be abandoned by the
* sender (item A3 in Section 3.5, RFC 3758), we can
* free all fragments on the list that are less then
* or equal to ctsn_point
*/
if (TSN_lte(tsn, fwd_tsn)) {
__skb_unlink(pos, &ulpq->reasm);
sctp_ulpevent_free(event);
} else
break;
}
}
/*
* Drain the reassembly queue. If we just cleared parted delivery, it
* is possible that the reassembly queue will contain already reassembled
* messages. Retrieve any such messages and give them to the user.
*/
static void sctp_ulpq_reasm_drain(struct sctp_ulpq *ulpq)
{
struct sctp_ulpevent *event = NULL;
struct sk_buff_head temp;
if (skb_queue_empty(&ulpq->reasm))
return;
while ((event = sctp_ulpq_retrieve_reassembled(ulpq)) != NULL) {
/* Do ordering if needed. */
if ((event) && (event->msg_flags & MSG_EOR)){
skb_queue_head_init(&temp);
__skb_queue_tail(&temp, sctp_event2skb(event));
event = sctp_ulpq_order(ulpq, event);
}
/* Send event to the ULP. 'event' is the
* sctp_ulpevent for very first SKB on the temp' list.
*/
if (event)
sctp_ulpq_tail_event(ulpq, event);
}
}
/* Helper function to gather skbs that have possibly become
* ordered by an an incoming chunk.
*/
static void sctp_ulpq_retrieve_ordered(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff_head *event_list;
struct sk_buff *pos, *tmp;
struct sctp_ulpevent *cevent;
struct sctp_stream *in;
__u16 sid, csid, cssn;
sid = event->stream;
in = &ulpq->asoc->ssnmap->in;
event_list = (struct sk_buff_head *) sctp_event2skb(event)->prev;
/* We are holding the chunks by stream, by SSN. */
sctp_skb_for_each(pos, &ulpq->lobby, tmp) {
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
/* Have we gone too far? */
if (csid > sid)
break;
/* Have we not gone far enough? */
if (csid < sid)
continue;
if (cssn != sctp_ssn_peek(in, sid))
break;
/* Found it, so mark in the ssnmap. */
sctp_ssn_next(in, sid);
__skb_unlink(pos, &ulpq->lobby);
/* Attach all gathered skbs to the event. */
__skb_queue_tail(event_list, pos);
}
}
/* Helper function to store chunks needing ordering. */
static void sctp_ulpq_store_ordered(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
struct sk_buff *pos;
struct sctp_ulpevent *cevent;
__u16 sid, csid;
__u16 ssn, cssn;
pos = skb_peek_tail(&ulpq->lobby);
if (!pos) {
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
return;
}
sid = event->stream;
ssn = event->ssn;
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
if (sid > csid) {
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
return;
}
if ((sid == csid) && SSN_lt(cssn, ssn)) {
__skb_queue_tail(&ulpq->lobby, sctp_event2skb(event));
return;
}
/* Find the right place in this list. We store them by
* stream ID and then by SSN.
*/
skb_queue_walk(&ulpq->lobby, pos) {
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
if (csid > sid)
break;
if (csid == sid && SSN_lt(ssn, cssn))
break;
}
/* Insert before pos. */
__skb_queue_before(&ulpq->lobby, pos, sctp_event2skb(event));
}
static struct sctp_ulpevent *sctp_ulpq_order(struct sctp_ulpq *ulpq,
struct sctp_ulpevent *event)
{
__u16 sid, ssn;
struct sctp_stream *in;
/* Check if this message needs ordering. */
if (SCTP_DATA_UNORDERED & event->msg_flags)
return event;
/* Note: The stream ID must be verified before this routine. */
sid = event->stream;
ssn = event->ssn;
in = &ulpq->asoc->ssnmap->in;
/* Is this the expected SSN for this stream ID? */
if (ssn != sctp_ssn_peek(in, sid)) {
/* We've received something out of order, so find where it
* needs to be placed. We order by stream and then by SSN.
*/
sctp_ulpq_store_ordered(ulpq, event);
return NULL;
}
/* Mark that the next chunk has been found. */
sctp_ssn_next(in, sid);
/* Go find any other chunks that were waiting for
* ordering.
*/
sctp_ulpq_retrieve_ordered(ulpq, event);
return event;
}
/* Helper function to gather skbs that have possibly become
* ordered by forward tsn skipping their dependencies.
*/
static void sctp_ulpq_reap_ordered(struct sctp_ulpq *ulpq, __u16 sid)
{
struct sk_buff *pos, *tmp;
struct sctp_ulpevent *cevent;
struct sctp_ulpevent *event;
struct sctp_stream *in;
struct sk_buff_head temp;
struct sk_buff_head *lobby = &ulpq->lobby;
__u16 csid, cssn;
in = &ulpq->asoc->ssnmap->in;
/* We are holding the chunks by stream, by SSN. */
skb_queue_head_init(&temp);
event = NULL;
sctp_skb_for_each(pos, lobby, tmp) {
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
/* Have we gone too far? */
if (csid > sid)
break;
/* Have we not gone far enough? */
if (csid < sid)
continue;
/* see if this ssn has been marked by skipping */
if (!SSN_lt(cssn, sctp_ssn_peek(in, csid)))
break;
__skb_unlink(pos, lobby);
if (!event)
/* Create a temporary list to collect chunks on. */
event = sctp_skb2event(pos);
/* Attach all gathered skbs to the event. */
__skb_queue_tail(&temp, pos);
}
/* If we didn't reap any data, see if the next expected SSN
* is next on the queue and if so, use that.
*/
if (event == NULL && pos != (struct sk_buff *)lobby) {
cevent = (struct sctp_ulpevent *) pos->cb;
csid = cevent->stream;
cssn = cevent->ssn;
if (csid == sid && cssn == sctp_ssn_peek(in, csid)) {
sctp_ssn_next(in, csid);
__skb_unlink(pos, lobby);
__skb_queue_tail(&temp, pos);
event = sctp_skb2event(pos);
}
}
/* Send event to the ULP. 'event' is the sctp_ulpevent for
* very first SKB on the 'temp' list.
*/
if (event) {
/* see if we have more ordered that we can deliver */
sctp_ulpq_retrieve_ordered(ulpq, event);
sctp_ulpq_tail_event(ulpq, event);
}
}
/* Skip over an SSN. This is used during the processing of
* Forwared TSN chunk to skip over the abandoned ordered data
*/
void sctp_ulpq_skip(struct sctp_ulpq *ulpq, __u16 sid, __u16 ssn)
{
struct sctp_stream *in;
/* Note: The stream ID must be verified before this routine. */
in = &ulpq->asoc->ssnmap->in;
/* Is this an old SSN? If so ignore. */
if (SSN_lt(ssn, sctp_ssn_peek(in, sid)))
return;
/* Mark that we are no longer expecting this SSN or lower. */
sctp_ssn_skip(in, sid, ssn);
/* Go find any other chunks that were waiting for
* ordering and deliver them if needed.
*/
sctp_ulpq_reap_ordered(ulpq, sid);
}
static __u16 sctp_ulpq_renege_list(struct sctp_ulpq *ulpq,
struct sk_buff_head *list, __u16 needed)
{
__u16 freed = 0;
__u32 tsn;
struct sk_buff *skb;
struct sctp_ulpevent *event;
struct sctp_tsnmap *tsnmap;
tsnmap = &ulpq->asoc->peer.tsn_map;
while ((skb = __skb_dequeue_tail(list)) != NULL) {
freed += skb_headlen(skb);
event = sctp_skb2event(skb);
tsn = event->tsn;
sctp_ulpevent_free(event);
sctp_tsnmap_renege(tsnmap, tsn);
if (freed >= needed)
return freed;
}
return freed;
}
/* Renege 'needed' bytes from the ordering queue. */
static __u16 sctp_ulpq_renege_order(struct sctp_ulpq *ulpq, __u16 needed)
{
return sctp_ulpq_renege_list(ulpq, &ulpq->lobby, needed);
}
/* Renege 'needed' bytes from the reassembly queue. */
static __u16 sctp_ulpq_renege_frags(struct sctp_ulpq *ulpq, __u16 needed)
{
return sctp_ulpq_renege_list(ulpq, &ulpq->reasm, needed);
}
/* Partial deliver the first message as there is pressure on rwnd. */
void sctp_ulpq_partial_delivery(struct sctp_ulpq *ulpq,
struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sctp_ulpevent *event;
struct sctp_association *asoc;
struct sctp_sock *sp;
asoc = ulpq->asoc;
sp = sctp_sk(asoc->base.sk);
/* If the association is already in Partial Delivery mode
* we have noting to do.
*/
if (ulpq->pd_mode)
return;
/* If the user enabled fragment interleave socket option,
* multiple associations can enter partial delivery.
* Otherwise, we can only enter partial delivery if the
* socket is not in partial deliver mode.
*/
if (sp->frag_interleave || atomic_read(&sp->pd_mode) == 0) {
/* Is partial delivery possible? */
event = sctp_ulpq_retrieve_first(ulpq);
/* Send event to the ULP. */
if (event) {
sctp_ulpq_tail_event(ulpq, event);
sctp_ulpq_set_pd(ulpq);
return;
}
}
}
/* Renege some packets to make room for an incoming chunk. */
void sctp_ulpq_renege(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk,
gfp_t gfp)
{
struct sctp_association *asoc;
__u16 needed, freed;
asoc = ulpq->asoc;
if (chunk) {
needed = ntohs(chunk->chunk_hdr->length);
needed -= sizeof(sctp_data_chunk_t);
} else
needed = SCTP_DEFAULT_MAXWINDOW;
freed = 0;
if (skb_queue_empty(&asoc->base.sk->sk_receive_queue)) {
freed = sctp_ulpq_renege_order(ulpq, needed);
if (freed < needed) {
freed += sctp_ulpq_renege_frags(ulpq, needed - freed);
}
}
/* If able to free enough room, accept this chunk. */
if (chunk && (freed >= needed)) {
__u32 tsn;
tsn = ntohl(chunk->subh.data_hdr->tsn);
sctp_tsnmap_mark(&asoc->peer.tsn_map, tsn);
sctp_ulpq_tail_data(ulpq, chunk, gfp);
sctp_ulpq_partial_delivery(ulpq, chunk, gfp);
}
sk_mem_reclaim(asoc->base.sk);
}
/* Notify the application if an association is aborted and in
* partial delivery mode. Send up any pending received messages.
*/
void sctp_ulpq_abort_pd(struct sctp_ulpq *ulpq, gfp_t gfp)
{
struct sctp_ulpevent *ev = NULL;
struct sock *sk;
if (!ulpq->pd_mode)
return;
sk = ulpq->asoc->base.sk;
if (sctp_ulpevent_type_enabled(SCTP_PARTIAL_DELIVERY_EVENT,
&sctp_sk(sk)->subscribe))
ev = sctp_ulpevent_make_pdapi(ulpq->asoc,
SCTP_PARTIAL_DELIVERY_ABORTED,
gfp);
if (ev)
__skb_queue_tail(&sk->sk_receive_queue, sctp_event2skb(ev));
/* If there is data waiting, send it up the socket now. */
if (sctp_ulpq_clear_pd(ulpq) || ev)
sk->sk_data_ready(sk, 0);
}
| gpl-2.0 |
Keeperv85/Blade_G_kernel | sound/pci/ice1712/delta.c | 8269 | 25303 | /*
* ALSA driver for ICEnsemble ICE1712 (Envy24)
*
* Lowlevel functions for M-Audio Delta 1010, 1010E, 44, 66, 66E, Dio2496,
* Audiophile, Digigram VX442
*
* Copyright (c) 2000 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 <asm/io.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/cs8427.h>
#include <sound/asoundef.h>
#include "ice1712.h"
#include "delta.h"
#define SND_CS8403
#include <sound/cs8403.h>
/*
* CS8427 via SPI mode (for Audiophile), emulated I2C
*/
/* send 8 bits */
static void ap_cs8427_write_byte(struct snd_ice1712 *ice, unsigned char data, unsigned char tmp)
{
int idx;
for (idx = 7; idx >= 0; idx--) {
tmp &= ~(ICE1712_DELTA_AP_DOUT|ICE1712_DELTA_AP_CCLK);
if (data & (1 << idx))
tmp |= ICE1712_DELTA_AP_DOUT;
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
udelay(5);
tmp |= ICE1712_DELTA_AP_CCLK;
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
udelay(5);
}
}
/* read 8 bits */
static unsigned char ap_cs8427_read_byte(struct snd_ice1712 *ice, unsigned char tmp)
{
unsigned char data = 0;
int idx;
for (idx = 7; idx >= 0; idx--) {
tmp &= ~ICE1712_DELTA_AP_CCLK;
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
udelay(5);
if (snd_ice1712_read(ice, ICE1712_IREG_GPIO_DATA) & ICE1712_DELTA_AP_DIN)
data |= 1 << idx;
tmp |= ICE1712_DELTA_AP_CCLK;
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
udelay(5);
}
return data;
}
/* assert chip select */
static unsigned char ap_cs8427_codec_select(struct snd_ice1712 *ice)
{
unsigned char tmp;
tmp = snd_ice1712_read(ice, ICE1712_IREG_GPIO_DATA);
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_DELTA1010E:
case ICE1712_SUBDEVICE_DELTA1010LT:
tmp &= ~ICE1712_DELTA_1010LT_CS;
tmp |= ICE1712_DELTA_1010LT_CCLK | ICE1712_DELTA_1010LT_CS_CS8427;
break;
case ICE1712_SUBDEVICE_AUDIOPHILE:
case ICE1712_SUBDEVICE_DELTA410:
tmp |= ICE1712_DELTA_AP_CCLK | ICE1712_DELTA_AP_CS_CODEC;
tmp &= ~ICE1712_DELTA_AP_CS_DIGITAL;
break;
case ICE1712_SUBDEVICE_DELTA66E:
tmp |= ICE1712_DELTA_66E_CCLK | ICE1712_DELTA_66E_CS_CHIP_A |
ICE1712_DELTA_66E_CS_CHIP_B;
tmp &= ~ICE1712_DELTA_66E_CS_CS8427;
break;
case ICE1712_SUBDEVICE_VX442:
tmp |= ICE1712_VX442_CCLK | ICE1712_VX442_CODEC_CHIP_A | ICE1712_VX442_CODEC_CHIP_B;
tmp &= ~ICE1712_VX442_CS_DIGITAL;
break;
}
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
udelay(5);
return tmp;
}
/* deassert chip select */
static void ap_cs8427_codec_deassert(struct snd_ice1712 *ice, unsigned char tmp)
{
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_DELTA1010E:
case ICE1712_SUBDEVICE_DELTA1010LT:
tmp &= ~ICE1712_DELTA_1010LT_CS;
tmp |= ICE1712_DELTA_1010LT_CS_NONE;
break;
case ICE1712_SUBDEVICE_AUDIOPHILE:
case ICE1712_SUBDEVICE_DELTA410:
tmp |= ICE1712_DELTA_AP_CS_DIGITAL;
break;
case ICE1712_SUBDEVICE_DELTA66E:
tmp |= ICE1712_DELTA_66E_CS_CS8427;
break;
case ICE1712_SUBDEVICE_VX442:
tmp |= ICE1712_VX442_CS_DIGITAL;
break;
}
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
}
/* sequential write */
static int ap_cs8427_sendbytes(struct snd_i2c_device *device, unsigned char *bytes, int count)
{
struct snd_ice1712 *ice = device->bus->private_data;
int res = count;
unsigned char tmp;
mutex_lock(&ice->gpio_mutex);
tmp = ap_cs8427_codec_select(ice);
ap_cs8427_write_byte(ice, (device->addr << 1) | 0, tmp); /* address + write mode */
while (count-- > 0)
ap_cs8427_write_byte(ice, *bytes++, tmp);
ap_cs8427_codec_deassert(ice, tmp);
mutex_unlock(&ice->gpio_mutex);
return res;
}
/* sequential read */
static int ap_cs8427_readbytes(struct snd_i2c_device *device, unsigned char *bytes, int count)
{
struct snd_ice1712 *ice = device->bus->private_data;
int res = count;
unsigned char tmp;
mutex_lock(&ice->gpio_mutex);
tmp = ap_cs8427_codec_select(ice);
ap_cs8427_write_byte(ice, (device->addr << 1) | 1, tmp); /* address + read mode */
while (count-- > 0)
*bytes++ = ap_cs8427_read_byte(ice, tmp);
ap_cs8427_codec_deassert(ice, tmp);
mutex_unlock(&ice->gpio_mutex);
return res;
}
static int ap_cs8427_probeaddr(struct snd_i2c_bus *bus, unsigned short addr)
{
if (addr == 0x10)
return 1;
return -ENOENT;
}
static struct snd_i2c_ops ap_cs8427_i2c_ops = {
.sendbytes = ap_cs8427_sendbytes,
.readbytes = ap_cs8427_readbytes,
.probeaddr = ap_cs8427_probeaddr,
};
/*
*/
static void snd_ice1712_delta_cs8403_spdif_write(struct snd_ice1712 *ice, unsigned char bits)
{
unsigned char tmp, mask1, mask2;
int idx;
/* send byte to transmitter */
mask1 = ICE1712_DELTA_SPDIF_OUT_STAT_CLOCK;
mask2 = ICE1712_DELTA_SPDIF_OUT_STAT_DATA;
mutex_lock(&ice->gpio_mutex);
tmp = snd_ice1712_read(ice, ICE1712_IREG_GPIO_DATA);
for (idx = 7; idx >= 0; idx--) {
tmp &= ~(mask1 | mask2);
if (bits & (1 << idx))
tmp |= mask2;
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
udelay(100);
tmp |= mask1;
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
udelay(100);
}
tmp &= ~mask1;
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
mutex_unlock(&ice->gpio_mutex);
}
static void delta_spdif_default_get(struct snd_ice1712 *ice, struct snd_ctl_elem_value *ucontrol)
{
snd_cs8403_decode_spdif_bits(&ucontrol->value.iec958, ice->spdif.cs8403_bits);
}
static int delta_spdif_default_put(struct snd_ice1712 *ice, struct snd_ctl_elem_value *ucontrol)
{
unsigned int val;
int change;
val = snd_cs8403_encode_spdif_bits(&ucontrol->value.iec958);
spin_lock_irq(&ice->reg_lock);
change = ice->spdif.cs8403_bits != val;
ice->spdif.cs8403_bits = val;
if (change && ice->playback_pro_substream == NULL) {
spin_unlock_irq(&ice->reg_lock);
snd_ice1712_delta_cs8403_spdif_write(ice, val);
} else {
spin_unlock_irq(&ice->reg_lock);
}
return change;
}
static void delta_spdif_stream_get(struct snd_ice1712 *ice, struct snd_ctl_elem_value *ucontrol)
{
snd_cs8403_decode_spdif_bits(&ucontrol->value.iec958, ice->spdif.cs8403_stream_bits);
}
static int delta_spdif_stream_put(struct snd_ice1712 *ice, struct snd_ctl_elem_value *ucontrol)
{
unsigned int val;
int change;
val = snd_cs8403_encode_spdif_bits(&ucontrol->value.iec958);
spin_lock_irq(&ice->reg_lock);
change = ice->spdif.cs8403_stream_bits != val;
ice->spdif.cs8403_stream_bits = val;
if (change && ice->playback_pro_substream != NULL) {
spin_unlock_irq(&ice->reg_lock);
snd_ice1712_delta_cs8403_spdif_write(ice, val);
} else {
spin_unlock_irq(&ice->reg_lock);
}
return change;
}
/*
* AK4524 on Delta 44 and 66 to choose the chip mask
*/
static void delta_ak4524_lock(struct snd_akm4xxx *ak, int chip)
{
struct snd_ak4xxx_private *priv = (void *)ak->private_value[0];
struct snd_ice1712 *ice = ak->private_data[0];
snd_ice1712_save_gpio_status(ice);
priv->cs_mask =
priv->cs_addr = chip == 0 ? ICE1712_DELTA_CODEC_CHIP_A :
ICE1712_DELTA_CODEC_CHIP_B;
}
/*
* AK4524 on Delta1010LT to choose the chip address
*/
static void delta1010lt_ak4524_lock(struct snd_akm4xxx *ak, int chip)
{
struct snd_ak4xxx_private *priv = (void *)ak->private_value[0];
struct snd_ice1712 *ice = ak->private_data[0];
snd_ice1712_save_gpio_status(ice);
priv->cs_mask = ICE1712_DELTA_1010LT_CS;
priv->cs_addr = chip << 4;
}
/*
* AK4524 on Delta66 rev E to choose the chip address
*/
static void delta66e_ak4524_lock(struct snd_akm4xxx *ak, int chip)
{
struct snd_ak4xxx_private *priv = (void *)ak->private_value[0];
struct snd_ice1712 *ice = ak->private_data[0];
snd_ice1712_save_gpio_status(ice);
priv->cs_mask =
priv->cs_addr = chip == 0 ? ICE1712_DELTA_66E_CS_CHIP_A :
ICE1712_DELTA_66E_CS_CHIP_B;
}
/*
* AK4528 on VX442 to choose the chip mask
*/
static void vx442_ak4524_lock(struct snd_akm4xxx *ak, int chip)
{
struct snd_ak4xxx_private *priv = (void *)ak->private_value[0];
struct snd_ice1712 *ice = ak->private_data[0];
snd_ice1712_save_gpio_status(ice);
priv->cs_mask =
priv->cs_addr = chip == 0 ? ICE1712_VX442_CODEC_CHIP_A :
ICE1712_VX442_CODEC_CHIP_B;
}
/*
* change the DFS bit according rate for Delta1010
*/
static void delta_1010_set_rate_val(struct snd_ice1712 *ice, unsigned int rate)
{
unsigned char tmp, tmp2;
if (rate == 0) /* no hint - S/PDIF input is master, simply return */
return;
mutex_lock(&ice->gpio_mutex);
tmp = snd_ice1712_read(ice, ICE1712_IREG_GPIO_DATA);
tmp2 = tmp & ~ICE1712_DELTA_DFS;
if (rate > 48000)
tmp2 |= ICE1712_DELTA_DFS;
if (tmp != tmp2)
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp2);
mutex_unlock(&ice->gpio_mutex);
}
/*
* change the rate of AK4524 on Delta 44/66, AP, 1010LT
*/
static void delta_ak4524_set_rate_val(struct snd_akm4xxx *ak, unsigned int rate)
{
unsigned char tmp, tmp2;
struct snd_ice1712 *ice = ak->private_data[0];
if (rate == 0) /* no hint - S/PDIF input is master, simply return */
return;
/* check before reset ak4524 to avoid unnecessary clicks */
mutex_lock(&ice->gpio_mutex);
tmp = snd_ice1712_read(ice, ICE1712_IREG_GPIO_DATA);
mutex_unlock(&ice->gpio_mutex);
tmp2 = tmp & ~ICE1712_DELTA_DFS;
if (rate > 48000)
tmp2 |= ICE1712_DELTA_DFS;
if (tmp == tmp2)
return;
/* do it again */
snd_akm4xxx_reset(ak, 1);
mutex_lock(&ice->gpio_mutex);
tmp = snd_ice1712_read(ice, ICE1712_IREG_GPIO_DATA) & ~ICE1712_DELTA_DFS;
if (rate > 48000)
tmp |= ICE1712_DELTA_DFS;
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
mutex_unlock(&ice->gpio_mutex);
snd_akm4xxx_reset(ak, 0);
}
/*
* change the rate of AK4524 on VX442
*/
static void vx442_ak4524_set_rate_val(struct snd_akm4xxx *ak, unsigned int rate)
{
unsigned char val;
val = (rate > 48000) ? 0x65 : 0x60;
if (snd_akm4xxx_get(ak, 0, 0x02) != val ||
snd_akm4xxx_get(ak, 1, 0x02) != val) {
snd_akm4xxx_reset(ak, 1);
snd_akm4xxx_write(ak, 0, 0x02, val);
snd_akm4xxx_write(ak, 1, 0x02, val);
snd_akm4xxx_reset(ak, 0);
}
}
/*
* SPDIF ops for Delta 1010, Dio, 66
*/
/* open callback */
static void delta_open_spdif(struct snd_ice1712 *ice, struct snd_pcm_substream *substream)
{
ice->spdif.cs8403_stream_bits = ice->spdif.cs8403_bits;
}
/* set up */
static void delta_setup_spdif(struct snd_ice1712 *ice, int rate)
{
unsigned long flags;
unsigned int tmp;
int change;
spin_lock_irqsave(&ice->reg_lock, flags);
tmp = ice->spdif.cs8403_stream_bits;
if (tmp & 0x01) /* consumer */
tmp &= (tmp & 0x01) ? ~0x06 : ~0x18;
switch (rate) {
case 32000: tmp |= (tmp & 0x01) ? 0x04 : 0x00; break;
case 44100: tmp |= (tmp & 0x01) ? 0x00 : 0x10; break;
case 48000: tmp |= (tmp & 0x01) ? 0x02 : 0x08; break;
default: tmp |= (tmp & 0x01) ? 0x00 : 0x18; break;
}
change = ice->spdif.cs8403_stream_bits != tmp;
ice->spdif.cs8403_stream_bits = tmp;
spin_unlock_irqrestore(&ice->reg_lock, flags);
if (change)
snd_ctl_notify(ice->card, SNDRV_CTL_EVENT_MASK_VALUE, &ice->spdif.stream_ctl->id);
snd_ice1712_delta_cs8403_spdif_write(ice, tmp);
}
#define snd_ice1712_delta1010lt_wordclock_status_info \
snd_ctl_boolean_mono_info
static int snd_ice1712_delta1010lt_wordclock_status_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
char reg = 0x10; /* CS8427 receiver error register */
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
if (snd_i2c_sendbytes(ice->cs8427, ®, 1) != 1)
snd_printk(KERN_ERR "unable to send register 0x%x byte to CS8427\n", reg);
snd_i2c_readbytes(ice->cs8427, ®, 1);
ucontrol->value.integer.value[0] = (reg & CS8427_UNLOCK) ? 1 : 0;
return 0;
}
static struct snd_kcontrol_new snd_ice1712_delta1010lt_wordclock_status __devinitdata =
{
.access = (SNDRV_CTL_ELEM_ACCESS_READ),
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Word Clock Status",
.info = snd_ice1712_delta1010lt_wordclock_status_info,
.get = snd_ice1712_delta1010lt_wordclock_status_get,
};
/*
* initialize the chips on M-Audio cards
*/
static struct snd_akm4xxx akm_audiophile __devinitdata = {
.type = SND_AK4528,
.num_adcs = 2,
.num_dacs = 2,
.ops = {
.set_rate_val = delta_ak4524_set_rate_val
}
};
static struct snd_ak4xxx_private akm_audiophile_priv __devinitdata = {
.caddr = 2,
.cif = 0,
.data_mask = ICE1712_DELTA_AP_DOUT,
.clk_mask = ICE1712_DELTA_AP_CCLK,
.cs_mask = ICE1712_DELTA_AP_CS_CODEC,
.cs_addr = ICE1712_DELTA_AP_CS_CODEC,
.cs_none = 0,
.add_flags = ICE1712_DELTA_AP_CS_DIGITAL,
.mask_flags = 0,
};
static struct snd_akm4xxx akm_delta410 __devinitdata = {
.type = SND_AK4529,
.num_adcs = 2,
.num_dacs = 8,
.ops = {
.set_rate_val = delta_ak4524_set_rate_val
}
};
static struct snd_ak4xxx_private akm_delta410_priv __devinitdata = {
.caddr = 0,
.cif = 0,
.data_mask = ICE1712_DELTA_AP_DOUT,
.clk_mask = ICE1712_DELTA_AP_CCLK,
.cs_mask = ICE1712_DELTA_AP_CS_CODEC,
.cs_addr = ICE1712_DELTA_AP_CS_CODEC,
.cs_none = 0,
.add_flags = ICE1712_DELTA_AP_CS_DIGITAL,
.mask_flags = 0,
};
static struct snd_akm4xxx akm_delta1010lt __devinitdata = {
.type = SND_AK4524,
.num_adcs = 8,
.num_dacs = 8,
.ops = {
.lock = delta1010lt_ak4524_lock,
.set_rate_val = delta_ak4524_set_rate_val
}
};
static struct snd_ak4xxx_private akm_delta1010lt_priv __devinitdata = {
.caddr = 2,
.cif = 0, /* the default level of the CIF pin from AK4524 */
.data_mask = ICE1712_DELTA_1010LT_DOUT,
.clk_mask = ICE1712_DELTA_1010LT_CCLK,
.cs_mask = 0,
.cs_addr = 0, /* set later */
.cs_none = ICE1712_DELTA_1010LT_CS_NONE,
.add_flags = 0,
.mask_flags = 0,
};
static struct snd_akm4xxx akm_delta66e __devinitdata = {
.type = SND_AK4524,
.num_adcs = 4,
.num_dacs = 4,
.ops = {
.lock = delta66e_ak4524_lock,
.set_rate_val = delta_ak4524_set_rate_val
}
};
static struct snd_ak4xxx_private akm_delta66e_priv __devinitdata = {
.caddr = 2,
.cif = 0, /* the default level of the CIF pin from AK4524 */
.data_mask = ICE1712_DELTA_66E_DOUT,
.clk_mask = ICE1712_DELTA_66E_CCLK,
.cs_mask = 0,
.cs_addr = 0, /* set later */
.cs_none = 0,
.add_flags = 0,
.mask_flags = 0,
};
static struct snd_akm4xxx akm_delta44 __devinitdata = {
.type = SND_AK4524,
.num_adcs = 4,
.num_dacs = 4,
.ops = {
.lock = delta_ak4524_lock,
.set_rate_val = delta_ak4524_set_rate_val
}
};
static struct snd_ak4xxx_private akm_delta44_priv __devinitdata = {
.caddr = 2,
.cif = 0, /* the default level of the CIF pin from AK4524 */
.data_mask = ICE1712_DELTA_CODEC_SERIAL_DATA,
.clk_mask = ICE1712_DELTA_CODEC_SERIAL_CLOCK,
.cs_mask = 0,
.cs_addr = 0, /* set later */
.cs_none = 0,
.add_flags = 0,
.mask_flags = 0,
};
static struct snd_akm4xxx akm_vx442 __devinitdata = {
.type = SND_AK4524,
.num_adcs = 4,
.num_dacs = 4,
.ops = {
.lock = vx442_ak4524_lock,
.set_rate_val = vx442_ak4524_set_rate_val
}
};
static struct snd_ak4xxx_private akm_vx442_priv __devinitdata = {
.caddr = 2,
.cif = 0,
.data_mask = ICE1712_VX442_DOUT,
.clk_mask = ICE1712_VX442_CCLK,
.cs_mask = 0,
.cs_addr = 0, /* set later */
.cs_none = 0,
.add_flags = 0,
.mask_flags = 0,
};
static int __devinit snd_ice1712_delta_init(struct snd_ice1712 *ice)
{
int err;
struct snd_akm4xxx *ak;
unsigned char tmp;
if (ice->eeprom.subvendor == ICE1712_SUBDEVICE_DELTA1010 &&
ice->eeprom.gpiodir == 0x7b)
ice->eeprom.subvendor = ICE1712_SUBDEVICE_DELTA1010E;
if (ice->eeprom.subvendor == ICE1712_SUBDEVICE_DELTA66 &&
ice->eeprom.gpiodir == 0xfb)
ice->eeprom.subvendor = ICE1712_SUBDEVICE_DELTA66E;
/* determine I2C, DACs and ADCs */
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_AUDIOPHILE:
ice->num_total_dacs = 2;
ice->num_total_adcs = 2;
break;
case ICE1712_SUBDEVICE_DELTA410:
ice->num_total_dacs = 8;
ice->num_total_adcs = 2;
break;
case ICE1712_SUBDEVICE_DELTA44:
case ICE1712_SUBDEVICE_DELTA66:
ice->num_total_dacs = ice->omni ? 8 : 4;
ice->num_total_adcs = ice->omni ? 8 : 4;
break;
case ICE1712_SUBDEVICE_DELTA1010:
case ICE1712_SUBDEVICE_DELTA1010E:
case ICE1712_SUBDEVICE_DELTA1010LT:
case ICE1712_SUBDEVICE_MEDIASTATION:
case ICE1712_SUBDEVICE_EDIROLDA2496:
ice->num_total_dacs = 8;
ice->num_total_adcs = 8;
break;
case ICE1712_SUBDEVICE_DELTADIO2496:
ice->num_total_dacs = 4; /* two AK4324 codecs */
break;
case ICE1712_SUBDEVICE_VX442:
case ICE1712_SUBDEVICE_DELTA66E: /* omni not suported yet */
ice->num_total_dacs = 4;
ice->num_total_adcs = 4;
break;
}
/* initialize the SPI clock to high */
tmp = snd_ice1712_read(ice, ICE1712_IREG_GPIO_DATA);
tmp |= ICE1712_DELTA_AP_CCLK;
snd_ice1712_write(ice, ICE1712_IREG_GPIO_DATA, tmp);
udelay(5);
/* initialize spdif */
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_AUDIOPHILE:
case ICE1712_SUBDEVICE_DELTA410:
case ICE1712_SUBDEVICE_DELTA1010E:
case ICE1712_SUBDEVICE_DELTA1010LT:
case ICE1712_SUBDEVICE_VX442:
case ICE1712_SUBDEVICE_DELTA66E:
if ((err = snd_i2c_bus_create(ice->card, "ICE1712 GPIO 1", NULL, &ice->i2c)) < 0) {
snd_printk(KERN_ERR "unable to create I2C bus\n");
return err;
}
ice->i2c->private_data = ice;
ice->i2c->ops = &ap_cs8427_i2c_ops;
if ((err = snd_ice1712_init_cs8427(ice, CS8427_BASE_ADDR)) < 0)
return err;
break;
case ICE1712_SUBDEVICE_DELTA1010:
case ICE1712_SUBDEVICE_MEDIASTATION:
ice->gpio.set_pro_rate = delta_1010_set_rate_val;
break;
case ICE1712_SUBDEVICE_DELTADIO2496:
ice->gpio.set_pro_rate = delta_1010_set_rate_val;
/* fall thru */
case ICE1712_SUBDEVICE_DELTA66:
ice->spdif.ops.open = delta_open_spdif;
ice->spdif.ops.setup_rate = delta_setup_spdif;
ice->spdif.ops.default_get = delta_spdif_default_get;
ice->spdif.ops.default_put = delta_spdif_default_put;
ice->spdif.ops.stream_get = delta_spdif_stream_get;
ice->spdif.ops.stream_put = delta_spdif_stream_put;
/* Set spdif defaults */
snd_ice1712_delta_cs8403_spdif_write(ice, ice->spdif.cs8403_bits);
break;
}
/* no analog? */
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_DELTA1010:
case ICE1712_SUBDEVICE_DELTA1010E:
case ICE1712_SUBDEVICE_DELTADIO2496:
case ICE1712_SUBDEVICE_MEDIASTATION:
return 0;
}
/* second stage of initialization, analog parts and others */
ak = ice->akm = kmalloc(sizeof(struct snd_akm4xxx), GFP_KERNEL);
if (! ak)
return -ENOMEM;
ice->akm_codecs = 1;
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_AUDIOPHILE:
err = snd_ice1712_akm4xxx_init(ak, &akm_audiophile, &akm_audiophile_priv, ice);
break;
case ICE1712_SUBDEVICE_DELTA410:
err = snd_ice1712_akm4xxx_init(ak, &akm_delta410, &akm_delta410_priv, ice);
break;
case ICE1712_SUBDEVICE_DELTA1010LT:
case ICE1712_SUBDEVICE_EDIROLDA2496:
err = snd_ice1712_akm4xxx_init(ak, &akm_delta1010lt, &akm_delta1010lt_priv, ice);
break;
case ICE1712_SUBDEVICE_DELTA66:
case ICE1712_SUBDEVICE_DELTA44:
err = snd_ice1712_akm4xxx_init(ak, &akm_delta44, &akm_delta44_priv, ice);
break;
case ICE1712_SUBDEVICE_VX442:
err = snd_ice1712_akm4xxx_init(ak, &akm_vx442, &akm_vx442_priv, ice);
break;
case ICE1712_SUBDEVICE_DELTA66E:
err = snd_ice1712_akm4xxx_init(ak, &akm_delta66e, &akm_delta66e_priv, ice);
break;
default:
snd_BUG();
return -EINVAL;
}
return err;
}
/*
* additional controls for M-Audio cards
*/
static struct snd_kcontrol_new snd_ice1712_delta1010_wordclock_select __devinitdata =
ICE1712_GPIO(SNDRV_CTL_ELEM_IFACE_MIXER, "Word Clock Sync", 0, ICE1712_DELTA_WORD_CLOCK_SELECT, 1, 0);
static struct snd_kcontrol_new snd_ice1712_delta1010lt_wordclock_select __devinitdata =
ICE1712_GPIO(SNDRV_CTL_ELEM_IFACE_MIXER, "Word Clock Sync", 0, ICE1712_DELTA_1010LT_WORDCLOCK, 0, 0);
static struct snd_kcontrol_new snd_ice1712_delta1010_wordclock_status __devinitdata =
ICE1712_GPIO(SNDRV_CTL_ELEM_IFACE_MIXER, "Word Clock Status", 0, ICE1712_DELTA_WORD_CLOCK_STATUS, 1, SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE);
static struct snd_kcontrol_new snd_ice1712_deltadio2496_spdif_in_select __devinitdata =
ICE1712_GPIO(SNDRV_CTL_ELEM_IFACE_MIXER, "IEC958 Input Optical", 0, ICE1712_DELTA_SPDIF_INPUT_SELECT, 0, 0);
static struct snd_kcontrol_new snd_ice1712_delta_spdif_in_status __devinitdata =
ICE1712_GPIO(SNDRV_CTL_ELEM_IFACE_MIXER, "Delta IEC958 Input Status", 0, ICE1712_DELTA_SPDIF_IN_STAT, 1, SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE);
static int __devinit snd_ice1712_delta_add_controls(struct snd_ice1712 *ice)
{
int err;
/* 1010 and dio specific controls */
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_DELTA1010:
case ICE1712_SUBDEVICE_MEDIASTATION:
err = snd_ctl_add(ice->card, snd_ctl_new1(&snd_ice1712_delta1010_wordclock_select, ice));
if (err < 0)
return err;
err = snd_ctl_add(ice->card, snd_ctl_new1(&snd_ice1712_delta1010_wordclock_status, ice));
if (err < 0)
return err;
break;
case ICE1712_SUBDEVICE_DELTADIO2496:
err = snd_ctl_add(ice->card, snd_ctl_new1(&snd_ice1712_deltadio2496_spdif_in_select, ice));
if (err < 0)
return err;
break;
case ICE1712_SUBDEVICE_DELTA1010E:
case ICE1712_SUBDEVICE_DELTA1010LT:
err = snd_ctl_add(ice->card, snd_ctl_new1(&snd_ice1712_delta1010lt_wordclock_select, ice));
if (err < 0)
return err;
err = snd_ctl_add(ice->card, snd_ctl_new1(&snd_ice1712_delta1010lt_wordclock_status, ice));
if (err < 0)
return err;
break;
}
/* normal spdif controls */
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_DELTA1010:
case ICE1712_SUBDEVICE_DELTADIO2496:
case ICE1712_SUBDEVICE_DELTA66:
case ICE1712_SUBDEVICE_MEDIASTATION:
err = snd_ice1712_spdif_build_controls(ice);
if (err < 0)
return err;
break;
}
/* spdif status in */
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_DELTA1010:
case ICE1712_SUBDEVICE_DELTADIO2496:
case ICE1712_SUBDEVICE_DELTA66:
case ICE1712_SUBDEVICE_MEDIASTATION:
err = snd_ctl_add(ice->card, snd_ctl_new1(&snd_ice1712_delta_spdif_in_status, ice));
if (err < 0)
return err;
break;
}
/* ak4524 controls */
switch (ice->eeprom.subvendor) {
case ICE1712_SUBDEVICE_DELTA1010LT:
case ICE1712_SUBDEVICE_AUDIOPHILE:
case ICE1712_SUBDEVICE_DELTA410:
case ICE1712_SUBDEVICE_DELTA44:
case ICE1712_SUBDEVICE_DELTA66:
case ICE1712_SUBDEVICE_VX442:
case ICE1712_SUBDEVICE_DELTA66E:
case ICE1712_SUBDEVICE_EDIROLDA2496:
err = snd_ice1712_akm4xxx_build_controls(ice);
if (err < 0)
return err;
break;
}
return 0;
}
/* entry point */
struct snd_ice1712_card_info snd_ice1712_delta_cards[] __devinitdata = {
{
.subvendor = ICE1712_SUBDEVICE_DELTA1010,
.name = "M Audio Delta 1010",
.model = "delta1010",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
},
{
.subvendor = ICE1712_SUBDEVICE_DELTADIO2496,
.name = "M Audio Delta DiO 2496",
.model = "dio2496",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
.no_mpu401 = 1,
},
{
.subvendor = ICE1712_SUBDEVICE_DELTA66,
.name = "M Audio Delta 66",
.model = "delta66",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
.no_mpu401 = 1,
},
{
.subvendor = ICE1712_SUBDEVICE_DELTA44,
.name = "M Audio Delta 44",
.model = "delta44",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
.no_mpu401 = 1,
},
{
.subvendor = ICE1712_SUBDEVICE_AUDIOPHILE,
.name = "M Audio Audiophile 24/96",
.model = "audiophile",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
},
{
.subvendor = ICE1712_SUBDEVICE_DELTA410,
.name = "M Audio Delta 410",
.model = "delta410",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
},
{
.subvendor = ICE1712_SUBDEVICE_DELTA1010LT,
.name = "M Audio Delta 1010LT",
.model = "delta1010lt",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
},
{
.subvendor = ICE1712_SUBDEVICE_VX442,
.name = "Digigram VX442",
.model = "vx442",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
.no_mpu401 = 1,
},
{
.subvendor = ICE1712_SUBDEVICE_MEDIASTATION,
.name = "Lionstracs Mediastation",
.model = "mediastation",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
},
{
.subvendor = ICE1712_SUBDEVICE_EDIROLDA2496,
.name = "Edirol DA2496",
.model = "da2496",
.chip_init = snd_ice1712_delta_init,
.build_controls = snd_ice1712_delta_add_controls,
},
{ } /* terminator */
};
| gpl-2.0 |
googyanas/Googy-Max4-CM-Kernel | arch/score/kernel/traps.c | 9293 | 9101 | /*
* arch/score/kernel/traps.c
*
* Score Processor version.
*
* Copyright (C) 2009 Sunplus Core Technology Co., Ltd.
* Chen Liqin <liqin.chen@sunplusct.com>
* Lennox Wu <lennox.wu@sunplusct.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, see the file COPYING, or write
* to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <asm/cacheflush.h>
#include <asm/irq.h>
#include <asm/irq_regs.h>
unsigned long exception_handlers[32];
/*
* The architecture-independent show_stack generator
*/
void show_stack(struct task_struct *task, unsigned long *sp)
{
int i;
long stackdata;
sp = sp ? sp : (unsigned long *)&sp;
printk(KERN_NOTICE "Stack: ");
i = 1;
while ((long) sp & (PAGE_SIZE - 1)) {
if (i && ((i % 8) == 0))
printk(KERN_NOTICE "\n");
if (i > 40) {
printk(KERN_NOTICE " ...");
break;
}
if (__get_user(stackdata, sp++)) {
printk(KERN_NOTICE " (Bad stack address)");
break;
}
printk(KERN_NOTICE " %08lx", stackdata);
i++;
}
printk(KERN_NOTICE "\n");
}
static void show_trace(long *sp)
{
int i;
long addr;
sp = sp ? sp : (long *) &sp;
printk(KERN_NOTICE "Call Trace: ");
i = 1;
while ((long) sp & (PAGE_SIZE - 1)) {
if (__get_user(addr, sp++)) {
if (i && ((i % 6) == 0))
printk(KERN_NOTICE "\n");
printk(KERN_NOTICE " (Bad stack address)\n");
break;
}
if (kernel_text_address(addr)) {
if (i && ((i % 6) == 0))
printk(KERN_NOTICE "\n");
if (i > 40) {
printk(KERN_NOTICE " ...");
break;
}
printk(KERN_NOTICE " [<%08lx>]", addr);
i++;
}
}
printk(KERN_NOTICE "\n");
}
static void show_code(unsigned int *pc)
{
long i;
printk(KERN_NOTICE "\nCode:");
for (i = -3; i < 6; i++) {
unsigned long insn;
if (__get_user(insn, pc + i)) {
printk(KERN_NOTICE " (Bad address in epc)\n");
break;
}
printk(KERN_NOTICE "%c%08lx%c", (i ? ' ' : '<'),
insn, (i ? ' ' : '>'));
}
}
/*
* FIXME: really the generic show_regs should take a const pointer argument.
*/
void show_regs(struct pt_regs *regs)
{
printk("r0 : %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
regs->regs[0], regs->regs[1], regs->regs[2], regs->regs[3],
regs->regs[4], regs->regs[5], regs->regs[6], regs->regs[7]);
printk("r8 : %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
regs->regs[8], regs->regs[9], regs->regs[10], regs->regs[11],
regs->regs[12], regs->regs[13], regs->regs[14], regs->regs[15]);
printk("r16: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
regs->regs[16], regs->regs[17], regs->regs[18], regs->regs[19],
regs->regs[20], regs->regs[21], regs->regs[22], regs->regs[23]);
printk("r24: %08lx %08lx %08lx %08lx %08lx %08lx %08lx %08lx\n",
regs->regs[24], regs->regs[25], regs->regs[26], regs->regs[27],
regs->regs[28], regs->regs[29], regs->regs[30], regs->regs[31]);
printk("CEH : %08lx\n", regs->ceh);
printk("CEL : %08lx\n", regs->cel);
printk("EMA:%08lx, epc:%08lx %s\nPSR: %08lx\nECR:%08lx\nCondition : %08lx\n",
regs->cp0_ema, regs->cp0_epc, print_tainted(), regs->cp0_psr,
regs->cp0_ecr, regs->cp0_condition);
}
static void show_registers(struct pt_regs *regs)
{
show_regs(regs);
printk(KERN_NOTICE "Process %s (pid: %d, stackpage=%08lx)\n",
current->comm, current->pid, (unsigned long) current);
show_stack(current_thread_info()->task, (long *) regs->regs[0]);
show_trace((long *) regs->regs[0]);
show_code((unsigned int *) regs->cp0_epc);
printk(KERN_NOTICE "\n");
}
/*
* The architecture-independent dump_stack generator
*/
void dump_stack(void)
{
show_stack(current_thread_info()->task,
(long *) get_irq_regs()->regs[0]);
}
EXPORT_SYMBOL(dump_stack);
void __die(const char *str, struct pt_regs *regs, const char *file,
const char *func, unsigned long line)
{
console_verbose();
printk("%s", str);
if (file && func)
printk(" in %s:%s, line %ld", file, func, line);
printk(":\n");
show_registers(regs);
do_exit(SIGSEGV);
}
void __die_if_kernel(const char *str, struct pt_regs *regs,
const char *file, const char *func, unsigned long line)
{
if (!user_mode(regs))
__die(str, regs, file, func, line);
}
asmlinkage void do_adelinsn(struct pt_regs *regs)
{
printk("do_ADE-linsn:ema:0x%08lx:epc:0x%08lx\n",
regs->cp0_ema, regs->cp0_epc);
die_if_kernel("do_ade execution Exception\n", regs);
force_sig(SIGBUS, current);
}
asmlinkage void do_adedata(struct pt_regs *regs)
{
const struct exception_table_entry *fixup;
fixup = search_exception_tables(regs->cp0_epc);
if (fixup) {
regs->cp0_epc = fixup->fixup;
return;
}
printk("do_ADE-data:ema:0x%08lx:epc:0x%08lx\n",
regs->cp0_ema, regs->cp0_epc);
die_if_kernel("do_ade execution Exception\n", regs);
force_sig(SIGBUS, current);
}
asmlinkage void do_pel(struct pt_regs *regs)
{
die_if_kernel("do_pel execution Exception", regs);
force_sig(SIGFPE, current);
}
asmlinkage void do_cee(struct pt_regs *regs)
{
die_if_kernel("do_cee execution Exception", regs);
force_sig(SIGFPE, current);
}
asmlinkage void do_cpe(struct pt_regs *regs)
{
die_if_kernel("do_cpe execution Exception", regs);
force_sig(SIGFPE, current);
}
asmlinkage void do_be(struct pt_regs *regs)
{
die_if_kernel("do_be execution Exception", regs);
force_sig(SIGBUS, current);
}
asmlinkage void do_ov(struct pt_regs *regs)
{
siginfo_t info;
die_if_kernel("do_ov execution Exception", regs);
info.si_code = FPE_INTOVF;
info.si_signo = SIGFPE;
info.si_errno = 0;
info.si_addr = (void *)regs->cp0_epc;
force_sig_info(SIGFPE, &info, current);
}
asmlinkage void do_tr(struct pt_regs *regs)
{
die_if_kernel("do_tr execution Exception", regs);
force_sig(SIGTRAP, current);
}
asmlinkage void do_ri(struct pt_regs *regs)
{
unsigned long epc_insn;
unsigned long epc = regs->cp0_epc;
read_tsk_long(current, epc, &epc_insn);
if (current->thread.single_step == 1) {
if ((epc == current->thread.addr1) ||
(epc == current->thread.addr2)) {
user_disable_single_step(current);
force_sig(SIGTRAP, current);
return;
} else
BUG();
} else if ((epc_insn == BREAKPOINT32_INSN) ||
((epc_insn & 0x0000FFFF) == 0x7002) ||
((epc_insn & 0xFFFF0000) == 0x70020000)) {
force_sig(SIGTRAP, current);
return;
} else {
die_if_kernel("do_ri execution Exception", regs);
force_sig(SIGILL, current);
}
}
asmlinkage void do_ccu(struct pt_regs *regs)
{
die_if_kernel("do_ccu execution Exception", regs);
force_sig(SIGILL, current);
}
asmlinkage void do_reserved(struct pt_regs *regs)
{
/*
* Game over - no way to handle this if it ever occurs. Most probably
* caused by a new unknown cpu type or after another deadly
* hard/software error.
*/
die_if_kernel("do_reserved execution Exception", regs);
show_regs(regs);
panic("Caught reserved exception - should not happen.");
}
/*
* NMI exception handler.
*/
void nmi_exception_handler(struct pt_regs *regs)
{
die_if_kernel("nmi_exception_handler execution Exception", regs);
die("NMI", regs);
}
/* Install CPU exception handler */
void *set_except_vector(int n, void *addr)
{
unsigned long handler = (unsigned long) addr;
unsigned long old_handler = exception_handlers[n];
exception_handlers[n] = handler;
return (void *)old_handler;
}
void __init trap_init(void)
{
int i;
pgd_current = (unsigned long)init_mm.pgd;
/* DEBUG EXCEPTION */
memcpy((void *)DEBUG_VECTOR_BASE_ADDR,
&debug_exception_vector, DEBUG_VECTOR_SIZE);
/* NMI EXCEPTION */
memcpy((void *)GENERAL_VECTOR_BASE_ADDR,
&general_exception_vector, GENERAL_VECTOR_SIZE);
/*
* Initialise exception handlers
*/
for (i = 0; i <= 31; i++)
set_except_vector(i, handle_reserved);
set_except_vector(1, handle_nmi);
set_except_vector(2, handle_adelinsn);
set_except_vector(3, handle_tlb_refill);
set_except_vector(4, handle_tlb_invaild);
set_except_vector(5, handle_ibe);
set_except_vector(6, handle_pel);
set_except_vector(7, handle_sys);
set_except_vector(8, handle_ccu);
set_except_vector(9, handle_ri);
set_except_vector(10, handle_tr);
set_except_vector(11, handle_adedata);
set_except_vector(12, handle_adedata);
set_except_vector(13, handle_tlb_refill);
set_except_vector(14, handle_tlb_invaild);
set_except_vector(15, handle_mod);
set_except_vector(16, handle_cee);
set_except_vector(17, handle_cpe);
set_except_vector(18, handle_dbe);
flush_icache_range(DEBUG_VECTOR_BASE_ADDR, IRQ_VECTOR_BASE_ADDR);
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
cpu_cache_init();
}
| gpl-2.0 |
Marvellousteam/android_kernel_sony_msm8930 | drivers/isdn/hysdn/hysdn_net.c | 9293 | 10140 | /* $Id: hysdn_net.c,v 1.8.6.4 2001/09/23 22:24:54 kai Exp $
*
* Linux driver for HYSDN cards, net (ethernet type) handling routines.
*
* Author Werner Cornelius (werner@titro.de) for Hypercope GmbH
* Copyright 1999 by Werner Cornelius (werner@titro.de)
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* This net module has been inspired by the skeleton driver from
* Donald Becker (becker@CESDIS.gsfc.nasa.gov)
*
*/
#include <linux/module.h>
#include <linux/signal.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/inetdevice.h>
#include "hysdn_defs.h"
unsigned int hynet_enable = 0xffffffff;
module_param(hynet_enable, uint, 0);
#define MAX_SKB_BUFFERS 20 /* number of buffers for keeping TX-data */
/****************************************************************************/
/* structure containing the complete network data. The structure is aligned */
/* in a way that both, the device and statistics are kept inside it. */
/* for proper access, the device structure MUST be the first var/struct */
/* inside the definition. */
/****************************************************************************/
struct net_local {
/* Tx control lock. This protects the transmit buffer ring
* state along with the "tx full" state of the driver. This
* means all netif_queue flow control actions are protected
* by this lock as well.
*/
struct net_device *dev;
spinlock_t lock;
struct sk_buff *skbs[MAX_SKB_BUFFERS]; /* pointers to tx-skbs */
int in_idx, out_idx; /* indexes to buffer ring */
int sk_count; /* number of buffers currently in ring */
}; /* net_local */
/*********************************************************************/
/* Open/initialize the board. This is called (in the current kernel) */
/* sometime after booting when the 'ifconfig' program is run. */
/* This routine should set everything up anew at each open, even */
/* registers that "should" only need to be set once at boot, so that */
/* there is non-reboot way to recover if something goes wrong. */
/*********************************************************************/
static int
net_open(struct net_device *dev)
{
struct in_device *in_dev;
hysdn_card *card = dev->ml_priv;
int i;
netif_start_queue(dev); /* start tx-queueing */
/* Fill in the MAC-level header (if not already set) */
if (!card->mac_addr[0]) {
for (i = 0; i < ETH_ALEN; i++)
dev->dev_addr[i] = 0xfc;
if ((in_dev = dev->ip_ptr) != NULL) {
struct in_ifaddr *ifa = in_dev->ifa_list;
if (ifa != NULL)
memcpy(dev->dev_addr + (ETH_ALEN - sizeof(ifa->ifa_local)), &ifa->ifa_local, sizeof(ifa->ifa_local));
}
} else
memcpy(dev->dev_addr, card->mac_addr, ETH_ALEN);
return (0);
} /* net_open */
/*******************************************/
/* flush the currently occupied tx-buffers */
/* must only be called when device closed */
/*******************************************/
static void
flush_tx_buffers(struct net_local *nl)
{
while (nl->sk_count) {
dev_kfree_skb(nl->skbs[nl->out_idx++]); /* free skb */
if (nl->out_idx >= MAX_SKB_BUFFERS)
nl->out_idx = 0; /* wrap around */
nl->sk_count--;
}
} /* flush_tx_buffers */
/*********************************************************************/
/* close/decativate the device. The device is not removed, but only */
/* deactivated. */
/*********************************************************************/
static int
net_close(struct net_device *dev)
{
netif_stop_queue(dev); /* disable queueing */
flush_tx_buffers((struct net_local *) dev);
return (0); /* success */
} /* net_close */
/************************************/
/* send a packet on this interface. */
/* new style for kernel >= 2.3.33 */
/************************************/
static netdev_tx_t
net_send_packet(struct sk_buff *skb, struct net_device *dev)
{
struct net_local *lp = (struct net_local *) dev;
spin_lock_irq(&lp->lock);
lp->skbs[lp->in_idx++] = skb; /* add to buffer list */
if (lp->in_idx >= MAX_SKB_BUFFERS)
lp->in_idx = 0; /* wrap around */
lp->sk_count++; /* adjust counter */
dev->trans_start = jiffies;
/* If we just used up the very last entry in the
* TX ring on this device, tell the queueing
* layer to send no more.
*/
if (lp->sk_count >= MAX_SKB_BUFFERS)
netif_stop_queue(dev);
/* When the TX completion hw interrupt arrives, this
* is when the transmit statistics are updated.
*/
spin_unlock_irq(&lp->lock);
if (lp->sk_count <= 3) {
schedule_work(&((hysdn_card *) dev->ml_priv)->irq_queue);
}
return NETDEV_TX_OK; /* success */
} /* net_send_packet */
/***********************************************************************/
/* acknowlegde a packet send. The network layer will be informed about */
/* completion */
/***********************************************************************/
void
hysdn_tx_netack(hysdn_card *card)
{
struct net_local *lp = card->netif;
if (!lp)
return; /* non existing device */
if (!lp->sk_count)
return; /* error condition */
lp->dev->stats.tx_packets++;
lp->dev->stats.tx_bytes += lp->skbs[lp->out_idx]->len;
dev_kfree_skb(lp->skbs[lp->out_idx++]); /* free skb */
if (lp->out_idx >= MAX_SKB_BUFFERS)
lp->out_idx = 0; /* wrap around */
if (lp->sk_count-- == MAX_SKB_BUFFERS) /* dec usage count */
netif_start_queue((struct net_device *) lp);
} /* hysdn_tx_netack */
/*****************************************************/
/* we got a packet from the network, go and queue it */
/*****************************************************/
void
hysdn_rx_netpkt(hysdn_card *card, unsigned char *buf, unsigned short len)
{
struct net_local *lp = card->netif;
struct net_device *dev;
struct sk_buff *skb;
if (!lp)
return; /* non existing device */
dev = lp->dev;
dev->stats.rx_bytes += len;
skb = dev_alloc_skb(len);
if (skb == NULL) {
printk(KERN_NOTICE "%s: Memory squeeze, dropping packet.\n",
dev->name);
dev->stats.rx_dropped++;
return;
}
/* copy the data */
memcpy(skb_put(skb, len), buf, len);
/* determine the used protocol */
skb->protocol = eth_type_trans(skb, dev);
dev->stats.rx_packets++; /* adjust packet count */
netif_rx(skb);
} /* hysdn_rx_netpkt */
/*****************************************************/
/* return the pointer to a network packet to be send */
/*****************************************************/
struct sk_buff *
hysdn_tx_netget(hysdn_card *card)
{
struct net_local *lp = card->netif;
if (!lp)
return (NULL); /* non existing device */
if (!lp->sk_count)
return (NULL); /* nothing available */
return (lp->skbs[lp->out_idx]); /* next packet to send */
} /* hysdn_tx_netget */
static const struct net_device_ops hysdn_netdev_ops = {
.ndo_open = net_open,
.ndo_stop = net_close,
.ndo_start_xmit = net_send_packet,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
/*****************************************************************************/
/* hysdn_net_create creates a new net device for the given card. If a device */
/* already exists, it will be deleted and created a new one. The return value */
/* 0 announces success, else a negative error code will be returned. */
/*****************************************************************************/
int
hysdn_net_create(hysdn_card *card)
{
struct net_device *dev;
int i;
struct net_local *lp;
if (!card) {
printk(KERN_WARNING "No card-pt in hysdn_net_create!\n");
return (-ENOMEM);
}
hysdn_net_release(card); /* release an existing net device */
dev = alloc_etherdev(sizeof(struct net_local));
if (!dev) {
printk(KERN_WARNING "HYSDN: unable to allocate mem\n");
return (-ENOMEM);
}
lp = netdev_priv(dev);
lp->dev = dev;
dev->netdev_ops = &hysdn_netdev_ops;
spin_lock_init(&((struct net_local *) dev)->lock);
/* initialise necessary or informing fields */
dev->base_addr = card->iobase; /* IO address */
dev->irq = card->irq; /* irq */
dev->netdev_ops = &hysdn_netdev_ops;
if ((i = register_netdev(dev))) {
printk(KERN_WARNING "HYSDN: unable to create network device\n");
free_netdev(dev);
return (i);
}
dev->ml_priv = card; /* remember pointer to own data structure */
card->netif = dev; /* setup the local pointer */
if (card->debug_flags & LOG_NET_INIT)
hysdn_addlog(card, "network device created");
return (0); /* and return success */
} /* hysdn_net_create */
/***************************************************************************/
/* hysdn_net_release deletes the net device for the given card. The return */
/* value 0 announces success, else a negative error code will be returned. */
/***************************************************************************/
int
hysdn_net_release(hysdn_card *card)
{
struct net_device *dev = card->netif;
if (!dev)
return (0); /* non existing */
card->netif = NULL; /* clear out pointer */
net_close(dev);
flush_tx_buffers((struct net_local *) dev); /* empty buffers */
unregister_netdev(dev); /* release the device */
free_netdev(dev); /* release the memory allocated */
if (card->debug_flags & LOG_NET_INIT)
hysdn_addlog(card, "network device deleted");
return (0); /* always successful */
} /* hysdn_net_release */
/*****************************************************************************/
/* hysdn_net_getname returns a pointer to the name of the network interface. */
/* if the interface is not existing, a "-" is returned. */
/*****************************************************************************/
char *
hysdn_net_getname(hysdn_card *card)
{
struct net_device *dev = card->netif;
if (!dev)
return ("-"); /* non existing */
return (dev->name);
} /* hysdn_net_getname */
| gpl-2.0 |
columbia/linux-2.6-mutable | arch/x86/lib/msr-smp.c | 11853 | 4060 | #include <linux/module.h>
#include <linux/preempt.h>
#include <linux/smp.h>
#include <asm/msr.h>
static void __rdmsr_on_cpu(void *info)
{
struct msr_info *rv = info;
struct msr *reg;
int this_cpu = raw_smp_processor_id();
if (rv->msrs)
reg = per_cpu_ptr(rv->msrs, this_cpu);
else
reg = &rv->reg;
rdmsr(rv->msr_no, reg->l, reg->h);
}
static void __wrmsr_on_cpu(void *info)
{
struct msr_info *rv = info;
struct msr *reg;
int this_cpu = raw_smp_processor_id();
if (rv->msrs)
reg = per_cpu_ptr(rv->msrs, this_cpu);
else
reg = &rv->reg;
wrmsr(rv->msr_no, reg->l, reg->h);
}
int rdmsr_on_cpu(unsigned int cpu, u32 msr_no, u32 *l, u32 *h)
{
int err;
struct msr_info rv;
memset(&rv, 0, sizeof(rv));
rv.msr_no = msr_no;
err = smp_call_function_single(cpu, __rdmsr_on_cpu, &rv, 1);
*l = rv.reg.l;
*h = rv.reg.h;
return err;
}
EXPORT_SYMBOL(rdmsr_on_cpu);
int wrmsr_on_cpu(unsigned int cpu, u32 msr_no, u32 l, u32 h)
{
int err;
struct msr_info rv;
memset(&rv, 0, sizeof(rv));
rv.msr_no = msr_no;
rv.reg.l = l;
rv.reg.h = h;
err = smp_call_function_single(cpu, __wrmsr_on_cpu, &rv, 1);
return err;
}
EXPORT_SYMBOL(wrmsr_on_cpu);
static void __rwmsr_on_cpus(const struct cpumask *mask, u32 msr_no,
struct msr *msrs,
void (*msr_func) (void *info))
{
struct msr_info rv;
int this_cpu;
memset(&rv, 0, sizeof(rv));
rv.msrs = msrs;
rv.msr_no = msr_no;
this_cpu = get_cpu();
if (cpumask_test_cpu(this_cpu, mask))
msr_func(&rv);
smp_call_function_many(mask, msr_func, &rv, 1);
put_cpu();
}
/* rdmsr on a bunch of CPUs
*
* @mask: which CPUs
* @msr_no: which MSR
* @msrs: array of MSR values
*
*/
void rdmsr_on_cpus(const struct cpumask *mask, u32 msr_no, struct msr *msrs)
{
__rwmsr_on_cpus(mask, msr_no, msrs, __rdmsr_on_cpu);
}
EXPORT_SYMBOL(rdmsr_on_cpus);
/*
* wrmsr on a bunch of CPUs
*
* @mask: which CPUs
* @msr_no: which MSR
* @msrs: array of MSR values
*
*/
void wrmsr_on_cpus(const struct cpumask *mask, u32 msr_no, struct msr *msrs)
{
__rwmsr_on_cpus(mask, msr_no, msrs, __wrmsr_on_cpu);
}
EXPORT_SYMBOL(wrmsr_on_cpus);
/* These "safe" variants are slower and should be used when the target MSR
may not actually exist. */
static void __rdmsr_safe_on_cpu(void *info)
{
struct msr_info *rv = info;
rv->err = rdmsr_safe(rv->msr_no, &rv->reg.l, &rv->reg.h);
}
static void __wrmsr_safe_on_cpu(void *info)
{
struct msr_info *rv = info;
rv->err = wrmsr_safe(rv->msr_no, rv->reg.l, rv->reg.h);
}
int rdmsr_safe_on_cpu(unsigned int cpu, u32 msr_no, u32 *l, u32 *h)
{
int err;
struct msr_info rv;
memset(&rv, 0, sizeof(rv));
rv.msr_no = msr_no;
err = smp_call_function_single(cpu, __rdmsr_safe_on_cpu, &rv, 1);
*l = rv.reg.l;
*h = rv.reg.h;
return err ? err : rv.err;
}
EXPORT_SYMBOL(rdmsr_safe_on_cpu);
int wrmsr_safe_on_cpu(unsigned int cpu, u32 msr_no, u32 l, u32 h)
{
int err;
struct msr_info rv;
memset(&rv, 0, sizeof(rv));
rv.msr_no = msr_no;
rv.reg.l = l;
rv.reg.h = h;
err = smp_call_function_single(cpu, __wrmsr_safe_on_cpu, &rv, 1);
return err ? err : rv.err;
}
EXPORT_SYMBOL(wrmsr_safe_on_cpu);
/*
* These variants are significantly slower, but allows control over
* the entire 32-bit GPR set.
*/
static void __rdmsr_safe_regs_on_cpu(void *info)
{
struct msr_regs_info *rv = info;
rv->err = rdmsr_safe_regs(rv->regs);
}
static void __wrmsr_safe_regs_on_cpu(void *info)
{
struct msr_regs_info *rv = info;
rv->err = wrmsr_safe_regs(rv->regs);
}
int rdmsr_safe_regs_on_cpu(unsigned int cpu, u32 *regs)
{
int err;
struct msr_regs_info rv;
rv.regs = regs;
rv.err = -EIO;
err = smp_call_function_single(cpu, __rdmsr_safe_regs_on_cpu, &rv, 1);
return err ? err : rv.err;
}
EXPORT_SYMBOL(rdmsr_safe_regs_on_cpu);
int wrmsr_safe_regs_on_cpu(unsigned int cpu, u32 *regs)
{
int err;
struct msr_regs_info rv;
rv.regs = regs;
rv.err = -EIO;
err = smp_call_function_single(cpu, __wrmsr_safe_regs_on_cpu, &rv, 1);
return err ? err : rv.err;
}
EXPORT_SYMBOL(wrmsr_safe_regs_on_cpu);
| gpl-2.0 |
SM-G920P/kernel_samsung_exynos7420 | Documentation/timers/hpet_example.c | 12621 | 5546 | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <memory.h>
#include <malloc.h>
#include <time.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <linux/hpet.h>
extern void hpet_open_close(int, const char **);
extern void hpet_info(int, const char **);
extern void hpet_poll(int, const char **);
extern void hpet_fasync(int, const char **);
extern void hpet_read(int, const char **);
#include <sys/poll.h>
#include <sys/ioctl.h>
struct hpet_command {
char *command;
void (*func)(int argc, const char ** argv);
} hpet_command[] = {
{
"open-close",
hpet_open_close
},
{
"info",
hpet_info
},
{
"poll",
hpet_poll
},
{
"fasync",
hpet_fasync
},
};
int
main(int argc, const char ** argv)
{
int i;
argc--;
argv++;
if (!argc) {
fprintf(stderr, "-hpet: requires command\n");
return -1;
}
for (i = 0; i < (sizeof (hpet_command) / sizeof (hpet_command[0])); i++)
if (!strcmp(argv[0], hpet_command[i].command)) {
argc--;
argv++;
fprintf(stderr, "-hpet: executing %s\n",
hpet_command[i].command);
hpet_command[i].func(argc, argv);
return 0;
}
fprintf(stderr, "do_hpet: command %s not implemented\n", argv[0]);
return -1;
}
void
hpet_open_close(int argc, const char **argv)
{
int fd;
if (argc != 1) {
fprintf(stderr, "hpet_open_close: device-name\n");
return;
}
fd = open(argv[0], O_RDONLY);
if (fd < 0)
fprintf(stderr, "hpet_open_close: open failed\n");
else
close(fd);
return;
}
void
hpet_info(int argc, const char **argv)
{
struct hpet_info info;
int fd;
if (argc != 1) {
fprintf(stderr, "hpet_info: device-name\n");
return;
}
fd = open(argv[0], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "hpet_info: open of %s failed\n", argv[0]);
return;
}
if (ioctl(fd, HPET_INFO, &info) < 0) {
fprintf(stderr, "hpet_info: failed to get info\n");
goto out;
}
fprintf(stderr, "hpet_info: hi_irqfreq 0x%lx hi_flags 0x%lx ",
info.hi_ireqfreq, info.hi_flags);
fprintf(stderr, "hi_hpet %d hi_timer %d\n",
info.hi_hpet, info.hi_timer);
out:
close(fd);
return;
}
void
hpet_poll(int argc, const char **argv)
{
unsigned long freq;
int iterations, i, fd;
struct pollfd pfd;
struct hpet_info info;
struct timeval stv, etv;
struct timezone tz;
long usec;
if (argc != 3) {
fprintf(stderr, "hpet_poll: device-name freq iterations\n");
return;
}
freq = atoi(argv[1]);
iterations = atoi(argv[2]);
fd = open(argv[0], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "hpet_poll: open of %s failed\n", argv[0]);
return;
}
if (ioctl(fd, HPET_IRQFREQ, freq) < 0) {
fprintf(stderr, "hpet_poll: HPET_IRQFREQ failed\n");
goto out;
}
if (ioctl(fd, HPET_INFO, &info) < 0) {
fprintf(stderr, "hpet_poll: failed to get info\n");
goto out;
}
fprintf(stderr, "hpet_poll: info.hi_flags 0x%lx\n", info.hi_flags);
if (info.hi_flags && (ioctl(fd, HPET_EPI, 0) < 0)) {
fprintf(stderr, "hpet_poll: HPET_EPI failed\n");
goto out;
}
if (ioctl(fd, HPET_IE_ON, 0) < 0) {
fprintf(stderr, "hpet_poll, HPET_IE_ON failed\n");
goto out;
}
pfd.fd = fd;
pfd.events = POLLIN;
for (i = 0; i < iterations; i++) {
pfd.revents = 0;
gettimeofday(&stv, &tz);
if (poll(&pfd, 1, -1) < 0)
fprintf(stderr, "hpet_poll: poll failed\n");
else {
long data;
gettimeofday(&etv, &tz);
usec = stv.tv_sec * 1000000 + stv.tv_usec;
usec = (etv.tv_sec * 1000000 + etv.tv_usec) - usec;
fprintf(stderr,
"hpet_poll: expired time = 0x%lx\n", usec);
fprintf(stderr, "hpet_poll: revents = 0x%x\n",
pfd.revents);
if (read(fd, &data, sizeof(data)) != sizeof(data)) {
fprintf(stderr, "hpet_poll: read failed\n");
}
else
fprintf(stderr, "hpet_poll: data 0x%lx\n",
data);
}
}
out:
close(fd);
return;
}
static int hpet_sigio_count;
static void
hpet_sigio(int val)
{
fprintf(stderr, "hpet_sigio: called\n");
hpet_sigio_count++;
}
void
hpet_fasync(int argc, const char **argv)
{
unsigned long freq;
int iterations, i, fd, value;
sig_t oldsig;
struct hpet_info info;
hpet_sigio_count = 0;
fd = -1;
if ((oldsig = signal(SIGIO, hpet_sigio)) == SIG_ERR) {
fprintf(stderr, "hpet_fasync: failed to set signal handler\n");
return;
}
if (argc != 3) {
fprintf(stderr, "hpet_fasync: device-name freq iterations\n");
goto out;
}
fd = open(argv[0], O_RDONLY);
if (fd < 0) {
fprintf(stderr, "hpet_fasync: failed to open %s\n", argv[0]);
return;
}
if ((fcntl(fd, F_SETOWN, getpid()) == 1) ||
((value = fcntl(fd, F_GETFL)) == 1) ||
(fcntl(fd, F_SETFL, value | O_ASYNC) == 1)) {
fprintf(stderr, "hpet_fasync: fcntl failed\n");
goto out;
}
freq = atoi(argv[1]);
iterations = atoi(argv[2]);
if (ioctl(fd, HPET_IRQFREQ, freq) < 0) {
fprintf(stderr, "hpet_fasync: HPET_IRQFREQ failed\n");
goto out;
}
if (ioctl(fd, HPET_INFO, &info) < 0) {
fprintf(stderr, "hpet_fasync: failed to get info\n");
goto out;
}
fprintf(stderr, "hpet_fasync: info.hi_flags 0x%lx\n", info.hi_flags);
if (info.hi_flags && (ioctl(fd, HPET_EPI, 0) < 0)) {
fprintf(stderr, "hpet_fasync: HPET_EPI failed\n");
goto out;
}
if (ioctl(fd, HPET_IE_ON, 0) < 0) {
fprintf(stderr, "hpet_fasync, HPET_IE_ON failed\n");
goto out;
}
for (i = 0; i < iterations; i++) {
(void) pause();
fprintf(stderr, "hpet_fasync: count = %d\n", hpet_sigio_count);
}
out:
signal(SIGIO, oldsig);
if (fd >= 0)
close(fd);
return;
}
| gpl-2.0 |
Fe-Pi/linux | drivers/watchdog/max77620_wdt.c | 78 | 5566 | /*
* Maxim MAX77620 Watchdog Driver
*
* Copyright (C) 2016 NVIDIA CORPORATION. All rights reserved.
*
* Author: Laxman Dewangan <ldewangan@nvidia.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/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/mfd/max77620.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#include <linux/watchdog.h>
static bool nowayout = WATCHDOG_NOWAYOUT;
struct max77620_wdt {
struct device *dev;
struct regmap *rmap;
struct watchdog_device wdt_dev;
};
static int max77620_wdt_start(struct watchdog_device *wdt_dev)
{
struct max77620_wdt *wdt = watchdog_get_drvdata(wdt_dev);
return regmap_update_bits(wdt->rmap, MAX77620_REG_CNFGGLBL2,
MAX77620_WDTEN, MAX77620_WDTEN);
}
static int max77620_wdt_stop(struct watchdog_device *wdt_dev)
{
struct max77620_wdt *wdt = watchdog_get_drvdata(wdt_dev);
return regmap_update_bits(wdt->rmap, MAX77620_REG_CNFGGLBL2,
MAX77620_WDTEN, 0);
}
static int max77620_wdt_ping(struct watchdog_device *wdt_dev)
{
struct max77620_wdt *wdt = watchdog_get_drvdata(wdt_dev);
return regmap_update_bits(wdt->rmap, MAX77620_REG_CNFGGLBL3,
MAX77620_WDTC_MASK, 0x1);
}
static int max77620_wdt_set_timeout(struct watchdog_device *wdt_dev,
unsigned int timeout)
{
struct max77620_wdt *wdt = watchdog_get_drvdata(wdt_dev);
unsigned int wdt_timeout;
u8 regval;
int ret;
switch (timeout) {
case 0 ... 2:
regval = MAX77620_TWD_2s;
wdt_timeout = 2;
break;
case 3 ... 16:
regval = MAX77620_TWD_16s;
wdt_timeout = 16;
break;
case 17 ... 64:
regval = MAX77620_TWD_64s;
wdt_timeout = 64;
break;
default:
regval = MAX77620_TWD_128s;
wdt_timeout = 128;
break;
}
ret = regmap_update_bits(wdt->rmap, MAX77620_REG_CNFGGLBL3,
MAX77620_WDTC_MASK, 0x1);
if (ret < 0)
return ret;
ret = regmap_update_bits(wdt->rmap, MAX77620_REG_CNFGGLBL2,
MAX77620_TWD_MASK, regval);
if (ret < 0)
return ret;
wdt_dev->timeout = wdt_timeout;
return 0;
}
static const struct watchdog_info max77620_wdt_info = {
.identity = "max77620-watchdog",
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE,
};
static const struct watchdog_ops max77620_wdt_ops = {
.start = max77620_wdt_start,
.stop = max77620_wdt_stop,
.ping = max77620_wdt_ping,
.set_timeout = max77620_wdt_set_timeout,
};
static int max77620_wdt_probe(struct platform_device *pdev)
{
struct max77620_wdt *wdt;
struct watchdog_device *wdt_dev;
unsigned int regval;
int ret;
wdt = devm_kzalloc(&pdev->dev, sizeof(*wdt), GFP_KERNEL);
if (!wdt)
return -ENOMEM;
wdt->dev = &pdev->dev;
wdt->rmap = dev_get_regmap(pdev->dev.parent, NULL);
if (!wdt->rmap) {
dev_err(wdt->dev, "Failed to get parent regmap\n");
return -ENODEV;
}
wdt_dev = &wdt->wdt_dev;
wdt_dev->info = &max77620_wdt_info;
wdt_dev->ops = &max77620_wdt_ops;
wdt_dev->min_timeout = 2;
wdt_dev->max_timeout = 128;
wdt_dev->max_hw_heartbeat_ms = 128 * 1000;
platform_set_drvdata(pdev, wdt);
/* Enable WD_RST_WK - WDT expire results in a restart */
ret = regmap_update_bits(wdt->rmap, MAX77620_REG_ONOFFCNFG2,
MAX77620_ONOFFCNFG2_WD_RST_WK,
MAX77620_ONOFFCNFG2_WD_RST_WK);
if (ret < 0) {
dev_err(wdt->dev, "Failed to set WD_RST_WK: %d\n", ret);
return ret;
}
/* Set WDT clear in OFF and sleep mode */
ret = regmap_update_bits(wdt->rmap, MAX77620_REG_CNFGGLBL2,
MAX77620_WDTOFFC | MAX77620_WDTSLPC,
MAX77620_WDTOFFC | MAX77620_WDTSLPC);
if (ret < 0) {
dev_err(wdt->dev, "Failed to set WDT OFF mode: %d\n", ret);
return ret;
}
/* Check if WDT running and if yes then set flags properly */
ret = regmap_read(wdt->rmap, MAX77620_REG_CNFGGLBL2, ®val);
if (ret < 0) {
dev_err(wdt->dev, "Failed to read WDT CFG register: %d\n", ret);
return ret;
}
switch (regval & MAX77620_TWD_MASK) {
case MAX77620_TWD_2s:
wdt_dev->timeout = 2;
break;
case MAX77620_TWD_16s:
wdt_dev->timeout = 16;
break;
case MAX77620_TWD_64s:
wdt_dev->timeout = 64;
break;
default:
wdt_dev->timeout = 128;
break;
}
if (regval & MAX77620_WDTEN)
set_bit(WDOG_HW_RUNNING, &wdt_dev->status);
watchdog_set_nowayout(wdt_dev, nowayout);
watchdog_set_drvdata(wdt_dev, wdt);
ret = watchdog_register_device(wdt_dev);
if (ret < 0) {
dev_err(&pdev->dev, "watchdog registration failed: %d\n", ret);
return ret;
}
return 0;
}
static int max77620_wdt_remove(struct platform_device *pdev)
{
struct max77620_wdt *wdt = platform_get_drvdata(pdev);
max77620_wdt_stop(&wdt->wdt_dev);
watchdog_unregister_device(&wdt->wdt_dev);
return 0;
}
static const struct platform_device_id max77620_wdt_devtype[] = {
{ .name = "max77620-watchdog", },
{ },
};
MODULE_DEVICE_TABLE(platform, max77620_wdt_devtype);
static struct platform_driver max77620_wdt_driver = {
.driver = {
.name = "max77620-watchdog",
},
.probe = max77620_wdt_probe,
.remove = max77620_wdt_remove,
.id_table = max77620_wdt_devtype,
};
module_platform_driver(max77620_wdt_driver);
MODULE_DESCRIPTION("Max77620 watchdog timer driver");
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started "
"(default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
MODULE_AUTHOR("Laxman Dewangan <ldewangan@nvidia.com>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
pcfighter/2.6.32 | drivers/misc/vidc/common/vcd/vcd_util.c | 78 | 2664 | /* Copyright (c) 2010, 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.
*
* 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.
*
*/
#include "vidc_type.h"
#include "vcd_util.h"
u32 vcd_critical_section_create(u32 **p_cs)
{
struct mutex *lock;
if (!p_cs) {
VCD_MSG_ERROR("Bad critical section ptr");
return VCD_ERR_BAD_POINTER;
} else {
lock = kmalloc(sizeof(struct mutex), GFP_KERNEL);
if (!lock) {
VCD_MSG_ERROR("Failed: vcd_critical_section_create");
return VCD_ERR_ALLOC_FAIL;
}
mutex_init(lock);
*p_cs = (u32 *) lock;
return VCD_S_SUCCESS;
}
}
u32 vcd_critical_section_release(u32 *cs)
{
struct mutex *lock = (struct mutex *)cs;
if (!lock) {
VCD_MSG_ERROR("Bad critical section object");
return VCD_ERR_BAD_POINTER;
}
mutex_destroy(lock);
kfree(cs);
return VCD_S_SUCCESS;
}
u32 vcd_critical_section_enter(u32 *cs)
{
struct mutex *lock = (struct mutex *)cs;
if (!lock) {
VCD_MSG_ERROR("Bad critical section object");
return VCD_ERR_BAD_POINTER;
} else
mutex_lock(lock);
return VCD_S_SUCCESS;
}
u32 vcd_critical_section_leave(u32 *cs)
{
struct mutex *lock = (struct mutex *)cs;
if (!lock) {
VCD_MSG_ERROR("Bad critical section object");
return VCD_ERR_BAD_POINTER;
} else
mutex_unlock(lock);
return VCD_S_SUCCESS;
}
int vcd_pmem_alloc(u32 size, u8 **kernel_vaddr, u8 **phy_addr)
{
*phy_addr =
(u8 *) pmem_kalloc(size, PMEM_MEMTYPE_EBI1 | PMEM_ALIGNMENT_4K);
if (!IS_ERR((void *)*phy_addr)) {
*kernel_vaddr = ioremap((unsigned long)*phy_addr, size);
if (!*kernel_vaddr) {
pr_err("%s: could not ioremap in kernel pmem buffers\n",
__func__);
pmem_kfree((s32) *phy_addr);
return -ENOMEM;
}
pr_debug("write buf: phy addr 0x%08x kernel addr 0x%08x\n",
(u32) *phy_addr, (u32) *kernel_vaddr);
return 0;
} else {
pr_err("%s: could not allocte in kernel pmem buffers\n",
__func__);
return -ENOMEM;
}
}
int vcd_pmem_free(u8 *kernel_vaddr, u8 *phy_addr)
{
iounmap((void *)kernel_vaddr);
pmem_kfree((s32) phy_addr);
return 0;
}
| gpl-2.0 |
ojdkbuild/lookaside_java-1.8.0-openjdk | jdk/src/solaris/native/sun/java2d/loops/vis_IntRgb.c | 78 | 20432 | /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#if !defined(JAVA2D_NO_MLIB) || defined(MLIB_ADD_SUFF)
#include "vis_AlphaMacros.h"
/***************************************************************/
#define Gray2Rgb(x) \
(x << 16) | (x << 8) | x
/***************************************************************/
#define INT_RGB(r, g, b) \
((r << 16) | (g << 8) | b)
/***************************************************************/
void ADD_SUFF(IntRgbToIntArgbConvert)(BLIT_PARAMS)
{
mlib_s32 dstScan = pDstInfo->scanStride;
mlib_s32 srcScan = pSrcInfo->scanStride;
mlib_d64 dd, mask;
mlib_s32 i, i0, j;
if (dstScan == 4*width && srcScan == 4*width) {
width *= height;
height = 1;
}
mask = vis_to_double_dup(0xFF000000);
for (j = 0; j < height; j++) {
mlib_f32 *src = srcBase;
mlib_f32 *dst = dstBase;
i = i0 = 0;
if ((mlib_s32)dst & 7) {
dst[i] = vis_fors(src[i], vis_read_hi(mask));
i0 = 1;
}
#pragma pipeloop(0)
for (i = i0; i <= (mlib_s32)width - 2; i += 2) {
dd = vis_freg_pair(src[i], src[i + 1]);
*(mlib_d64*)(dst + i) = vis_for(dd, mask);
}
if (i < width) {
dst[i] = vis_fors(src[i], vis_read_hi(mask));
}
PTR_ADD(dstBase, dstScan);
PTR_ADD(srcBase, srcScan);
}
}
/***************************************************************/
void ADD_SUFF(IntRgbToIntArgbScaleConvert)(SCALE_PARAMS)
{
mlib_s32 dstScan = pDstInfo->scanStride;
mlib_s32 srcScan = pSrcInfo->scanStride;
mlib_d64 dd, mask;
mlib_s32 j;
mask = vis_to_double_dup(0xFF000000);
for (j = 0; j < height; j++) {
mlib_f32 *src = srcBase;
mlib_f32 *dst = dstBase;
mlib_f32 *dst_end = dst + width;
mlib_s32 tmpsxloc = sxloc;
PTR_ADD(src, (syloc >> shift) * srcScan);
if ((mlib_s32)dst & 7) {
*dst++ = vis_fors(src[tmpsxloc >> shift], vis_read_hi(mask));
tmpsxloc += sxinc;
}
#pragma pipeloop(0)
for (; dst <= dst_end - 2; dst += 2) {
dd = vis_freg_pair(src[tmpsxloc >> shift],
src[(tmpsxloc + sxinc) >> shift]);
*(mlib_d64*)dst = vis_for(dd, mask);
tmpsxloc += 2*sxinc;
}
for (; dst < dst_end; dst++) {
*dst++ = vis_fors(src[tmpsxloc >> shift], vis_read_hi(mask));
tmpsxloc += sxinc;
}
PTR_ADD(dstBase, dstScan);
syloc += syinc;
}
}
/***************************************************************/
#define BGR_TO_ARGB { \
mlib_d64 sda, sdb, sdc, sdd, sde, sdf; \
mlib_d64 s_1, s_2, s_3, a13, b13, a02, b02; \
\
sda = vis_fpmerge(vis_read_hi(sd0), vis_read_lo(sd1)); \
sdb = vis_fpmerge(vis_read_lo(sd0), vis_read_hi(sd2)); \
sdc = vis_fpmerge(vis_read_hi(sd1), vis_read_lo(sd2)); \
\
sdd = vis_fpmerge(vis_read_hi(sda), vis_read_lo(sdb)); \
sde = vis_fpmerge(vis_read_lo(sda), vis_read_hi(sdc)); \
sdf = vis_fpmerge(vis_read_hi(sdb), vis_read_lo(sdc)); \
\
s_3 = vis_fpmerge(vis_read_hi(sdd), vis_read_lo(sde)); \
s_2 = vis_fpmerge(vis_read_lo(sdd), vis_read_hi(sdf)); \
s_1 = vis_fpmerge(vis_read_hi(sde), vis_read_lo(sdf)); \
\
a13 = vis_fpmerge(vis_read_hi(s_1), vis_read_hi(s_3)); \
b13 = vis_fpmerge(vis_read_lo(s_1), vis_read_lo(s_3)); \
a02 = vis_fpmerge(vis_read_hi(s_0), vis_read_hi(s_2)); \
b02 = vis_fpmerge(vis_read_lo(s_0), vis_read_lo(s_2)); \
\
dd0 = vis_fpmerge(vis_read_hi(a02), vis_read_hi(a13)); \
dd1 = vis_fpmerge(vis_read_lo(a02), vis_read_lo(a13)); \
dd2 = vis_fpmerge(vis_read_hi(b02), vis_read_hi(b13)); \
dd3 = vis_fpmerge(vis_read_lo(b02), vis_read_lo(b13)); \
}
/***************************************************************/
void ADD_SUFF(ThreeByteBgrToIntRgbConvert)(BLIT_PARAMS)
{
mlib_s32 dstScan = pDstInfo->scanStride;
mlib_s32 srcScan = pSrcInfo->scanStride;
mlib_d64 *sp;
mlib_d64 s_0;
mlib_d64 s0, s1, s2, s3, sd0, sd1, sd2, dd0, dd1, dd2, dd3;
mlib_s32 i, i0, j;
if (width < 16) {
for (j = 0; j < height; j++) {
mlib_u8 *src = srcBase;
mlib_s32 *dst = dstBase;
for (i = 0; i < width; i++) {
dst[i] = INT_RGB(src[3*i + 2], src[3*i + 1], src[3*i]);
}
PTR_ADD(dstBase, dstScan);
PTR_ADD(srcBase, srcScan);
}
return;
}
if (srcScan == 3*width && dstScan == 4*width) {
width *= height;
height = 1;
}
s_0 = vis_fzero();
for (j = 0; j < height; j++) {
mlib_u8 *src = srcBase;
mlib_f32 *dst = dstBase;
i = i0 = 0;
if ((mlib_s32)dst & 7) {
((mlib_s32*)dst)[i] = INT_RGB(src[3*i + 2], src[3*i + 1], src[3*i]);
i0 = 1;
}
sp = vis_alignaddr(src, 3*i0);
s3 = *sp++;
#pragma pipeloop(0)
for (i = i0; i <= (mlib_s32)width - 8; i += 8) {
s0 = s3;
s1 = *sp++;
s2 = *sp++;
s3 = *sp++;
sd0 = vis_faligndata(s0, s1);
sd1 = vis_faligndata(s1, s2);
sd2 = vis_faligndata(s2, s3);
BGR_TO_ARGB
*(mlib_d64*)(dst + i ) = dd0;
*(mlib_d64*)(dst + i + 2) = dd1;
*(mlib_d64*)(dst + i + 4) = dd2;
*(mlib_d64*)(dst + i + 6) = dd3;
}
for (; i < width; i++) {
((mlib_s32*)dst)[i] = INT_RGB(src[3*i + 2], src[3*i + 1], src[3*i]);
}
PTR_ADD(dstBase, dstScan);
PTR_ADD(srcBase, srcScan);
}
}
/***************************************************************/
void ADD_SUFF(ThreeByteBgrToIntRgbScaleConvert)(SCALE_PARAMS)
{
mlib_s32 dstScan = pDstInfo->scanStride;
mlib_s32 srcScan = pSrcInfo->scanStride;
mlib_d64 dd, maskFF;
mlib_s32 i, i0, i1, j;
if (width < 16) {
for (j = 0; j < height; j++) {
mlib_u8 *src = srcBase;
mlib_s32 *dst = dstBase;
mlib_s32 *dst_end = dst + width;
mlib_s32 tmpsxloc = sxloc;
PTR_ADD(src, (syloc >> shift) * srcScan);
for (; dst < dst_end; dst++) {
i = tmpsxloc >> shift;
tmpsxloc += sxinc;
*(mlib_s32*)dst = INT_RGB(src[3*i + 2], src[3*i + 1], src[3*i]);
}
PTR_ADD(dstBase, dstScan);
syloc += syinc;
}
return;
}
maskFF = vis_fzero();
vis_alignaddr(NULL, 7);
for (j = 0; j < height; j++) {
mlib_u8 *src = srcBase;
mlib_f32 *dst = dstBase;
mlib_f32 *dst_end = dst + width;
mlib_s32 tmpsxloc = sxloc;
PTR_ADD(src, (syloc >> shift) * srcScan);
if ((mlib_s32)dst & 7) {
i = tmpsxloc >> shift;
tmpsxloc += sxinc;
*(mlib_s32*)dst = INT_RGB(src[3*i + 2], src[3*i + 1], src[3*i]);
dst++;
}
#pragma pipeloop(0)
for (; dst <= dst_end - 2; dst += 2) {
i0 = tmpsxloc >> shift;
i1 = (tmpsxloc + sxinc) >> shift;
tmpsxloc += 2*sxinc;
dd = vis_faligndata(vis_ld_u8(src + 3*i1 ), dd);
dd = vis_faligndata(vis_ld_u8(src + 3*i1 + 1), dd);
dd = vis_faligndata(vis_ld_u8(src + 3*i1 + 2), dd);
dd = vis_faligndata(maskFF, dd);
dd = vis_faligndata(vis_ld_u8(src + 3*i0 ), dd);
dd = vis_faligndata(vis_ld_u8(src + 3*i0 + 1), dd);
dd = vis_faligndata(vis_ld_u8(src + 3*i0 + 2), dd);
dd = vis_faligndata(maskFF, dd);
*(mlib_d64*)dst = dd;
}
for (; dst < dst_end; dst++) {
i = tmpsxloc >> shift;
tmpsxloc += sxinc;
*(mlib_s32*)dst = INT_RGB(src[3*i + 2], src[3*i + 1], src[3*i]);
}
PTR_ADD(dstBase, dstScan);
syloc += syinc;
}
}
/***************************************************************/
void ADD_SUFF(ByteGrayToIntRgbConvert)(BLIT_PARAMS)
{
mlib_s32 dstScan = pDstInfo->scanStride;
mlib_s32 srcScan = pSrcInfo->scanStride;
mlib_d64 d0, d1, d2, d3;
mlib_f32 ff, aa = vis_fzero();
mlib_s32 i, j, x;
if (width < 8) {
for (j = 0; j < height; j++) {
mlib_u8 *src = srcBase;
mlib_s32 *dst = dstBase;
for (i = 0; i < width; i++) {
x = src[i];
dst[i] = Gray2Rgb(x);
}
PTR_ADD(dstBase, dstScan);
PTR_ADD(srcBase, srcScan);
}
return;
}
if (srcScan == width && dstScan == 4*width) {
width *= height;
height = 1;
}
for (j = 0; j < height; j++) {
mlib_u8 *src = srcBase;
mlib_s32 *dst = dstBase;
mlib_s32 *dst_end;
dst_end = dst + width;
while (((mlib_s32)src & 3) && dst < dst_end) {
x = *src++;
*dst++ = Gray2Rgb(x);
}
#pragma pipeloop(0)
for (; dst <= (dst_end - 4); dst += 4) {
ff = *(mlib_f32*)src;
d0 = vis_fpmerge(aa, ff);
d1 = vis_fpmerge(ff, ff);
d2 = vis_fpmerge(vis_read_hi(d0), vis_read_hi(d1));
d3 = vis_fpmerge(vis_read_lo(d0), vis_read_lo(d1));
((mlib_f32*)dst)[0] = vis_read_hi(d2);
((mlib_f32*)dst)[1] = vis_read_lo(d2);
((mlib_f32*)dst)[2] = vis_read_hi(d3);
((mlib_f32*)dst)[3] = vis_read_lo(d3);
src += 4;
}
while (dst < dst_end) {
x = *src++;
*dst++ = Gray2Rgb(x);
}
PTR_ADD(dstBase, dstScan);
PTR_ADD(srcBase, srcScan);
}
}
/***************************************************************/
void ADD_SUFF(ByteGrayToIntRgbScaleConvert)(SCALE_PARAMS)
{
mlib_s32 dstScan = pDstInfo->scanStride;
mlib_s32 srcScan = pSrcInfo->scanStride;
mlib_d64 d0, d1, d2, d3, dd;
mlib_f32 ff, aa = vis_fzero();
mlib_s32 i, j, x;
if (width < 16) {
for (j = 0; j < height; j++) {
mlib_u8 *src = srcBase;
mlib_s32 *dst = dstBase;
mlib_s32 tmpsxloc = sxloc;
PTR_ADD(src, (syloc >> shift) * srcScan);
for (i = 0; i < width; i++) {
x = src[tmpsxloc >> shift];
tmpsxloc += sxinc;
dst[i] = Gray2Rgb(x);
}
PTR_ADD(dstBase, dstScan);
syloc += syinc;
}
return;
}
vis_alignaddr(NULL, 7);
for (j = 0; j < height; j++) {
mlib_u8 *src = srcBase;
mlib_s32 *dst = dstBase;
mlib_s32 *dst_end;
mlib_s32 tmpsxloc = sxloc;
PTR_ADD(src, (syloc >> shift) * srcScan);
dst_end = dst + width;
#pragma pipeloop(0)
for (; dst <= (dst_end - 4); dst += 4) {
LOAD_NEXT_U8(dd, src + ((tmpsxloc + 3*sxinc) >> shift));
LOAD_NEXT_U8(dd, src + ((tmpsxloc + 2*sxinc) >> shift));
LOAD_NEXT_U8(dd, src + ((tmpsxloc + sxinc) >> shift));
LOAD_NEXT_U8(dd, src + ((tmpsxloc ) >> shift));
tmpsxloc += 4*sxinc;
ff = vis_read_hi(dd);
d0 = vis_fpmerge(aa, ff);
d1 = vis_fpmerge(ff, ff);
d2 = vis_fpmerge(vis_read_hi(d0), vis_read_hi(d1));
d3 = vis_fpmerge(vis_read_lo(d0), vis_read_lo(d1));
((mlib_f32*)dst)[0] = vis_read_hi(d2);
((mlib_f32*)dst)[1] = vis_read_lo(d2);
((mlib_f32*)dst)[2] = vis_read_hi(d3);
((mlib_f32*)dst)[3] = vis_read_lo(d3);
}
while (dst < dst_end) {
x = src[tmpsxloc >> shift];
tmpsxloc += sxinc;
*dst++ = Gray2Rgb(x);
}
PTR_ADD(dstBase, dstScan);
syloc += syinc;
}
}
/***************************************************************/
void ADD_SUFF(IntArgbBmToIntRgbXparOver)(BLIT_PARAMS)
{
mlib_s32 dstScan = pDstInfo->scanStride;
mlib_s32 srcScan = pSrcInfo->scanStride;
mlib_d64 dd;
mlib_s32 i, i0, j, mask;
if (dstScan == 4*width && srcScan == 4*width) {
width *= height;
height = 1;
}
for (j = 0; j < height; j++) {
mlib_f32 *src = srcBase;
mlib_f32 *dst = dstBase;
i = i0 = 0;
if ((mlib_s32)dst & 7) {
if (*(mlib_u8*)(src + i)) {
dst[i] = src[i];
}
i0 = 1;
}
#pragma pipeloop(0)
for (i = i0; i <= (mlib_s32)width - 2; i += 2) {
dd = vis_freg_pair(src[i], src[i + 1]);
mask = (((-*(mlib_u8*)(src + i)) >> 31) & 2) |
(((-*(mlib_u8*)(src + i + 1)) >> 31) & 1);
vis_pst_32(dd, dst + i, mask);
}
if (i < width) {
if (*(mlib_u8*)(src + i)) {
dst[i] = src[i];
}
}
PTR_ADD(dstBase, dstScan);
PTR_ADD(srcBase, srcScan);
}
}
/***************************************************************/
void ADD_SUFF(IntArgbBmToIntRgbXparBgCopy)(BCOPY_PARAMS)
{
mlib_s32 dstScan = pDstInfo->scanStride;
mlib_s32 srcScan = pSrcInfo->scanStride;
mlib_d64 dd, d_bgpixel;
mlib_s32 i, i0, j, mask;
if (dstScan == 4*width && srcScan == 4*width) {
width *= height;
height = 1;
}
d_bgpixel = vis_to_double_dup(bgpixel);
for (j = 0; j < height; j++) {
mlib_f32 *src = srcBase;
mlib_f32 *dst = dstBase;
i = i0 = 0;
if ((mlib_s32)dst & 7) {
if (*(mlib_u8*)(src + i)) {
dst[i] = src[i];
} else {
dst[i] = vis_read_hi(d_bgpixel);
}
i0 = 1;
}
#pragma pipeloop(0)
for (i = i0; i <= (mlib_s32)width - 2; i += 2) {
dd = vis_freg_pair(src[i], src[i + 1]);
mask = (((-*(mlib_u8*)(src + i)) >> 31) & 2) |
(((-*(mlib_u8*)(src + i + 1)) >> 31) & 1);
*(mlib_d64*)(dst + i) = d_bgpixel;
vis_pst_32(dd, dst + i, mask);
}
if (i < width) {
if (*(mlib_u8*)(src + i)) {
dst[i] = src[i];
} else {
dst[i] = vis_read_hi(d_bgpixel);
}
}
PTR_ADD(dstBase, dstScan);
PTR_ADD(srcBase, srcScan);
}
}
/***************************************************************/
void ADD_SUFF(IntRgbDrawGlyphListAA)(GLYPH_LIST_PARAMS)
{
mlib_s32 glyphCounter;
mlib_s32 scan = pRasInfo->scanStride;
mlib_u8 *dstBase;
mlib_s32 j;
mlib_d64 dmix0, dmix1, dd, d0, d1, e0, e1, fgpixel_d;
mlib_d64 done, done16, d_half, maskRGB, dzero;
mlib_s32 pix, mask, mask_z;
mlib_f32 srcG_f;
done = vis_to_double_dup(0x7fff7fff);
done16 = vis_to_double_dup(0x7fff);
d_half = vis_to_double_dup((1 << (16 + 6)) | (1 << 6));
fgpixel_d = vis_to_double_dup(fgpixel);
srcG_f = vis_to_float(argbcolor);
maskRGB = vis_to_double_dup(0xffffff);
dzero = vis_fzero();
vis_write_gsr(0 << 3);
for (glyphCounter = 0; glyphCounter < totalGlyphs; glyphCounter++) {
const jubyte *pixels;
unsigned int rowBytes;
int left, top;
int width, height;
int right, bottom;
pixels = (const jubyte *) glyphs[glyphCounter].pixels;
if (!pixels) continue;
left = glyphs[glyphCounter].x;
top = glyphs[glyphCounter].y;
width = glyphs[glyphCounter].width;
height = glyphs[glyphCounter].height;
rowBytes = width;
right = left + width;
bottom = top + height;
if (left < clipLeft) {
pixels += clipLeft - left;
left = clipLeft;
}
if (top < clipTop) {
pixels += (clipTop - top) * rowBytes;
top = clipTop;
}
if (right > clipRight) {
right = clipRight;
}
if (bottom > clipBottom) {
bottom = clipBottom;
}
if (right <= left || bottom <= top) {
continue;
}
width = right - left;
height = bottom - top;
dstBase = pRasInfo->rasBase;
PTR_ADD(dstBase, top*scan + 4*left);
for (j = 0; j < height; j++) {
mlib_u8 *src = (void*)pixels;
mlib_s32 *dst, *dst_end;
dst = (void*)dstBase;
dst_end = dst + width;
if ((mlib_s32)dst & 7) {
pix = *src++;
if (pix) {
dd = vis_fpadd16(MUL8_VIS(srcG_f, pix), d_half);
dd = vis_fpadd16(MUL8_VIS(*(mlib_f32*)dst, 255 - pix), dd);
*(mlib_f32*)dst = vis_fands(vis_fpack16(dd),
vis_read_hi(maskRGB));
if (pix == 255) *(mlib_f32*)dst = vis_read_hi(fgpixel_d);
}
dst++;
}
#pragma pipeloop(0)
for (; dst <= (dst_end - 2); dst += 2) {
dmix0 = vis_freg_pair(((mlib_f32 *)vis_mul8s_tbl)[src[0]],
((mlib_f32 *)vis_mul8s_tbl)[src[1]]);
mask = vis_fcmplt32(dmix0, done16);
mask_z = vis_fcmpne32(dmix0, dzero);
dmix1 = vis_fpsub16(done, dmix0);
src += 2;
dd = *(mlib_d64*)dst;
d0 = vis_fmul8x16al(srcG_f, vis_read_hi(dmix0));
d1 = vis_fmul8x16al(srcG_f, vis_read_lo(dmix0));
e0 = vis_fmul8x16al(vis_read_hi(dd), vis_read_hi(dmix1));
e1 = vis_fmul8x16al(vis_read_lo(dd), vis_read_lo(dmix1));
d0 = vis_fpadd16(vis_fpadd16(d0, d_half), e0);
d1 = vis_fpadd16(vis_fpadd16(d1, d_half), e1);
dd = vis_fpack16_pair(d0, d1);
dd = vis_fand(dd, maskRGB);
vis_pst_32(fgpixel_d, dst, mask_z);
vis_pst_32(dd, dst, mask & mask_z);
}
while (dst < dst_end) {
pix = *src++;
if (pix) {
dd = vis_fpadd16(MUL8_VIS(srcG_f, pix), d_half);
dd = vis_fpadd16(MUL8_VIS(*(mlib_f32*)dst, 255 - pix), dd);
*(mlib_f32*)dst = vis_fands(vis_fpack16(dd),
vis_read_hi(maskRGB));
if (pix == 255) *(mlib_f32*)dst = vis_read_hi(fgpixel_d);
}
dst++;
}
PTR_ADD(dstBase, scan);
pixels += rowBytes;
}
}
}
/***************************************************************/
#endif /* JAVA2D_NO_MLIB */
| gpl-2.0 |
googlehim/linux | arch/ia64/kernel/setup.c | 590 | 29309 | /*
* Architecture-specific setup.
*
* Copyright (C) 1998-2001, 2003-2004 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
* Stephane Eranian <eranian@hpl.hp.com>
* Copyright (C) 2000, 2004 Intel Corp
* Rohit Seth <rohit.seth@intel.com>
* Suresh Siddha <suresh.b.siddha@intel.com>
* Gordon Jin <gordon.jin@intel.com>
* Copyright (C) 1999 VA Linux Systems
* Copyright (C) 1999 Walt Drummond <drummond@valinux.com>
*
* 12/26/04 S.Siddha, G.Jin, R.Seth
* Add multi-threading and multi-core detection
* 11/12/01 D.Mosberger Convert get_cpuinfo() to seq_file based show_cpuinfo().
* 04/04/00 D.Mosberger renamed cpu_initialized to cpu_online_map
* 03/31/00 R.Seth cpu_initialized and current->processor fixes
* 02/04/00 D.Mosberger some more get_cpuinfo fixes...
* 02/01/00 R.Seth fixed get_cpuinfo for SMP
* 01/07/99 S.Eranian added the support for command line argument
* 06/24/99 W.Drummond added boot_cpu_data.
* 05/28/05 Z. Menyhart Dynamic stride size for "flush_icache_range()"
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/acpi.h>
#include <linux/bootmem.h>
#include <linux/console.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/reboot.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/string.h>
#include <linux/threads.h>
#include <linux/screen_info.h>
#include <linux/dmi.h>
#include <linux/serial.h>
#include <linux/serial_core.h>
#include <linux/efi.h>
#include <linux/initrd.h>
#include <linux/pm.h>
#include <linux/cpufreq.h>
#include <linux/kexec.h>
#include <linux/crash_dump.h>
#include <asm/machvec.h>
#include <asm/mca.h>
#include <asm/meminit.h>
#include <asm/page.h>
#include <asm/patch.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/sal.h>
#include <asm/sections.h>
#include <asm/setup.h>
#include <asm/smp.h>
#include <asm/tlbflush.h>
#include <asm/unistd.h>
#include <asm/hpsim.h>
#if defined(CONFIG_SMP) && (IA64_CPU_SIZE > PAGE_SIZE)
# error "struct cpuinfo_ia64 too big!"
#endif
#ifdef CONFIG_SMP
unsigned long __per_cpu_offset[NR_CPUS];
EXPORT_SYMBOL(__per_cpu_offset);
#endif
DEFINE_PER_CPU(struct cpuinfo_ia64, ia64_cpu_info);
DEFINE_PER_CPU(unsigned long, local_per_cpu_offset);
unsigned long ia64_cycles_per_usec;
struct ia64_boot_param *ia64_boot_param;
struct screen_info screen_info;
unsigned long vga_console_iobase;
unsigned long vga_console_membase;
static struct resource data_resource = {
.name = "Kernel data",
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
static struct resource code_resource = {
.name = "Kernel code",
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
static struct resource bss_resource = {
.name = "Kernel bss",
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
unsigned long ia64_max_cacheline_size;
unsigned long ia64_iobase; /* virtual address for I/O accesses */
EXPORT_SYMBOL(ia64_iobase);
struct io_space io_space[MAX_IO_SPACES];
EXPORT_SYMBOL(io_space);
unsigned int num_io_spaces;
/*
* "flush_icache_range()" needs to know what processor dependent stride size to use
* when it makes i-cache(s) coherent with d-caches.
*/
#define I_CACHE_STRIDE_SHIFT 5 /* Safest way to go: 32 bytes by 32 bytes */
unsigned long ia64_i_cache_stride_shift = ~0;
/*
* "clflush_cache_range()" needs to know what processor dependent stride size to
* use when it flushes cache lines including both d-cache and i-cache.
*/
/* Safest way to go: 32 bytes by 32 bytes */
#define CACHE_STRIDE_SHIFT 5
unsigned long ia64_cache_stride_shift = ~0;
/*
* The merge_mask variable needs to be set to (max(iommu_page_size(iommu)) - 1). This
* mask specifies a mask of address bits that must be 0 in order for two buffers to be
* mergeable by the I/O MMU (i.e., the end address of the first buffer and the start
* address of the second buffer must be aligned to (merge_mask+1) in order to be
* mergeable). By default, we assume there is no I/O MMU which can merge physically
* discontiguous buffers, so we set the merge_mask to ~0UL, which corresponds to a iommu
* page-size of 2^64.
*/
unsigned long ia64_max_iommu_merge_mask = ~0UL;
EXPORT_SYMBOL(ia64_max_iommu_merge_mask);
/*
* We use a special marker for the end of memory and it uses the extra (+1) slot
*/
struct rsvd_region rsvd_region[IA64_MAX_RSVD_REGIONS + 1] __initdata;
int num_rsvd_regions __initdata;
/*
* Filter incoming memory segments based on the primitive map created from the boot
* parameters. Segments contained in the map are removed from the memory ranges. A
* caller-specified function is called with the memory ranges that remain after filtering.
* This routine does not assume the incoming segments are sorted.
*/
int __init
filter_rsvd_memory (u64 start, u64 end, void *arg)
{
u64 range_start, range_end, prev_start;
void (*func)(unsigned long, unsigned long, int);
int i;
#if IGNORE_PFN0
if (start == PAGE_OFFSET) {
printk(KERN_WARNING "warning: skipping physical page 0\n");
start += PAGE_SIZE;
if (start >= end) return 0;
}
#endif
/*
* lowest possible address(walker uses virtual)
*/
prev_start = PAGE_OFFSET;
func = arg;
for (i = 0; i < num_rsvd_regions; ++i) {
range_start = max(start, prev_start);
range_end = min(end, rsvd_region[i].start);
if (range_start < range_end)
call_pernode_memory(__pa(range_start), range_end - range_start, func);
/* nothing more available in this segment */
if (range_end == end) return 0;
prev_start = rsvd_region[i].end;
}
/* end of memory marker allows full processing inside loop body */
return 0;
}
/*
* Similar to "filter_rsvd_memory()", but the reserved memory ranges
* are not filtered out.
*/
int __init
filter_memory(u64 start, u64 end, void *arg)
{
void (*func)(unsigned long, unsigned long, int);
#if IGNORE_PFN0
if (start == PAGE_OFFSET) {
printk(KERN_WARNING "warning: skipping physical page 0\n");
start += PAGE_SIZE;
if (start >= end)
return 0;
}
#endif
func = arg;
if (start < end)
call_pernode_memory(__pa(start), end - start, func);
return 0;
}
static void __init
sort_regions (struct rsvd_region *rsvd_region, int max)
{
int j;
/* simple bubble sorting */
while (max--) {
for (j = 0; j < max; ++j) {
if (rsvd_region[j].start > rsvd_region[j+1].start) {
struct rsvd_region tmp;
tmp = rsvd_region[j];
rsvd_region[j] = rsvd_region[j + 1];
rsvd_region[j + 1] = tmp;
}
}
}
}
/* merge overlaps */
static int __init
merge_regions (struct rsvd_region *rsvd_region, int max)
{
int i;
for (i = 1; i < max; ++i) {
if (rsvd_region[i].start >= rsvd_region[i-1].end)
continue;
if (rsvd_region[i].end > rsvd_region[i-1].end)
rsvd_region[i-1].end = rsvd_region[i].end;
--max;
memmove(&rsvd_region[i], &rsvd_region[i+1],
(max - i) * sizeof(struct rsvd_region));
}
return max;
}
/*
* Request address space for all standard resources
*/
static int __init register_memory(void)
{
code_resource.start = ia64_tpa(_text);
code_resource.end = ia64_tpa(_etext) - 1;
data_resource.start = ia64_tpa(_etext);
data_resource.end = ia64_tpa(_edata) - 1;
bss_resource.start = ia64_tpa(__bss_start);
bss_resource.end = ia64_tpa(_end) - 1;
efi_initialize_iomem_resources(&code_resource, &data_resource,
&bss_resource);
return 0;
}
__initcall(register_memory);
#ifdef CONFIG_KEXEC
/*
* This function checks if the reserved crashkernel is allowed on the specific
* IA64 machine flavour. Machines without an IO TLB use swiotlb and require
* some memory below 4 GB (i.e. in 32 bit area), see the implementation of
* lib/swiotlb.c. The hpzx1 architecture has an IO TLB but cannot use that
* in kdump case. See the comment in sba_init() in sba_iommu.c.
*
* So, the only machvec that really supports loading the kdump kernel
* over 4 GB is "sn2".
*/
static int __init check_crashkernel_memory(unsigned long pbase, size_t size)
{
if (ia64_platform_is("sn2") || ia64_platform_is("uv"))
return 1;
else
return pbase < (1UL << 32);
}
static void __init setup_crashkernel(unsigned long total, int *n)
{
unsigned long long base = 0, size = 0;
int ret;
ret = parse_crashkernel(boot_command_line, total,
&size, &base);
if (ret == 0 && size > 0) {
if (!base) {
sort_regions(rsvd_region, *n);
*n = merge_regions(rsvd_region, *n);
base = kdump_find_rsvd_region(size,
rsvd_region, *n);
}
if (!check_crashkernel_memory(base, size)) {
pr_warning("crashkernel: There would be kdump memory "
"at %ld GB but this is unusable because it "
"must\nbe below 4 GB. Change the memory "
"configuration of the machine.\n",
(unsigned long)(base >> 30));
return;
}
if (base != ~0UL) {
printk(KERN_INFO "Reserving %ldMB of memory at %ldMB "
"for crashkernel (System RAM: %ldMB)\n",
(unsigned long)(size >> 20),
(unsigned long)(base >> 20),
(unsigned long)(total >> 20));
rsvd_region[*n].start =
(unsigned long)__va(base);
rsvd_region[*n].end =
(unsigned long)__va(base + size);
(*n)++;
crashk_res.start = base;
crashk_res.end = base + size - 1;
}
}
efi_memmap_res.start = ia64_boot_param->efi_memmap;
efi_memmap_res.end = efi_memmap_res.start +
ia64_boot_param->efi_memmap_size;
boot_param_res.start = __pa(ia64_boot_param);
boot_param_res.end = boot_param_res.start +
sizeof(*ia64_boot_param);
}
#else
static inline void __init setup_crashkernel(unsigned long total, int *n)
{}
#endif
/**
* reserve_memory - setup reserved memory areas
*
* Setup the reserved memory areas set aside for the boot parameters,
* initrd, etc. There are currently %IA64_MAX_RSVD_REGIONS defined,
* see arch/ia64/include/asm/meminit.h if you need to define more.
*/
void __init
reserve_memory (void)
{
int n = 0;
unsigned long total_memory;
/*
* none of the entries in this table overlap
*/
rsvd_region[n].start = (unsigned long) ia64_boot_param;
rsvd_region[n].end = rsvd_region[n].start + sizeof(*ia64_boot_param);
n++;
rsvd_region[n].start = (unsigned long) __va(ia64_boot_param->efi_memmap);
rsvd_region[n].end = rsvd_region[n].start + ia64_boot_param->efi_memmap_size;
n++;
rsvd_region[n].start = (unsigned long) __va(ia64_boot_param->command_line);
rsvd_region[n].end = (rsvd_region[n].start
+ strlen(__va(ia64_boot_param->command_line)) + 1);
n++;
rsvd_region[n].start = (unsigned long) ia64_imva((void *)KERNEL_START);
rsvd_region[n].end = (unsigned long) ia64_imva(_end);
n++;
#ifdef CONFIG_BLK_DEV_INITRD
if (ia64_boot_param->initrd_start) {
rsvd_region[n].start = (unsigned long)__va(ia64_boot_param->initrd_start);
rsvd_region[n].end = rsvd_region[n].start + ia64_boot_param->initrd_size;
n++;
}
#endif
#ifdef CONFIG_CRASH_DUMP
if (reserve_elfcorehdr(&rsvd_region[n].start,
&rsvd_region[n].end) == 0)
n++;
#endif
total_memory = efi_memmap_init(&rsvd_region[n].start, &rsvd_region[n].end);
n++;
setup_crashkernel(total_memory, &n);
/* end of memory marker */
rsvd_region[n].start = ~0UL;
rsvd_region[n].end = ~0UL;
n++;
num_rsvd_regions = n;
BUG_ON(IA64_MAX_RSVD_REGIONS + 1 < n);
sort_regions(rsvd_region, num_rsvd_regions);
num_rsvd_regions = merge_regions(rsvd_region, num_rsvd_regions);
}
/**
* find_initrd - get initrd parameters from the boot parameter structure
*
* Grab the initrd start and end from the boot parameter struct given us by
* the boot loader.
*/
void __init
find_initrd (void)
{
#ifdef CONFIG_BLK_DEV_INITRD
if (ia64_boot_param->initrd_start) {
initrd_start = (unsigned long)__va(ia64_boot_param->initrd_start);
initrd_end = initrd_start+ia64_boot_param->initrd_size;
printk(KERN_INFO "Initial ramdisk at: 0x%lx (%llu bytes)\n",
initrd_start, ia64_boot_param->initrd_size);
}
#endif
}
static void __init
io_port_init (void)
{
unsigned long phys_iobase;
/*
* Set `iobase' based on the EFI memory map or, failing that, the
* value firmware left in ar.k0.
*
* Note that in ia32 mode, IN/OUT instructions use ar.k0 to compute
* the port's virtual address, so ia32_load_state() loads it with a
* user virtual address. But in ia64 mode, glibc uses the
* *physical* address in ar.k0 to mmap the appropriate area from
* /dev/mem, and the inX()/outX() interfaces use MMIO. In both
* cases, user-mode can only use the legacy 0-64K I/O port space.
*
* ar.k0 is not involved in kernel I/O port accesses, which can use
* any of the I/O port spaces and are done via MMIO using the
* virtual mmio_base from the appropriate io_space[].
*/
phys_iobase = efi_get_iobase();
if (!phys_iobase) {
phys_iobase = ia64_get_kr(IA64_KR_IO_BASE);
printk(KERN_INFO "No I/O port range found in EFI memory map, "
"falling back to AR.KR0 (0x%lx)\n", phys_iobase);
}
ia64_iobase = (unsigned long) ioremap(phys_iobase, 0);
ia64_set_kr(IA64_KR_IO_BASE, __pa(ia64_iobase));
/* setup legacy IO port space */
io_space[0].mmio_base = ia64_iobase;
io_space[0].sparse = 1;
num_io_spaces = 1;
}
/**
* early_console_setup - setup debugging console
*
* Consoles started here require little enough setup that we can start using
* them very early in the boot process, either right after the machine
* vector initialization, or even before if the drivers can detect their hw.
*
* Returns non-zero if a console couldn't be setup.
*/
static inline int __init
early_console_setup (char *cmdline)
{
int earlycons = 0;
#ifdef CONFIG_SERIAL_SGI_L1_CONSOLE
{
extern int sn_serial_console_early_setup(void);
if (!sn_serial_console_early_setup())
earlycons++;
}
#endif
#ifdef CONFIG_EFI_PCDP
if (!efi_setup_pcdp_console(cmdline))
earlycons++;
#endif
if (!simcons_register())
earlycons++;
return (earlycons) ? 0 : -1;
}
static inline void
mark_bsp_online (void)
{
#ifdef CONFIG_SMP
/* If we register an early console, allow CPU 0 to printk */
set_cpu_online(smp_processor_id(), true);
#endif
}
static __initdata int nomca;
static __init int setup_nomca(char *s)
{
nomca = 1;
return 0;
}
early_param("nomca", setup_nomca);
#ifdef CONFIG_CRASH_DUMP
int __init reserve_elfcorehdr(u64 *start, u64 *end)
{
u64 length;
/* We get the address using the kernel command line,
* but the size is extracted from the EFI tables.
* Both address and size are required for reservation
* to work properly.
*/
if (!is_vmcore_usable())
return -EINVAL;
if ((length = vmcore_find_descriptor_size(elfcorehdr_addr)) == 0) {
vmcore_unusable();
return -EINVAL;
}
*start = (unsigned long)__va(elfcorehdr_addr);
*end = *start + length;
return 0;
}
#endif /* CONFIG_PROC_VMCORE */
void __init
setup_arch (char **cmdline_p)
{
unw_init();
ia64_patch_vtop((u64) __start___vtop_patchlist, (u64) __end___vtop_patchlist);
*cmdline_p = __va(ia64_boot_param->command_line);
strlcpy(boot_command_line, *cmdline_p, COMMAND_LINE_SIZE);
efi_init();
io_port_init();
#ifdef CONFIG_IA64_GENERIC
/* machvec needs to be parsed from the command line
* before parse_early_param() is called to ensure
* that ia64_mv is initialised before any command line
* settings may cause console setup to occur
*/
machvec_init_from_cmdline(*cmdline_p);
#endif
parse_early_param();
if (early_console_setup(*cmdline_p) == 0)
mark_bsp_online();
#ifdef CONFIG_ACPI
/* Initialize the ACPI boot-time table parser */
acpi_table_init();
early_acpi_boot_init();
# ifdef CONFIG_ACPI_NUMA
acpi_numa_init();
# ifdef CONFIG_ACPI_HOTPLUG_CPU
prefill_possible_map();
# endif
per_cpu_scan_finalize((cpumask_weight(&early_cpu_possible_map) == 0 ?
32 : cpumask_weight(&early_cpu_possible_map)),
additional_cpus > 0 ? additional_cpus : 0);
# endif
#endif /* CONFIG_APCI_BOOT */
#ifdef CONFIG_SMP
smp_build_cpu_map();
#endif
find_memory();
/* process SAL system table: */
ia64_sal_init(__va(efi.sal_systab));
#ifdef CONFIG_ITANIUM
ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist);
#else
{
unsigned long num_phys_stacked;
if (ia64_pal_rse_info(&num_phys_stacked, 0) == 0 && num_phys_stacked > 96)
ia64_patch_rse((u64) __start___rse_patchlist, (u64) __end___rse_patchlist);
}
#endif
#ifdef CONFIG_SMP
cpu_physical_id(0) = hard_smp_processor_id();
#endif
cpu_init(); /* initialize the bootstrap CPU */
mmu_context_init(); /* initialize context_id bitmap */
#ifdef CONFIG_VT
if (!conswitchp) {
# if defined(CONFIG_DUMMY_CONSOLE)
conswitchp = &dummy_con;
# endif
# if defined(CONFIG_VGA_CONSOLE)
/*
* Non-legacy systems may route legacy VGA MMIO range to system
* memory. vga_con probes the MMIO hole, so memory looks like
* a VGA device to it. The EFI memory map can tell us if it's
* memory so we can avoid this problem.
*/
if (efi_mem_type(0xA0000) != EFI_CONVENTIONAL_MEMORY)
conswitchp = &vga_con;
# endif
}
#endif
/* enable IA-64 Machine Check Abort Handling unless disabled */
if (!nomca)
ia64_mca_init();
platform_setup(cmdline_p);
#ifndef CONFIG_IA64_HP_SIM
check_sal_cache_flush();
#endif
paging_init();
}
/*
* Display cpu info for all CPUs.
*/
static int
show_cpuinfo (struct seq_file *m, void *v)
{
#ifdef CONFIG_SMP
# define lpj c->loops_per_jiffy
# define cpunum c->cpu
#else
# define lpj loops_per_jiffy
# define cpunum 0
#endif
static struct {
unsigned long mask;
const char *feature_name;
} feature_bits[] = {
{ 1UL << 0, "branchlong" },
{ 1UL << 1, "spontaneous deferral"},
{ 1UL << 2, "16-byte atomic ops" }
};
char features[128], *cp, *sep;
struct cpuinfo_ia64 *c = v;
unsigned long mask;
unsigned long proc_freq;
int i, size;
mask = c->features;
/* build the feature string: */
memcpy(features, "standard", 9);
cp = features;
size = sizeof(features);
sep = "";
for (i = 0; i < ARRAY_SIZE(feature_bits) && size > 1; ++i) {
if (mask & feature_bits[i].mask) {
cp += snprintf(cp, size, "%s%s", sep,
feature_bits[i].feature_name),
sep = ", ";
mask &= ~feature_bits[i].mask;
size = sizeof(features) - (cp - features);
}
}
if (mask && size > 1) {
/* print unknown features as a hex value */
snprintf(cp, size, "%s0x%lx", sep, mask);
}
proc_freq = cpufreq_quick_get(cpunum);
if (!proc_freq)
proc_freq = c->proc_freq / 1000;
seq_printf(m,
"processor : %d\n"
"vendor : %s\n"
"arch : IA-64\n"
"family : %u\n"
"model : %u\n"
"model name : %s\n"
"revision : %u\n"
"archrev : %u\n"
"features : %s\n"
"cpu number : %lu\n"
"cpu regs : %u\n"
"cpu MHz : %lu.%03lu\n"
"itc MHz : %lu.%06lu\n"
"BogoMIPS : %lu.%02lu\n",
cpunum, c->vendor, c->family, c->model,
c->model_name, c->revision, c->archrev,
features, c->ppn, c->number,
proc_freq / 1000, proc_freq % 1000,
c->itc_freq / 1000000, c->itc_freq % 1000000,
lpj*HZ/500000, (lpj*HZ/5000) % 100);
#ifdef CONFIG_SMP
seq_printf(m, "siblings : %u\n",
cpumask_weight(&cpu_core_map[cpunum]));
if (c->socket_id != -1)
seq_printf(m, "physical id: %u\n", c->socket_id);
if (c->threads_per_core > 1 || c->cores_per_socket > 1)
seq_printf(m,
"core id : %u\n"
"thread id : %u\n",
c->core_id, c->thread_id);
#endif
seq_printf(m,"\n");
return 0;
}
static void *
c_start (struct seq_file *m, loff_t *pos)
{
#ifdef CONFIG_SMP
while (*pos < nr_cpu_ids && !cpu_online(*pos))
++*pos;
#endif
return *pos < nr_cpu_ids ? 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
};
#define MAX_BRANDS 8
static char brandname[MAX_BRANDS][128];
static char *
get_model_name(__u8 family, __u8 model)
{
static int overflow;
char brand[128];
int i;
memcpy(brand, "Unknown", 8);
if (ia64_pal_get_brand_info(brand)) {
if (family == 0x7)
memcpy(brand, "Merced", 7);
else if (family == 0x1f) switch (model) {
case 0: memcpy(brand, "McKinley", 9); break;
case 1: memcpy(brand, "Madison", 8); break;
case 2: memcpy(brand, "Madison up to 9M cache", 23); break;
}
}
for (i = 0; i < MAX_BRANDS; i++)
if (strcmp(brandname[i], brand) == 0)
return brandname[i];
for (i = 0; i < MAX_BRANDS; i++)
if (brandname[i][0] == '\0')
return strcpy(brandname[i], brand);
if (overflow++ == 0)
printk(KERN_ERR
"%s: Table overflow. Some processor model information will be missing\n",
__func__);
return "Unknown";
}
static void
identify_cpu (struct cpuinfo_ia64 *c)
{
union {
unsigned long bits[5];
struct {
/* id 0 & 1: */
char vendor[16];
/* id 2 */
u64 ppn; /* processor serial number */
/* id 3: */
unsigned number : 8;
unsigned revision : 8;
unsigned model : 8;
unsigned family : 8;
unsigned archrev : 8;
unsigned reserved : 24;
/* id 4: */
u64 features;
} field;
} cpuid;
pal_vm_info_1_u_t vm1;
pal_vm_info_2_u_t vm2;
pal_status_t status;
unsigned long impl_va_msb = 50, phys_addr_size = 44; /* Itanium defaults */
int i;
for (i = 0; i < 5; ++i)
cpuid.bits[i] = ia64_get_cpuid(i);
memcpy(c->vendor, cpuid.field.vendor, 16);
#ifdef CONFIG_SMP
c->cpu = smp_processor_id();
/* below default values will be overwritten by identify_siblings()
* for Multi-Threading/Multi-Core capable CPUs
*/
c->threads_per_core = c->cores_per_socket = c->num_log = 1;
c->socket_id = -1;
identify_siblings(c);
if (c->threads_per_core > smp_num_siblings)
smp_num_siblings = c->threads_per_core;
#endif
c->ppn = cpuid.field.ppn;
c->number = cpuid.field.number;
c->revision = cpuid.field.revision;
c->model = cpuid.field.model;
c->family = cpuid.field.family;
c->archrev = cpuid.field.archrev;
c->features = cpuid.field.features;
c->model_name = get_model_name(c->family, c->model);
status = ia64_pal_vm_summary(&vm1, &vm2);
if (status == PAL_STATUS_SUCCESS) {
impl_va_msb = vm2.pal_vm_info_2_s.impl_va_msb;
phys_addr_size = vm1.pal_vm_info_1_s.phys_add_size;
}
c->unimpl_va_mask = ~((7L<<61) | ((1L << (impl_va_msb + 1)) - 1));
c->unimpl_pa_mask = ~((1L<<63) | ((1L << phys_addr_size) - 1));
}
/*
* Do the following calculations:
*
* 1. the max. cache line size.
* 2. the minimum of the i-cache stride sizes for "flush_icache_range()".
* 3. the minimum of the cache stride sizes for "clflush_cache_range()".
*/
static void
get_cache_info(void)
{
unsigned long line_size, max = 1;
unsigned long l, levels, unique_caches;
pal_cache_config_info_t cci;
long status;
status = ia64_pal_cache_summary(&levels, &unique_caches);
if (status != 0) {
printk(KERN_ERR "%s: ia64_pal_cache_summary() failed (status=%ld)\n",
__func__, status);
max = SMP_CACHE_BYTES;
/* Safest setup for "flush_icache_range()" */
ia64_i_cache_stride_shift = I_CACHE_STRIDE_SHIFT;
/* Safest setup for "clflush_cache_range()" */
ia64_cache_stride_shift = CACHE_STRIDE_SHIFT;
goto out;
}
for (l = 0; l < levels; ++l) {
/* cache_type (data_or_unified)=2 */
status = ia64_pal_cache_config_info(l, 2, &cci);
if (status != 0) {
printk(KERN_ERR "%s: ia64_pal_cache_config_info"
"(l=%lu, 2) failed (status=%ld)\n",
__func__, l, status);
max = SMP_CACHE_BYTES;
/* The safest setup for "flush_icache_range()" */
cci.pcci_stride = I_CACHE_STRIDE_SHIFT;
/* The safest setup for "clflush_cache_range()" */
ia64_cache_stride_shift = CACHE_STRIDE_SHIFT;
cci.pcci_unified = 1;
} else {
if (cci.pcci_stride < ia64_cache_stride_shift)
ia64_cache_stride_shift = cci.pcci_stride;
line_size = 1 << cci.pcci_line_size;
if (line_size > max)
max = line_size;
}
if (!cci.pcci_unified) {
/* cache_type (instruction)=1*/
status = ia64_pal_cache_config_info(l, 1, &cci);
if (status != 0) {
printk(KERN_ERR "%s: ia64_pal_cache_config_info"
"(l=%lu, 1) failed (status=%ld)\n",
__func__, l, status);
/* The safest setup for flush_icache_range() */
cci.pcci_stride = I_CACHE_STRIDE_SHIFT;
}
}
if (cci.pcci_stride < ia64_i_cache_stride_shift)
ia64_i_cache_stride_shift = cci.pcci_stride;
}
out:
if (max > ia64_max_cacheline_size)
ia64_max_cacheline_size = max;
}
/*
* cpu_init() initializes state that is per-CPU. This function acts
* as a 'CPU state barrier', nothing should get across.
*/
void
cpu_init (void)
{
extern void ia64_mmu_init(void *);
static unsigned long max_num_phys_stacked = IA64_NUM_PHYS_STACK_REG;
unsigned long num_phys_stacked;
pal_vm_info_2_u_t vmi;
unsigned int max_ctx;
struct cpuinfo_ia64 *cpu_info;
void *cpu_data;
cpu_data = per_cpu_init();
#ifdef CONFIG_SMP
/*
* insert boot cpu into sibling and core mapes
* (must be done after per_cpu area is setup)
*/
if (smp_processor_id() == 0) {
cpumask_set_cpu(0, &per_cpu(cpu_sibling_map, 0));
cpumask_set_cpu(0, &cpu_core_map[0]);
} else {
/*
* Set ar.k3 so that assembly code in MCA handler can compute
* physical addresses of per cpu variables with a simple:
* phys = ar.k3 + &per_cpu_var
* and the alt-dtlb-miss handler can set per-cpu mapping into
* the TLB when needed. head.S already did this for cpu0.
*/
ia64_set_kr(IA64_KR_PER_CPU_DATA,
ia64_tpa(cpu_data) - (long) __per_cpu_start);
}
#endif
get_cache_info();
/*
* We can't pass "local_cpu_data" to identify_cpu() because we haven't called
* ia64_mmu_init() yet. And we can't call ia64_mmu_init() first because it
* depends on the data returned by identify_cpu(). We break the dependency by
* accessing cpu_data() through the canonical per-CPU address.
*/
cpu_info = cpu_data + ((char *) &__ia64_per_cpu_var(ia64_cpu_info) - __per_cpu_start);
identify_cpu(cpu_info);
#ifdef CONFIG_MCKINLEY
{
# define FEATURE_SET 16
struct ia64_pal_retval iprv;
if (cpu_info->family == 0x1f) {
PAL_CALL_PHYS(iprv, PAL_PROC_GET_FEATURES, 0, FEATURE_SET, 0);
if ((iprv.status == 0) && (iprv.v0 & 0x80) && (iprv.v2 & 0x80))
PAL_CALL_PHYS(iprv, PAL_PROC_SET_FEATURES,
(iprv.v1 | 0x80), FEATURE_SET, 0);
}
}
#endif
/* Clear the stack memory reserved for pt_regs: */
memset(task_pt_regs(current), 0, sizeof(struct pt_regs));
ia64_set_kr(IA64_KR_FPU_OWNER, 0);
/*
* Initialize the page-table base register to a global
* directory with all zeroes. This ensure that we can handle
* TLB-misses to user address-space even before we created the
* first user address-space. This may happen, e.g., due to
* aggressive use of lfetch.fault.
*/
ia64_set_kr(IA64_KR_PT_BASE, __pa(ia64_imva(empty_zero_page)));
/*
* Initialize default control register to defer speculative faults except
* for those arising from TLB misses, which are not deferred. The
* kernel MUST NOT depend on a particular setting of these bits (in other words,
* the kernel must have recovery code for all speculative accesses). Turn on
* dcr.lc as per recommendation by the architecture team. Most IA-32 apps
* shouldn't be affected by this (moral: keep your ia32 locks aligned and you'll
* be fine).
*/
ia64_setreg(_IA64_REG_CR_DCR, ( IA64_DCR_DP | IA64_DCR_DK | IA64_DCR_DX | IA64_DCR_DR
| IA64_DCR_DA | IA64_DCR_DD | IA64_DCR_LC));
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
BUG_ON(current->mm);
ia64_mmu_init(ia64_imva(cpu_data));
ia64_mca_cpu_init(ia64_imva(cpu_data));
/* Clear ITC to eliminate sched_clock() overflows in human time. */
ia64_set_itc(0);
/* disable all local interrupt sources: */
ia64_set_itv(1 << 16);
ia64_set_lrr0(1 << 16);
ia64_set_lrr1(1 << 16);
ia64_setreg(_IA64_REG_CR_PMV, 1 << 16);
ia64_setreg(_IA64_REG_CR_CMCV, 1 << 16);
/* clear TPR & XTP to enable all interrupt classes: */
ia64_setreg(_IA64_REG_CR_TPR, 0);
/* Clear any pending interrupts left by SAL/EFI */
while (ia64_get_ivr() != IA64_SPURIOUS_INT_VECTOR)
ia64_eoi();
#ifdef CONFIG_SMP
normal_xtp();
#endif
/* set ia64_ctx.max_rid to the maximum RID that is supported by all CPUs: */
if (ia64_pal_vm_summary(NULL, &vmi) == 0) {
max_ctx = (1U << (vmi.pal_vm_info_2_s.rid_size - 3)) - 1;
setup_ptcg_sem(vmi.pal_vm_info_2_s.max_purges, NPTCG_FROM_PAL);
} else {
printk(KERN_WARNING "cpu_init: PAL VM summary failed, assuming 18 RID bits\n");
max_ctx = (1U << 15) - 1; /* use architected minimum */
}
while (max_ctx < ia64_ctx.max_ctx) {
unsigned int old = ia64_ctx.max_ctx;
if (cmpxchg(&ia64_ctx.max_ctx, old, max_ctx) == old)
break;
}
if (ia64_pal_rse_info(&num_phys_stacked, NULL) != 0) {
printk(KERN_WARNING "cpu_init: PAL RSE info failed; assuming 96 physical "
"stacked regs\n");
num_phys_stacked = 96;
}
/* size of physical stacked register partition plus 8 bytes: */
if (num_phys_stacked > max_num_phys_stacked) {
ia64_patch_phys_stack_reg(num_phys_stacked*8 + 8);
max_num_phys_stacked = num_phys_stacked;
}
platform_cpu_init();
}
void __init
check_bugs (void)
{
ia64_patch_mckinley_e9((unsigned long) __start___mckinley_e9_bundles,
(unsigned long) __end___mckinley_e9_bundles);
}
static int __init run_dmi_scan(void)
{
dmi_scan_machine();
dmi_memdev_walk();
dmi_set_dump_stack_arch_desc();
return 0;
}
core_initcall(run_dmi_scan);
| gpl-2.0 |
showp1984/bricked-shooteru-ics-sense | drivers/net/appletalk/ltpc.c | 846 | 31523 | /*** ltpc.c -- a driver for the LocalTalk PC card.
*
* Copyright (c) 1995,1996 Bradford W. Johnson <johns393@maroon.tc.umn.edu>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* This is ALPHA code at best. It may not work for you. It may
* damage your equipment. It may damage your relations with other
* users of your network. Use it at your own risk!
*
* Based in part on:
* skeleton.c by Donald Becker
* dummy.c by Nick Holloway and Alan Cox
* loopback.c by Ross Biro, Fred van Kampen, Donald Becker
* the netatalk source code (UMICH)
* lots of work on the card...
*
* I do not have access to the (proprietary) SDK that goes with the card.
* If you do, I don't want to know about it, and you can probably write
* a better driver yourself anyway. This does mean that the pieces that
* talk to the card are guesswork on my part, so use at your own risk!
*
* This is my first try at writing Linux networking code, and is also
* guesswork. Again, use at your own risk! (Although on this part, I'd
* welcome suggestions)
*
* This is a loadable kernel module which seems to work at my site
* consisting of a 1.2.13 linux box running netatalk 1.3.3, and with
* the kernel support from 1.3.3b2 including patches routing.patch
* and ddp.disappears.from.chooser. In order to run it, you will need
* to patch ddp.c and aarp.c in the kernel, but only a little...
*
* I'm fairly confident that while this is arguably badly written, the
* problems that people experience will be "higher level", that is, with
* complications in the netatalk code. The driver itself doesn't do
* anything terribly complicated -- it pretends to be an ether device
* as far as netatalk is concerned, strips the DDP data out of the ether
* frame and builds a LLAP packet to send out the card. In the other
* direction, it receives LLAP frames from the card and builds a fake
* ether packet that it then tosses up to the networking code. You can
* argue (correctly) that this is an ugly way to do things, but it
* requires a minimal amount of fooling with the code in ddp.c and aarp.c.
*
* The card will do a lot more than is used here -- I *think* it has the
* layers up through ATP. Even if you knew how that part works (which I
* don't) it would be a big job to carve up the kernel ddp code to insert
* things at a higher level, and probably a bad idea...
*
* There are a number of other cards that do LocalTalk on the PC. If
* nobody finds any insurmountable (at the netatalk level) problems
* here, this driver should encourage people to put some work into the
* other cards (some of which I gather are still commercially available)
* and also to put hooks for LocalTalk into the official ddp code.
*
* I welcome comments and suggestions. This is my first try at Linux
* networking stuff, and there are probably lots of things that I did
* suboptimally.
*
***/
/***
*
* $Log: ltpc.c,v $
* Revision 1.1.2.1 2000/03/01 05:35:07 jgarzik
* at and tr cleanup
*
* Revision 1.8 1997/01/28 05:44:54 bradford
* Clean up for non-module a little.
* Hacked about a bit to clean things up - Alan Cox
* Probably broken it from the origina 1.8
*
* 1998/11/09: David Huggins-Daines <dhd@debian.org>
* Cleaned up the initialization code to use the standard autoirq methods,
and to probe for things in the standard order of i/o, irq, dma. This
removes the "reset the reset" hack, because I couldn't figure out an
easy way to get the card to trigger an interrupt after it.
* Added support for passing configuration parameters on the kernel command
line and through insmod
* Changed the device name from "ltalk0" to "lt0", both to conform with the
other localtalk driver, and to clear up the inconsistency between the
module and the non-module versions of the driver :-)
* Added a bunch of comments (I was going to make some enums for the state
codes and the register offsets, but I'm still not sure exactly what their
semantics are)
* Don't poll anymore in interrupt-driven mode
* It seems to work as a module now (as of 2.1.127), but I don't think
I'm responsible for that...
*
* Revision 1.7 1996/12/12 03:42:33 bradford
* DMA alloc cribbed from 3c505.c.
*
* Revision 1.6 1996/12/12 03:18:58 bradford
* Added virt_to_bus; works in 2.1.13.
*
* Revision 1.5 1996/12/12 03:13:22 root
* xmitQel initialization -- think through better though.
*
* Revision 1.4 1996/06/18 14:55:55 root
* Change names to ltpc. Tabs. Took a shot at dma alloc,
* although more needs to be done eventually.
*
* Revision 1.3 1996/05/22 14:59:39 root
* Change dev->open, dev->close to track dummy.c in 1.99.(around 7)
*
* Revision 1.2 1996/05/22 14:58:24 root
* Change tabs mostly.
*
* Revision 1.1 1996/04/23 04:45:09 root
* Initial revision
*
* Revision 0.16 1996/03/05 15:59:56 root
* Change ARPHRD_LOCALTLK definition to the "real" one.
*
* Revision 0.15 1996/03/05 06:28:30 root
* Changes for kernel 1.3.70. Still need a few patches to kernel, but
* it's getting closer.
*
* Revision 0.14 1996/02/25 17:38:32 root
* More cleanups. Removed query to card on get_stats.
*
* Revision 0.13 1996/02/21 16:27:40 root
* Refix debug_print_skb. Fix mac.raw gotcha that appeared in 1.3.65.
* Clean up receive code a little.
*
* Revision 0.12 1996/02/19 16:34:53 root
* Fix debug_print_skb. Kludge outgoing snet to 0 when using startup
* range. Change debug to mask: 1 for verbose, 2 for higher level stuff
* including packet printing, 4 for lower level (card i/o) stuff.
*
* Revision 0.11 1996/02/12 15:53:38 root
* Added router sends (requires new aarp.c patch)
*
* Revision 0.10 1996/02/11 00:19:35 root
* Change source LTALK_LOGGING debug switch to insmod ... debug=2.
*
* Revision 0.9 1996/02/10 23:59:35 root
* Fixed those fixes for 1.2 -- DANGER! The at.h that comes with netatalk
* has a *different* definition of struct sockaddr_at than the Linux kernel
* does. This is an "insidious and invidious" bug...
* (Actually the preceding comment is false -- it's the atalk.h in the
* ancient atalk-0.06 that's the problem)
*
* Revision 0.8 1996/02/10 19:09:00 root
* Merge 1.3 changes. Tested OK under 1.3.60.
*
* Revision 0.7 1996/02/10 17:56:56 root
* Added debug=1 parameter on insmod for debugging prints. Tried
* to fix timer unload on rmmod, but I don't think that's the problem.
*
* Revision 0.6 1995/12/31 19:01:09 root
* Clean up rmmod, irq comments per feedback from Corin Anderson (Thanks Corey!)
* Clean up initial probing -- sometimes the card wakes up latched in reset.
*
* Revision 0.5 1995/12/22 06:03:44 root
* Added comments in front and cleaned up a bit.
* This version sent out to people.
*
* Revision 0.4 1995/12/18 03:46:44 root
* Return shortDDP to longDDP fake to 0/0. Added command structs.
*
***/
/* ltpc jumpers are:
*
* Interrupts -- set at most one. If none are set, the driver uses
* polled mode. Because the card was developed in the XT era, the
* original documentation refers to IRQ2. Since you'll be running
* this on an AT (or later) class machine, that really means IRQ9.
*
* SW1 IRQ 4
* SW2 IRQ 3
* SW3 IRQ 9 (2 in original card documentation only applies to XT)
*
*
* DMA -- choose DMA 1 or 3, and set both corresponding switches.
*
* SW4 DMA 3
* SW5 DMA 1
* SW6 DMA 3
* SW7 DMA 1
*
*
* I/O address -- choose one.
*
* SW8 220 / 240
*/
/* To have some stuff logged, do
* insmod ltpc.o debug=1
*
* For a whole bunch of stuff, use higher numbers.
*
* The default is 0, i.e. no messages except for the probe results.
*/
/* insmod-tweakable variables */
static int debug;
#define DEBUG_VERBOSE 1
#define DEBUG_UPPER 2
#define DEBUG_LOWER 4
static int io;
static int irq;
static int dma;
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ptrace.h>
#include <linux/ioport.h>
#include <linux/spinlock.h>
#include <linux/in.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/if_ltalk.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/atalk.h>
#include <linux/bitops.h>
#include <linux/gfp.h>
#include <asm/system.h>
#include <asm/dma.h>
#include <asm/io.h>
/* our stuff */
#include "ltpc.h"
static DEFINE_SPINLOCK(txqueue_lock);
static DEFINE_SPINLOCK(mbox_lock);
/* function prototypes */
static int do_read(struct net_device *dev, void *cbuf, int cbuflen,
void *dbuf, int dbuflen);
static int sendup_buffer (struct net_device *dev);
/* Dma Memory related stuff, cribbed directly from 3c505.c */
static unsigned long dma_mem_alloc(int size)
{
int order = get_order(size);
return __get_dma_pages(GFP_KERNEL, order);
}
/* DMA data buffer, DMA command buffer */
static unsigned char *ltdmabuf;
static unsigned char *ltdmacbuf;
/* private struct, holds our appletalk address */
struct ltpc_private
{
struct atalk_addr my_addr;
};
/* transmit queue element struct */
struct xmitQel {
struct xmitQel *next;
/* command buffer */
unsigned char *cbuf;
short cbuflen;
/* data buffer */
unsigned char *dbuf;
short dbuflen;
unsigned char QWrite; /* read or write data */
unsigned char mailbox;
};
/* the transmit queue itself */
static struct xmitQel *xmQhd, *xmQtl;
static void enQ(struct xmitQel *qel)
{
unsigned long flags;
qel->next = NULL;
spin_lock_irqsave(&txqueue_lock, flags);
if (xmQtl) {
xmQtl->next = qel;
} else {
xmQhd = qel;
}
xmQtl = qel;
spin_unlock_irqrestore(&txqueue_lock, flags);
if (debug & DEBUG_LOWER)
printk("enqueued a 0x%02x command\n",qel->cbuf[0]);
}
static struct xmitQel *deQ(void)
{
unsigned long flags;
int i;
struct xmitQel *qel=NULL;
spin_lock_irqsave(&txqueue_lock, flags);
if (xmQhd) {
qel = xmQhd;
xmQhd = qel->next;
if(!xmQhd) xmQtl = NULL;
}
spin_unlock_irqrestore(&txqueue_lock, flags);
if ((debug & DEBUG_LOWER) && qel) {
int n;
printk(KERN_DEBUG "ltpc: dequeued command ");
n = qel->cbuflen;
if (n>100) n=100;
for(i=0;i<n;i++) printk("%02x ",qel->cbuf[i]);
printk("\n");
}
return qel;
}
/* and... the queue elements we'll be using */
static struct xmitQel qels[16];
/* and their corresponding mailboxes */
static unsigned char mailbox[16];
static unsigned char mboxinuse[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static int wait_timeout(struct net_device *dev, int c)
{
/* returns true if it stayed c */
/* this uses base+6, but it's ok */
int i;
/* twenty second or so total */
for(i=0;i<200000;i++) {
if ( c != inb_p(dev->base_addr+6) ) return 0;
udelay(100);
}
return 1; /* timed out */
}
/* get the first free mailbox */
static int getmbox(void)
{
unsigned long flags;
int i;
spin_lock_irqsave(&mbox_lock, flags);
for(i=1;i<16;i++) if(!mboxinuse[i]) {
mboxinuse[i]=1;
spin_unlock_irqrestore(&mbox_lock, flags);
return i;
}
spin_unlock_irqrestore(&mbox_lock, flags);
return 0;
}
/* read a command from the card */
static void handlefc(struct net_device *dev)
{
/* called *only* from idle, non-reentrant */
int dma = dev->dma;
int base = dev->base_addr;
unsigned long flags;
flags=claim_dma_lock();
disable_dma(dma);
clear_dma_ff(dma);
set_dma_mode(dma,DMA_MODE_READ);
set_dma_addr(dma,virt_to_bus(ltdmacbuf));
set_dma_count(dma,50);
enable_dma(dma);
release_dma_lock(flags);
inb_p(base+3);
inb_p(base+2);
if ( wait_timeout(dev,0xfc) ) printk("timed out in handlefc\n");
}
/* read data from the card */
static void handlefd(struct net_device *dev)
{
int dma = dev->dma;
int base = dev->base_addr;
unsigned long flags;
flags=claim_dma_lock();
disable_dma(dma);
clear_dma_ff(dma);
set_dma_mode(dma,DMA_MODE_READ);
set_dma_addr(dma,virt_to_bus(ltdmabuf));
set_dma_count(dma,800);
enable_dma(dma);
release_dma_lock(flags);
inb_p(base+3);
inb_p(base+2);
if ( wait_timeout(dev,0xfd) ) printk("timed out in handlefd\n");
sendup_buffer(dev);
}
static void handlewrite(struct net_device *dev)
{
/* called *only* from idle, non-reentrant */
/* on entry, 0xfb and ltdmabuf holds data */
int dma = dev->dma;
int base = dev->base_addr;
unsigned long flags;
flags=claim_dma_lock();
disable_dma(dma);
clear_dma_ff(dma);
set_dma_mode(dma,DMA_MODE_WRITE);
set_dma_addr(dma,virt_to_bus(ltdmabuf));
set_dma_count(dma,800);
enable_dma(dma);
release_dma_lock(flags);
inb_p(base+3);
inb_p(base+2);
if ( wait_timeout(dev,0xfb) ) {
flags=claim_dma_lock();
printk("timed out in handlewrite, dma res %d\n",
get_dma_residue(dev->dma) );
release_dma_lock(flags);
}
}
static void handleread(struct net_device *dev)
{
/* on entry, 0xfb */
/* on exit, ltdmabuf holds data */
int dma = dev->dma;
int base = dev->base_addr;
unsigned long flags;
flags=claim_dma_lock();
disable_dma(dma);
clear_dma_ff(dma);
set_dma_mode(dma,DMA_MODE_READ);
set_dma_addr(dma,virt_to_bus(ltdmabuf));
set_dma_count(dma,800);
enable_dma(dma);
release_dma_lock(flags);
inb_p(base+3);
inb_p(base+2);
if ( wait_timeout(dev,0xfb) ) printk("timed out in handleread\n");
}
static void handlecommand(struct net_device *dev)
{
/* on entry, 0xfa and ltdmacbuf holds command */
int dma = dev->dma;
int base = dev->base_addr;
unsigned long flags;
flags=claim_dma_lock();
disable_dma(dma);
clear_dma_ff(dma);
set_dma_mode(dma,DMA_MODE_WRITE);
set_dma_addr(dma,virt_to_bus(ltdmacbuf));
set_dma_count(dma,50);
enable_dma(dma);
release_dma_lock(flags);
inb_p(base+3);
inb_p(base+2);
if ( wait_timeout(dev,0xfa) ) printk("timed out in handlecommand\n");
}
/* ready made command for getting the result from the card */
static unsigned char rescbuf[2] = {LT_GETRESULT,0};
static unsigned char resdbuf[2];
static int QInIdle;
/* idle expects to be called with the IRQ line high -- either because of
* an interrupt, or because the line is tri-stated
*/
static void idle(struct net_device *dev)
{
unsigned long flags;
int state;
/* FIXME This is initialized to shut the warning up, but I need to
* think this through again.
*/
struct xmitQel *q = NULL;
int oops;
int i;
int base = dev->base_addr;
spin_lock_irqsave(&txqueue_lock, flags);
if(QInIdle) {
spin_unlock_irqrestore(&txqueue_lock, flags);
return;
}
QInIdle = 1;
spin_unlock_irqrestore(&txqueue_lock, flags);
/* this tri-states the IRQ line */
(void) inb_p(base+6);
oops = 100;
loop:
if (0>oops--) {
printk("idle: looped too many times\n");
goto done;
}
state = inb_p(base+6);
if (state != inb_p(base+6)) goto loop;
switch(state) {
case 0xfc:
/* incoming command */
if (debug & DEBUG_LOWER) printk("idle: fc\n");
handlefc(dev);
break;
case 0xfd:
/* incoming data */
if(debug & DEBUG_LOWER) printk("idle: fd\n");
handlefd(dev);
break;
case 0xf9:
/* result ready */
if (debug & DEBUG_LOWER) printk("idle: f9\n");
if(!mboxinuse[0]) {
mboxinuse[0] = 1;
qels[0].cbuf = rescbuf;
qels[0].cbuflen = 2;
qels[0].dbuf = resdbuf;
qels[0].dbuflen = 2;
qels[0].QWrite = 0;
qels[0].mailbox = 0;
enQ(&qels[0]);
}
inb_p(dev->base_addr+1);
inb_p(dev->base_addr+0);
if( wait_timeout(dev,0xf9) )
printk("timed out idle f9\n");
break;
case 0xf8:
/* ?? */
if (xmQhd) {
inb_p(dev->base_addr+1);
inb_p(dev->base_addr+0);
if(wait_timeout(dev,0xf8) )
printk("timed out idle f8\n");
} else {
goto done;
}
break;
case 0xfa:
/* waiting for command */
if(debug & DEBUG_LOWER) printk("idle: fa\n");
if (xmQhd) {
q=deQ();
memcpy(ltdmacbuf,q->cbuf,q->cbuflen);
ltdmacbuf[1] = q->mailbox;
if (debug>1) {
int n;
printk("ltpc: sent command ");
n = q->cbuflen;
if (n>100) n=100;
for(i=0;i<n;i++)
printk("%02x ",ltdmacbuf[i]);
printk("\n");
}
handlecommand(dev);
if(0xfa==inb_p(base+6)) {
/* we timed out, so return */
goto done;
}
} else {
/* we don't seem to have a command */
if (!mboxinuse[0]) {
mboxinuse[0] = 1;
qels[0].cbuf = rescbuf;
qels[0].cbuflen = 2;
qels[0].dbuf = resdbuf;
qels[0].dbuflen = 2;
qels[0].QWrite = 0;
qels[0].mailbox = 0;
enQ(&qels[0]);
} else {
printk("trouble: response command already queued\n");
goto done;
}
}
break;
case 0Xfb:
/* data transfer ready */
if(debug & DEBUG_LOWER) printk("idle: fb\n");
if(q->QWrite) {
memcpy(ltdmabuf,q->dbuf,q->dbuflen);
handlewrite(dev);
} else {
handleread(dev);
/* non-zero mailbox numbers are for
commmands, 0 is for GETRESULT
requests */
if(q->mailbox) {
memcpy(q->dbuf,ltdmabuf,q->dbuflen);
} else {
/* this was a result */
mailbox[ 0x0f & ltdmabuf[0] ] = ltdmabuf[1];
mboxinuse[0]=0;
}
}
break;
}
goto loop;
done:
QInIdle=0;
/* now set the interrupts back as appropriate */
/* the first read takes it out of tri-state (but still high) */
/* the second resets it */
/* note that after this point, any read of base+6 will
trigger an interrupt */
if (dev->irq) {
inb_p(base+7);
inb_p(base+7);
}
}
static int do_write(struct net_device *dev, void *cbuf, int cbuflen,
void *dbuf, int dbuflen)
{
int i = getmbox();
int ret;
if(i) {
qels[i].cbuf = (unsigned char *) cbuf;
qels[i].cbuflen = cbuflen;
qels[i].dbuf = (unsigned char *) dbuf;
qels[i].dbuflen = dbuflen;
qels[i].QWrite = 1;
qels[i].mailbox = i; /* this should be initted rather */
enQ(&qels[i]);
idle(dev);
ret = mailbox[i];
mboxinuse[i]=0;
return ret;
}
printk("ltpc: could not allocate mbox\n");
return -1;
}
static int do_read(struct net_device *dev, void *cbuf, int cbuflen,
void *dbuf, int dbuflen)
{
int i = getmbox();
int ret;
if(i) {
qels[i].cbuf = (unsigned char *) cbuf;
qels[i].cbuflen = cbuflen;
qels[i].dbuf = (unsigned char *) dbuf;
qels[i].dbuflen = dbuflen;
qels[i].QWrite = 0;
qels[i].mailbox = i; /* this should be initted rather */
enQ(&qels[i]);
idle(dev);
ret = mailbox[i];
mboxinuse[i]=0;
return ret;
}
printk("ltpc: could not allocate mbox\n");
return -1;
}
/* end of idle handlers -- what should be seen is do_read, do_write */
static struct timer_list ltpc_timer;
static netdev_tx_t ltpc_xmit(struct sk_buff *skb, struct net_device *dev);
static int read_30 ( struct net_device *dev)
{
lt_command c;
c.getflags.command = LT_GETFLAGS;
return do_read(dev, &c, sizeof(c.getflags),&c,0);
}
static int set_30 (struct net_device *dev,int x)
{
lt_command c;
c.setflags.command = LT_SETFLAGS;
c.setflags.flags = x;
return do_write(dev, &c, sizeof(c.setflags),&c,0);
}
/* LLAP to DDP translation */
static int sendup_buffer (struct net_device *dev)
{
/* on entry, command is in ltdmacbuf, data in ltdmabuf */
/* called from idle, non-reentrant */
int dnode, snode, llaptype, len;
int sklen;
struct sk_buff *skb;
struct lt_rcvlap *ltc = (struct lt_rcvlap *) ltdmacbuf;
if (ltc->command != LT_RCVLAP) {
printk("unknown command 0x%02x from ltpc card\n",ltc->command);
return(-1);
}
dnode = ltc->dnode;
snode = ltc->snode;
llaptype = ltc->laptype;
len = ltc->length;
sklen = len;
if (llaptype == 1)
sklen += 8; /* correct for short ddp */
if(sklen > 800) {
printk(KERN_INFO "%s: nonsense length in ltpc command 0x14: 0x%08x\n",
dev->name,sklen);
return -1;
}
if ( (llaptype==0) || (llaptype>2) ) {
printk(KERN_INFO "%s: unknown LLAP type: %d\n",dev->name,llaptype);
return -1;
}
skb = dev_alloc_skb(3+sklen);
if (skb == NULL)
{
printk("%s: dropping packet due to memory squeeze.\n",
dev->name);
return -1;
}
skb->dev = dev;
if (sklen > len)
skb_reserve(skb,8);
skb_put(skb,len+3);
skb->protocol = htons(ETH_P_LOCALTALK);
/* add LLAP header */
skb->data[0] = dnode;
skb->data[1] = snode;
skb->data[2] = llaptype;
skb_reset_mac_header(skb); /* save pointer to llap header */
skb_pull(skb,3);
/* copy ddp(s,e)hdr + contents */
skb_copy_to_linear_data(skb, ltdmabuf, len);
skb_reset_transport_header(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += skb->len;
/* toss it onwards */
netif_rx(skb);
return 0;
}
/* the handler for the board interrupt */
static irqreturn_t
ltpc_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
if (dev==NULL) {
printk("ltpc_interrupt: unknown device.\n");
return IRQ_NONE;
}
inb_p(dev->base_addr+6); /* disable further interrupts from board */
idle(dev); /* handle whatever is coming in */
/* idle re-enables interrupts from board */
return IRQ_HANDLED;
}
/***
*
* The ioctls that the driver responds to are:
*
* SIOCSIFADDR -- do probe using the passed node hint.
* SIOCGIFADDR -- return net, node.
*
* some of this stuff should be done elsewhere.
*
***/
static int ltpc_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct sockaddr_at *sa = (struct sockaddr_at *) &ifr->ifr_addr;
/* we'll keep the localtalk node address in dev->pa_addr */
struct ltpc_private *ltpc_priv = netdev_priv(dev);
struct atalk_addr *aa = <pc_priv->my_addr;
struct lt_init c;
int ltflags;
if(debug & DEBUG_VERBOSE) printk("ltpc_ioctl called\n");
switch(cmd) {
case SIOCSIFADDR:
aa->s_net = sa->sat_addr.s_net;
/* this does the probe and returns the node addr */
c.command = LT_INIT;
c.hint = sa->sat_addr.s_node;
aa->s_node = do_read(dev,&c,sizeof(c),&c,0);
/* get all llap frames raw */
ltflags = read_30(dev);
ltflags |= LT_FLAG_ALLLAP;
set_30 (dev,ltflags);
dev->broadcast[0] = 0xFF;
dev->dev_addr[0] = aa->s_node;
dev->addr_len=1;
return 0;
case SIOCGIFADDR:
sa->sat_addr.s_net = aa->s_net;
sa->sat_addr.s_node = aa->s_node;
return 0;
default:
return -EINVAL;
}
}
static void set_multicast_list(struct net_device *dev)
{
/* This needs to be present to keep netatalk happy. */
/* Actually netatalk needs fixing! */
}
static int ltpc_poll_counter;
static void ltpc_poll(unsigned long l)
{
struct net_device *dev = (struct net_device *) l;
del_timer(<pc_timer);
if(debug & DEBUG_VERBOSE) {
if (!ltpc_poll_counter) {
ltpc_poll_counter = 50;
printk("ltpc poll is alive\n");
}
ltpc_poll_counter--;
}
if (!dev)
return; /* we've been downed */
/* poll 20 times per second */
idle(dev);
ltpc_timer.expires = jiffies + HZ/20;
add_timer(<pc_timer);
}
/* DDP to LLAP translation */
static netdev_tx_t ltpc_xmit(struct sk_buff *skb, struct net_device *dev)
{
/* in kernel 1.3.xx, on entry skb->data points to ddp header,
* and skb->len is the length of the ddp data + ddp header
*/
int i;
struct lt_sendlap cbuf;
unsigned char *hdr;
cbuf.command = LT_SENDLAP;
cbuf.dnode = skb->data[0];
cbuf.laptype = skb->data[2];
skb_pull(skb,3); /* skip past LLAP header */
cbuf.length = skb->len; /* this is host order */
skb_reset_transport_header(skb);
if(debug & DEBUG_UPPER) {
printk("command ");
for(i=0;i<6;i++)
printk("%02x ",((unsigned char *)&cbuf)[i]);
printk("\n");
}
hdr = skb_transport_header(skb);
do_write(dev, &cbuf, sizeof(cbuf), hdr, skb->len);
if(debug & DEBUG_UPPER) {
printk("sent %d ddp bytes\n",skb->len);
for (i = 0; i < skb->len; i++)
printk("%02x ", hdr[i]);
printk("\n");
}
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
/* initialization stuff */
static int __init ltpc_probe_dma(int base, int dma)
{
int want = (dma == 3) ? 2 : (dma == 1) ? 1 : 3;
unsigned long timeout;
unsigned long f;
if (want & 1) {
if (request_dma(1,"ltpc")) {
want &= ~1;
} else {
f=claim_dma_lock();
disable_dma(1);
clear_dma_ff(1);
set_dma_mode(1,DMA_MODE_WRITE);
set_dma_addr(1,virt_to_bus(ltdmabuf));
set_dma_count(1,sizeof(struct lt_mem));
enable_dma(1);
release_dma_lock(f);
}
}
if (want & 2) {
if (request_dma(3,"ltpc")) {
want &= ~2;
} else {
f=claim_dma_lock();
disable_dma(3);
clear_dma_ff(3);
set_dma_mode(3,DMA_MODE_WRITE);
set_dma_addr(3,virt_to_bus(ltdmabuf));
set_dma_count(3,sizeof(struct lt_mem));
enable_dma(3);
release_dma_lock(f);
}
}
/* set up request */
/* FIXME -- do timings better! */
ltdmabuf[0] = LT_READMEM;
ltdmabuf[1] = 1; /* mailbox */
ltdmabuf[2] = 0; ltdmabuf[3] = 0; /* address */
ltdmabuf[4] = 0; ltdmabuf[5] = 1; /* read 0x0100 bytes */
ltdmabuf[6] = 0; /* dunno if this is necessary */
inb_p(io+1);
inb_p(io+0);
timeout = jiffies+100*HZ/100;
while(time_before(jiffies, timeout)) {
if ( 0xfa == inb_p(io+6) ) break;
}
inb_p(io+3);
inb_p(io+2);
while(time_before(jiffies, timeout)) {
if ( 0xfb == inb_p(io+6) ) break;
}
/* release the other dma channel (if we opened both of them) */
if ((want & 2) && (get_dma_residue(3)==sizeof(struct lt_mem))) {
want &= ~2;
free_dma(3);
}
if ((want & 1) && (get_dma_residue(1)==sizeof(struct lt_mem))) {
want &= ~1;
free_dma(1);
}
if (!want)
return 0;
return (want & 2) ? 3 : 1;
}
static const struct net_device_ops ltpc_netdev = {
.ndo_start_xmit = ltpc_xmit,
.ndo_do_ioctl = ltpc_ioctl,
.ndo_set_multicast_list = set_multicast_list,
};
struct net_device * __init ltpc_probe(void)
{
struct net_device *dev;
int err = -ENOMEM;
int x=0,y=0;
int autoirq;
unsigned long f;
unsigned long timeout;
dev = alloc_ltalkdev(sizeof(struct ltpc_private));
if (!dev)
goto out;
/* probe for the I/O port address */
if (io != 0x240 && request_region(0x220,8,"ltpc")) {
x = inb_p(0x220+6);
if ( (x!=0xff) && (x>=0xf0) ) {
io = 0x220;
goto got_port;
}
release_region(0x220,8);
}
if (io != 0x220 && request_region(0x240,8,"ltpc")) {
y = inb_p(0x240+6);
if ( (y!=0xff) && (y>=0xf0) ){
io = 0x240;
goto got_port;
}
release_region(0x240,8);
}
/* give up in despair */
printk(KERN_ERR "LocalTalk card not found; 220 = %02x, 240 = %02x.\n", x,y);
err = -ENODEV;
goto out1;
got_port:
/* probe for the IRQ line */
if (irq < 2) {
unsigned long irq_mask;
irq_mask = probe_irq_on();
/* reset the interrupt line */
inb_p(io+7);
inb_p(io+7);
/* trigger an interrupt (I hope) */
inb_p(io+6);
mdelay(2);
autoirq = probe_irq_off(irq_mask);
if (autoirq == 0) {
printk(KERN_ERR "ltpc: probe at %#x failed to detect IRQ line.\n", io);
} else {
irq = autoirq;
}
}
/* allocate a DMA buffer */
ltdmabuf = (unsigned char *) dma_mem_alloc(1000);
if (!ltdmabuf) {
printk(KERN_ERR "ltpc: mem alloc failed\n");
err = -ENOMEM;
goto out2;
}
ltdmacbuf = <dmabuf[800];
if(debug & DEBUG_VERBOSE) {
printk("ltdmabuf pointer %08lx\n",(unsigned long) ltdmabuf);
}
/* reset the card */
inb_p(io+1);
inb_p(io+3);
msleep(20);
inb_p(io+0);
inb_p(io+2);
inb_p(io+7); /* clear reset */
inb_p(io+4);
inb_p(io+5);
inb_p(io+5); /* enable dma */
inb_p(io+6); /* tri-state interrupt line */
ssleep(1);
/* now, figure out which dma channel we're using, unless it's
already been specified */
/* well, 0 is a legal DMA channel, but the LTPC card doesn't
use it... */
dma = ltpc_probe_dma(io, dma);
if (!dma) { /* no dma channel */
printk(KERN_ERR "No DMA channel found on ltpc card.\n");
err = -ENODEV;
goto out3;
}
/* print out friendly message */
if(irq)
printk(KERN_INFO "Apple/Farallon LocalTalk-PC card at %03x, IR%d, DMA%d.\n",io,irq,dma);
else
printk(KERN_INFO "Apple/Farallon LocalTalk-PC card at %03x, DMA%d. Using polled mode.\n",io,dma);
dev->netdev_ops = <pc_netdev;
dev->base_addr = io;
dev->irq = irq;
dev->dma = dma;
/* the card will want to send a result at this point */
/* (I think... leaving out this part makes the kernel crash,
so I put it back in...) */
f=claim_dma_lock();
disable_dma(dma);
clear_dma_ff(dma);
set_dma_mode(dma,DMA_MODE_READ);
set_dma_addr(dma,virt_to_bus(ltdmabuf));
set_dma_count(dma,0x100);
enable_dma(dma);
release_dma_lock(f);
(void) inb_p(io+3);
(void) inb_p(io+2);
timeout = jiffies+100*HZ/100;
while(time_before(jiffies, timeout)) {
if( 0xf9 == inb_p(io+6))
break;
schedule();
}
if(debug & DEBUG_VERBOSE) {
printk("setting up timer and irq\n");
}
/* grab it and don't let go :-) */
if (irq && request_irq( irq, ltpc_interrupt, 0, "ltpc", dev) >= 0)
{
(void) inb_p(io+7); /* enable interrupts from board */
(void) inb_p(io+7); /* and reset irq line */
} else {
if( irq )
printk(KERN_ERR "ltpc: IRQ already in use, using polled mode.\n");
dev->irq = 0;
/* polled mode -- 20 times per second */
/* this is really, really slow... should it poll more often? */
init_timer(<pc_timer);
ltpc_timer.function=ltpc_poll;
ltpc_timer.data = (unsigned long) dev;
ltpc_timer.expires = jiffies + HZ/20;
add_timer(<pc_timer);
}
err = register_netdev(dev);
if (err)
goto out4;
return NULL;
out4:
del_timer_sync(<pc_timer);
if (dev->irq)
free_irq(dev->irq, dev);
out3:
free_pages((unsigned long)ltdmabuf, get_order(1000));
out2:
release_region(io, 8);
out1:
free_netdev(dev);
out:
return ERR_PTR(err);
}
#ifndef MODULE
/* handles "ltpc=io,irq,dma" kernel command lines */
static int __init ltpc_setup(char *str)
{
int ints[5];
str = get_options(str, ARRAY_SIZE(ints), ints);
if (ints[0] == 0) {
if (str && !strncmp(str, "auto", 4)) {
/* do nothing :-) */
}
else {
/* usage message */
printk (KERN_ERR
"ltpc: usage: ltpc=auto|iobase[,irq[,dma]]\n");
return 0;
}
} else {
io = ints[1];
if (ints[0] > 1) {
irq = ints[2];
}
if (ints[0] > 2) {
dma = ints[3];
}
/* ignore any other parameters */
}
return 1;
}
__setup("ltpc=", ltpc_setup);
#endif /* MODULE */
static struct net_device *dev_ltpc;
#ifdef MODULE
MODULE_LICENSE("GPL");
module_param(debug, int, 0);
module_param(io, int, 0);
module_param(irq, int, 0);
module_param(dma, int, 0);
static int __init ltpc_module_init(void)
{
if(io == 0)
printk(KERN_NOTICE
"ltpc: Autoprobing is not recommended for modules\n");
dev_ltpc = ltpc_probe();
if (IS_ERR(dev_ltpc))
return PTR_ERR(dev_ltpc);
return 0;
}
module_init(ltpc_module_init);
#endif
static void __exit ltpc_cleanup(void)
{
if(debug & DEBUG_VERBOSE) printk("unregister_netdev\n");
unregister_netdev(dev_ltpc);
ltpc_timer.data = 0; /* signal the poll routine that we're done */
del_timer_sync(<pc_timer);
if(debug & DEBUG_VERBOSE) printk("freeing irq\n");
if (dev_ltpc->irq)
free_irq(dev_ltpc->irq, dev_ltpc);
if(debug & DEBUG_VERBOSE) printk("freeing dma\n");
if (dev_ltpc->dma)
free_dma(dev_ltpc->dma);
if(debug & DEBUG_VERBOSE) printk("freeing ioaddr\n");
if (dev_ltpc->base_addr)
release_region(dev_ltpc->base_addr,8);
free_netdev(dev_ltpc);
if(debug & DEBUG_VERBOSE) printk("free_pages\n");
free_pages( (unsigned long) ltdmabuf, get_order(1000));
if(debug & DEBUG_VERBOSE) printk("returning from cleanup_module\n");
}
module_exit(ltpc_cleanup);
| gpl-2.0 |
mozilla-b2g/kernel-omap | drivers/media/video/ivtv/ivtv-ioctl.c | 2382 | 53643 | /*
ioctl system call
Copyright (C) 2003-2004 Kevin Thayer <nufan_wfk at yahoo.com>
Copyright (C) 2005-2007 Hans Verkuil <hverkuil@xs4all.nl>
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 "ivtv-driver.h"
#include "ivtv-version.h"
#include "ivtv-mailbox.h"
#include "ivtv-i2c.h"
#include "ivtv-queue.h"
#include "ivtv-fileops.h"
#include "ivtv-vbi.h"
#include "ivtv-routing.h"
#include "ivtv-streams.h"
#include "ivtv-yuv.h"
#include "ivtv-ioctl.h"
#include "ivtv-gpio.h"
#include "ivtv-controls.h"
#include "ivtv-cards.h"
#include <media/saa7127.h>
#include <media/tveeprom.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-event.h>
#include <linux/dvb/audio.h>
u16 ivtv_service2vbi(int type)
{
switch (type) {
case V4L2_SLICED_TELETEXT_B:
return IVTV_SLICED_TYPE_TELETEXT_B;
case V4L2_SLICED_CAPTION_525:
return IVTV_SLICED_TYPE_CAPTION_525;
case V4L2_SLICED_WSS_625:
return IVTV_SLICED_TYPE_WSS_625;
case V4L2_SLICED_VPS:
return IVTV_SLICED_TYPE_VPS;
default:
return 0;
}
}
static int valid_service_line(int field, int line, int is_pal)
{
return (is_pal && line >= 6 && (line != 23 || field == 0)) ||
(!is_pal && line >= 10 && line < 22);
}
static u16 select_service_from_set(int field, int line, u16 set, int is_pal)
{
u16 valid_set = (is_pal ? V4L2_SLICED_VBI_625 : V4L2_SLICED_VBI_525);
int i;
set = set & valid_set;
if (set == 0 || !valid_service_line(field, line, is_pal)) {
return 0;
}
if (!is_pal) {
if (line == 21 && (set & V4L2_SLICED_CAPTION_525))
return V4L2_SLICED_CAPTION_525;
}
else {
if (line == 16 && field == 0 && (set & V4L2_SLICED_VPS))
return V4L2_SLICED_VPS;
if (line == 23 && field == 0 && (set & V4L2_SLICED_WSS_625))
return V4L2_SLICED_WSS_625;
if (line == 23)
return 0;
}
for (i = 0; i < 32; i++) {
if ((1 << i) & set)
return 1 << i;
}
return 0;
}
void ivtv_expand_service_set(struct v4l2_sliced_vbi_format *fmt, int is_pal)
{
u16 set = fmt->service_set;
int f, l;
fmt->service_set = 0;
for (f = 0; f < 2; f++) {
for (l = 0; l < 24; l++) {
fmt->service_lines[f][l] = select_service_from_set(f, l, set, is_pal);
}
}
}
static void check_service_set(struct v4l2_sliced_vbi_format *fmt, int is_pal)
{
int f, l;
for (f = 0; f < 2; f++) {
for (l = 0; l < 24; l++) {
fmt->service_lines[f][l] = select_service_from_set(f, l, fmt->service_lines[f][l], is_pal);
}
}
}
u16 ivtv_get_service_set(struct v4l2_sliced_vbi_format *fmt)
{
int f, l;
u16 set = 0;
for (f = 0; f < 2; f++) {
for (l = 0; l < 24; l++) {
set |= fmt->service_lines[f][l];
}
}
return set;
}
void ivtv_set_osd_alpha(struct ivtv *itv)
{
ivtv_vapi(itv, CX2341X_OSD_SET_GLOBAL_ALPHA, 3,
itv->osd_global_alpha_state, itv->osd_global_alpha, !itv->osd_local_alpha_state);
ivtv_vapi(itv, CX2341X_OSD_SET_CHROMA_KEY, 2, itv->osd_chroma_key_state, itv->osd_chroma_key);
}
int ivtv_set_speed(struct ivtv *itv, int speed)
{
u32 data[CX2341X_MBOX_MAX_DATA];
struct ivtv_stream *s;
int single_step = (speed == 1 || speed == -1);
DEFINE_WAIT(wait);
if (speed == 0) speed = 1000;
/* No change? */
if (speed == itv->speed && !single_step)
return 0;
s = &itv->streams[IVTV_DEC_STREAM_TYPE_MPG];
if (single_step && (speed < 0) == (itv->speed < 0)) {
/* Single step video and no need to change direction */
ivtv_vapi(itv, CX2341X_DEC_STEP_VIDEO, 1, 0);
itv->speed = speed;
return 0;
}
if (single_step)
/* Need to change direction */
speed = speed < 0 ? -1000 : 1000;
data[0] = (speed > 1000 || speed < -1000) ? 0x80000000 : 0;
data[0] |= (speed > 1000 || speed < -1500) ? 0x40000000 : 0;
data[1] = (speed < 0);
data[2] = speed < 0 ? 3 : 7;
data[3] = v4l2_ctrl_g_ctrl(itv->cxhdl.video_b_frames);
data[4] = (speed == 1500 || speed == 500) ? itv->speed_mute_audio : 0;
data[5] = 0;
data[6] = 0;
if (speed == 1500 || speed == -1500) data[0] |= 1;
else if (speed == 2000 || speed == -2000) data[0] |= 2;
else if (speed > -1000 && speed < 0) data[0] |= (-1000 / speed);
else if (speed < 1000 && speed > 0) data[0] |= (1000 / speed);
/* If not decoding, just change speed setting */
if (atomic_read(&itv->decoding) > 0) {
int got_sig = 0;
/* Stop all DMA and decoding activity */
ivtv_vapi(itv, CX2341X_DEC_PAUSE_PLAYBACK, 1, 0);
/* Wait for any DMA to finish */
prepare_to_wait(&itv->dma_waitq, &wait, TASK_INTERRUPTIBLE);
while (test_bit(IVTV_F_I_DMA, &itv->i_flags)) {
got_sig = signal_pending(current);
if (got_sig)
break;
got_sig = 0;
schedule();
}
finish_wait(&itv->dma_waitq, &wait);
if (got_sig)
return -EINTR;
/* Change Speed safely */
ivtv_api(itv, CX2341X_DEC_SET_PLAYBACK_SPEED, 7, data);
IVTV_DEBUG_INFO("Setting Speed to 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
data[0], data[1], data[2], data[3], data[4], data[5], data[6]);
}
if (single_step) {
speed = (speed < 0) ? -1 : 1;
ivtv_vapi(itv, CX2341X_DEC_STEP_VIDEO, 1, 0);
}
itv->speed = speed;
return 0;
}
static int ivtv_validate_speed(int cur_speed, int new_speed)
{
int fact = new_speed < 0 ? -1 : 1;
int s;
if (cur_speed == 0)
cur_speed = 1000;
if (new_speed < 0)
new_speed = -new_speed;
if (cur_speed < 0)
cur_speed = -cur_speed;
if (cur_speed <= new_speed) {
if (new_speed > 1500)
return fact * 2000;
if (new_speed > 1000)
return fact * 1500;
}
else {
if (new_speed >= 2000)
return fact * 2000;
if (new_speed >= 1500)
return fact * 1500;
if (new_speed >= 1000)
return fact * 1000;
}
if (new_speed == 0)
return 1000;
if (new_speed == 1 || new_speed == 1000)
return fact * new_speed;
s = new_speed;
new_speed = 1000 / new_speed;
if (1000 / cur_speed == new_speed)
new_speed += (cur_speed < s) ? -1 : 1;
if (new_speed > 60) return 1000 / (fact * 60);
return 1000 / (fact * new_speed);
}
static int ivtv_video_command(struct ivtv *itv, struct ivtv_open_id *id,
struct video_command *vc, int try)
{
struct ivtv_stream *s = &itv->streams[IVTV_DEC_STREAM_TYPE_MPG];
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
switch (vc->cmd) {
case VIDEO_CMD_PLAY: {
vc->flags = 0;
vc->play.speed = ivtv_validate_speed(itv->speed, vc->play.speed);
if (vc->play.speed < 0)
vc->play.format = VIDEO_PLAY_FMT_GOP;
if (try) break;
if (ivtv_set_output_mode(itv, OUT_MPG) != OUT_MPG)
return -EBUSY;
if (test_and_clear_bit(IVTV_F_I_DEC_PAUSED, &itv->i_flags)) {
/* forces ivtv_set_speed to be called */
itv->speed = 0;
}
return ivtv_start_decoding(id, vc->play.speed);
}
case VIDEO_CMD_STOP:
vc->flags &= VIDEO_CMD_STOP_IMMEDIATELY|VIDEO_CMD_STOP_TO_BLACK;
if (vc->flags & VIDEO_CMD_STOP_IMMEDIATELY)
vc->stop.pts = 0;
if (try) break;
if (atomic_read(&itv->decoding) == 0)
return 0;
if (itv->output_mode != OUT_MPG)
return -EBUSY;
itv->output_mode = OUT_NONE;
return ivtv_stop_v4l2_decode_stream(s, vc->flags, vc->stop.pts);
case VIDEO_CMD_FREEZE:
vc->flags &= VIDEO_CMD_FREEZE_TO_BLACK;
if (try) break;
if (itv->output_mode != OUT_MPG)
return -EBUSY;
if (atomic_read(&itv->decoding) > 0) {
ivtv_vapi(itv, CX2341X_DEC_PAUSE_PLAYBACK, 1,
(vc->flags & VIDEO_CMD_FREEZE_TO_BLACK) ? 1 : 0);
set_bit(IVTV_F_I_DEC_PAUSED, &itv->i_flags);
}
break;
case VIDEO_CMD_CONTINUE:
vc->flags = 0;
if (try) break;
if (itv->output_mode != OUT_MPG)
return -EBUSY;
if (test_and_clear_bit(IVTV_F_I_DEC_PAUSED, &itv->i_flags)) {
int speed = itv->speed;
itv->speed = 0;
return ivtv_start_decoding(id, speed);
}
break;
default:
return -EINVAL;
}
return 0;
}
static int ivtv_g_fmt_sliced_vbi_out(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv *itv = fh2id(fh)->itv;
struct v4l2_sliced_vbi_format *vbifmt = &fmt->fmt.sliced;
vbifmt->reserved[0] = 0;
vbifmt->reserved[1] = 0;
if (!(itv->v4l2_cap & V4L2_CAP_SLICED_VBI_OUTPUT))
return -EINVAL;
vbifmt->io_size = sizeof(struct v4l2_sliced_vbi_data) * 36;
if (itv->is_60hz) {
vbifmt->service_lines[0][21] = V4L2_SLICED_CAPTION_525;
vbifmt->service_lines[1][21] = V4L2_SLICED_CAPTION_525;
} else {
vbifmt->service_lines[0][23] = V4L2_SLICED_WSS_625;
vbifmt->service_lines[0][16] = V4L2_SLICED_VPS;
}
vbifmt->service_set = ivtv_get_service_set(vbifmt);
return 0;
}
static int ivtv_g_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
struct v4l2_pix_format *pixfmt = &fmt->fmt.pix;
pixfmt->width = itv->cxhdl.width;
pixfmt->height = itv->cxhdl.height;
pixfmt->colorspace = V4L2_COLORSPACE_SMPTE170M;
pixfmt->field = V4L2_FIELD_INTERLACED;
pixfmt->priv = 0;
if (id->type == IVTV_ENC_STREAM_TYPE_YUV) {
pixfmt->pixelformat = V4L2_PIX_FMT_HM12;
/* YUV size is (Y=(h*720) + UV=(h*(720/2))) */
pixfmt->sizeimage = pixfmt->height * 720 * 3 / 2;
pixfmt->bytesperline = 720;
} else {
pixfmt->pixelformat = V4L2_PIX_FMT_MPEG;
pixfmt->sizeimage = 128 * 1024;
pixfmt->bytesperline = 0;
}
return 0;
}
static int ivtv_g_fmt_vbi_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv *itv = fh2id(fh)->itv;
struct v4l2_vbi_format *vbifmt = &fmt->fmt.vbi;
vbifmt->sampling_rate = 27000000;
vbifmt->offset = 248;
vbifmt->samples_per_line = itv->vbi.raw_decoder_line_size - 4;
vbifmt->sample_format = V4L2_PIX_FMT_GREY;
vbifmt->start[0] = itv->vbi.start[0];
vbifmt->start[1] = itv->vbi.start[1];
vbifmt->count[0] = vbifmt->count[1] = itv->vbi.count;
vbifmt->flags = 0;
vbifmt->reserved[0] = 0;
vbifmt->reserved[1] = 0;
return 0;
}
static int ivtv_g_fmt_sliced_vbi_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct v4l2_sliced_vbi_format *vbifmt = &fmt->fmt.sliced;
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
vbifmt->reserved[0] = 0;
vbifmt->reserved[1] = 0;
vbifmt->io_size = sizeof(struct v4l2_sliced_vbi_data) * 36;
if (id->type == IVTV_DEC_STREAM_TYPE_VBI) {
vbifmt->service_set = itv->is_50hz ? V4L2_SLICED_VBI_625 :
V4L2_SLICED_VBI_525;
ivtv_expand_service_set(vbifmt, itv->is_50hz);
return 0;
}
v4l2_subdev_call(itv->sd_video, vbi, g_sliced_fmt, vbifmt);
vbifmt->service_set = ivtv_get_service_set(vbifmt);
return 0;
}
static int ivtv_g_fmt_vid_out(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
struct v4l2_pix_format *pixfmt = &fmt->fmt.pix;
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
pixfmt->width = itv->main_rect.width;
pixfmt->height = itv->main_rect.height;
pixfmt->colorspace = V4L2_COLORSPACE_SMPTE170M;
pixfmt->field = V4L2_FIELD_INTERLACED;
pixfmt->priv = 0;
if (id->type == IVTV_DEC_STREAM_TYPE_YUV) {
switch (itv->yuv_info.lace_mode & IVTV_YUV_MODE_MASK) {
case IVTV_YUV_MODE_INTERLACED:
pixfmt->field = (itv->yuv_info.lace_mode & IVTV_YUV_SYNC_MASK) ?
V4L2_FIELD_INTERLACED_BT : V4L2_FIELD_INTERLACED_TB;
break;
case IVTV_YUV_MODE_PROGRESSIVE:
pixfmt->field = V4L2_FIELD_NONE;
break;
default:
pixfmt->field = V4L2_FIELD_ANY;
break;
}
pixfmt->pixelformat = V4L2_PIX_FMT_HM12;
pixfmt->bytesperline = 720;
pixfmt->width = itv->yuv_info.v4l2_src_w;
pixfmt->height = itv->yuv_info.v4l2_src_h;
/* YUV size is (Y=(h*w) + UV=(h*(w/2))) */
pixfmt->sizeimage =
1080 * ((pixfmt->height + 31) & ~31);
} else {
pixfmt->pixelformat = V4L2_PIX_FMT_MPEG;
pixfmt->sizeimage = 128 * 1024;
pixfmt->bytesperline = 0;
}
return 0;
}
static int ivtv_g_fmt_vid_out_overlay(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv *itv = fh2id(fh)->itv;
struct v4l2_window *winfmt = &fmt->fmt.win;
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
winfmt->chromakey = itv->osd_chroma_key;
winfmt->global_alpha = itv->osd_global_alpha;
winfmt->field = V4L2_FIELD_INTERLACED;
winfmt->clips = NULL;
winfmt->clipcount = 0;
winfmt->bitmap = NULL;
winfmt->w.top = winfmt->w.left = 0;
winfmt->w.width = itv->osd_rect.width;
winfmt->w.height = itv->osd_rect.height;
return 0;
}
static int ivtv_try_fmt_sliced_vbi_out(struct file *file, void *fh, struct v4l2_format *fmt)
{
return ivtv_g_fmt_sliced_vbi_out(file, fh, fmt);
}
static int ivtv_try_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
int w = fmt->fmt.pix.width;
int h = fmt->fmt.pix.height;
int min_h = 2;
w = min(w, 720);
w = max(w, 2);
if (id->type == IVTV_ENC_STREAM_TYPE_YUV) {
/* YUV height must be a multiple of 32 */
h &= ~0x1f;
min_h = 32;
}
h = min(h, itv->is_50hz ? 576 : 480);
h = max(h, min_h);
ivtv_g_fmt_vid_cap(file, fh, fmt);
fmt->fmt.pix.width = w;
fmt->fmt.pix.height = h;
return 0;
}
static int ivtv_try_fmt_vbi_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
return ivtv_g_fmt_vbi_cap(file, fh, fmt);
}
static int ivtv_try_fmt_sliced_vbi_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct v4l2_sliced_vbi_format *vbifmt = &fmt->fmt.sliced;
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
if (id->type == IVTV_DEC_STREAM_TYPE_VBI)
return ivtv_g_fmt_sliced_vbi_cap(file, fh, fmt);
/* set sliced VBI capture format */
vbifmt->io_size = sizeof(struct v4l2_sliced_vbi_data) * 36;
vbifmt->reserved[0] = 0;
vbifmt->reserved[1] = 0;
if (vbifmt->service_set)
ivtv_expand_service_set(vbifmt, itv->is_50hz);
check_service_set(vbifmt, itv->is_50hz);
vbifmt->service_set = ivtv_get_service_set(vbifmt);
return 0;
}
static int ivtv_try_fmt_vid_out(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv_open_id *id = fh2id(fh);
s32 w = fmt->fmt.pix.width;
s32 h = fmt->fmt.pix.height;
int field = fmt->fmt.pix.field;
int ret = ivtv_g_fmt_vid_out(file, fh, fmt);
w = min(w, 720);
w = max(w, 2);
/* Why can the height be 576 even when the output is NTSC?
Internally the buffers of the PVR350 are always set to 720x576. The
decoded video frame will always be placed in the top left corner of
this buffer. For any video which is not 720x576, the buffer will
then be cropped to remove the unused right and lower areas, with
the remaining image being scaled by the hardware to fit the display
area. The video can be scaled both up and down, so a 720x480 video
can be displayed full-screen on PAL and a 720x576 video can be
displayed without cropping on NTSC.
Note that the scaling only occurs on the video stream, the osd
resolution is locked to the broadcast standard and not scaled.
Thanks to Ian Armstrong for this explanation. */
h = min(h, 576);
h = max(h, 2);
if (id->type == IVTV_DEC_STREAM_TYPE_YUV)
fmt->fmt.pix.field = field;
fmt->fmt.pix.width = w;
fmt->fmt.pix.height = h;
return ret;
}
static int ivtv_try_fmt_vid_out_overlay(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv *itv = fh2id(fh)->itv;
u32 chromakey = fmt->fmt.win.chromakey;
u8 global_alpha = fmt->fmt.win.global_alpha;
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
ivtv_g_fmt_vid_out_overlay(file, fh, fmt);
fmt->fmt.win.chromakey = chromakey;
fmt->fmt.win.global_alpha = global_alpha;
return 0;
}
static int ivtv_s_fmt_sliced_vbi_out(struct file *file, void *fh, struct v4l2_format *fmt)
{
return ivtv_g_fmt_sliced_vbi_out(file, fh, fmt);
}
static int ivtv_s_fmt_vid_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
struct v4l2_mbus_framefmt mbus_fmt;
int ret = ivtv_try_fmt_vid_cap(file, fh, fmt);
int w = fmt->fmt.pix.width;
int h = fmt->fmt.pix.height;
if (ret)
return ret;
if (itv->cxhdl.width == w && itv->cxhdl.height == h)
return 0;
if (atomic_read(&itv->capturing) > 0)
return -EBUSY;
itv->cxhdl.width = w;
itv->cxhdl.height = h;
if (v4l2_ctrl_g_ctrl(itv->cxhdl.video_encoding) == V4L2_MPEG_VIDEO_ENCODING_MPEG_1)
fmt->fmt.pix.width /= 2;
mbus_fmt.width = fmt->fmt.pix.width;
mbus_fmt.height = h;
mbus_fmt.code = V4L2_MBUS_FMT_FIXED;
v4l2_subdev_call(itv->sd_video, video, s_mbus_fmt, &mbus_fmt);
return ivtv_g_fmt_vid_cap(file, fh, fmt);
}
static int ivtv_s_fmt_vbi_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv *itv = fh2id(fh)->itv;
if (!ivtv_raw_vbi(itv) && atomic_read(&itv->capturing) > 0)
return -EBUSY;
itv->vbi.sliced_in->service_set = 0;
itv->vbi.in.type = V4L2_BUF_TYPE_VBI_CAPTURE;
v4l2_subdev_call(itv->sd_video, vbi, s_raw_fmt, &fmt->fmt.vbi);
return ivtv_g_fmt_vbi_cap(file, fh, fmt);
}
static int ivtv_s_fmt_sliced_vbi_cap(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct v4l2_sliced_vbi_format *vbifmt = &fmt->fmt.sliced;
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
int ret = ivtv_try_fmt_sliced_vbi_cap(file, fh, fmt);
if (ret || id->type == IVTV_DEC_STREAM_TYPE_VBI)
return ret;
check_service_set(vbifmt, itv->is_50hz);
if (ivtv_raw_vbi(itv) && atomic_read(&itv->capturing) > 0)
return -EBUSY;
itv->vbi.in.type = V4L2_BUF_TYPE_SLICED_VBI_CAPTURE;
v4l2_subdev_call(itv->sd_video, vbi, s_sliced_fmt, vbifmt);
memcpy(itv->vbi.sliced_in, vbifmt, sizeof(*itv->vbi.sliced_in));
return 0;
}
static int ivtv_s_fmt_vid_out(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
struct yuv_playback_info *yi = &itv->yuv_info;
int ret = ivtv_try_fmt_vid_out(file, fh, fmt);
if (ret)
return ret;
if (id->type != IVTV_DEC_STREAM_TYPE_YUV)
return 0;
/* Return now if we already have some frame data */
if (yi->stream_size)
return -EBUSY;
yi->v4l2_src_w = fmt->fmt.pix.width;
yi->v4l2_src_h = fmt->fmt.pix.height;
switch (fmt->fmt.pix.field) {
case V4L2_FIELD_NONE:
yi->lace_mode = IVTV_YUV_MODE_PROGRESSIVE;
break;
case V4L2_FIELD_ANY:
yi->lace_mode = IVTV_YUV_MODE_AUTO;
break;
case V4L2_FIELD_INTERLACED_BT:
yi->lace_mode =
IVTV_YUV_MODE_INTERLACED|IVTV_YUV_SYNC_ODD;
break;
case V4L2_FIELD_INTERLACED_TB:
default:
yi->lace_mode = IVTV_YUV_MODE_INTERLACED;
break;
}
yi->lace_sync_field = (yi->lace_mode & IVTV_YUV_SYNC_MASK) == IVTV_YUV_SYNC_EVEN ? 0 : 1;
if (test_bit(IVTV_F_I_DEC_YUV, &itv->i_flags))
itv->dma_data_req_size =
1080 * ((yi->v4l2_src_h + 31) & ~31);
return 0;
}
static int ivtv_s_fmt_vid_out_overlay(struct file *file, void *fh, struct v4l2_format *fmt)
{
struct ivtv *itv = fh2id(fh)->itv;
int ret = ivtv_try_fmt_vid_out_overlay(file, fh, fmt);
if (ret == 0) {
itv->osd_chroma_key = fmt->fmt.win.chromakey;
itv->osd_global_alpha = fmt->fmt.win.global_alpha;
ivtv_set_osd_alpha(itv);
}
return ret;
}
static int ivtv_g_chip_ident(struct file *file, void *fh, struct v4l2_dbg_chip_ident *chip)
{
struct ivtv *itv = fh2id(fh)->itv;
chip->ident = V4L2_IDENT_NONE;
chip->revision = 0;
if (chip->match.type == V4L2_CHIP_MATCH_HOST) {
if (v4l2_chip_match_host(&chip->match))
chip->ident = itv->has_cx23415 ? V4L2_IDENT_CX23415 : V4L2_IDENT_CX23416;
return 0;
}
if (chip->match.type != V4L2_CHIP_MATCH_I2C_DRIVER &&
chip->match.type != V4L2_CHIP_MATCH_I2C_ADDR)
return -EINVAL;
/* TODO: is this correct? */
return ivtv_call_all_err(itv, core, g_chip_ident, chip);
}
#ifdef CONFIG_VIDEO_ADV_DEBUG
static int ivtv_itvc(struct ivtv *itv, unsigned int cmd, void *arg)
{
struct v4l2_dbg_register *regs = arg;
volatile u8 __iomem *reg_start;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (regs->reg >= IVTV_REG_OFFSET && regs->reg < IVTV_REG_OFFSET + IVTV_REG_SIZE)
reg_start = itv->reg_mem - IVTV_REG_OFFSET;
else if (itv->has_cx23415 && regs->reg >= IVTV_DECODER_OFFSET &&
regs->reg < IVTV_DECODER_OFFSET + IVTV_DECODER_SIZE)
reg_start = itv->dec_mem - IVTV_DECODER_OFFSET;
else if (regs->reg < IVTV_ENCODER_SIZE)
reg_start = itv->enc_mem;
else
return -EINVAL;
regs->size = 4;
if (cmd == VIDIOC_DBG_G_REGISTER)
regs->val = readl(regs->reg + reg_start);
else
writel(regs->val, regs->reg + reg_start);
return 0;
}
static int ivtv_g_register(struct file *file, void *fh, struct v4l2_dbg_register *reg)
{
struct ivtv *itv = fh2id(fh)->itv;
if (v4l2_chip_match_host(®->match))
return ivtv_itvc(itv, VIDIOC_DBG_G_REGISTER, reg);
/* TODO: subdev errors should not be ignored, this should become a
subdev helper function. */
ivtv_call_all(itv, core, g_register, reg);
return 0;
}
static int ivtv_s_register(struct file *file, void *fh, struct v4l2_dbg_register *reg)
{
struct ivtv *itv = fh2id(fh)->itv;
if (v4l2_chip_match_host(®->match))
return ivtv_itvc(itv, VIDIOC_DBG_S_REGISTER, reg);
/* TODO: subdev errors should not be ignored, this should become a
subdev helper function. */
ivtv_call_all(itv, core, s_register, reg);
return 0;
}
#endif
static int ivtv_querycap(struct file *file, void *fh, struct v4l2_capability *vcap)
{
struct ivtv *itv = fh2id(fh)->itv;
strlcpy(vcap->driver, IVTV_DRIVER_NAME, sizeof(vcap->driver));
strlcpy(vcap->card, itv->card_name, sizeof(vcap->card));
snprintf(vcap->bus_info, sizeof(vcap->bus_info), "PCI:%s", pci_name(itv->pdev));
vcap->version = IVTV_DRIVER_VERSION; /* version */
vcap->capabilities = itv->v4l2_cap; /* capabilities */
return 0;
}
static int ivtv_enumaudio(struct file *file, void *fh, struct v4l2_audio *vin)
{
struct ivtv *itv = fh2id(fh)->itv;
return ivtv_get_audio_input(itv, vin->index, vin);
}
static int ivtv_g_audio(struct file *file, void *fh, struct v4l2_audio *vin)
{
struct ivtv *itv = fh2id(fh)->itv;
vin->index = itv->audio_input;
return ivtv_get_audio_input(itv, vin->index, vin);
}
static int ivtv_s_audio(struct file *file, void *fh, struct v4l2_audio *vout)
{
struct ivtv *itv = fh2id(fh)->itv;
if (vout->index >= itv->nof_audio_inputs)
return -EINVAL;
itv->audio_input = vout->index;
ivtv_audio_set_io(itv);
return 0;
}
static int ivtv_enumaudout(struct file *file, void *fh, struct v4l2_audioout *vin)
{
struct ivtv *itv = fh2id(fh)->itv;
/* set it to defaults from our table */
return ivtv_get_audio_output(itv, vin->index, vin);
}
static int ivtv_g_audout(struct file *file, void *fh, struct v4l2_audioout *vin)
{
struct ivtv *itv = fh2id(fh)->itv;
vin->index = 0;
return ivtv_get_audio_output(itv, vin->index, vin);
}
static int ivtv_s_audout(struct file *file, void *fh, struct v4l2_audioout *vout)
{
struct ivtv *itv = fh2id(fh)->itv;
return ivtv_get_audio_output(itv, vout->index, vout);
}
static int ivtv_enum_input(struct file *file, void *fh, struct v4l2_input *vin)
{
struct ivtv *itv = fh2id(fh)->itv;
/* set it to defaults from our table */
return ivtv_get_input(itv, vin->index, vin);
}
static int ivtv_enum_output(struct file *file, void *fh, struct v4l2_output *vout)
{
struct ivtv *itv = fh2id(fh)->itv;
return ivtv_get_output(itv, vout->index, vout);
}
static int ivtv_cropcap(struct file *file, void *fh, struct v4l2_cropcap *cropcap)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
struct yuv_playback_info *yi = &itv->yuv_info;
int streamtype;
streamtype = id->type;
if (cropcap->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
return -EINVAL;
cropcap->bounds.top = cropcap->bounds.left = 0;
cropcap->bounds.width = 720;
if (cropcap->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
cropcap->bounds.height = itv->is_50hz ? 576 : 480;
cropcap->pixelaspect.numerator = itv->is_50hz ? 59 : 10;
cropcap->pixelaspect.denominator = itv->is_50hz ? 54 : 11;
} else if (streamtype == IVTV_DEC_STREAM_TYPE_YUV) {
if (yi->track_osd) {
cropcap->bounds.width = yi->osd_full_w;
cropcap->bounds.height = yi->osd_full_h;
} else {
cropcap->bounds.width = 720;
cropcap->bounds.height =
itv->is_out_50hz ? 576 : 480;
}
cropcap->pixelaspect.numerator = itv->is_out_50hz ? 59 : 10;
cropcap->pixelaspect.denominator = itv->is_out_50hz ? 54 : 11;
} else {
cropcap->bounds.height = itv->is_out_50hz ? 576 : 480;
cropcap->pixelaspect.numerator = itv->is_out_50hz ? 59 : 10;
cropcap->pixelaspect.denominator = itv->is_out_50hz ? 54 : 11;
}
cropcap->defrect = cropcap->bounds;
return 0;
}
static int ivtv_s_crop(struct file *file, void *fh, struct v4l2_crop *crop)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
struct yuv_playback_info *yi = &itv->yuv_info;
int streamtype;
streamtype = id->type;
if (crop->type == V4L2_BUF_TYPE_VIDEO_OUTPUT &&
(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT)) {
if (streamtype == IVTV_DEC_STREAM_TYPE_YUV) {
yi->main_rect = crop->c;
return 0;
} else {
if (!ivtv_vapi(itv, CX2341X_OSD_SET_FRAMEBUFFER_WINDOW, 4,
crop->c.width, crop->c.height, crop->c.left, crop->c.top)) {
itv->main_rect = crop->c;
return 0;
}
}
return -EINVAL;
}
return -EINVAL;
}
static int ivtv_g_crop(struct file *file, void *fh, struct v4l2_crop *crop)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
struct yuv_playback_info *yi = &itv->yuv_info;
int streamtype;
streamtype = id->type;
if (crop->type == V4L2_BUF_TYPE_VIDEO_OUTPUT &&
(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT)) {
if (streamtype == IVTV_DEC_STREAM_TYPE_YUV)
crop->c = yi->main_rect;
else
crop->c = itv->main_rect;
return 0;
}
return -EINVAL;
}
static int ivtv_enum_fmt_vid_cap(struct file *file, void *fh, struct v4l2_fmtdesc *fmt)
{
static struct v4l2_fmtdesc formats[] = {
{ 0, 0, 0,
"HM12 (YUV 4:2:0)", V4L2_PIX_FMT_HM12,
{ 0, 0, 0, 0 }
},
{ 1, 0, V4L2_FMT_FLAG_COMPRESSED,
"MPEG", V4L2_PIX_FMT_MPEG,
{ 0, 0, 0, 0 }
}
};
enum v4l2_buf_type type = fmt->type;
if (fmt->index > 1)
return -EINVAL;
*fmt = formats[fmt->index];
fmt->type = type;
return 0;
}
static int ivtv_enum_fmt_vid_out(struct file *file, void *fh, struct v4l2_fmtdesc *fmt)
{
struct ivtv *itv = fh2id(fh)->itv;
static struct v4l2_fmtdesc formats[] = {
{ 0, 0, 0,
"HM12 (YUV 4:2:0)", V4L2_PIX_FMT_HM12,
{ 0, 0, 0, 0 }
},
{ 1, 0, V4L2_FMT_FLAG_COMPRESSED,
"MPEG", V4L2_PIX_FMT_MPEG,
{ 0, 0, 0, 0 }
}
};
enum v4l2_buf_type type = fmt->type;
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
if (fmt->index > 1)
return -EINVAL;
*fmt = formats[fmt->index];
fmt->type = type;
return 0;
}
static int ivtv_g_input(struct file *file, void *fh, unsigned int *i)
{
struct ivtv *itv = fh2id(fh)->itv;
*i = itv->active_input;
return 0;
}
int ivtv_s_input(struct file *file, void *fh, unsigned int inp)
{
struct ivtv *itv = fh2id(fh)->itv;
if (inp < 0 || inp >= itv->nof_inputs)
return -EINVAL;
if (inp == itv->active_input) {
IVTV_DEBUG_INFO("Input unchanged\n");
return 0;
}
if (atomic_read(&itv->capturing) > 0) {
return -EBUSY;
}
IVTV_DEBUG_INFO("Changing input from %d to %d\n",
itv->active_input, inp);
itv->active_input = inp;
/* Set the audio input to whatever is appropriate for the
input type. */
itv->audio_input = itv->card->video_inputs[inp].audio_index;
/* prevent others from messing with the streams until
we're finished changing inputs. */
ivtv_mute(itv);
ivtv_video_set_io(itv);
ivtv_audio_set_io(itv);
ivtv_unmute(itv);
return 0;
}
static int ivtv_g_output(struct file *file, void *fh, unsigned int *i)
{
struct ivtv *itv = fh2id(fh)->itv;
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
*i = itv->active_output;
return 0;
}
static int ivtv_s_output(struct file *file, void *fh, unsigned int outp)
{
struct ivtv *itv = fh2id(fh)->itv;
if (outp >= itv->card->nof_outputs)
return -EINVAL;
if (outp == itv->active_output) {
IVTV_DEBUG_INFO("Output unchanged\n");
return 0;
}
IVTV_DEBUG_INFO("Changing output from %d to %d\n",
itv->active_output, outp);
itv->active_output = outp;
ivtv_call_hw(itv, IVTV_HW_SAA7127, video, s_routing,
SAA7127_INPUT_TYPE_NORMAL,
itv->card->video_outputs[outp].video_output, 0);
return 0;
}
static int ivtv_g_frequency(struct file *file, void *fh, struct v4l2_frequency *vf)
{
struct ivtv *itv = fh2id(fh)->itv;
if (vf->tuner != 0)
return -EINVAL;
ivtv_call_all(itv, tuner, g_frequency, vf);
return 0;
}
int ivtv_s_frequency(struct file *file, void *fh, struct v4l2_frequency *vf)
{
struct ivtv *itv = fh2id(fh)->itv;
if (vf->tuner != 0)
return -EINVAL;
ivtv_mute(itv);
IVTV_DEBUG_INFO("v4l2 ioctl: set frequency %d\n", vf->frequency);
ivtv_call_all(itv, tuner, s_frequency, vf);
ivtv_unmute(itv);
return 0;
}
static int ivtv_g_std(struct file *file, void *fh, v4l2_std_id *std)
{
struct ivtv *itv = fh2id(fh)->itv;
*std = itv->std;
return 0;
}
void ivtv_s_std_enc(struct ivtv *itv, v4l2_std_id *std)
{
itv->std = *std;
itv->is_60hz = (*std & V4L2_STD_525_60) ? 1 : 0;
itv->is_50hz = !itv->is_60hz;
cx2341x_handler_set_50hz(&itv->cxhdl, itv->is_50hz);
itv->cxhdl.width = 720;
itv->cxhdl.height = itv->is_50hz ? 576 : 480;
itv->vbi.count = itv->is_50hz ? 18 : 12;
itv->vbi.start[0] = itv->is_50hz ? 6 : 10;
itv->vbi.start[1] = itv->is_50hz ? 318 : 273;
if (itv->hw_flags & IVTV_HW_CX25840)
itv->vbi.sliced_decoder_line_size = itv->is_60hz ? 272 : 284;
/* Tuner */
ivtv_call_all(itv, core, s_std, itv->std);
}
void ivtv_s_std_dec(struct ivtv *itv, v4l2_std_id *std)
{
struct yuv_playback_info *yi = &itv->yuv_info;
DEFINE_WAIT(wait);
int f;
/* set display standard */
itv->std_out = *std;
itv->is_out_60hz = (*std & V4L2_STD_525_60) ? 1 : 0;
itv->is_out_50hz = !itv->is_out_60hz;
ivtv_call_all(itv, video, s_std_output, itv->std_out);
/*
* The next firmware call is time sensitive. Time it to
* avoid risk of a hard lock, by trying to ensure the call
* happens within the first 100 lines of the top field.
* Make 4 attempts to sync to the decoder before giving up.
*/
for (f = 0; f < 4; f++) {
prepare_to_wait(&itv->vsync_waitq, &wait,
TASK_UNINTERRUPTIBLE);
if ((read_reg(IVTV_REG_DEC_LINE_FIELD) >> 16) < 100)
break;
schedule_timeout(msecs_to_jiffies(25));
}
finish_wait(&itv->vsync_waitq, &wait);
if (f == 4)
IVTV_WARN("Mode change failed to sync to decoder\n");
ivtv_vapi(itv, CX2341X_DEC_SET_STANDARD, 1, itv->is_out_50hz);
itv->main_rect.left = 0;
itv->main_rect.top = 0;
itv->main_rect.width = 720;
itv->main_rect.height = itv->is_out_50hz ? 576 : 480;
ivtv_vapi(itv, CX2341X_OSD_SET_FRAMEBUFFER_WINDOW, 4,
720, itv->main_rect.height, 0, 0);
yi->main_rect = itv->main_rect;
if (!itv->osd_info) {
yi->osd_full_w = 720;
yi->osd_full_h = itv->is_out_50hz ? 576 : 480;
}
}
int ivtv_s_std(struct file *file, void *fh, v4l2_std_id *std)
{
struct ivtv *itv = fh2id(fh)->itv;
if ((*std & V4L2_STD_ALL) == 0)
return -EINVAL;
if (*std == itv->std)
return 0;
if (test_bit(IVTV_F_I_RADIO_USER, &itv->i_flags) ||
atomic_read(&itv->capturing) > 0 ||
atomic_read(&itv->decoding) > 0) {
/* Switching standard would mess with already running
streams, prevent that by returning EBUSY. */
return -EBUSY;
}
IVTV_DEBUG_INFO("Switching standard to %llx.\n",
(unsigned long long)itv->std);
ivtv_s_std_enc(itv, std);
if (itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT)
ivtv_s_std_dec(itv, std);
return 0;
}
static int ivtv_s_tuner(struct file *file, void *fh, struct v4l2_tuner *vt)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
if (vt->index != 0)
return -EINVAL;
ivtv_call_all(itv, tuner, s_tuner, vt);
return 0;
}
static int ivtv_g_tuner(struct file *file, void *fh, struct v4l2_tuner *vt)
{
struct ivtv *itv = fh2id(fh)->itv;
if (vt->index != 0)
return -EINVAL;
ivtv_call_all(itv, tuner, g_tuner, vt);
if (vt->type == V4L2_TUNER_RADIO)
strlcpy(vt->name, "ivtv Radio Tuner", sizeof(vt->name));
else
strlcpy(vt->name, "ivtv TV Tuner", sizeof(vt->name));
return 0;
}
static int ivtv_g_sliced_vbi_cap(struct file *file, void *fh, struct v4l2_sliced_vbi_cap *cap)
{
struct ivtv *itv = fh2id(fh)->itv;
int set = itv->is_50hz ? V4L2_SLICED_VBI_625 : V4L2_SLICED_VBI_525;
int f, l;
if (cap->type == V4L2_BUF_TYPE_SLICED_VBI_CAPTURE) {
for (f = 0; f < 2; f++) {
for (l = 0; l < 24; l++) {
if (valid_service_line(f, l, itv->is_50hz))
cap->service_lines[f][l] = set;
}
}
return 0;
}
if (cap->type == V4L2_BUF_TYPE_SLICED_VBI_OUTPUT) {
if (!(itv->v4l2_cap & V4L2_CAP_SLICED_VBI_OUTPUT))
return -EINVAL;
if (itv->is_60hz) {
cap->service_lines[0][21] = V4L2_SLICED_CAPTION_525;
cap->service_lines[1][21] = V4L2_SLICED_CAPTION_525;
} else {
cap->service_lines[0][23] = V4L2_SLICED_WSS_625;
cap->service_lines[0][16] = V4L2_SLICED_VPS;
}
return 0;
}
return -EINVAL;
}
static int ivtv_g_enc_index(struct file *file, void *fh, struct v4l2_enc_idx *idx)
{
struct ivtv *itv = fh2id(fh)->itv;
struct v4l2_enc_idx_entry *e = idx->entry;
int entries;
int i;
entries = (itv->pgm_info_write_idx + IVTV_MAX_PGM_INDEX - itv->pgm_info_read_idx) %
IVTV_MAX_PGM_INDEX;
if (entries > V4L2_ENC_IDX_ENTRIES)
entries = V4L2_ENC_IDX_ENTRIES;
idx->entries = 0;
for (i = 0; i < entries; i++) {
*e = itv->pgm_info[(itv->pgm_info_read_idx + i) % IVTV_MAX_PGM_INDEX];
if ((e->flags & V4L2_ENC_IDX_FRAME_MASK) <= V4L2_ENC_IDX_FRAME_B) {
idx->entries++;
e++;
}
}
itv->pgm_info_read_idx = (itv->pgm_info_read_idx + idx->entries) % IVTV_MAX_PGM_INDEX;
return 0;
}
static int ivtv_encoder_cmd(struct file *file, void *fh, struct v4l2_encoder_cmd *enc)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
switch (enc->cmd) {
case V4L2_ENC_CMD_START:
IVTV_DEBUG_IOCTL("V4L2_ENC_CMD_START\n");
enc->flags = 0;
return ivtv_start_capture(id);
case V4L2_ENC_CMD_STOP:
IVTV_DEBUG_IOCTL("V4L2_ENC_CMD_STOP\n");
enc->flags &= V4L2_ENC_CMD_STOP_AT_GOP_END;
ivtv_stop_capture(id, enc->flags & V4L2_ENC_CMD_STOP_AT_GOP_END);
return 0;
case V4L2_ENC_CMD_PAUSE:
IVTV_DEBUG_IOCTL("V4L2_ENC_CMD_PAUSE\n");
enc->flags = 0;
if (!atomic_read(&itv->capturing))
return -EPERM;
if (test_and_set_bit(IVTV_F_I_ENC_PAUSED, &itv->i_flags))
return 0;
ivtv_mute(itv);
ivtv_vapi(itv, CX2341X_ENC_PAUSE_ENCODER, 1, 0);
break;
case V4L2_ENC_CMD_RESUME:
IVTV_DEBUG_IOCTL("V4L2_ENC_CMD_RESUME\n");
enc->flags = 0;
if (!atomic_read(&itv->capturing))
return -EPERM;
if (!test_and_clear_bit(IVTV_F_I_ENC_PAUSED, &itv->i_flags))
return 0;
ivtv_vapi(itv, CX2341X_ENC_PAUSE_ENCODER, 1, 1);
ivtv_unmute(itv);
break;
default:
IVTV_DEBUG_IOCTL("Unknown cmd %d\n", enc->cmd);
return -EINVAL;
}
return 0;
}
static int ivtv_try_encoder_cmd(struct file *file, void *fh, struct v4l2_encoder_cmd *enc)
{
struct ivtv *itv = fh2id(fh)->itv;
switch (enc->cmd) {
case V4L2_ENC_CMD_START:
IVTV_DEBUG_IOCTL("V4L2_ENC_CMD_START\n");
enc->flags = 0;
return 0;
case V4L2_ENC_CMD_STOP:
IVTV_DEBUG_IOCTL("V4L2_ENC_CMD_STOP\n");
enc->flags &= V4L2_ENC_CMD_STOP_AT_GOP_END;
return 0;
case V4L2_ENC_CMD_PAUSE:
IVTV_DEBUG_IOCTL("V4L2_ENC_CMD_PAUSE\n");
enc->flags = 0;
return 0;
case V4L2_ENC_CMD_RESUME:
IVTV_DEBUG_IOCTL("V4L2_ENC_CMD_RESUME\n");
enc->flags = 0;
return 0;
default:
IVTV_DEBUG_IOCTL("Unknown cmd %d\n", enc->cmd);
return -EINVAL;
}
}
static int ivtv_g_fbuf(struct file *file, void *fh, struct v4l2_framebuffer *fb)
{
struct ivtv *itv = fh2id(fh)->itv;
u32 data[CX2341X_MBOX_MAX_DATA];
struct yuv_playback_info *yi = &itv->yuv_info;
int pixfmt;
static u32 pixel_format[16] = {
V4L2_PIX_FMT_PAL8, /* Uses a 256-entry RGB colormap */
V4L2_PIX_FMT_RGB565,
V4L2_PIX_FMT_RGB555,
V4L2_PIX_FMT_RGB444,
V4L2_PIX_FMT_RGB32,
0,
0,
0,
V4L2_PIX_FMT_PAL8, /* Uses a 256-entry YUV colormap */
V4L2_PIX_FMT_YUV565,
V4L2_PIX_FMT_YUV555,
V4L2_PIX_FMT_YUV444,
V4L2_PIX_FMT_YUV32,
0,
0,
0,
};
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT_OVERLAY))
return -EINVAL;
if (!itv->osd_video_pbase)
return -EINVAL;
fb->capability = V4L2_FBUF_CAP_EXTERNOVERLAY | V4L2_FBUF_CAP_CHROMAKEY |
V4L2_FBUF_CAP_GLOBAL_ALPHA;
ivtv_vapi_result(itv, data, CX2341X_OSD_GET_STATE, 0);
data[0] |= (read_reg(0x2a00) >> 7) & 0x40;
pixfmt = (data[0] >> 3) & 0xf;
fb->fmt.pixelformat = pixel_format[pixfmt];
fb->fmt.width = itv->osd_rect.width;
fb->fmt.height = itv->osd_rect.height;
fb->fmt.field = V4L2_FIELD_INTERLACED;
fb->fmt.bytesperline = fb->fmt.width;
fb->fmt.colorspace = V4L2_COLORSPACE_SMPTE170M;
fb->fmt.field = V4L2_FIELD_INTERLACED;
fb->fmt.priv = 0;
if (fb->fmt.pixelformat != V4L2_PIX_FMT_PAL8)
fb->fmt.bytesperline *= 2;
if (fb->fmt.pixelformat == V4L2_PIX_FMT_RGB32 ||
fb->fmt.pixelformat == V4L2_PIX_FMT_YUV32)
fb->fmt.bytesperline *= 2;
fb->fmt.sizeimage = fb->fmt.bytesperline * fb->fmt.height;
fb->base = (void *)itv->osd_video_pbase;
fb->flags = 0;
if (itv->osd_chroma_key_state)
fb->flags |= V4L2_FBUF_FLAG_CHROMAKEY;
if (itv->osd_global_alpha_state)
fb->flags |= V4L2_FBUF_FLAG_GLOBAL_ALPHA;
if (yi->track_osd)
fb->flags |= V4L2_FBUF_FLAG_OVERLAY;
pixfmt &= 7;
/* no local alpha for RGB565 or unknown formats */
if (pixfmt == 1 || pixfmt > 4)
return 0;
/* 16-bit formats have inverted local alpha */
if (pixfmt == 2 || pixfmt == 3)
fb->capability |= V4L2_FBUF_CAP_LOCAL_INV_ALPHA;
else
fb->capability |= V4L2_FBUF_CAP_LOCAL_ALPHA;
if (itv->osd_local_alpha_state) {
/* 16-bit formats have inverted local alpha */
if (pixfmt == 2 || pixfmt == 3)
fb->flags |= V4L2_FBUF_FLAG_LOCAL_INV_ALPHA;
else
fb->flags |= V4L2_FBUF_FLAG_LOCAL_ALPHA;
}
return 0;
}
static int ivtv_s_fbuf(struct file *file, void *fh, struct v4l2_framebuffer *fb)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
struct yuv_playback_info *yi = &itv->yuv_info;
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT_OVERLAY))
return -EINVAL;
if (!itv->osd_video_pbase)
return -EINVAL;
itv->osd_global_alpha_state = (fb->flags & V4L2_FBUF_FLAG_GLOBAL_ALPHA) != 0;
itv->osd_local_alpha_state =
(fb->flags & (V4L2_FBUF_FLAG_LOCAL_ALPHA|V4L2_FBUF_FLAG_LOCAL_INV_ALPHA)) != 0;
itv->osd_chroma_key_state = (fb->flags & V4L2_FBUF_FLAG_CHROMAKEY) != 0;
ivtv_set_osd_alpha(itv);
yi->track_osd = (fb->flags & V4L2_FBUF_FLAG_OVERLAY) != 0;
return ivtv_g_fbuf(file, fh, fb);
}
static int ivtv_overlay(struct file *file, void *fh, unsigned int on)
{
struct ivtv_open_id *id = fh2id(fh);
struct ivtv *itv = id->itv;
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT_OVERLAY))
return -EINVAL;
ivtv_vapi(itv, CX2341X_OSD_SET_STATE, 1, on != 0);
return 0;
}
static int ivtv_subscribe_event(struct v4l2_fh *fh, struct v4l2_event_subscription *sub)
{
switch (sub->type) {
case V4L2_EVENT_VSYNC:
case V4L2_EVENT_EOS:
break;
default:
return -EINVAL;
}
return v4l2_event_subscribe(fh, sub);
}
static int ivtv_log_status(struct file *file, void *fh)
{
struct ivtv *itv = fh2id(fh)->itv;
u32 data[CX2341X_MBOX_MAX_DATA];
int has_output = itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT;
struct v4l2_input vidin;
struct v4l2_audio audin;
int i;
IVTV_INFO("================= START STATUS CARD #%d =================\n",
itv->instance);
IVTV_INFO("Version: %s Card: %s\n", IVTV_VERSION, itv->card_name);
if (itv->hw_flags & IVTV_HW_TVEEPROM) {
struct tveeprom tv;
ivtv_read_eeprom(itv, &tv);
}
ivtv_call_all(itv, core, log_status);
ivtv_get_input(itv, itv->active_input, &vidin);
ivtv_get_audio_input(itv, itv->audio_input, &audin);
IVTV_INFO("Video Input: %s\n", vidin.name);
IVTV_INFO("Audio Input: %s%s\n", audin.name,
(itv->dualwatch_stereo_mode & ~0x300) == 0x200 ? " (Bilingual)" : "");
if (has_output) {
struct v4l2_output vidout;
struct v4l2_audioout audout;
int mode = itv->output_mode;
static const char * const output_modes[5] = {
"None",
"MPEG Streaming",
"YUV Streaming",
"YUV Frames",
"Passthrough",
};
static const char * const audio_modes[5] = {
"Stereo",
"Left",
"Right",
"Mono",
"Swapped"
};
static const char * const alpha_mode[4] = {
"None",
"Global",
"Local",
"Global and Local"
};
static const char * const pixel_format[16] = {
"ARGB Indexed",
"RGB 5:6:5",
"ARGB 1:5:5:5",
"ARGB 1:4:4:4",
"ARGB 8:8:8:8",
"5",
"6",
"7",
"AYUV Indexed",
"YUV 5:6:5",
"AYUV 1:5:5:5",
"AYUV 1:4:4:4",
"AYUV 8:8:8:8",
"13",
"14",
"15",
};
ivtv_get_output(itv, itv->active_output, &vidout);
ivtv_get_audio_output(itv, 0, &audout);
IVTV_INFO("Video Output: %s\n", vidout.name);
IVTV_INFO("Audio Output: %s (Stereo/Bilingual: %s/%s)\n", audout.name,
audio_modes[itv->audio_stereo_mode],
audio_modes[itv->audio_bilingual_mode]);
if (mode < 0 || mode > OUT_PASSTHROUGH)
mode = OUT_NONE;
IVTV_INFO("Output Mode: %s\n", output_modes[mode]);
ivtv_vapi_result(itv, data, CX2341X_OSD_GET_STATE, 0);
data[0] |= (read_reg(0x2a00) >> 7) & 0x40;
IVTV_INFO("Overlay: %s, Alpha: %s, Pixel Format: %s\n",
data[0] & 1 ? "On" : "Off",
alpha_mode[(data[0] >> 1) & 0x3],
pixel_format[(data[0] >> 3) & 0xf]);
}
IVTV_INFO("Tuner: %s\n",
test_bit(IVTV_F_I_RADIO_USER, &itv->i_flags) ? "Radio" : "TV");
v4l2_ctrl_handler_log_status(&itv->cxhdl.hdl, itv->v4l2_dev.name);
IVTV_INFO("Status flags: 0x%08lx\n", itv->i_flags);
for (i = 0; i < IVTV_MAX_STREAMS; i++) {
struct ivtv_stream *s = &itv->streams[i];
if (s->vdev == NULL || s->buffers == 0)
continue;
IVTV_INFO("Stream %s: status 0x%04lx, %d%% of %d KiB (%d buffers) in use\n", s->name, s->s_flags,
(s->buffers - s->q_free.buffers) * 100 / s->buffers,
(s->buffers * s->buf_size) / 1024, s->buffers);
}
IVTV_INFO("Read MPG/VBI: %lld/%lld bytes\n",
(long long)itv->mpg_data_received,
(long long)itv->vbi_data_inserted);
IVTV_INFO("================== END STATUS CARD #%d ==================\n",
itv->instance);
return 0;
}
static int ivtv_decoder_ioctls(struct file *filp, unsigned int cmd, void *arg)
{
struct ivtv_open_id *id = fh2id(filp->private_data);
struct ivtv *itv = id->itv;
int nonblocking = filp->f_flags & O_NONBLOCK;
struct ivtv_stream *s = &itv->streams[id->type];
unsigned long iarg = (unsigned long)arg;
switch (cmd) {
case IVTV_IOC_DMA_FRAME: {
struct ivtv_dma_frame *args = arg;
IVTV_DEBUG_IOCTL("IVTV_IOC_DMA_FRAME\n");
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
if (args->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
return -EINVAL;
if (itv->output_mode == OUT_UDMA_YUV && args->y_source == NULL)
return 0;
if (ivtv_start_decoding(id, id->type)) {
return -EBUSY;
}
if (ivtv_set_output_mode(itv, OUT_UDMA_YUV) != OUT_UDMA_YUV) {
ivtv_release_stream(s);
return -EBUSY;
}
/* Mark that this file handle started the UDMA_YUV mode */
id->yuv_frames = 1;
if (args->y_source == NULL)
return 0;
return ivtv_yuv_prep_frame(itv, args);
}
case VIDEO_GET_PTS: {
u32 data[CX2341X_MBOX_MAX_DATA];
u64 *pts = arg;
IVTV_DEBUG_IOCTL("VIDEO_GET_PTS\n");
if (s->type < IVTV_DEC_STREAM_TYPE_MPG) {
*pts = s->dma_pts;
break;
}
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
if (test_bit(IVTV_F_I_VALID_DEC_TIMINGS, &itv->i_flags)) {
*pts = (u64) ((u64)itv->last_dec_timing[2] << 32) |
(u64)itv->last_dec_timing[1];
break;
}
*pts = 0;
if (atomic_read(&itv->decoding)) {
if (ivtv_api(itv, CX2341X_DEC_GET_TIMING_INFO, 5, data)) {
IVTV_DEBUG_WARN("GET_TIMING: couldn't read clock\n");
return -EIO;
}
memcpy(itv->last_dec_timing, data, sizeof(itv->last_dec_timing));
set_bit(IVTV_F_I_VALID_DEC_TIMINGS, &itv->i_flags);
*pts = (u64) ((u64) data[2] << 32) | (u64) data[1];
/*timing->scr = (u64) (((u64) data[4] << 32) | (u64) (data[3]));*/
}
break;
}
case VIDEO_GET_FRAME_COUNT: {
u32 data[CX2341X_MBOX_MAX_DATA];
u64 *frame = arg;
IVTV_DEBUG_IOCTL("VIDEO_GET_FRAME_COUNT\n");
if (s->type < IVTV_DEC_STREAM_TYPE_MPG) {
*frame = 0;
break;
}
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
if (test_bit(IVTV_F_I_VALID_DEC_TIMINGS, &itv->i_flags)) {
*frame = itv->last_dec_timing[0];
break;
}
*frame = 0;
if (atomic_read(&itv->decoding)) {
if (ivtv_api(itv, CX2341X_DEC_GET_TIMING_INFO, 5, data)) {
IVTV_DEBUG_WARN("GET_TIMING: couldn't read clock\n");
return -EIO;
}
memcpy(itv->last_dec_timing, data, sizeof(itv->last_dec_timing));
set_bit(IVTV_F_I_VALID_DEC_TIMINGS, &itv->i_flags);
*frame = data[0];
}
break;
}
case VIDEO_PLAY: {
struct video_command vc;
IVTV_DEBUG_IOCTL("VIDEO_PLAY\n");
memset(&vc, 0, sizeof(vc));
vc.cmd = VIDEO_CMD_PLAY;
return ivtv_video_command(itv, id, &vc, 0);
}
case VIDEO_STOP: {
struct video_command vc;
IVTV_DEBUG_IOCTL("VIDEO_STOP\n");
memset(&vc, 0, sizeof(vc));
vc.cmd = VIDEO_CMD_STOP;
vc.flags = VIDEO_CMD_STOP_TO_BLACK | VIDEO_CMD_STOP_IMMEDIATELY;
return ivtv_video_command(itv, id, &vc, 0);
}
case VIDEO_FREEZE: {
struct video_command vc;
IVTV_DEBUG_IOCTL("VIDEO_FREEZE\n");
memset(&vc, 0, sizeof(vc));
vc.cmd = VIDEO_CMD_FREEZE;
return ivtv_video_command(itv, id, &vc, 0);
}
case VIDEO_CONTINUE: {
struct video_command vc;
IVTV_DEBUG_IOCTL("VIDEO_CONTINUE\n");
memset(&vc, 0, sizeof(vc));
vc.cmd = VIDEO_CMD_CONTINUE;
return ivtv_video_command(itv, id, &vc, 0);
}
case VIDEO_COMMAND:
case VIDEO_TRY_COMMAND: {
struct video_command *vc = arg;
int try = (cmd == VIDEO_TRY_COMMAND);
if (try)
IVTV_DEBUG_IOCTL("VIDEO_TRY_COMMAND %d\n", vc->cmd);
else
IVTV_DEBUG_IOCTL("VIDEO_COMMAND %d\n", vc->cmd);
return ivtv_video_command(itv, id, vc, try);
}
case VIDEO_GET_EVENT: {
struct video_event *ev = arg;
DEFINE_WAIT(wait);
IVTV_DEBUG_IOCTL("VIDEO_GET_EVENT\n");
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
memset(ev, 0, sizeof(*ev));
set_bit(IVTV_F_I_EV_VSYNC_ENABLED, &itv->i_flags);
while (1) {
if (test_and_clear_bit(IVTV_F_I_EV_DEC_STOPPED, &itv->i_flags))
ev->type = VIDEO_EVENT_DECODER_STOPPED;
else if (test_and_clear_bit(IVTV_F_I_EV_VSYNC, &itv->i_flags)) {
ev->type = VIDEO_EVENT_VSYNC;
ev->u.vsync_field = test_bit(IVTV_F_I_EV_VSYNC_FIELD, &itv->i_flags) ?
VIDEO_VSYNC_FIELD_ODD : VIDEO_VSYNC_FIELD_EVEN;
if (itv->output_mode == OUT_UDMA_YUV &&
(itv->yuv_info.lace_mode & IVTV_YUV_MODE_MASK) ==
IVTV_YUV_MODE_PROGRESSIVE) {
ev->u.vsync_field = VIDEO_VSYNC_FIELD_PROGRESSIVE;
}
}
if (ev->type)
return 0;
if (nonblocking)
return -EAGAIN;
/* Wait for event. Note that serialize_lock is locked,
so to allow other processes to access the driver while
we are waiting unlock first and later lock again. */
mutex_unlock(&itv->serialize_lock);
prepare_to_wait(&itv->event_waitq, &wait, TASK_INTERRUPTIBLE);
if (!test_bit(IVTV_F_I_EV_DEC_STOPPED, &itv->i_flags) &&
!test_bit(IVTV_F_I_EV_VSYNC, &itv->i_flags))
schedule();
finish_wait(&itv->event_waitq, &wait);
mutex_lock(&itv->serialize_lock);
if (signal_pending(current)) {
/* return if a signal was received */
IVTV_DEBUG_INFO("User stopped wait for event\n");
return -EINTR;
}
}
break;
}
case VIDEO_SELECT_SOURCE:
IVTV_DEBUG_IOCTL("VIDEO_SELECT_SOURCE\n");
if (!(itv->v4l2_cap & V4L2_CAP_VIDEO_OUTPUT))
return -EINVAL;
return ivtv_passthrough_mode(itv, iarg == VIDEO_SOURCE_DEMUX);
case AUDIO_SET_MUTE:
IVTV_DEBUG_IOCTL("AUDIO_SET_MUTE\n");
itv->speed_mute_audio = iarg;
return 0;
case AUDIO_CHANNEL_SELECT:
IVTV_DEBUG_IOCTL("AUDIO_CHANNEL_SELECT\n");
if (iarg > AUDIO_STEREO_SWAPPED)
return -EINVAL;
itv->audio_stereo_mode = iarg;
ivtv_vapi(itv, CX2341X_DEC_SET_AUDIO_MODE, 2, itv->audio_bilingual_mode, itv->audio_stereo_mode);
return 0;
case AUDIO_BILINGUAL_CHANNEL_SELECT:
IVTV_DEBUG_IOCTL("AUDIO_BILINGUAL_CHANNEL_SELECT\n");
if (iarg > AUDIO_STEREO_SWAPPED)
return -EINVAL;
itv->audio_bilingual_mode = iarg;
ivtv_vapi(itv, CX2341X_DEC_SET_AUDIO_MODE, 2, itv->audio_bilingual_mode, itv->audio_stereo_mode);
return 0;
default:
return -EINVAL;
}
return 0;
}
static long ivtv_default(struct file *file, void *fh, bool valid_prio,
int cmd, void *arg)
{
struct ivtv *itv = fh2id(fh)->itv;
if (!valid_prio) {
switch (cmd) {
case VIDEO_PLAY:
case VIDEO_STOP:
case VIDEO_FREEZE:
case VIDEO_CONTINUE:
case VIDEO_COMMAND:
case VIDEO_SELECT_SOURCE:
case AUDIO_SET_MUTE:
case AUDIO_CHANNEL_SELECT:
case AUDIO_BILINGUAL_CHANNEL_SELECT:
return -EBUSY;
}
}
switch (cmd) {
case VIDIOC_INT_RESET: {
u32 val = *(u32 *)arg;
if ((val == 0 && itv->options.newi2c) || (val & 0x01))
ivtv_reset_ir_gpio(itv);
if (val & 0x02)
v4l2_subdev_call(itv->sd_video, core, reset, 0);
break;
}
case IVTV_IOC_DMA_FRAME:
case VIDEO_GET_PTS:
case VIDEO_GET_FRAME_COUNT:
case VIDEO_GET_EVENT:
case VIDEO_PLAY:
case VIDEO_STOP:
case VIDEO_FREEZE:
case VIDEO_CONTINUE:
case VIDEO_COMMAND:
case VIDEO_TRY_COMMAND:
case VIDEO_SELECT_SOURCE:
case AUDIO_SET_MUTE:
case AUDIO_CHANNEL_SELECT:
case AUDIO_BILINGUAL_CHANNEL_SELECT:
return ivtv_decoder_ioctls(file, cmd, (void *)arg);
default:
return -EINVAL;
}
return 0;
}
static long ivtv_serialized_ioctl(struct ivtv *itv, struct file *filp,
unsigned int cmd, unsigned long arg)
{
struct video_device *vfd = video_devdata(filp);
long ret;
if (ivtv_debug & IVTV_DBGFLG_IOCTL)
vfd->debug = V4L2_DEBUG_IOCTL | V4L2_DEBUG_IOCTL_ARG;
ret = video_ioctl2(filp, cmd, arg);
vfd->debug = 0;
return ret;
}
long ivtv_v4l2_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct ivtv_open_id *id = fh2id(filp->private_data);
struct ivtv *itv = id->itv;
long res;
/* DQEVENT can block, so this should not run with the serialize lock */
if (cmd == VIDIOC_DQEVENT)
return ivtv_serialized_ioctl(itv, filp, cmd, arg);
mutex_lock(&itv->serialize_lock);
res = ivtv_serialized_ioctl(itv, filp, cmd, arg);
mutex_unlock(&itv->serialize_lock);
return res;
}
static const struct v4l2_ioctl_ops ivtv_ioctl_ops = {
.vidioc_querycap = ivtv_querycap,
.vidioc_s_audio = ivtv_s_audio,
.vidioc_g_audio = ivtv_g_audio,
.vidioc_enumaudio = ivtv_enumaudio,
.vidioc_s_audout = ivtv_s_audout,
.vidioc_g_audout = ivtv_g_audout,
.vidioc_enum_input = ivtv_enum_input,
.vidioc_enum_output = ivtv_enum_output,
.vidioc_enumaudout = ivtv_enumaudout,
.vidioc_cropcap = ivtv_cropcap,
.vidioc_s_crop = ivtv_s_crop,
.vidioc_g_crop = ivtv_g_crop,
.vidioc_g_input = ivtv_g_input,
.vidioc_s_input = ivtv_s_input,
.vidioc_g_output = ivtv_g_output,
.vidioc_s_output = ivtv_s_output,
.vidioc_g_frequency = ivtv_g_frequency,
.vidioc_s_frequency = ivtv_s_frequency,
.vidioc_s_tuner = ivtv_s_tuner,
.vidioc_g_tuner = ivtv_g_tuner,
.vidioc_g_enc_index = ivtv_g_enc_index,
.vidioc_g_fbuf = ivtv_g_fbuf,
.vidioc_s_fbuf = ivtv_s_fbuf,
.vidioc_g_std = ivtv_g_std,
.vidioc_s_std = ivtv_s_std,
.vidioc_overlay = ivtv_overlay,
.vidioc_log_status = ivtv_log_status,
.vidioc_enum_fmt_vid_cap = ivtv_enum_fmt_vid_cap,
.vidioc_encoder_cmd = ivtv_encoder_cmd,
.vidioc_try_encoder_cmd = ivtv_try_encoder_cmd,
.vidioc_enum_fmt_vid_out = ivtv_enum_fmt_vid_out,
.vidioc_g_fmt_vid_cap = ivtv_g_fmt_vid_cap,
.vidioc_g_fmt_vbi_cap = ivtv_g_fmt_vbi_cap,
.vidioc_g_fmt_sliced_vbi_cap = ivtv_g_fmt_sliced_vbi_cap,
.vidioc_g_fmt_vid_out = ivtv_g_fmt_vid_out,
.vidioc_g_fmt_vid_out_overlay = ivtv_g_fmt_vid_out_overlay,
.vidioc_g_fmt_sliced_vbi_out = ivtv_g_fmt_sliced_vbi_out,
.vidioc_s_fmt_vid_cap = ivtv_s_fmt_vid_cap,
.vidioc_s_fmt_vbi_cap = ivtv_s_fmt_vbi_cap,
.vidioc_s_fmt_sliced_vbi_cap = ivtv_s_fmt_sliced_vbi_cap,
.vidioc_s_fmt_vid_out = ivtv_s_fmt_vid_out,
.vidioc_s_fmt_vid_out_overlay = ivtv_s_fmt_vid_out_overlay,
.vidioc_s_fmt_sliced_vbi_out = ivtv_s_fmt_sliced_vbi_out,
.vidioc_try_fmt_vid_cap = ivtv_try_fmt_vid_cap,
.vidioc_try_fmt_vbi_cap = ivtv_try_fmt_vbi_cap,
.vidioc_try_fmt_sliced_vbi_cap = ivtv_try_fmt_sliced_vbi_cap,
.vidioc_try_fmt_vid_out = ivtv_try_fmt_vid_out,
.vidioc_try_fmt_vid_out_overlay = ivtv_try_fmt_vid_out_overlay,
.vidioc_try_fmt_sliced_vbi_out = ivtv_try_fmt_sliced_vbi_out,
.vidioc_g_sliced_vbi_cap = ivtv_g_sliced_vbi_cap,
.vidioc_g_chip_ident = ivtv_g_chip_ident,
#ifdef CONFIG_VIDEO_ADV_DEBUG
.vidioc_g_register = ivtv_g_register,
.vidioc_s_register = ivtv_s_register,
#endif
.vidioc_default = ivtv_default,
.vidioc_subscribe_event = ivtv_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
void ivtv_set_funcs(struct video_device *vdev)
{
vdev->ioctl_ops = &ivtv_ioctl_ops;
}
| gpl-2.0 |
jmztaylor/android_kernel_htc_primoc_backup | fs/ubifs/recovery.c | 2382 | 44272 | /*
* This file is part of UBIFS.
*
* Copyright (C) 2006-2008 Nokia Corporation
*
* 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
*
* Authors: Adrian Hunter
* Artem Bityutskiy (Битюцкий Артём)
*/
/*
* This file implements functions needed to recover from unclean un-mounts.
* When UBIFS is mounted, it checks a flag on the master node to determine if
* an un-mount was completed successfully. If not, the process of mounting
* incorporates additional checking and fixing of on-flash data structures.
* UBIFS always cleans away all remnants of an unclean un-mount, so that
* errors do not accumulate. However UBIFS defers recovery if it is mounted
* read-only, and the flash is not modified in that case.
*
* The general UBIFS approach to the recovery is that it recovers from
* corruptions which could be caused by power cuts, but it refuses to recover
* from corruption caused by other reasons. And UBIFS tries to distinguish
* between these 2 reasons of corruptions and silently recover in the former
* case and loudly complain in the latter case.
*
* UBIFS writes only to erased LEBs, so it writes only to the flash space
* containing only 0xFFs. UBIFS also always writes strictly from the beginning
* of the LEB to the end. And UBIFS assumes that the underlying flash media
* writes in @c->max_write_size bytes at a time.
*
* Hence, if UBIFS finds a corrupted node at offset X, it expects only the min.
* I/O unit corresponding to offset X to contain corrupted data, all the
* following min. I/O units have to contain empty space (all 0xFFs). If this is
* not true, the corruption cannot be the result of a power cut, and UBIFS
* refuses to mount.
*/
#include <linux/crc32.h>
#include <linux/slab.h>
#include "ubifs.h"
/**
* is_empty - determine whether a buffer is empty (contains all 0xff).
* @buf: buffer to clean
* @len: length of buffer
*
* This function returns %1 if the buffer is empty (contains all 0xff) otherwise
* %0 is returned.
*/
static int is_empty(void *buf, int len)
{
uint8_t *p = buf;
int i;
for (i = 0; i < len; i++)
if (*p++ != 0xff)
return 0;
return 1;
}
/**
* first_non_ff - find offset of the first non-0xff byte.
* @buf: buffer to search in
* @len: length of buffer
*
* This function returns offset of the first non-0xff byte in @buf or %-1 if
* the buffer contains only 0xff bytes.
*/
static int first_non_ff(void *buf, int len)
{
uint8_t *p = buf;
int i;
for (i = 0; i < len; i++)
if (*p++ != 0xff)
return i;
return -1;
}
/**
* get_master_node - get the last valid master node allowing for corruption.
* @c: UBIFS file-system description object
* @lnum: LEB number
* @pbuf: buffer containing the LEB read, is returned here
* @mst: master node, if found, is returned here
* @cor: corruption, if found, is returned here
*
* This function allocates a buffer, reads the LEB into it, and finds and
* returns the last valid master node allowing for one area of corruption.
* The corrupt area, if there is one, must be consistent with the assumption
* that it is the result of an unclean unmount while the master node was being
* written. Under those circumstances, it is valid to use the previously written
* master node.
*
* This function returns %0 on success and a negative error code on failure.
*/
static int get_master_node(const struct ubifs_info *c, int lnum, void **pbuf,
struct ubifs_mst_node **mst, void **cor)
{
const int sz = c->mst_node_alsz;
int err, offs, len;
void *sbuf, *buf;
sbuf = vmalloc(c->leb_size);
if (!sbuf)
return -ENOMEM;
err = ubi_read(c->ubi, lnum, sbuf, 0, c->leb_size);
if (err && err != -EBADMSG)
goto out_free;
/* Find the first position that is definitely not a node */
offs = 0;
buf = sbuf;
len = c->leb_size;
while (offs + UBIFS_MST_NODE_SZ <= c->leb_size) {
struct ubifs_ch *ch = buf;
if (le32_to_cpu(ch->magic) != UBIFS_NODE_MAGIC)
break;
offs += sz;
buf += sz;
len -= sz;
}
/* See if there was a valid master node before that */
if (offs) {
int ret;
offs -= sz;
buf -= sz;
len += sz;
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
if (ret != SCANNED_A_NODE && offs) {
/* Could have been corruption so check one place back */
offs -= sz;
buf -= sz;
len += sz;
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
if (ret != SCANNED_A_NODE)
/*
* We accept only one area of corruption because
* we are assuming that it was caused while
* trying to write a master node.
*/
goto out_err;
}
if (ret == SCANNED_A_NODE) {
struct ubifs_ch *ch = buf;
if (ch->node_type != UBIFS_MST_NODE)
goto out_err;
dbg_rcvry("found a master node at %d:%d", lnum, offs);
*mst = buf;
offs += sz;
buf += sz;
len -= sz;
}
}
/* Check for corruption */
if (offs < c->leb_size) {
if (!is_empty(buf, min_t(int, len, sz))) {
*cor = buf;
dbg_rcvry("found corruption at %d:%d", lnum, offs);
}
offs += sz;
buf += sz;
len -= sz;
}
/* Check remaining empty space */
if (offs < c->leb_size)
if (!is_empty(buf, len))
goto out_err;
*pbuf = sbuf;
return 0;
out_err:
err = -EINVAL;
out_free:
vfree(sbuf);
*mst = NULL;
*cor = NULL;
return err;
}
/**
* write_rcvrd_mst_node - write recovered master node.
* @c: UBIFS file-system description object
* @mst: master node
*
* This function returns %0 on success and a negative error code on failure.
*/
static int write_rcvrd_mst_node(struct ubifs_info *c,
struct ubifs_mst_node *mst)
{
int err = 0, lnum = UBIFS_MST_LNUM, sz = c->mst_node_alsz;
__le32 save_flags;
dbg_rcvry("recovery");
save_flags = mst->flags;
mst->flags |= cpu_to_le32(UBIFS_MST_RCVRY);
ubifs_prepare_node(c, mst, UBIFS_MST_NODE_SZ, 1);
err = ubi_leb_change(c->ubi, lnum, mst, sz, UBI_SHORTTERM);
if (err)
goto out;
err = ubi_leb_change(c->ubi, lnum + 1, mst, sz, UBI_SHORTTERM);
if (err)
goto out;
out:
mst->flags = save_flags;
return err;
}
/**
* ubifs_recover_master_node - recover the master node.
* @c: UBIFS file-system description object
*
* This function recovers the master node from corruption that may occur due to
* an unclean unmount.
*
* This function returns %0 on success and a negative error code on failure.
*/
int ubifs_recover_master_node(struct ubifs_info *c)
{
void *buf1 = NULL, *buf2 = NULL, *cor1 = NULL, *cor2 = NULL;
struct ubifs_mst_node *mst1 = NULL, *mst2 = NULL, *mst;
const int sz = c->mst_node_alsz;
int err, offs1, offs2;
dbg_rcvry("recovery");
err = get_master_node(c, UBIFS_MST_LNUM, &buf1, &mst1, &cor1);
if (err)
goto out_free;
err = get_master_node(c, UBIFS_MST_LNUM + 1, &buf2, &mst2, &cor2);
if (err)
goto out_free;
if (mst1) {
offs1 = (void *)mst1 - buf1;
if ((le32_to_cpu(mst1->flags) & UBIFS_MST_RCVRY) &&
(offs1 == 0 && !cor1)) {
/*
* mst1 was written by recovery at offset 0 with no
* corruption.
*/
dbg_rcvry("recovery recovery");
mst = mst1;
} else if (mst2) {
offs2 = (void *)mst2 - buf2;
if (offs1 == offs2) {
/* Same offset, so must be the same */
if (memcmp((void *)mst1 + UBIFS_CH_SZ,
(void *)mst2 + UBIFS_CH_SZ,
UBIFS_MST_NODE_SZ - UBIFS_CH_SZ))
goto out_err;
mst = mst1;
} else if (offs2 + sz == offs1) {
/* 1st LEB was written, 2nd was not */
if (cor1)
goto out_err;
mst = mst1;
} else if (offs1 == 0 && offs2 + sz >= c->leb_size) {
/* 1st LEB was unmapped and written, 2nd not */
if (cor1)
goto out_err;
mst = mst1;
} else
goto out_err;
} else {
/*
* 2nd LEB was unmapped and about to be written, so
* there must be only one master node in the first LEB
* and no corruption.
*/
if (offs1 != 0 || cor1)
goto out_err;
mst = mst1;
}
} else {
if (!mst2)
goto out_err;
/*
* 1st LEB was unmapped and about to be written, so there must
* be no room left in 2nd LEB.
*/
offs2 = (void *)mst2 - buf2;
if (offs2 + sz + sz <= c->leb_size)
goto out_err;
mst = mst2;
}
ubifs_msg("recovered master node from LEB %d",
(mst == mst1 ? UBIFS_MST_LNUM : UBIFS_MST_LNUM + 1));
memcpy(c->mst_node, mst, UBIFS_MST_NODE_SZ);
if (c->ro_mount) {
/* Read-only mode. Keep a copy for switching to rw mode */
c->rcvrd_mst_node = kmalloc(sz, GFP_KERNEL);
if (!c->rcvrd_mst_node) {
err = -ENOMEM;
goto out_free;
}
memcpy(c->rcvrd_mst_node, c->mst_node, UBIFS_MST_NODE_SZ);
/*
* We had to recover the master node, which means there was an
* unclean reboot. However, it is possible that the master node
* is clean at this point, i.e., %UBIFS_MST_DIRTY is not set.
* E.g., consider the following chain of events:
*
* 1. UBIFS was cleanly unmounted, so the master node is clean
* 2. UBIFS is being mounted R/W and starts changing the master
* node in the first (%UBIFS_MST_LNUM). A power cut happens,
* so this LEB ends up with some amount of garbage at the
* end.
* 3. UBIFS is being mounted R/O. We reach this place and
* recover the master node from the second LEB
* (%UBIFS_MST_LNUM + 1). But we cannot update the media
* because we are being mounted R/O. We have to defer the
* operation.
* 4. However, this master node (@c->mst_node) is marked as
* clean (since the step 1). And if we just return, the
* mount code will be confused and won't recover the master
* node when it is re-mounter R/W later.
*
* Thus, to force the recovery by marking the master node as
* dirty.
*/
c->mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
} else {
/* Write the recovered master node */
c->max_sqnum = le64_to_cpu(mst->ch.sqnum) - 1;
err = write_rcvrd_mst_node(c, c->mst_node);
if (err)
goto out_free;
}
vfree(buf2);
vfree(buf1);
return 0;
out_err:
err = -EINVAL;
out_free:
ubifs_err("failed to recover master node");
if (mst1) {
dbg_err("dumping first master node");
dbg_dump_node(c, mst1);
}
if (mst2) {
dbg_err("dumping second master node");
dbg_dump_node(c, mst2);
}
vfree(buf2);
vfree(buf1);
return err;
}
/**
* ubifs_write_rcvrd_mst_node - write the recovered master node.
* @c: UBIFS file-system description object
*
* This function writes the master node that was recovered during mounting in
* read-only mode and must now be written because we are remounting rw.
*
* This function returns %0 on success and a negative error code on failure.
*/
int ubifs_write_rcvrd_mst_node(struct ubifs_info *c)
{
int err;
if (!c->rcvrd_mst_node)
return 0;
c->rcvrd_mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
c->mst_node->flags |= cpu_to_le32(UBIFS_MST_DIRTY);
err = write_rcvrd_mst_node(c, c->rcvrd_mst_node);
if (err)
return err;
kfree(c->rcvrd_mst_node);
c->rcvrd_mst_node = NULL;
return 0;
}
/**
* is_last_write - determine if an offset was in the last write to a LEB.
* @c: UBIFS file-system description object
* @buf: buffer to check
* @offs: offset to check
*
* This function returns %1 if @offs was in the last write to the LEB whose data
* is in @buf, otherwise %0 is returned. The determination is made by checking
* for subsequent empty space starting from the next @c->max_write_size
* boundary.
*/
static int is_last_write(const struct ubifs_info *c, void *buf, int offs)
{
int empty_offs, check_len;
uint8_t *p;
/*
* Round up to the next @c->max_write_size boundary i.e. @offs is in
* the last wbuf written. After that should be empty space.
*/
empty_offs = ALIGN(offs + 1, c->max_write_size);
check_len = c->leb_size - empty_offs;
p = buf + empty_offs - offs;
return is_empty(p, check_len);
}
/**
* clean_buf - clean the data from an LEB sitting in a buffer.
* @c: UBIFS file-system description object
* @buf: buffer to clean
* @lnum: LEB number to clean
* @offs: offset from which to clean
* @len: length of buffer
*
* This function pads up to the next min_io_size boundary (if there is one) and
* sets empty space to all 0xff. @buf, @offs and @len are updated to the next
* @c->min_io_size boundary.
*/
static void clean_buf(const struct ubifs_info *c, void **buf, int lnum,
int *offs, int *len)
{
int empty_offs, pad_len;
lnum = lnum;
dbg_rcvry("cleaning corruption at %d:%d", lnum, *offs);
ubifs_assert(!(*offs & 7));
empty_offs = ALIGN(*offs, c->min_io_size);
pad_len = empty_offs - *offs;
ubifs_pad(c, *buf, pad_len);
*offs += pad_len;
*buf += pad_len;
*len -= pad_len;
memset(*buf, 0xff, c->leb_size - empty_offs);
}
/**
* no_more_nodes - determine if there are no more nodes in a buffer.
* @c: UBIFS file-system description object
* @buf: buffer to check
* @len: length of buffer
* @lnum: LEB number of the LEB from which @buf was read
* @offs: offset from which @buf was read
*
* This function ensures that the corrupted node at @offs is the last thing
* written to a LEB. This function returns %1 if more data is not found and
* %0 if more data is found.
*/
static int no_more_nodes(const struct ubifs_info *c, void *buf, int len,
int lnum, int offs)
{
struct ubifs_ch *ch = buf;
int skip, dlen = le32_to_cpu(ch->len);
/* Check for empty space after the corrupt node's common header */
skip = ALIGN(offs + UBIFS_CH_SZ, c->max_write_size) - offs;
if (is_empty(buf + skip, len - skip))
return 1;
/*
* The area after the common header size is not empty, so the common
* header must be intact. Check it.
*/
if (ubifs_check_node(c, buf, lnum, offs, 1, 0) != -EUCLEAN) {
dbg_rcvry("unexpected bad common header at %d:%d", lnum, offs);
return 0;
}
/* Now we know the corrupt node's length we can skip over it */
skip = ALIGN(offs + dlen, c->max_write_size) - offs;
/* After which there should be empty space */
if (is_empty(buf + skip, len - skip))
return 1;
dbg_rcvry("unexpected data at %d:%d", lnum, offs + skip);
return 0;
}
/**
* fix_unclean_leb - fix an unclean LEB.
* @c: UBIFS file-system description object
* @sleb: scanned LEB information
* @start: offset where scan started
*/
static int fix_unclean_leb(struct ubifs_info *c, struct ubifs_scan_leb *sleb,
int start)
{
int lnum = sleb->lnum, endpt = start;
/* Get the end offset of the last node we are keeping */
if (!list_empty(&sleb->nodes)) {
struct ubifs_scan_node *snod;
snod = list_entry(sleb->nodes.prev,
struct ubifs_scan_node, list);
endpt = snod->offs + snod->len;
}
if (c->ro_mount && !c->remounting_rw) {
/* Add to recovery list */
struct ubifs_unclean_leb *ucleb;
dbg_rcvry("need to fix LEB %d start %d endpt %d",
lnum, start, sleb->endpt);
ucleb = kzalloc(sizeof(struct ubifs_unclean_leb), GFP_NOFS);
if (!ucleb)
return -ENOMEM;
ucleb->lnum = lnum;
ucleb->endpt = endpt;
list_add_tail(&ucleb->list, &c->unclean_leb_list);
} else {
/* Write the fixed LEB back to flash */
int err;
dbg_rcvry("fixing LEB %d start %d endpt %d",
lnum, start, sleb->endpt);
if (endpt == 0) {
err = ubifs_leb_unmap(c, lnum);
if (err)
return err;
} else {
int len = ALIGN(endpt, c->min_io_size);
if (start) {
err = ubi_read(c->ubi, lnum, sleb->buf, 0,
start);
if (err)
return err;
}
/* Pad to min_io_size */
if (len > endpt) {
int pad_len = len - ALIGN(endpt, 8);
if (pad_len > 0) {
void *buf = sleb->buf + len - pad_len;
ubifs_pad(c, buf, pad_len);
}
}
err = ubi_leb_change(c->ubi, lnum, sleb->buf, len,
UBI_UNKNOWN);
if (err)
return err;
}
}
return 0;
}
/**
* drop_last_group - drop the last group of nodes.
* @sleb: scanned LEB information
* @offs: offset of dropped nodes is returned here
*
* This is a helper function for 'ubifs_recover_leb()' which drops the last
* group of nodes of the scanned LEB.
*/
static void drop_last_group(struct ubifs_scan_leb *sleb, int *offs)
{
while (!list_empty(&sleb->nodes)) {
struct ubifs_scan_node *snod;
struct ubifs_ch *ch;
snod = list_entry(sleb->nodes.prev, struct ubifs_scan_node,
list);
ch = snod->node;
if (ch->group_type != UBIFS_IN_NODE_GROUP)
break;
dbg_rcvry("dropping grouped node at %d:%d",
sleb->lnum, snod->offs);
*offs = snod->offs;
list_del(&snod->list);
kfree(snod);
sleb->nodes_cnt -= 1;
}
}
/**
* drop_last_node - drop the last node.
* @sleb: scanned LEB information
* @offs: offset of dropped nodes is returned here
* @grouped: non-zero if whole group of nodes have to be dropped
*
* This is a helper function for 'ubifs_recover_leb()' which drops the last
* node of the scanned LEB.
*/
static void drop_last_node(struct ubifs_scan_leb *sleb, int *offs)
{
struct ubifs_scan_node *snod;
if (!list_empty(&sleb->nodes)) {
snod = list_entry(sleb->nodes.prev, struct ubifs_scan_node,
list);
dbg_rcvry("dropping last node at %d:%d", sleb->lnum, snod->offs);
*offs = snod->offs;
list_del(&snod->list);
kfree(snod);
sleb->nodes_cnt -= 1;
}
}
/**
* ubifs_recover_leb - scan and recover a LEB.
* @c: UBIFS file-system description object
* @lnum: LEB number
* @offs: offset
* @sbuf: LEB-sized buffer to use
* @jhead: journal head number this LEB belongs to (%-1 if the LEB does not
* belong to any journal head)
*
* This function does a scan of a LEB, but caters for errors that might have
* been caused by the unclean unmount from which we are attempting to recover.
* Returns %0 in case of success, %-EUCLEAN if an unrecoverable corruption is
* found, and a negative error code in case of failure.
*/
struct ubifs_scan_leb *ubifs_recover_leb(struct ubifs_info *c, int lnum,
int offs, void *sbuf, int jhead)
{
int ret = 0, err, len = c->leb_size - offs, start = offs, min_io_unit;
int grouped = jhead == -1 ? 0 : c->jheads[jhead].grouped;
struct ubifs_scan_leb *sleb;
void *buf = sbuf + offs;
dbg_rcvry("%d:%d, jhead %d, grouped %d", lnum, offs, jhead, grouped);
sleb = ubifs_start_scan(c, lnum, offs, sbuf);
if (IS_ERR(sleb))
return sleb;
ubifs_assert(len >= 8);
while (len >= 8) {
dbg_scan("look at LEB %d:%d (%d bytes left)",
lnum, offs, len);
cond_resched();
/*
* Scan quietly until there is an error from which we cannot
* recover
*/
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
if (ret == SCANNED_A_NODE) {
/* A valid node, and not a padding node */
struct ubifs_ch *ch = buf;
int node_len;
err = ubifs_add_snod(c, sleb, buf, offs);
if (err)
goto error;
node_len = ALIGN(le32_to_cpu(ch->len), 8);
offs += node_len;
buf += node_len;
len -= node_len;
} else if (ret > 0) {
/* Padding bytes or a valid padding node */
offs += ret;
buf += ret;
len -= ret;
} else if (ret == SCANNED_EMPTY_SPACE ||
ret == SCANNED_GARBAGE ||
ret == SCANNED_A_BAD_PAD_NODE ||
ret == SCANNED_A_CORRUPT_NODE) {
dbg_rcvry("found corruption - %d", ret);
break;
} else {
dbg_err("unexpected return value %d", ret);
err = -EINVAL;
goto error;
}
}
if (ret == SCANNED_GARBAGE || ret == SCANNED_A_BAD_PAD_NODE) {
if (!is_last_write(c, buf, offs))
goto corrupted_rescan;
} else if (ret == SCANNED_A_CORRUPT_NODE) {
if (!no_more_nodes(c, buf, len, lnum, offs))
goto corrupted_rescan;
} else if (!is_empty(buf, len)) {
if (!is_last_write(c, buf, offs)) {
int corruption = first_non_ff(buf, len);
/*
* See header comment for this file for more
* explanations about the reasons we have this check.
*/
ubifs_err("corrupt empty space LEB %d:%d, corruption "
"starts at %d", lnum, offs, corruption);
/* Make sure we dump interesting non-0xFF data */
offs += corruption;
buf += corruption;
goto corrupted;
}
}
min_io_unit = round_down(offs, c->min_io_size);
if (grouped)
/*
* If nodes are grouped, always drop the incomplete group at
* the end.
*/
drop_last_group(sleb, &offs);
if (jhead == GCHD) {
/*
* If this LEB belongs to the GC head then while we are in the
* middle of the same min. I/O unit keep dropping nodes. So
* basically, what we want is to make sure that the last min.
* I/O unit where we saw the corruption is dropped completely
* with all the uncorrupted nodes which may possibly sit there.
*
* In other words, let's name the min. I/O unit where the
* corruption starts B, and the previous min. I/O unit A. The
* below code tries to deal with a situation when half of B
* contains valid nodes or the end of a valid node, and the
* second half of B contains corrupted data or garbage. This
* means that UBIFS had been writing to B just before the power
* cut happened. I do not know how realistic is this scenario
* that half of the min. I/O unit had been written successfully
* and the other half not, but this is possible in our 'failure
* mode emulation' infrastructure at least.
*
* So what is the problem, why we need to drop those nodes? Why
* can't we just clean-up the second half of B by putting a
* padding node there? We can, and this works fine with one
* exception which was reproduced with power cut emulation
* testing and happens extremely rarely.
*
* Imagine the file-system is full, we run GC which starts
* moving valid nodes from LEB X to LEB Y (obviously, LEB Y is
* the current GC head LEB). The @c->gc_lnum is -1, which means
* that GC will retain LEB X and will try to continue. Imagine
* that LEB X is currently the dirtiest LEB, and the amount of
* used space in LEB Y is exactly the same as amount of free
* space in LEB X.
*
* And a power cut happens when nodes are moved from LEB X to
* LEB Y. We are here trying to recover LEB Y which is the GC
* head LEB. We find the min. I/O unit B as described above.
* Then we clean-up LEB Y by padding min. I/O unit. And later
* 'ubifs_rcvry_gc_commit()' function fails, because it cannot
* find a dirty LEB which could be GC'd into LEB Y! Even LEB X
* does not match because the amount of valid nodes there does
* not fit the free space in LEB Y any more! And this is
* because of the padding node which we added to LEB Y. The
* user-visible effect of this which I once observed and
* analysed is that we cannot mount the file-system with
* -ENOSPC error.
*
* So obviously, to make sure that situation does not happen we
* should free min. I/O unit B in LEB Y completely and the last
* used min. I/O unit in LEB Y should be A. This is basically
* what the below code tries to do.
*/
while (offs > min_io_unit)
drop_last_node(sleb, &offs);
}
buf = sbuf + offs;
len = c->leb_size - offs;
clean_buf(c, &buf, lnum, &offs, &len);
ubifs_end_scan(c, sleb, lnum, offs);
err = fix_unclean_leb(c, sleb, start);
if (err)
goto error;
return sleb;
corrupted_rescan:
/* Re-scan the corrupted data with verbose messages */
dbg_err("corruptio %d", ret);
ubifs_scan_a_node(c, buf, len, lnum, offs, 1);
corrupted:
ubifs_scanned_corruption(c, lnum, offs, buf);
err = -EUCLEAN;
error:
ubifs_err("LEB %d scanning failed", lnum);
ubifs_scan_destroy(sleb);
return ERR_PTR(err);
}
/**
* get_cs_sqnum - get commit start sequence number.
* @c: UBIFS file-system description object
* @lnum: LEB number of commit start node
* @offs: offset of commit start node
* @cs_sqnum: commit start sequence number is returned here
*
* This function returns %0 on success and a negative error code on failure.
*/
static int get_cs_sqnum(struct ubifs_info *c, int lnum, int offs,
unsigned long long *cs_sqnum)
{
struct ubifs_cs_node *cs_node = NULL;
int err, ret;
dbg_rcvry("at %d:%d", lnum, offs);
cs_node = kmalloc(UBIFS_CS_NODE_SZ, GFP_KERNEL);
if (!cs_node)
return -ENOMEM;
if (c->leb_size - offs < UBIFS_CS_NODE_SZ)
goto out_err;
err = ubi_read(c->ubi, lnum, (void *)cs_node, offs, UBIFS_CS_NODE_SZ);
if (err && err != -EBADMSG)
goto out_free;
ret = ubifs_scan_a_node(c, cs_node, UBIFS_CS_NODE_SZ, lnum, offs, 0);
if (ret != SCANNED_A_NODE) {
dbg_err("Not a valid node");
goto out_err;
}
if (cs_node->ch.node_type != UBIFS_CS_NODE) {
dbg_err("Node a CS node, type is %d", cs_node->ch.node_type);
goto out_err;
}
if (le64_to_cpu(cs_node->cmt_no) != c->cmt_no) {
dbg_err("CS node cmt_no %llu != current cmt_no %llu",
(unsigned long long)le64_to_cpu(cs_node->cmt_no),
c->cmt_no);
goto out_err;
}
*cs_sqnum = le64_to_cpu(cs_node->ch.sqnum);
dbg_rcvry("commit start sqnum %llu", *cs_sqnum);
kfree(cs_node);
return 0;
out_err:
err = -EINVAL;
out_free:
ubifs_err("failed to get CS sqnum");
kfree(cs_node);
return err;
}
/**
* ubifs_recover_log_leb - scan and recover a log LEB.
* @c: UBIFS file-system description object
* @lnum: LEB number
* @offs: offset
* @sbuf: LEB-sized buffer to use
*
* This function does a scan of a LEB, but caters for errors that might have
* been caused by unclean reboots from which we are attempting to recover
* (assume that only the last log LEB can be corrupted by an unclean reboot).
*
* This function returns %0 on success and a negative error code on failure.
*/
struct ubifs_scan_leb *ubifs_recover_log_leb(struct ubifs_info *c, int lnum,
int offs, void *sbuf)
{
struct ubifs_scan_leb *sleb;
int next_lnum;
dbg_rcvry("LEB %d", lnum);
next_lnum = lnum + 1;
if (next_lnum >= UBIFS_LOG_LNUM + c->log_lebs)
next_lnum = UBIFS_LOG_LNUM;
if (next_lnum != c->ltail_lnum) {
/*
* We can only recover at the end of the log, so check that the
* next log LEB is empty or out of date.
*/
sleb = ubifs_scan(c, next_lnum, 0, sbuf, 0);
if (IS_ERR(sleb))
return sleb;
if (sleb->nodes_cnt) {
struct ubifs_scan_node *snod;
unsigned long long cs_sqnum = c->cs_sqnum;
snod = list_entry(sleb->nodes.next,
struct ubifs_scan_node, list);
if (cs_sqnum == 0) {
int err;
err = get_cs_sqnum(c, lnum, offs, &cs_sqnum);
if (err) {
ubifs_scan_destroy(sleb);
return ERR_PTR(err);
}
}
if (snod->sqnum > cs_sqnum) {
ubifs_err("unrecoverable log corruption "
"in LEB %d", lnum);
ubifs_scan_destroy(sleb);
return ERR_PTR(-EUCLEAN);
}
}
ubifs_scan_destroy(sleb);
}
return ubifs_recover_leb(c, lnum, offs, sbuf, -1);
}
/**
* recover_head - recover a head.
* @c: UBIFS file-system description object
* @lnum: LEB number of head to recover
* @offs: offset of head to recover
* @sbuf: LEB-sized buffer to use
*
* This function ensures that there is no data on the flash at a head location.
*
* This function returns %0 on success and a negative error code on failure.
*/
static int recover_head(const struct ubifs_info *c, int lnum, int offs,
void *sbuf)
{
int len = c->max_write_size, err;
if (offs + len > c->leb_size)
len = c->leb_size - offs;
if (!len)
return 0;
/* Read at the head location and check it is empty flash */
err = ubi_read(c->ubi, lnum, sbuf, offs, len);
if (err || !is_empty(sbuf, len)) {
dbg_rcvry("cleaning head at %d:%d", lnum, offs);
if (offs == 0)
return ubifs_leb_unmap(c, lnum);
err = ubi_read(c->ubi, lnum, sbuf, 0, offs);
if (err)
return err;
return ubi_leb_change(c->ubi, lnum, sbuf, offs, UBI_UNKNOWN);
}
return 0;
}
/**
* ubifs_recover_inl_heads - recover index and LPT heads.
* @c: UBIFS file-system description object
* @sbuf: LEB-sized buffer to use
*
* This function ensures that there is no data on the flash at the index and
* LPT head locations.
*
* This deals with the recovery of a half-completed journal commit. UBIFS is
* careful never to overwrite the last version of the index or the LPT. Because
* the index and LPT are wandering trees, data from a half-completed commit will
* not be referenced anywhere in UBIFS. The data will be either in LEBs that are
* assumed to be empty and will be unmapped anyway before use, or in the index
* and LPT heads.
*
* This function returns %0 on success and a negative error code on failure.
*/
int ubifs_recover_inl_heads(const struct ubifs_info *c, void *sbuf)
{
int err;
ubifs_assert(!c->ro_mount || c->remounting_rw);
dbg_rcvry("checking index head at %d:%d", c->ihead_lnum, c->ihead_offs);
err = recover_head(c, c->ihead_lnum, c->ihead_offs, sbuf);
if (err)
return err;
dbg_rcvry("checking LPT head at %d:%d", c->nhead_lnum, c->nhead_offs);
err = recover_head(c, c->nhead_lnum, c->nhead_offs, sbuf);
if (err)
return err;
return 0;
}
/**
* clean_an_unclean_leb - read and write a LEB to remove corruption.
* @c: UBIFS file-system description object
* @ucleb: unclean LEB information
* @sbuf: LEB-sized buffer to use
*
* This function reads a LEB up to a point pre-determined by the mount recovery,
* checks the nodes, and writes the result back to the flash, thereby cleaning
* off any following corruption, or non-fatal ECC errors.
*
* This function returns %0 on success and a negative error code on failure.
*/
static int clean_an_unclean_leb(const struct ubifs_info *c,
struct ubifs_unclean_leb *ucleb, void *sbuf)
{
int err, lnum = ucleb->lnum, offs = 0, len = ucleb->endpt, quiet = 1;
void *buf = sbuf;
dbg_rcvry("LEB %d len %d", lnum, len);
if (len == 0) {
/* Nothing to read, just unmap it */
err = ubifs_leb_unmap(c, lnum);
if (err)
return err;
return 0;
}
err = ubi_read(c->ubi, lnum, buf, offs, len);
if (err && err != -EBADMSG)
return err;
while (len >= 8) {
int ret;
cond_resched();
/* Scan quietly until there is an error */
ret = ubifs_scan_a_node(c, buf, len, lnum, offs, quiet);
if (ret == SCANNED_A_NODE) {
/* A valid node, and not a padding node */
struct ubifs_ch *ch = buf;
int node_len;
node_len = ALIGN(le32_to_cpu(ch->len), 8);
offs += node_len;
buf += node_len;
len -= node_len;
continue;
}
if (ret > 0) {
/* Padding bytes or a valid padding node */
offs += ret;
buf += ret;
len -= ret;
continue;
}
if (ret == SCANNED_EMPTY_SPACE) {
ubifs_err("unexpected empty space at %d:%d",
lnum, offs);
return -EUCLEAN;
}
if (quiet) {
/* Redo the last scan but noisily */
quiet = 0;
continue;
}
ubifs_scanned_corruption(c, lnum, offs, buf);
return -EUCLEAN;
}
/* Pad to min_io_size */
len = ALIGN(ucleb->endpt, c->min_io_size);
if (len > ucleb->endpt) {
int pad_len = len - ALIGN(ucleb->endpt, 8);
if (pad_len > 0) {
buf = c->sbuf + len - pad_len;
ubifs_pad(c, buf, pad_len);
}
}
/* Write back the LEB atomically */
err = ubi_leb_change(c->ubi, lnum, sbuf, len, UBI_UNKNOWN);
if (err)
return err;
dbg_rcvry("cleaned LEB %d", lnum);
return 0;
}
/**
* ubifs_clean_lebs - clean LEBs recovered during read-only mount.
* @c: UBIFS file-system description object
* @sbuf: LEB-sized buffer to use
*
* This function cleans a LEB identified during recovery that needs to be
* written but was not because UBIFS was mounted read-only. This happens when
* remounting to read-write mode.
*
* This function returns %0 on success and a negative error code on failure.
*/
int ubifs_clean_lebs(const struct ubifs_info *c, void *sbuf)
{
dbg_rcvry("recovery");
while (!list_empty(&c->unclean_leb_list)) {
struct ubifs_unclean_leb *ucleb;
int err;
ucleb = list_entry(c->unclean_leb_list.next,
struct ubifs_unclean_leb, list);
err = clean_an_unclean_leb(c, ucleb, sbuf);
if (err)
return err;
list_del(&ucleb->list);
kfree(ucleb);
}
return 0;
}
/**
* grab_empty_leb - grab an empty LEB to use as GC LEB and run commit.
* @c: UBIFS file-system description object
*
* This is a helper function for 'ubifs_rcvry_gc_commit()' which grabs an empty
* LEB to be used as GC LEB (@c->gc_lnum), and then runs the commit. Returns
* zero in case of success and a negative error code in case of failure.
*/
static int grab_empty_leb(struct ubifs_info *c)
{
int lnum, err;
/*
* Note, it is very important to first search for an empty LEB and then
* run the commit, not vice-versa. The reason is that there might be
* only one empty LEB at the moment, the one which has been the
* @c->gc_lnum just before the power cut happened. During the regular
* UBIFS operation (not now) @c->gc_lnum is marked as "taken", so no
* one but GC can grab it. But at this moment this single empty LEB is
* not marked as taken, so if we run commit - what happens? Right, the
* commit will grab it and write the index there. Remember that the
* index always expands as long as there is free space, and it only
* starts consolidating when we run out of space.
*
* IOW, if we run commit now, we might not be able to find a free LEB
* after this.
*/
lnum = ubifs_find_free_leb_for_idx(c);
if (lnum < 0) {
dbg_err("could not find an empty LEB");
dbg_dump_lprops(c);
dbg_dump_budg(c, &c->bi);
return lnum;
}
/* Reset the index flag */
err = ubifs_change_one_lp(c, lnum, LPROPS_NC, LPROPS_NC, 0,
LPROPS_INDEX, 0);
if (err)
return err;
c->gc_lnum = lnum;
dbg_rcvry("found empty LEB %d, run commit", lnum);
return ubifs_run_commit(c);
}
/**
* ubifs_rcvry_gc_commit - recover the GC LEB number and run the commit.
* @c: UBIFS file-system description object
*
* Out-of-place garbage collection requires always one empty LEB with which to
* start garbage collection. The LEB number is recorded in c->gc_lnum and is
* written to the master node on unmounting. In the case of an unclean unmount
* the value of gc_lnum recorded in the master node is out of date and cannot
* be used. Instead, recovery must allocate an empty LEB for this purpose.
* However, there may not be enough empty space, in which case it must be
* possible to GC the dirtiest LEB into the GC head LEB.
*
* This function also runs the commit which causes the TNC updates from
* size-recovery and orphans to be written to the flash. That is important to
* ensure correct replay order for subsequent mounts.
*
* This function returns %0 on success and a negative error code on failure.
*/
int ubifs_rcvry_gc_commit(struct ubifs_info *c)
{
struct ubifs_wbuf *wbuf = &c->jheads[GCHD].wbuf;
struct ubifs_lprops lp;
int err;
dbg_rcvry("GC head LEB %d, offs %d", wbuf->lnum, wbuf->offs);
c->gc_lnum = -1;
if (wbuf->lnum == -1 || wbuf->offs == c->leb_size)
return grab_empty_leb(c);
err = ubifs_find_dirty_leb(c, &lp, wbuf->offs, 2);
if (err) {
if (err != -ENOSPC)
return err;
dbg_rcvry("could not find a dirty LEB");
return grab_empty_leb(c);
}
ubifs_assert(!(lp.flags & LPROPS_INDEX));
ubifs_assert(lp.free + lp.dirty >= wbuf->offs);
/*
* We run the commit before garbage collection otherwise subsequent
* mounts will see the GC and orphan deletion in a different order.
*/
dbg_rcvry("committing");
err = ubifs_run_commit(c);
if (err)
return err;
dbg_rcvry("GC'ing LEB %d", lp.lnum);
mutex_lock_nested(&wbuf->io_mutex, wbuf->jhead);
err = ubifs_garbage_collect_leb(c, &lp);
if (err >= 0) {
int err2 = ubifs_wbuf_sync_nolock(wbuf);
if (err2)
err = err2;
}
mutex_unlock(&wbuf->io_mutex);
if (err < 0) {
dbg_err("GC failed, error %d", err);
if (err == -EAGAIN)
err = -EINVAL;
return err;
}
ubifs_assert(err == LEB_RETAINED);
if (err != LEB_RETAINED)
return -EINVAL;
err = ubifs_leb_unmap(c, c->gc_lnum);
if (err)
return err;
dbg_rcvry("allocated LEB %d for GC", lp.lnum);
return 0;
}
/**
* struct size_entry - inode size information for recovery.
* @rb: link in the RB-tree of sizes
* @inum: inode number
* @i_size: size on inode
* @d_size: maximum size based on data nodes
* @exists: indicates whether the inode exists
* @inode: inode if pinned in memory awaiting rw mode to fix it
*/
struct size_entry {
struct rb_node rb;
ino_t inum;
loff_t i_size;
loff_t d_size;
int exists;
struct inode *inode;
};
/**
* add_ino - add an entry to the size tree.
* @c: UBIFS file-system description object
* @inum: inode number
* @i_size: size on inode
* @d_size: maximum size based on data nodes
* @exists: indicates whether the inode exists
*/
static int add_ino(struct ubifs_info *c, ino_t inum, loff_t i_size,
loff_t d_size, int exists)
{
struct rb_node **p = &c->size_tree.rb_node, *parent = NULL;
struct size_entry *e;
while (*p) {
parent = *p;
e = rb_entry(parent, struct size_entry, rb);
if (inum < e->inum)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
e = kzalloc(sizeof(struct size_entry), GFP_KERNEL);
if (!e)
return -ENOMEM;
e->inum = inum;
e->i_size = i_size;
e->d_size = d_size;
e->exists = exists;
rb_link_node(&e->rb, parent, p);
rb_insert_color(&e->rb, &c->size_tree);
return 0;
}
/**
* find_ino - find an entry on the size tree.
* @c: UBIFS file-system description object
* @inum: inode number
*/
static struct size_entry *find_ino(struct ubifs_info *c, ino_t inum)
{
struct rb_node *p = c->size_tree.rb_node;
struct size_entry *e;
while (p) {
e = rb_entry(p, struct size_entry, rb);
if (inum < e->inum)
p = p->rb_left;
else if (inum > e->inum)
p = p->rb_right;
else
return e;
}
return NULL;
}
/**
* remove_ino - remove an entry from the size tree.
* @c: UBIFS file-system description object
* @inum: inode number
*/
static void remove_ino(struct ubifs_info *c, ino_t inum)
{
struct size_entry *e = find_ino(c, inum);
if (!e)
return;
rb_erase(&e->rb, &c->size_tree);
kfree(e);
}
/**
* ubifs_destroy_size_tree - free resources related to the size tree.
* @c: UBIFS file-system description object
*/
void ubifs_destroy_size_tree(struct ubifs_info *c)
{
struct rb_node *this = c->size_tree.rb_node;
struct size_entry *e;
while (this) {
if (this->rb_left) {
this = this->rb_left;
continue;
} else if (this->rb_right) {
this = this->rb_right;
continue;
}
e = rb_entry(this, struct size_entry, rb);
if (e->inode)
iput(e->inode);
this = rb_parent(this);
if (this) {
if (this->rb_left == &e->rb)
this->rb_left = NULL;
else
this->rb_right = NULL;
}
kfree(e);
}
c->size_tree = RB_ROOT;
}
/**
* ubifs_recover_size_accum - accumulate inode sizes for recovery.
* @c: UBIFS file-system description object
* @key: node key
* @deletion: node is for a deletion
* @new_size: inode size
*
* This function has two purposes:
* 1) to ensure there are no data nodes that fall outside the inode size
* 2) to ensure there are no data nodes for inodes that do not exist
* To accomplish those purposes, a rb-tree is constructed containing an entry
* for each inode number in the journal that has not been deleted, and recording
* the size from the inode node, the maximum size of any data node (also altered
* by truncations) and a flag indicating a inode number for which no inode node
* was present in the journal.
*
* Note that there is still the possibility that there are data nodes that have
* been committed that are beyond the inode size, however the only way to find
* them would be to scan the entire index. Alternatively, some provision could
* be made to record the size of inodes at the start of commit, which would seem
* very cumbersome for a scenario that is quite unlikely and the only negative
* consequence of which is wasted space.
*
* This functions returns %0 on success and a negative error code on failure.
*/
int ubifs_recover_size_accum(struct ubifs_info *c, union ubifs_key *key,
int deletion, loff_t new_size)
{
ino_t inum = key_inum(c, key);
struct size_entry *e;
int err;
switch (key_type(c, key)) {
case UBIFS_INO_KEY:
if (deletion)
remove_ino(c, inum);
else {
e = find_ino(c, inum);
if (e) {
e->i_size = new_size;
e->exists = 1;
} else {
err = add_ino(c, inum, new_size, 0, 1);
if (err)
return err;
}
}
break;
case UBIFS_DATA_KEY:
e = find_ino(c, inum);
if (e) {
if (new_size > e->d_size)
e->d_size = new_size;
} else {
err = add_ino(c, inum, 0, new_size, 0);
if (err)
return err;
}
break;
case UBIFS_TRUN_KEY:
e = find_ino(c, inum);
if (e)
e->d_size = new_size;
break;
}
return 0;
}
/**
* fix_size_in_place - fix inode size in place on flash.
* @c: UBIFS file-system description object
* @e: inode size information for recovery
*/
static int fix_size_in_place(struct ubifs_info *c, struct size_entry *e)
{
struct ubifs_ino_node *ino = c->sbuf;
unsigned char *p;
union ubifs_key key;
int err, lnum, offs, len;
loff_t i_size;
uint32_t crc;
/* Locate the inode node LEB number and offset */
ino_key_init(c, &key, e->inum);
err = ubifs_tnc_locate(c, &key, ino, &lnum, &offs);
if (err)
goto out;
/*
* If the size recorded on the inode node is greater than the size that
* was calculated from nodes in the journal then don't change the inode.
*/
i_size = le64_to_cpu(ino->size);
if (i_size >= e->d_size)
return 0;
/* Read the LEB */
err = ubi_read(c->ubi, lnum, c->sbuf, 0, c->leb_size);
if (err)
goto out;
/* Change the size field and recalculate the CRC */
ino = c->sbuf + offs;
ino->size = cpu_to_le64(e->d_size);
len = le32_to_cpu(ino->ch.len);
crc = crc32(UBIFS_CRC32_INIT, (void *)ino + 8, len - 8);
ino->ch.crc = cpu_to_le32(crc);
/* Work out where data in the LEB ends and free space begins */
p = c->sbuf;
len = c->leb_size - 1;
while (p[len] == 0xff)
len -= 1;
len = ALIGN(len + 1, c->min_io_size);
/* Atomically write the fixed LEB back again */
err = ubi_leb_change(c->ubi, lnum, c->sbuf, len, UBI_UNKNOWN);
if (err)
goto out;
dbg_rcvry("inode %lu at %d:%d size %lld -> %lld",
(unsigned long)e->inum, lnum, offs, i_size, e->d_size);
return 0;
out:
ubifs_warn("inode %lu failed to fix size %lld -> %lld error %d",
(unsigned long)e->inum, e->i_size, e->d_size, err);
return err;
}
/**
* ubifs_recover_size - recover inode size.
* @c: UBIFS file-system description object
*
* This function attempts to fix inode size discrepancies identified by the
* 'ubifs_recover_size_accum()' function.
*
* This functions returns %0 on success and a negative error code on failure.
*/
int ubifs_recover_size(struct ubifs_info *c)
{
struct rb_node *this = rb_first(&c->size_tree);
while (this) {
struct size_entry *e;
int err;
e = rb_entry(this, struct size_entry, rb);
if (!e->exists) {
union ubifs_key key;
ino_key_init(c, &key, e->inum);
err = ubifs_tnc_lookup(c, &key, c->sbuf);
if (err && err != -ENOENT)
return err;
if (err == -ENOENT) {
/* Remove data nodes that have no inode */
dbg_rcvry("removing ino %lu",
(unsigned long)e->inum);
err = ubifs_tnc_remove_ino(c, e->inum);
if (err)
return err;
} else {
struct ubifs_ino_node *ino = c->sbuf;
e->exists = 1;
e->i_size = le64_to_cpu(ino->size);
}
}
if (e->exists && e->i_size < e->d_size) {
if (c->ro_mount) {
/* Fix the inode size and pin it in memory */
struct inode *inode;
struct ubifs_inode *ui;
ubifs_assert(!e->inode);
inode = ubifs_iget(c->vfs_sb, e->inum);
if (IS_ERR(inode))
return PTR_ERR(inode);
ui = ubifs_inode(inode);
if (inode->i_size < e->d_size) {
dbg_rcvry("ino %lu size %lld -> %lld",
(unsigned long)e->inum,
inode->i_size, e->d_size);
inode->i_size = e->d_size;
ui->ui_size = e->d_size;
ui->synced_i_size = e->d_size;
e->inode = inode;
this = rb_next(this);
continue;
}
iput(inode);
} else {
/* Fix the size in place */
err = fix_size_in_place(c, e);
if (err)
return err;
if (e->inode)
iput(e->inode);
}
}
this = rb_next(this);
rb_erase(&e->rb, &c->size_tree);
kfree(e);
}
return 0;
}
| gpl-2.0 |
hiikezoe/android_kernel_kyocera_msm8960 | arch/m68k/sun3x/time.c | 4686 | 2078 | /*
* linux/arch/m68k/sun3x/time.c
*
* Sun3x-specific time handling
*/
#include <linux/types.h>
#include <linux/kd.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/kernel_stat.h>
#include <linux/interrupt.h>
#include <linux/rtc.h>
#include <linux/bcd.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/traps.h>
#include <asm/sun3x.h>
#include <asm/sun3ints.h>
#include <asm/rtc.h>
#include "time.h"
#define M_CONTROL 0xf8
#define M_SEC 0xf9
#define M_MIN 0xfa
#define M_HOUR 0xfb
#define M_DAY 0xfc
#define M_DATE 0xfd
#define M_MONTH 0xfe
#define M_YEAR 0xff
#define C_WRITE 0x80
#define C_READ 0x40
#define C_SIGN 0x20
#define C_CALIB 0x1f
int sun3x_hwclk(int set, struct rtc_time *t)
{
volatile struct mostek_dt *h =
(struct mostek_dt *)(SUN3X_EEPROM+M_CONTROL);
unsigned long flags;
local_irq_save(flags);
if(set) {
h->csr |= C_WRITE;
h->sec = bin2bcd(t->tm_sec);
h->min = bin2bcd(t->tm_min);
h->hour = bin2bcd(t->tm_hour);
h->wday = bin2bcd(t->tm_wday);
h->mday = bin2bcd(t->tm_mday);
h->month = bin2bcd(t->tm_mon);
h->year = bin2bcd(t->tm_year);
h->csr &= ~C_WRITE;
} else {
h->csr |= C_READ;
t->tm_sec = bcd2bin(h->sec);
t->tm_min = bcd2bin(h->min);
t->tm_hour = bcd2bin(h->hour);
t->tm_wday = bcd2bin(h->wday);
t->tm_mday = bcd2bin(h->mday);
t->tm_mon = bcd2bin(h->month);
t->tm_year = bcd2bin(h->year);
h->csr &= ~C_READ;
}
local_irq_restore(flags);
return 0;
}
/* Not much we can do here */
unsigned long sun3x_gettimeoffset (void)
{
return 0L;
}
#if 0
static void sun3x_timer_tick(int irq, void *dev_id, struct pt_regs *regs)
{
void (*vector)(int, void *, struct pt_regs *) = dev_id;
/* Clear the pending interrupt - pulse the enable line low */
disable_irq(5);
enable_irq(5);
vector(irq, NULL, regs);
}
#endif
void __init sun3x_sched_init(irq_handler_t vector)
{
sun3_disable_interrupts();
/* Pulse enable low to get the clock started */
sun3_disable_irq(5);
sun3_enable_irq(5);
sun3_enable_interrupts();
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.