repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
hallovveen31/Magic | drivers/edac/cpc925_edac.c | 2779 | 30542 | /*
* cpc925_edac.c, EDAC driver for IBM CPC925 Bridge and Memory Controller.
*
* Copyright (c) 2008 Wind River Systems, Inc.
*
* Authors: Cao Qingtao <qingtao.cao@windriver.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
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/edac.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/gfp.h>
#include "edac_core.h"
#include "edac_module.h"
#define CPC925_EDAC_REVISION " Ver: 1.0.0"
#define CPC925_EDAC_MOD_STR "cpc925_edac"
#define cpc925_printk(level, fmt, arg...) \
edac_printk(level, "CPC925", fmt, ##arg)
#define cpc925_mc_printk(mci, level, fmt, arg...) \
edac_mc_chipset_printk(mci, level, "CPC925", fmt, ##arg)
/*
* CPC925 registers are of 32 bits with bit0 defined at the
* most significant bit and bit31 at that of least significant.
*/
#define CPC925_BITS_PER_REG 32
#define CPC925_BIT(nr) (1UL << (CPC925_BITS_PER_REG - 1 - nr))
/*
* EDAC device names for the error detections of
* CPU Interface and Hypertransport Link.
*/
#define CPC925_CPU_ERR_DEV "cpu"
#define CPC925_HT_LINK_DEV "htlink"
/* Suppose DDR Refresh cycle is 15.6 microsecond */
#define CPC925_REF_FREQ 0xFA69
#define CPC925_SCRUB_BLOCK_SIZE 64 /* bytes */
#define CPC925_NR_CSROWS 8
/*
* All registers and bits definitions are taken from
* "CPC925 Bridge and Memory Controller User Manual, SA14-2761-02".
*/
/*
* CPU and Memory Controller Registers
*/
/************************************************************
* Processor Interface Exception Mask Register (APIMASK)
************************************************************/
#define REG_APIMASK_OFFSET 0x30070
enum apimask_bits {
APIMASK_DART = CPC925_BIT(0), /* DART Exception */
APIMASK_ADI0 = CPC925_BIT(1), /* Handshake Error on PI0_ADI */
APIMASK_ADI1 = CPC925_BIT(2), /* Handshake Error on PI1_ADI */
APIMASK_STAT = CPC925_BIT(3), /* Status Exception */
APIMASK_DERR = CPC925_BIT(4), /* Data Error Exception */
APIMASK_ADRS0 = CPC925_BIT(5), /* Addressing Exception on PI0 */
APIMASK_ADRS1 = CPC925_BIT(6), /* Addressing Exception on PI1 */
/* BIT(7) Reserved */
APIMASK_ECC_UE_H = CPC925_BIT(8), /* UECC upper */
APIMASK_ECC_CE_H = CPC925_BIT(9), /* CECC upper */
APIMASK_ECC_UE_L = CPC925_BIT(10), /* UECC lower */
APIMASK_ECC_CE_L = CPC925_BIT(11), /* CECC lower */
CPU_MASK_ENABLE = (APIMASK_DART | APIMASK_ADI0 | APIMASK_ADI1 |
APIMASK_STAT | APIMASK_DERR | APIMASK_ADRS0 |
APIMASK_ADRS1),
ECC_MASK_ENABLE = (APIMASK_ECC_UE_H | APIMASK_ECC_CE_H |
APIMASK_ECC_UE_L | APIMASK_ECC_CE_L),
};
/************************************************************
* Processor Interface Exception Register (APIEXCP)
************************************************************/
#define REG_APIEXCP_OFFSET 0x30060
enum apiexcp_bits {
APIEXCP_DART = CPC925_BIT(0), /* DART Exception */
APIEXCP_ADI0 = CPC925_BIT(1), /* Handshake Error on PI0_ADI */
APIEXCP_ADI1 = CPC925_BIT(2), /* Handshake Error on PI1_ADI */
APIEXCP_STAT = CPC925_BIT(3), /* Status Exception */
APIEXCP_DERR = CPC925_BIT(4), /* Data Error Exception */
APIEXCP_ADRS0 = CPC925_BIT(5), /* Addressing Exception on PI0 */
APIEXCP_ADRS1 = CPC925_BIT(6), /* Addressing Exception on PI1 */
/* BIT(7) Reserved */
APIEXCP_ECC_UE_H = CPC925_BIT(8), /* UECC upper */
APIEXCP_ECC_CE_H = CPC925_BIT(9), /* CECC upper */
APIEXCP_ECC_UE_L = CPC925_BIT(10), /* UECC lower */
APIEXCP_ECC_CE_L = CPC925_BIT(11), /* CECC lower */
CPU_EXCP_DETECTED = (APIEXCP_DART | APIEXCP_ADI0 | APIEXCP_ADI1 |
APIEXCP_STAT | APIEXCP_DERR | APIEXCP_ADRS0 |
APIEXCP_ADRS1),
UECC_EXCP_DETECTED = (APIEXCP_ECC_UE_H | APIEXCP_ECC_UE_L),
CECC_EXCP_DETECTED = (APIEXCP_ECC_CE_H | APIEXCP_ECC_CE_L),
ECC_EXCP_DETECTED = (UECC_EXCP_DETECTED | CECC_EXCP_DETECTED),
};
/************************************************************
* Memory Bus Configuration Register (MBCR)
************************************************************/
#define REG_MBCR_OFFSET 0x2190
#define MBCR_64BITCFG_SHIFT 23
#define MBCR_64BITCFG_MASK (1UL << MBCR_64BITCFG_SHIFT)
#define MBCR_64BITBUS_SHIFT 22
#define MBCR_64BITBUS_MASK (1UL << MBCR_64BITBUS_SHIFT)
/************************************************************
* Memory Bank Mode Register (MBMR)
************************************************************/
#define REG_MBMR_OFFSET 0x21C0
#define MBMR_MODE_MAX_VALUE 0xF
#define MBMR_MODE_SHIFT 25
#define MBMR_MODE_MASK (MBMR_MODE_MAX_VALUE << MBMR_MODE_SHIFT)
#define MBMR_BBA_SHIFT 24
#define MBMR_BBA_MASK (1UL << MBMR_BBA_SHIFT)
/************************************************************
* Memory Bank Boundary Address Register (MBBAR)
************************************************************/
#define REG_MBBAR_OFFSET 0x21D0
#define MBBAR_BBA_MAX_VALUE 0xFF
#define MBBAR_BBA_SHIFT 24
#define MBBAR_BBA_MASK (MBBAR_BBA_MAX_VALUE << MBBAR_BBA_SHIFT)
/************************************************************
* Memory Scrub Control Register (MSCR)
************************************************************/
#define REG_MSCR_OFFSET 0x2400
#define MSCR_SCRUB_MOD_MASK 0xC0000000 /* scrub_mod - bit0:1*/
#define MSCR_BACKGR_SCRUB 0x40000000 /* 01 */
#define MSCR_SI_SHIFT 16 /* si - bit8:15*/
#define MSCR_SI_MAX_VALUE 0xFF
#define MSCR_SI_MASK (MSCR_SI_MAX_VALUE << MSCR_SI_SHIFT)
/************************************************************
* Memory Scrub Range Start Register (MSRSR)
************************************************************/
#define REG_MSRSR_OFFSET 0x2410
/************************************************************
* Memory Scrub Range End Register (MSRER)
************************************************************/
#define REG_MSRER_OFFSET 0x2420
/************************************************************
* Memory Scrub Pattern Register (MSPR)
************************************************************/
#define REG_MSPR_OFFSET 0x2430
/************************************************************
* Memory Check Control Register (MCCR)
************************************************************/
#define REG_MCCR_OFFSET 0x2440
enum mccr_bits {
MCCR_ECC_EN = CPC925_BIT(0), /* ECC high and low check */
};
/************************************************************
* Memory Check Range End Register (MCRER)
************************************************************/
#define REG_MCRER_OFFSET 0x2450
/************************************************************
* Memory Error Address Register (MEAR)
************************************************************/
#define REG_MEAR_OFFSET 0x2460
#define MEAR_BCNT_MAX_VALUE 0x3
#define MEAR_BCNT_SHIFT 30
#define MEAR_BCNT_MASK (MEAR_BCNT_MAX_VALUE << MEAR_BCNT_SHIFT)
#define MEAR_RANK_MAX_VALUE 0x7
#define MEAR_RANK_SHIFT 27
#define MEAR_RANK_MASK (MEAR_RANK_MAX_VALUE << MEAR_RANK_SHIFT)
#define MEAR_COL_MAX_VALUE 0x7FF
#define MEAR_COL_SHIFT 16
#define MEAR_COL_MASK (MEAR_COL_MAX_VALUE << MEAR_COL_SHIFT)
#define MEAR_BANK_MAX_VALUE 0x3
#define MEAR_BANK_SHIFT 14
#define MEAR_BANK_MASK (MEAR_BANK_MAX_VALUE << MEAR_BANK_SHIFT)
#define MEAR_ROW_MASK 0x00003FFF
/************************************************************
* Memory Error Syndrome Register (MESR)
************************************************************/
#define REG_MESR_OFFSET 0x2470
#define MESR_ECC_SYN_H_MASK 0xFF00
#define MESR_ECC_SYN_L_MASK 0x00FF
/************************************************************
* Memory Mode Control Register (MMCR)
************************************************************/
#define REG_MMCR_OFFSET 0x2500
enum mmcr_bits {
MMCR_REG_DIMM_MODE = CPC925_BIT(3),
};
/*
* HyperTransport Link Registers
*/
/************************************************************
* Error Handling/Enumeration Scratch Pad Register (ERRCTRL)
************************************************************/
#define REG_ERRCTRL_OFFSET 0x70140
enum errctrl_bits { /* nonfatal interrupts for */
ERRCTRL_SERR_NF = CPC925_BIT(0), /* system error */
ERRCTRL_CRC_NF = CPC925_BIT(1), /* CRC error */
ERRCTRL_RSP_NF = CPC925_BIT(2), /* Response error */
ERRCTRL_EOC_NF = CPC925_BIT(3), /* End-Of-Chain error */
ERRCTRL_OVF_NF = CPC925_BIT(4), /* Overflow error */
ERRCTRL_PROT_NF = CPC925_BIT(5), /* Protocol error */
ERRCTRL_RSP_ERR = CPC925_BIT(6), /* Response error received */
ERRCTRL_CHN_FAL = CPC925_BIT(7), /* Sync flooding detected */
HT_ERRCTRL_ENABLE = (ERRCTRL_SERR_NF | ERRCTRL_CRC_NF |
ERRCTRL_RSP_NF | ERRCTRL_EOC_NF |
ERRCTRL_OVF_NF | ERRCTRL_PROT_NF),
HT_ERRCTRL_DETECTED = (ERRCTRL_RSP_ERR | ERRCTRL_CHN_FAL),
};
/************************************************************
* Link Configuration and Link Control Register (LINKCTRL)
************************************************************/
#define REG_LINKCTRL_OFFSET 0x70110
enum linkctrl_bits {
LINKCTRL_CRC_ERR = (CPC925_BIT(22) | CPC925_BIT(23)),
LINKCTRL_LINK_FAIL = CPC925_BIT(27),
HT_LINKCTRL_DETECTED = (LINKCTRL_CRC_ERR | LINKCTRL_LINK_FAIL),
};
/************************************************************
* Link FreqCap/Error/Freq/Revision ID Register (LINKERR)
************************************************************/
#define REG_LINKERR_OFFSET 0x70120
enum linkerr_bits {
LINKERR_EOC_ERR = CPC925_BIT(17), /* End-Of-Chain error */
LINKERR_OVF_ERR = CPC925_BIT(18), /* Receive Buffer Overflow */
LINKERR_PROT_ERR = CPC925_BIT(19), /* Protocol error */
HT_LINKERR_DETECTED = (LINKERR_EOC_ERR | LINKERR_OVF_ERR |
LINKERR_PROT_ERR),
};
/************************************************************
* Bridge Control Register (BRGCTRL)
************************************************************/
#define REG_BRGCTRL_OFFSET 0x70300
enum brgctrl_bits {
BRGCTRL_DETSERR = CPC925_BIT(0), /* SERR on Secondary Bus */
BRGCTRL_SECBUSRESET = CPC925_BIT(9), /* Secondary Bus Reset */
};
/* Private structure for edac memory controller */
struct cpc925_mc_pdata {
void __iomem *vbase;
unsigned long total_mem;
const char *name;
int edac_idx;
};
/* Private structure for common edac device */
struct cpc925_dev_info {
void __iomem *vbase;
struct platform_device *pdev;
char *ctl_name;
int edac_idx;
struct edac_device_ctl_info *edac_dev;
void (*init)(struct cpc925_dev_info *dev_info);
void (*exit)(struct cpc925_dev_info *dev_info);
void (*check)(struct edac_device_ctl_info *edac_dev);
};
/* Get total memory size from Open Firmware DTB */
static void get_total_mem(struct cpc925_mc_pdata *pdata)
{
struct device_node *np = NULL;
const unsigned int *reg, *reg_end;
int len, sw, aw;
unsigned long start, size;
np = of_find_node_by_type(NULL, "memory");
if (!np)
return;
aw = of_n_addr_cells(np);
sw = of_n_size_cells(np);
reg = (const unsigned int *)of_get_property(np, "reg", &len);
reg_end = reg + len/4;
pdata->total_mem = 0;
do {
start = of_read_number(reg, aw);
reg += aw;
size = of_read_number(reg, sw);
reg += sw;
debugf1("%s: start 0x%lx, size 0x%lx\n", __func__,
start, size);
pdata->total_mem += size;
} while (reg < reg_end);
of_node_put(np);
debugf0("%s: total_mem 0x%lx\n", __func__, pdata->total_mem);
}
static void cpc925_init_csrows(struct mem_ctl_info *mci)
{
struct cpc925_mc_pdata *pdata = mci->pvt_info;
struct csrow_info *csrow;
int index;
u32 mbmr, mbbar, bba;
unsigned long row_size, last_nr_pages = 0;
get_total_mem(pdata);
for (index = 0; index < mci->nr_csrows; index++) {
mbmr = __raw_readl(pdata->vbase + REG_MBMR_OFFSET +
0x20 * index);
mbbar = __raw_readl(pdata->vbase + REG_MBBAR_OFFSET +
0x20 + index);
bba = (((mbmr & MBMR_BBA_MASK) >> MBMR_BBA_SHIFT) << 8) |
((mbbar & MBBAR_BBA_MASK) >> MBBAR_BBA_SHIFT);
if (bba == 0)
continue; /* not populated */
csrow = &mci->csrows[index];
row_size = bba * (1UL << 28); /* 256M */
csrow->first_page = last_nr_pages;
csrow->nr_pages = row_size >> PAGE_SHIFT;
csrow->last_page = csrow->first_page + csrow->nr_pages - 1;
last_nr_pages = csrow->last_page + 1;
csrow->mtype = MEM_RDDR;
csrow->edac_mode = EDAC_SECDED;
switch (csrow->nr_channels) {
case 1: /* Single channel */
csrow->grain = 32; /* four-beat burst of 32 bytes */
break;
case 2: /* Dual channel */
default:
csrow->grain = 64; /* four-beat burst of 64 bytes */
break;
}
switch ((mbmr & MBMR_MODE_MASK) >> MBMR_MODE_SHIFT) {
case 6: /* 0110, no way to differentiate X8 VS X16 */
case 5: /* 0101 */
case 8: /* 1000 */
csrow->dtype = DEV_X16;
break;
case 7: /* 0111 */
case 9: /* 1001 */
csrow->dtype = DEV_X8;
break;
default:
csrow->dtype = DEV_UNKNOWN;
break;
}
}
}
/* Enable memory controller ECC detection */
static void cpc925_mc_init(struct mem_ctl_info *mci)
{
struct cpc925_mc_pdata *pdata = mci->pvt_info;
u32 apimask;
u32 mccr;
/* Enable various ECC error exceptions */
apimask = __raw_readl(pdata->vbase + REG_APIMASK_OFFSET);
if ((apimask & ECC_MASK_ENABLE) == 0) {
apimask |= ECC_MASK_ENABLE;
__raw_writel(apimask, pdata->vbase + REG_APIMASK_OFFSET);
}
/* Enable ECC detection */
mccr = __raw_readl(pdata->vbase + REG_MCCR_OFFSET);
if ((mccr & MCCR_ECC_EN) == 0) {
mccr |= MCCR_ECC_EN;
__raw_writel(mccr, pdata->vbase + REG_MCCR_OFFSET);
}
}
/* Disable memory controller ECC detection */
static void cpc925_mc_exit(struct mem_ctl_info *mci)
{
/*
* WARNING:
* We are supposed to clear the ECC error detection bits,
* and it will be no problem to do so. However, once they
* are cleared here if we want to re-install CPC925 EDAC
* module later, setting them up in cpc925_mc_init() will
* trigger machine check exception.
* Also, it's ok to leave ECC error detection bits enabled,
* since they are reset to 1 by default or by boot loader.
*/
return;
}
/*
* Revert DDR column/row/bank addresses into page frame number and
* offset in page.
*
* Suppose memory mode is 0x0111(128-bit mode, identical DIMM pairs),
* physical address(PA) bits to column address(CA) bits mappings are:
* CA 0 1 2 3 4 5 6 7 8 9 10
* PA 59 58 57 56 55 54 53 52 51 50 49
*
* physical address(PA) bits to bank address(BA) bits mappings are:
* BA 0 1
* PA 43 44
*
* physical address(PA) bits to row address(RA) bits mappings are:
* RA 0 1 2 3 4 5 6 7 8 9 10 11 12
* PA 36 35 34 48 47 46 45 40 41 42 39 38 37
*/
static void cpc925_mc_get_pfn(struct mem_ctl_info *mci, u32 mear,
unsigned long *pfn, unsigned long *offset, int *csrow)
{
u32 bcnt, rank, col, bank, row;
u32 c;
unsigned long pa;
int i;
bcnt = (mear & MEAR_BCNT_MASK) >> MEAR_BCNT_SHIFT;
rank = (mear & MEAR_RANK_MASK) >> MEAR_RANK_SHIFT;
col = (mear & MEAR_COL_MASK) >> MEAR_COL_SHIFT;
bank = (mear & MEAR_BANK_MASK) >> MEAR_BANK_SHIFT;
row = mear & MEAR_ROW_MASK;
*csrow = rank;
#ifdef CONFIG_EDAC_DEBUG
if (mci->csrows[rank].first_page == 0) {
cpc925_mc_printk(mci, KERN_ERR, "ECC occurs in a "
"non-populated csrow, broken hardware?\n");
return;
}
#endif
/* Revert csrow number */
pa = mci->csrows[rank].first_page << PAGE_SHIFT;
/* Revert column address */
col += bcnt;
for (i = 0; i < 11; i++) {
c = col & 0x1;
col >>= 1;
pa |= c << (14 - i);
}
/* Revert bank address */
pa |= bank << 19;
/* Revert row address, in 4 steps */
for (i = 0; i < 3; i++) {
c = row & 0x1;
row >>= 1;
pa |= c << (26 - i);
}
for (i = 0; i < 3; i++) {
c = row & 0x1;
row >>= 1;
pa |= c << (21 + i);
}
for (i = 0; i < 4; i++) {
c = row & 0x1;
row >>= 1;
pa |= c << (18 - i);
}
for (i = 0; i < 3; i++) {
c = row & 0x1;
row >>= 1;
pa |= c << (29 - i);
}
*offset = pa & (PAGE_SIZE - 1);
*pfn = pa >> PAGE_SHIFT;
debugf0("%s: ECC physical address 0x%lx\n", __func__, pa);
}
static int cpc925_mc_find_channel(struct mem_ctl_info *mci, u16 syndrome)
{
if ((syndrome & MESR_ECC_SYN_H_MASK) == 0)
return 0;
if ((syndrome & MESR_ECC_SYN_L_MASK) == 0)
return 1;
cpc925_mc_printk(mci, KERN_INFO, "Unexpected syndrome value: 0x%x\n",
syndrome);
return 1;
}
/* Check memory controller registers for ECC errors */
static void cpc925_mc_check(struct mem_ctl_info *mci)
{
struct cpc925_mc_pdata *pdata = mci->pvt_info;
u32 apiexcp;
u32 mear;
u32 mesr;
u16 syndrome;
unsigned long pfn = 0, offset = 0;
int csrow = 0, channel = 0;
/* APIEXCP is cleared when read */
apiexcp = __raw_readl(pdata->vbase + REG_APIEXCP_OFFSET);
if ((apiexcp & ECC_EXCP_DETECTED) == 0)
return;
mesr = __raw_readl(pdata->vbase + REG_MESR_OFFSET);
syndrome = mesr | (MESR_ECC_SYN_H_MASK | MESR_ECC_SYN_L_MASK);
mear = __raw_readl(pdata->vbase + REG_MEAR_OFFSET);
/* Revert column/row addresses into page frame number, etc */
cpc925_mc_get_pfn(mci, mear, &pfn, &offset, &csrow);
if (apiexcp & CECC_EXCP_DETECTED) {
cpc925_mc_printk(mci, KERN_INFO, "DRAM CECC Fault\n");
channel = cpc925_mc_find_channel(mci, syndrome);
edac_mc_handle_ce(mci, pfn, offset, syndrome,
csrow, channel, mci->ctl_name);
}
if (apiexcp & UECC_EXCP_DETECTED) {
cpc925_mc_printk(mci, KERN_INFO, "DRAM UECC Fault\n");
edac_mc_handle_ue(mci, pfn, offset, csrow, mci->ctl_name);
}
cpc925_mc_printk(mci, KERN_INFO, "Dump registers:\n");
cpc925_mc_printk(mci, KERN_INFO, "APIMASK 0x%08x\n",
__raw_readl(pdata->vbase + REG_APIMASK_OFFSET));
cpc925_mc_printk(mci, KERN_INFO, "APIEXCP 0x%08x\n",
apiexcp);
cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Ctrl 0x%08x\n",
__raw_readl(pdata->vbase + REG_MSCR_OFFSET));
cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Rge Start 0x%08x\n",
__raw_readl(pdata->vbase + REG_MSRSR_OFFSET));
cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Rge End 0x%08x\n",
__raw_readl(pdata->vbase + REG_MSRER_OFFSET));
cpc925_mc_printk(mci, KERN_INFO, "Mem Scrub Pattern 0x%08x\n",
__raw_readl(pdata->vbase + REG_MSPR_OFFSET));
cpc925_mc_printk(mci, KERN_INFO, "Mem Chk Ctrl 0x%08x\n",
__raw_readl(pdata->vbase + REG_MCCR_OFFSET));
cpc925_mc_printk(mci, KERN_INFO, "Mem Chk Rge End 0x%08x\n",
__raw_readl(pdata->vbase + REG_MCRER_OFFSET));
cpc925_mc_printk(mci, KERN_INFO, "Mem Err Address 0x%08x\n",
mesr);
cpc925_mc_printk(mci, KERN_INFO, "Mem Err Syndrome 0x%08x\n",
syndrome);
}
/******************** CPU err device********************************/
/* Enable CPU Errors detection */
static void cpc925_cpu_init(struct cpc925_dev_info *dev_info)
{
u32 apimask;
apimask = __raw_readl(dev_info->vbase + REG_APIMASK_OFFSET);
if ((apimask & CPU_MASK_ENABLE) == 0) {
apimask |= CPU_MASK_ENABLE;
__raw_writel(apimask, dev_info->vbase + REG_APIMASK_OFFSET);
}
}
/* Disable CPU Errors detection */
static void cpc925_cpu_exit(struct cpc925_dev_info *dev_info)
{
/*
* WARNING:
* We are supposed to clear the CPU error detection bits,
* and it will be no problem to do so. However, once they
* are cleared here if we want to re-install CPC925 EDAC
* module later, setting them up in cpc925_cpu_init() will
* trigger machine check exception.
* Also, it's ok to leave CPU error detection bits enabled,
* since they are reset to 1 by default.
*/
return;
}
/* Check for CPU Errors */
static void cpc925_cpu_check(struct edac_device_ctl_info *edac_dev)
{
struct cpc925_dev_info *dev_info = edac_dev->pvt_info;
u32 apiexcp;
u32 apimask;
/* APIEXCP is cleared when read */
apiexcp = __raw_readl(dev_info->vbase + REG_APIEXCP_OFFSET);
if ((apiexcp & CPU_EXCP_DETECTED) == 0)
return;
apimask = __raw_readl(dev_info->vbase + REG_APIMASK_OFFSET);
cpc925_printk(KERN_INFO, "Processor Interface Fault\n"
"Processor Interface register dump:\n");
cpc925_printk(KERN_INFO, "APIMASK 0x%08x\n", apimask);
cpc925_printk(KERN_INFO, "APIEXCP 0x%08x\n", apiexcp);
edac_device_handle_ue(edac_dev, 0, 0, edac_dev->ctl_name);
}
/******************** HT Link err device****************************/
/* Enable HyperTransport Link Error detection */
static void cpc925_htlink_init(struct cpc925_dev_info *dev_info)
{
u32 ht_errctrl;
ht_errctrl = __raw_readl(dev_info->vbase + REG_ERRCTRL_OFFSET);
if ((ht_errctrl & HT_ERRCTRL_ENABLE) == 0) {
ht_errctrl |= HT_ERRCTRL_ENABLE;
__raw_writel(ht_errctrl, dev_info->vbase + REG_ERRCTRL_OFFSET);
}
}
/* Disable HyperTransport Link Error detection */
static void cpc925_htlink_exit(struct cpc925_dev_info *dev_info)
{
u32 ht_errctrl;
ht_errctrl = __raw_readl(dev_info->vbase + REG_ERRCTRL_OFFSET);
ht_errctrl &= ~HT_ERRCTRL_ENABLE;
__raw_writel(ht_errctrl, dev_info->vbase + REG_ERRCTRL_OFFSET);
}
/* Check for HyperTransport Link errors */
static void cpc925_htlink_check(struct edac_device_ctl_info *edac_dev)
{
struct cpc925_dev_info *dev_info = edac_dev->pvt_info;
u32 brgctrl = __raw_readl(dev_info->vbase + REG_BRGCTRL_OFFSET);
u32 linkctrl = __raw_readl(dev_info->vbase + REG_LINKCTRL_OFFSET);
u32 errctrl = __raw_readl(dev_info->vbase + REG_ERRCTRL_OFFSET);
u32 linkerr = __raw_readl(dev_info->vbase + REG_LINKERR_OFFSET);
if (!((brgctrl & BRGCTRL_DETSERR) ||
(linkctrl & HT_LINKCTRL_DETECTED) ||
(errctrl & HT_ERRCTRL_DETECTED) ||
(linkerr & HT_LINKERR_DETECTED)))
return;
cpc925_printk(KERN_INFO, "HT Link Fault\n"
"HT register dump:\n");
cpc925_printk(KERN_INFO, "Bridge Ctrl 0x%08x\n",
brgctrl);
cpc925_printk(KERN_INFO, "Link Config Ctrl 0x%08x\n",
linkctrl);
cpc925_printk(KERN_INFO, "Error Enum and Ctrl 0x%08x\n",
errctrl);
cpc925_printk(KERN_INFO, "Link Error 0x%08x\n",
linkerr);
/* Clear by write 1 */
if (brgctrl & BRGCTRL_DETSERR)
__raw_writel(BRGCTRL_DETSERR,
dev_info->vbase + REG_BRGCTRL_OFFSET);
if (linkctrl & HT_LINKCTRL_DETECTED)
__raw_writel(HT_LINKCTRL_DETECTED,
dev_info->vbase + REG_LINKCTRL_OFFSET);
/* Initiate Secondary Bus Reset to clear the chain failure */
if (errctrl & ERRCTRL_CHN_FAL)
__raw_writel(BRGCTRL_SECBUSRESET,
dev_info->vbase + REG_BRGCTRL_OFFSET);
if (errctrl & ERRCTRL_RSP_ERR)
__raw_writel(ERRCTRL_RSP_ERR,
dev_info->vbase + REG_ERRCTRL_OFFSET);
if (linkerr & HT_LINKERR_DETECTED)
__raw_writel(HT_LINKERR_DETECTED,
dev_info->vbase + REG_LINKERR_OFFSET);
edac_device_handle_ce(edac_dev, 0, 0, edac_dev->ctl_name);
}
static struct cpc925_dev_info cpc925_devs[] = {
{
.ctl_name = CPC925_CPU_ERR_DEV,
.init = cpc925_cpu_init,
.exit = cpc925_cpu_exit,
.check = cpc925_cpu_check,
},
{
.ctl_name = CPC925_HT_LINK_DEV,
.init = cpc925_htlink_init,
.exit = cpc925_htlink_exit,
.check = cpc925_htlink_check,
},
{0}, /* Terminated by NULL */
};
/*
* Add CPU Err detection and HyperTransport Link Err detection
* as common "edac_device", they have no corresponding device
* nodes in the Open Firmware DTB and we have to add platform
* devices for them. Also, they will share the MMIO with that
* of memory controller.
*/
static void cpc925_add_edac_devices(void __iomem *vbase)
{
struct cpc925_dev_info *dev_info;
if (!vbase) {
cpc925_printk(KERN_ERR, "MMIO not established yet\n");
return;
}
for (dev_info = &cpc925_devs[0]; dev_info->init; dev_info++) {
dev_info->vbase = vbase;
dev_info->pdev = platform_device_register_simple(
dev_info->ctl_name, 0, NULL, 0);
if (IS_ERR(dev_info->pdev)) {
cpc925_printk(KERN_ERR,
"Can't register platform device for %s\n",
dev_info->ctl_name);
continue;
}
/*
* Don't have to allocate private structure but
* make use of cpc925_devs[] instead.
*/
dev_info->edac_idx = edac_device_alloc_index();
dev_info->edac_dev =
edac_device_alloc_ctl_info(0, dev_info->ctl_name,
1, NULL, 0, 0, NULL, 0, dev_info->edac_idx);
if (!dev_info->edac_dev) {
cpc925_printk(KERN_ERR, "No memory for edac device\n");
goto err1;
}
dev_info->edac_dev->pvt_info = dev_info;
dev_info->edac_dev->dev = &dev_info->pdev->dev;
dev_info->edac_dev->ctl_name = dev_info->ctl_name;
dev_info->edac_dev->mod_name = CPC925_EDAC_MOD_STR;
dev_info->edac_dev->dev_name = dev_name(&dev_info->pdev->dev);
if (edac_op_state == EDAC_OPSTATE_POLL)
dev_info->edac_dev->edac_check = dev_info->check;
if (dev_info->init)
dev_info->init(dev_info);
if (edac_device_add_device(dev_info->edac_dev) > 0) {
cpc925_printk(KERN_ERR,
"Unable to add edac device for %s\n",
dev_info->ctl_name);
goto err2;
}
debugf0("%s: Successfully added edac device for %s\n",
__func__, dev_info->ctl_name);
continue;
err2:
if (dev_info->exit)
dev_info->exit(dev_info);
edac_device_free_ctl_info(dev_info->edac_dev);
err1:
platform_device_unregister(dev_info->pdev);
}
}
/*
* Delete the common "edac_device" for CPU Err Detection
* and HyperTransport Link Err Detection
*/
static void cpc925_del_edac_devices(void)
{
struct cpc925_dev_info *dev_info;
for (dev_info = &cpc925_devs[0]; dev_info->init; dev_info++) {
if (dev_info->edac_dev) {
edac_device_del_device(dev_info->edac_dev->dev);
edac_device_free_ctl_info(dev_info->edac_dev);
platform_device_unregister(dev_info->pdev);
}
if (dev_info->exit)
dev_info->exit(dev_info);
debugf0("%s: Successfully deleted edac device for %s\n",
__func__, dev_info->ctl_name);
}
}
/* Convert current back-ground scrub rate into byte/sec bandwidth */
static int cpc925_get_sdram_scrub_rate(struct mem_ctl_info *mci)
{
struct cpc925_mc_pdata *pdata = mci->pvt_info;
int bw;
u32 mscr;
u8 si;
mscr = __raw_readl(pdata->vbase + REG_MSCR_OFFSET);
si = (mscr & MSCR_SI_MASK) >> MSCR_SI_SHIFT;
debugf0("%s, Mem Scrub Ctrl Register 0x%x\n", __func__, mscr);
if (((mscr & MSCR_SCRUB_MOD_MASK) != MSCR_BACKGR_SCRUB) ||
(si == 0)) {
cpc925_mc_printk(mci, KERN_INFO, "Scrub mode not enabled\n");
bw = 0;
} else
bw = CPC925_SCRUB_BLOCK_SIZE * 0xFA67 / si;
return bw;
}
/* Return 0 for single channel; 1 for dual channel */
static int cpc925_mc_get_channels(void __iomem *vbase)
{
int dual = 0;
u32 mbcr;
mbcr = __raw_readl(vbase + REG_MBCR_OFFSET);
/*
* Dual channel only when 128-bit wide physical bus
* and 128-bit configuration.
*/
if (((mbcr & MBCR_64BITCFG_MASK) == 0) &&
((mbcr & MBCR_64BITBUS_MASK) == 0))
dual = 1;
debugf0("%s: %s channel\n", __func__,
(dual > 0) ? "Dual" : "Single");
return dual;
}
static int __devinit cpc925_probe(struct platform_device *pdev)
{
static int edac_mc_idx;
struct mem_ctl_info *mci;
void __iomem *vbase;
struct cpc925_mc_pdata *pdata;
struct resource *r;
int res = 0, nr_channels;
debugf0("%s: %s platform device found!\n", __func__, pdev->name);
if (!devres_open_group(&pdev->dev, cpc925_probe, GFP_KERNEL)) {
res = -ENOMEM;
goto out;
}
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r) {
cpc925_printk(KERN_ERR, "Unable to get resource\n");
res = -ENOENT;
goto err1;
}
if (!devm_request_mem_region(&pdev->dev,
r->start,
resource_size(r),
pdev->name)) {
cpc925_printk(KERN_ERR, "Unable to request mem region\n");
res = -EBUSY;
goto err1;
}
vbase = devm_ioremap(&pdev->dev, r->start, resource_size(r));
if (!vbase) {
cpc925_printk(KERN_ERR, "Unable to ioremap device\n");
res = -ENOMEM;
goto err2;
}
nr_channels = cpc925_mc_get_channels(vbase);
mci = edac_mc_alloc(sizeof(struct cpc925_mc_pdata),
CPC925_NR_CSROWS, nr_channels + 1, edac_mc_idx);
if (!mci) {
cpc925_printk(KERN_ERR, "No memory for mem_ctl_info\n");
res = -ENOMEM;
goto err2;
}
pdata = mci->pvt_info;
pdata->vbase = vbase;
pdata->edac_idx = edac_mc_idx++;
pdata->name = pdev->name;
mci->dev = &pdev->dev;
platform_set_drvdata(pdev, mci);
mci->dev_name = dev_name(&pdev->dev);
mci->mtype_cap = MEM_FLAG_RDDR | MEM_FLAG_DDR;
mci->edac_ctl_cap = EDAC_FLAG_NONE | EDAC_FLAG_SECDED;
mci->edac_cap = EDAC_FLAG_SECDED;
mci->mod_name = CPC925_EDAC_MOD_STR;
mci->mod_ver = CPC925_EDAC_REVISION;
mci->ctl_name = pdev->name;
if (edac_op_state == EDAC_OPSTATE_POLL)
mci->edac_check = cpc925_mc_check;
mci->ctl_page_to_phys = NULL;
mci->scrub_mode = SCRUB_SW_SRC;
mci->set_sdram_scrub_rate = NULL;
mci->get_sdram_scrub_rate = cpc925_get_sdram_scrub_rate;
cpc925_init_csrows(mci);
/* Setup memory controller registers */
cpc925_mc_init(mci);
if (edac_mc_add_mc(mci) > 0) {
cpc925_mc_printk(mci, KERN_ERR, "Failed edac_mc_add_mc()\n");
goto err3;
}
cpc925_add_edac_devices(vbase);
/* get this far and it's successful */
debugf0("%s: success\n", __func__);
res = 0;
goto out;
err3:
cpc925_mc_exit(mci);
edac_mc_free(mci);
err2:
devm_release_mem_region(&pdev->dev, r->start, resource_size(r));
err1:
devres_release_group(&pdev->dev, cpc925_probe);
out:
return res;
}
static int cpc925_remove(struct platform_device *pdev)
{
struct mem_ctl_info *mci = platform_get_drvdata(pdev);
/*
* Delete common edac devices before edac mc, because
* the former share the MMIO of the latter.
*/
cpc925_del_edac_devices();
cpc925_mc_exit(mci);
edac_mc_del_mc(&pdev->dev);
edac_mc_free(mci);
return 0;
}
static struct platform_driver cpc925_edac_driver = {
.probe = cpc925_probe,
.remove = cpc925_remove,
.driver = {
.name = "cpc925_edac",
}
};
static int __init cpc925_edac_init(void)
{
int ret = 0;
printk(KERN_INFO "IBM CPC925 EDAC driver " CPC925_EDAC_REVISION "\n");
printk(KERN_INFO "\t(c) 2008 Wind River Systems, Inc\n");
/* Only support POLL mode so far */
edac_op_state = EDAC_OPSTATE_POLL;
ret = platform_driver_register(&cpc925_edac_driver);
if (ret) {
printk(KERN_WARNING "Failed to register %s\n",
CPC925_EDAC_MOD_STR);
}
return ret;
}
static void __exit cpc925_edac_exit(void)
{
platform_driver_unregister(&cpc925_edac_driver);
}
module_init(cpc925_edac_init);
module_exit(cpc925_edac_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Cao Qingtao <qingtao.cao@windriver.com>");
MODULE_DESCRIPTION("IBM CPC925 Bridge and MC EDAC kernel module");
| gpl-2.0 |
blazingwolf/HTC_Fireball_Kernel | drivers/mtd/nand/s3c2410.c | 2779 | 29706 | /* linux/drivers/mtd/nand/s3c2410.c
*
* Copyright © 2004-2008 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* Samsung S3C2410/S3C2440/S3C2412 NAND driver
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef CONFIG_MTD_NAND_S3C2410_DEBUG
#define DEBUG
#endif
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/cpufreq.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <asm/io.h>
#include <plat/regs-nand.h>
#include <plat/nand.h>
#ifdef CONFIG_MTD_NAND_S3C2410_HWECC
static int hardware_ecc = 1;
#else
static int hardware_ecc = 0;
#endif
#ifdef CONFIG_MTD_NAND_S3C2410_CLKSTOP
static const int clock_stop = 1;
#else
static const int clock_stop = 0;
#endif
/* new oob placement block for use with hardware ecc generation
*/
static struct nand_ecclayout nand_hw_eccoob = {
.eccbytes = 3,
.eccpos = {0, 1, 2},
.oobfree = {{8, 8}}
};
/* controller and mtd information */
struct s3c2410_nand_info;
/**
* struct s3c2410_nand_mtd - driver MTD structure
* @mtd: The MTD instance to pass to the MTD layer.
* @chip: The NAND chip information.
* @set: The platform information supplied for this set of NAND chips.
* @info: Link back to the hardware information.
* @scan_res: The result from calling nand_scan_ident().
*/
struct s3c2410_nand_mtd {
struct mtd_info mtd;
struct nand_chip chip;
struct s3c2410_nand_set *set;
struct s3c2410_nand_info *info;
int scan_res;
};
enum s3c_cpu_type {
TYPE_S3C2410,
TYPE_S3C2412,
TYPE_S3C2440,
};
enum s3c_nand_clk_state {
CLOCK_DISABLE = 0,
CLOCK_ENABLE,
CLOCK_SUSPEND,
};
/* overview of the s3c2410 nand state */
/**
* struct s3c2410_nand_info - NAND controller state.
* @mtds: An array of MTD instances on this controoler.
* @platform: The platform data for this board.
* @device: The platform device we bound to.
* @area: The IO area resource that came from request_mem_region().
* @clk: The clock resource for this controller.
* @regs: The area mapped for the hardware registers described by @area.
* @sel_reg: Pointer to the register controlling the NAND selection.
* @sel_bit: The bit in @sel_reg to select the NAND chip.
* @mtd_count: The number of MTDs created from this controller.
* @save_sel: The contents of @sel_reg to be saved over suspend.
* @clk_rate: The clock rate from @clk.
* @clk_state: The current clock state.
* @cpu_type: The exact type of this controller.
*/
struct s3c2410_nand_info {
/* mtd info */
struct nand_hw_control controller;
struct s3c2410_nand_mtd *mtds;
struct s3c2410_platform_nand *platform;
/* device info */
struct device *device;
struct resource *area;
struct clk *clk;
void __iomem *regs;
void __iomem *sel_reg;
int sel_bit;
int mtd_count;
unsigned long save_sel;
unsigned long clk_rate;
enum s3c_nand_clk_state clk_state;
enum s3c_cpu_type cpu_type;
#ifdef CONFIG_CPU_FREQ
struct notifier_block freq_transition;
#endif
};
/* conversion functions */
static struct s3c2410_nand_mtd *s3c2410_nand_mtd_toours(struct mtd_info *mtd)
{
return container_of(mtd, struct s3c2410_nand_mtd, mtd);
}
static struct s3c2410_nand_info *s3c2410_nand_mtd_toinfo(struct mtd_info *mtd)
{
return s3c2410_nand_mtd_toours(mtd)->info;
}
static struct s3c2410_nand_info *to_nand_info(struct platform_device *dev)
{
return platform_get_drvdata(dev);
}
static struct s3c2410_platform_nand *to_nand_plat(struct platform_device *dev)
{
return dev->dev.platform_data;
}
static inline int allow_clk_suspend(struct s3c2410_nand_info *info)
{
return clock_stop;
}
/**
* s3c2410_nand_clk_set_state - Enable, disable or suspend NAND clock.
* @info: The controller instance.
* @new_state: State to which clock should be set.
*/
static void s3c2410_nand_clk_set_state(struct s3c2410_nand_info *info,
enum s3c_nand_clk_state new_state)
{
if (!allow_clk_suspend(info) && new_state == CLOCK_SUSPEND)
return;
if (info->clk_state == CLOCK_ENABLE) {
if (new_state != CLOCK_ENABLE)
clk_disable(info->clk);
} else {
if (new_state == CLOCK_ENABLE)
clk_enable(info->clk);
}
info->clk_state = new_state;
}
/* timing calculations */
#define NS_IN_KHZ 1000000
/**
* s3c_nand_calc_rate - calculate timing data.
* @wanted: The cycle time in nanoseconds.
* @clk: The clock rate in kHz.
* @max: The maximum divider value.
*
* Calculate the timing value from the given parameters.
*/
static int s3c_nand_calc_rate(int wanted, unsigned long clk, int max)
{
int result;
result = DIV_ROUND_UP((wanted * clk), NS_IN_KHZ);
pr_debug("result %d from %ld, %d\n", result, clk, wanted);
if (result > max) {
printk("%d ns is too big for current clock rate %ld\n", wanted, clk);
return -1;
}
if (result < 1)
result = 1;
return result;
}
#define to_ns(ticks,clk) (((ticks) * NS_IN_KHZ) / (unsigned int)(clk))
/* controller setup */
/**
* s3c2410_nand_setrate - setup controller timing information.
* @info: The controller instance.
*
* Given the information supplied by the platform, calculate and set
* the necessary timing registers in the hardware to generate the
* necessary timing cycles to the hardware.
*/
static int s3c2410_nand_setrate(struct s3c2410_nand_info *info)
{
struct s3c2410_platform_nand *plat = info->platform;
int tacls_max = (info->cpu_type == TYPE_S3C2412) ? 8 : 4;
int tacls, twrph0, twrph1;
unsigned long clkrate = clk_get_rate(info->clk);
unsigned long uninitialized_var(set), cfg, uninitialized_var(mask);
unsigned long flags;
/* calculate the timing information for the controller */
info->clk_rate = clkrate;
clkrate /= 1000; /* turn clock into kHz for ease of use */
if (plat != NULL) {
tacls = s3c_nand_calc_rate(plat->tacls, clkrate, tacls_max);
twrph0 = s3c_nand_calc_rate(plat->twrph0, clkrate, 8);
twrph1 = s3c_nand_calc_rate(plat->twrph1, clkrate, 8);
} else {
/* default timings */
tacls = tacls_max;
twrph0 = 8;
twrph1 = 8;
}
if (tacls < 0 || twrph0 < 0 || twrph1 < 0) {
dev_err(info->device, "cannot get suitable timings\n");
return -EINVAL;
}
dev_info(info->device, "Tacls=%d, %dns Twrph0=%d %dns, Twrph1=%d %dns\n",
tacls, to_ns(tacls, clkrate), twrph0, to_ns(twrph0, clkrate), twrph1, to_ns(twrph1, clkrate));
switch (info->cpu_type) {
case TYPE_S3C2410:
mask = (S3C2410_NFCONF_TACLS(3) |
S3C2410_NFCONF_TWRPH0(7) |
S3C2410_NFCONF_TWRPH1(7));
set = S3C2410_NFCONF_EN;
set |= S3C2410_NFCONF_TACLS(tacls - 1);
set |= S3C2410_NFCONF_TWRPH0(twrph0 - 1);
set |= S3C2410_NFCONF_TWRPH1(twrph1 - 1);
break;
case TYPE_S3C2440:
case TYPE_S3C2412:
mask = (S3C2440_NFCONF_TACLS(tacls_max - 1) |
S3C2440_NFCONF_TWRPH0(7) |
S3C2440_NFCONF_TWRPH1(7));
set = S3C2440_NFCONF_TACLS(tacls - 1);
set |= S3C2440_NFCONF_TWRPH0(twrph0 - 1);
set |= S3C2440_NFCONF_TWRPH1(twrph1 - 1);
break;
default:
BUG();
}
local_irq_save(flags);
cfg = readl(info->regs + S3C2410_NFCONF);
cfg &= ~mask;
cfg |= set;
writel(cfg, info->regs + S3C2410_NFCONF);
local_irq_restore(flags);
dev_dbg(info->device, "NF_CONF is 0x%lx\n", cfg);
return 0;
}
/**
* s3c2410_nand_inithw - basic hardware initialisation
* @info: The hardware state.
*
* Do the basic initialisation of the hardware, using s3c2410_nand_setrate()
* to setup the hardware access speeds and set the controller to be enabled.
*/
static int s3c2410_nand_inithw(struct s3c2410_nand_info *info)
{
int ret;
ret = s3c2410_nand_setrate(info);
if (ret < 0)
return ret;
switch (info->cpu_type) {
case TYPE_S3C2410:
default:
break;
case TYPE_S3C2440:
case TYPE_S3C2412:
/* enable the controller and de-assert nFCE */
writel(S3C2440_NFCONT_ENABLE, info->regs + S3C2440_NFCONT);
}
return 0;
}
/**
* s3c2410_nand_select_chip - select the given nand chip
* @mtd: The MTD instance for this chip.
* @chip: The chip number.
*
* This is called by the MTD layer to either select a given chip for the
* @mtd instance, or to indicate that the access has finished and the
* chip can be de-selected.
*
* The routine ensures that the nFCE line is correctly setup, and any
* platform specific selection code is called to route nFCE to the specific
* chip.
*/
static void s3c2410_nand_select_chip(struct mtd_info *mtd, int chip)
{
struct s3c2410_nand_info *info;
struct s3c2410_nand_mtd *nmtd;
struct nand_chip *this = mtd->priv;
unsigned long cur;
nmtd = this->priv;
info = nmtd->info;
if (chip != -1)
s3c2410_nand_clk_set_state(info, CLOCK_ENABLE);
cur = readl(info->sel_reg);
if (chip == -1) {
cur |= info->sel_bit;
} else {
if (nmtd->set != NULL && chip > nmtd->set->nr_chips) {
dev_err(info->device, "invalid chip %d\n", chip);
return;
}
if (info->platform != NULL) {
if (info->platform->select_chip != NULL)
(info->platform->select_chip) (nmtd->set, chip);
}
cur &= ~info->sel_bit;
}
writel(cur, info->sel_reg);
if (chip == -1)
s3c2410_nand_clk_set_state(info, CLOCK_SUSPEND);
}
/* s3c2410_nand_hwcontrol
*
* Issue command and address cycles to the chip
*/
static void s3c2410_nand_hwcontrol(struct mtd_info *mtd, int cmd,
unsigned int ctrl)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
if (cmd == NAND_CMD_NONE)
return;
if (ctrl & NAND_CLE)
writeb(cmd, info->regs + S3C2410_NFCMD);
else
writeb(cmd, info->regs + S3C2410_NFADDR);
}
/* command and control functions */
static void s3c2440_nand_hwcontrol(struct mtd_info *mtd, int cmd,
unsigned int ctrl)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
if (cmd == NAND_CMD_NONE)
return;
if (ctrl & NAND_CLE)
writeb(cmd, info->regs + S3C2440_NFCMD);
else
writeb(cmd, info->regs + S3C2440_NFADDR);
}
/* s3c2410_nand_devready()
*
* returns 0 if the nand is busy, 1 if it is ready
*/
static int s3c2410_nand_devready(struct mtd_info *mtd)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
return readb(info->regs + S3C2410_NFSTAT) & S3C2410_NFSTAT_BUSY;
}
static int s3c2440_nand_devready(struct mtd_info *mtd)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
return readb(info->regs + S3C2440_NFSTAT) & S3C2440_NFSTAT_READY;
}
static int s3c2412_nand_devready(struct mtd_info *mtd)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
return readb(info->regs + S3C2412_NFSTAT) & S3C2412_NFSTAT_READY;
}
/* ECC handling functions */
static int s3c2410_nand_correct_data(struct mtd_info *mtd, u_char *dat,
u_char *read_ecc, u_char *calc_ecc)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned int diff0, diff1, diff2;
unsigned int bit, byte;
pr_debug("%s(%p,%p,%p,%p)\n", __func__, mtd, dat, read_ecc, calc_ecc);
diff0 = read_ecc[0] ^ calc_ecc[0];
diff1 = read_ecc[1] ^ calc_ecc[1];
diff2 = read_ecc[2] ^ calc_ecc[2];
pr_debug("%s: rd %02x%02x%02x calc %02x%02x%02x diff %02x%02x%02x\n",
__func__,
read_ecc[0], read_ecc[1], read_ecc[2],
calc_ecc[0], calc_ecc[1], calc_ecc[2],
diff0, diff1, diff2);
if (diff0 == 0 && diff1 == 0 && diff2 == 0)
return 0; /* ECC is ok */
/* sometimes people do not think about using the ECC, so check
* to see if we have an 0xff,0xff,0xff read ECC and then ignore
* the error, on the assumption that this is an un-eccd page.
*/
if (read_ecc[0] == 0xff && read_ecc[1] == 0xff && read_ecc[2] == 0xff
&& info->platform->ignore_unset_ecc)
return 0;
/* Can we correct this ECC (ie, one row and column change).
* Note, this is similar to the 256 error code on smartmedia */
if (((diff0 ^ (diff0 >> 1)) & 0x55) == 0x55 &&
((diff1 ^ (diff1 >> 1)) & 0x55) == 0x55 &&
((diff2 ^ (diff2 >> 1)) & 0x55) == 0x55) {
/* calculate the bit position of the error */
bit = ((diff2 >> 3) & 1) |
((diff2 >> 4) & 2) |
((diff2 >> 5) & 4);
/* calculate the byte position of the error */
byte = ((diff2 << 7) & 0x100) |
((diff1 << 0) & 0x80) |
((diff1 << 1) & 0x40) |
((diff1 << 2) & 0x20) |
((diff1 << 3) & 0x10) |
((diff0 >> 4) & 0x08) |
((diff0 >> 3) & 0x04) |
((diff0 >> 2) & 0x02) |
((diff0 >> 1) & 0x01);
dev_dbg(info->device, "correcting error bit %d, byte %d\n",
bit, byte);
dat[byte] ^= (1 << bit);
return 1;
}
/* if there is only one bit difference in the ECC, then
* one of only a row or column parity has changed, which
* means the error is most probably in the ECC itself */
diff0 |= (diff1 << 8);
diff0 |= (diff2 << 16);
if ((diff0 & ~(1<<fls(diff0))) == 0)
return 1;
return -1;
}
/* ECC functions
*
* These allow the s3c2410 and s3c2440 to use the controller's ECC
* generator block to ECC the data as it passes through]
*/
static void s3c2410_nand_enable_hwecc(struct mtd_info *mtd, int mode)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ctrl;
ctrl = readl(info->regs + S3C2410_NFCONF);
ctrl |= S3C2410_NFCONF_INITECC;
writel(ctrl, info->regs + S3C2410_NFCONF);
}
static void s3c2412_nand_enable_hwecc(struct mtd_info *mtd, int mode)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ctrl;
ctrl = readl(info->regs + S3C2440_NFCONT);
writel(ctrl | S3C2412_NFCONT_INIT_MAIN_ECC, info->regs + S3C2440_NFCONT);
}
static void s3c2440_nand_enable_hwecc(struct mtd_info *mtd, int mode)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ctrl;
ctrl = readl(info->regs + S3C2440_NFCONT);
writel(ctrl | S3C2440_NFCONT_INITECC, info->regs + S3C2440_NFCONT);
}
static int s3c2410_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
ecc_code[0] = readb(info->regs + S3C2410_NFECC + 0);
ecc_code[1] = readb(info->regs + S3C2410_NFECC + 1);
ecc_code[2] = readb(info->regs + S3C2410_NFECC + 2);
pr_debug("%s: returning ecc %02x%02x%02x\n", __func__,
ecc_code[0], ecc_code[1], ecc_code[2]);
return 0;
}
static int s3c2412_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ecc = readl(info->regs + S3C2412_NFMECC0);
ecc_code[0] = ecc;
ecc_code[1] = ecc >> 8;
ecc_code[2] = ecc >> 16;
pr_debug("calculate_ecc: returning ecc %02x,%02x,%02x\n", ecc_code[0], ecc_code[1], ecc_code[2]);
return 0;
}
static int s3c2440_nand_calculate_ecc(struct mtd_info *mtd, const u_char *dat, u_char *ecc_code)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
unsigned long ecc = readl(info->regs + S3C2440_NFMECC0);
ecc_code[0] = ecc;
ecc_code[1] = ecc >> 8;
ecc_code[2] = ecc >> 16;
pr_debug("%s: returning ecc %06lx\n", __func__, ecc & 0xffffff);
return 0;
}
/* over-ride the standard functions for a little more speed. We can
* use read/write block to move the data buffers to/from the controller
*/
static void s3c2410_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
readsb(this->IO_ADDR_R, buf, len);
}
static void s3c2440_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
readsl(info->regs + S3C2440_NFDATA, buf, len >> 2);
/* cleanup if we've got less than a word to do */
if (len & 3) {
buf += len & ~3;
for (; len & 3; len--)
*buf++ = readb(info->regs + S3C2440_NFDATA);
}
}
static void s3c2410_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
struct nand_chip *this = mtd->priv;
writesb(this->IO_ADDR_W, buf, len);
}
static void s3c2440_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
{
struct s3c2410_nand_info *info = s3c2410_nand_mtd_toinfo(mtd);
writesl(info->regs + S3C2440_NFDATA, buf, len >> 2);
/* cleanup any fractional write */
if (len & 3) {
buf += len & ~3;
for (; len & 3; len--, buf++)
writeb(*buf, info->regs + S3C2440_NFDATA);
}
}
/* cpufreq driver support */
#ifdef CONFIG_CPU_FREQ
static int s3c2410_nand_cpufreq_transition(struct notifier_block *nb,
unsigned long val, void *data)
{
struct s3c2410_nand_info *info;
unsigned long newclk;
info = container_of(nb, struct s3c2410_nand_info, freq_transition);
newclk = clk_get_rate(info->clk);
if ((val == CPUFREQ_POSTCHANGE && newclk < info->clk_rate) ||
(val == CPUFREQ_PRECHANGE && newclk > info->clk_rate)) {
s3c2410_nand_setrate(info);
}
return 0;
}
static inline int s3c2410_nand_cpufreq_register(struct s3c2410_nand_info *info)
{
info->freq_transition.notifier_call = s3c2410_nand_cpufreq_transition;
return cpufreq_register_notifier(&info->freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
}
static inline void s3c2410_nand_cpufreq_deregister(struct s3c2410_nand_info *info)
{
cpufreq_unregister_notifier(&info->freq_transition,
CPUFREQ_TRANSITION_NOTIFIER);
}
#else
static inline int s3c2410_nand_cpufreq_register(struct s3c2410_nand_info *info)
{
return 0;
}
static inline void s3c2410_nand_cpufreq_deregister(struct s3c2410_nand_info *info)
{
}
#endif
/* device management functions */
static int s3c24xx_nand_remove(struct platform_device *pdev)
{
struct s3c2410_nand_info *info = to_nand_info(pdev);
platform_set_drvdata(pdev, NULL);
if (info == NULL)
return 0;
s3c2410_nand_cpufreq_deregister(info);
/* Release all our mtds and their partitions, then go through
* freeing the resources used
*/
if (info->mtds != NULL) {
struct s3c2410_nand_mtd *ptr = info->mtds;
int mtdno;
for (mtdno = 0; mtdno < info->mtd_count; mtdno++, ptr++) {
pr_debug("releasing mtd %d (%p)\n", mtdno, ptr);
nand_release(&ptr->mtd);
}
kfree(info->mtds);
}
/* free the common resources */
if (info->clk != NULL && !IS_ERR(info->clk)) {
s3c2410_nand_clk_set_state(info, CLOCK_DISABLE);
clk_put(info->clk);
}
if (info->regs != NULL) {
iounmap(info->regs);
info->regs = NULL;
}
if (info->area != NULL) {
release_resource(info->area);
kfree(info->area);
info->area = NULL;
}
kfree(info);
return 0;
}
const char *part_probes[] = { "cmdlinepart", NULL };
static int s3c2410_nand_add_partition(struct s3c2410_nand_info *info,
struct s3c2410_nand_mtd *mtd,
struct s3c2410_nand_set *set)
{
struct mtd_partition *part_info;
int nr_part = 0;
if (set == NULL)
return mtd_device_register(&mtd->mtd, NULL, 0);
mtd->mtd.name = set->name;
nr_part = parse_mtd_partitions(&mtd->mtd, part_probes, &part_info, 0);
if (nr_part <= 0 && set->nr_partitions > 0) {
nr_part = set->nr_partitions;
part_info = set->partitions;
}
return mtd_device_register(&mtd->mtd, part_info, nr_part);
}
/**
* s3c2410_nand_init_chip - initialise a single instance of an chip
* @info: The base NAND controller the chip is on.
* @nmtd: The new controller MTD instance to fill in.
* @set: The information passed from the board specific platform data.
*
* Initialise the given @nmtd from the information in @info and @set. This
* readies the structure for use with the MTD layer functions by ensuring
* all pointers are setup and the necessary control routines selected.
*/
static void s3c2410_nand_init_chip(struct s3c2410_nand_info *info,
struct s3c2410_nand_mtd *nmtd,
struct s3c2410_nand_set *set)
{
struct nand_chip *chip = &nmtd->chip;
void __iomem *regs = info->regs;
chip->write_buf = s3c2410_nand_write_buf;
chip->read_buf = s3c2410_nand_read_buf;
chip->select_chip = s3c2410_nand_select_chip;
chip->chip_delay = 50;
chip->priv = nmtd;
chip->options = set->options;
chip->controller = &info->controller;
switch (info->cpu_type) {
case TYPE_S3C2410:
chip->IO_ADDR_W = regs + S3C2410_NFDATA;
info->sel_reg = regs + S3C2410_NFCONF;
info->sel_bit = S3C2410_NFCONF_nFCE;
chip->cmd_ctrl = s3c2410_nand_hwcontrol;
chip->dev_ready = s3c2410_nand_devready;
break;
case TYPE_S3C2440:
chip->IO_ADDR_W = regs + S3C2440_NFDATA;
info->sel_reg = regs + S3C2440_NFCONT;
info->sel_bit = S3C2440_NFCONT_nFCE;
chip->cmd_ctrl = s3c2440_nand_hwcontrol;
chip->dev_ready = s3c2440_nand_devready;
chip->read_buf = s3c2440_nand_read_buf;
chip->write_buf = s3c2440_nand_write_buf;
break;
case TYPE_S3C2412:
chip->IO_ADDR_W = regs + S3C2440_NFDATA;
info->sel_reg = regs + S3C2440_NFCONT;
info->sel_bit = S3C2412_NFCONT_nFCE0;
chip->cmd_ctrl = s3c2440_nand_hwcontrol;
chip->dev_ready = s3c2412_nand_devready;
if (readl(regs + S3C2410_NFCONF) & S3C2412_NFCONF_NANDBOOT)
dev_info(info->device, "System booted from NAND\n");
break;
}
chip->IO_ADDR_R = chip->IO_ADDR_W;
nmtd->info = info;
nmtd->mtd.priv = chip;
nmtd->mtd.owner = THIS_MODULE;
nmtd->set = set;
if (hardware_ecc) {
chip->ecc.calculate = s3c2410_nand_calculate_ecc;
chip->ecc.correct = s3c2410_nand_correct_data;
chip->ecc.mode = NAND_ECC_HW;
switch (info->cpu_type) {
case TYPE_S3C2410:
chip->ecc.hwctl = s3c2410_nand_enable_hwecc;
chip->ecc.calculate = s3c2410_nand_calculate_ecc;
break;
case TYPE_S3C2412:
chip->ecc.hwctl = s3c2412_nand_enable_hwecc;
chip->ecc.calculate = s3c2412_nand_calculate_ecc;
break;
case TYPE_S3C2440:
chip->ecc.hwctl = s3c2440_nand_enable_hwecc;
chip->ecc.calculate = s3c2440_nand_calculate_ecc;
break;
}
} else {
chip->ecc.mode = NAND_ECC_SOFT;
}
if (set->ecc_layout != NULL)
chip->ecc.layout = set->ecc_layout;
if (set->disable_ecc)
chip->ecc.mode = NAND_ECC_NONE;
switch (chip->ecc.mode) {
case NAND_ECC_NONE:
dev_info(info->device, "NAND ECC disabled\n");
break;
case NAND_ECC_SOFT:
dev_info(info->device, "NAND soft ECC\n");
break;
case NAND_ECC_HW:
dev_info(info->device, "NAND hardware ECC\n");
break;
default:
dev_info(info->device, "NAND ECC UNKNOWN\n");
break;
}
/* If you use u-boot BBT creation code, specifying this flag will
* let the kernel fish out the BBT from the NAND, and also skip the
* full NAND scan that can take 1/2s or so. Little things... */
if (set->flash_bbt)
chip->options |= NAND_USE_FLASH_BBT | NAND_SKIP_BBTSCAN;
}
/**
* s3c2410_nand_update_chip - post probe update
* @info: The controller instance.
* @nmtd: The driver version of the MTD instance.
*
* This routine is called after the chip probe has successfully completed
* and the relevant per-chip information updated. This call ensure that
* we update the internal state accordingly.
*
* The internal state is currently limited to the ECC state information.
*/
static void s3c2410_nand_update_chip(struct s3c2410_nand_info *info,
struct s3c2410_nand_mtd *nmtd)
{
struct nand_chip *chip = &nmtd->chip;
dev_dbg(info->device, "chip %p => page shift %d\n",
chip, chip->page_shift);
if (chip->ecc.mode != NAND_ECC_HW)
return;
/* change the behaviour depending on wether we are using
* the large or small page nand device */
if (chip->page_shift > 10) {
chip->ecc.size = 256;
chip->ecc.bytes = 3;
} else {
chip->ecc.size = 512;
chip->ecc.bytes = 3;
chip->ecc.layout = &nand_hw_eccoob;
}
}
/* s3c24xx_nand_probe
*
* called by device layer when it finds a device matching
* one our driver can handled. This code checks to see if
* it can allocate all necessary resources then calls the
* nand layer to look for devices
*/
static int s3c24xx_nand_probe(struct platform_device *pdev)
{
struct s3c2410_platform_nand *plat = to_nand_plat(pdev);
enum s3c_cpu_type cpu_type;
struct s3c2410_nand_info *info;
struct s3c2410_nand_mtd *nmtd;
struct s3c2410_nand_set *sets;
struct resource *res;
int err = 0;
int size;
int nr_sets;
int setno;
cpu_type = platform_get_device_id(pdev)->driver_data;
pr_debug("s3c2410_nand_probe(%p)\n", pdev);
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (info == NULL) {
dev_err(&pdev->dev, "no memory for flash info\n");
err = -ENOMEM;
goto exit_error;
}
platform_set_drvdata(pdev, info);
spin_lock_init(&info->controller.lock);
init_waitqueue_head(&info->controller.wq);
/* get the clock source and enable it */
info->clk = clk_get(&pdev->dev, "nand");
if (IS_ERR(info->clk)) {
dev_err(&pdev->dev, "failed to get clock\n");
err = -ENOENT;
goto exit_error;
}
s3c2410_nand_clk_set_state(info, CLOCK_ENABLE);
/* allocate and map the resource */
/* currently we assume we have the one resource */
res = pdev->resource;
size = resource_size(res);
info->area = request_mem_region(res->start, size, pdev->name);
if (info->area == NULL) {
dev_err(&pdev->dev, "cannot reserve register region\n");
err = -ENOENT;
goto exit_error;
}
info->device = &pdev->dev;
info->platform = plat;
info->regs = ioremap(res->start, size);
info->cpu_type = cpu_type;
if (info->regs == NULL) {
dev_err(&pdev->dev, "cannot reserve register region\n");
err = -EIO;
goto exit_error;
}
dev_dbg(&pdev->dev, "mapped registers at %p\n", info->regs);
/* initialise the hardware */
err = s3c2410_nand_inithw(info);
if (err != 0)
goto exit_error;
sets = (plat != NULL) ? plat->sets : NULL;
nr_sets = (plat != NULL) ? plat->nr_sets : 1;
info->mtd_count = nr_sets;
/* allocate our information */
size = nr_sets * sizeof(*info->mtds);
info->mtds = kzalloc(size, GFP_KERNEL);
if (info->mtds == NULL) {
dev_err(&pdev->dev, "failed to allocate mtd storage\n");
err = -ENOMEM;
goto exit_error;
}
/* initialise all possible chips */
nmtd = info->mtds;
for (setno = 0; setno < nr_sets; setno++, nmtd++) {
pr_debug("initialising set %d (%p, info %p)\n", setno, nmtd, info);
s3c2410_nand_init_chip(info, nmtd, sets);
nmtd->scan_res = nand_scan_ident(&nmtd->mtd,
(sets) ? sets->nr_chips : 1,
NULL);
if (nmtd->scan_res == 0) {
s3c2410_nand_update_chip(info, nmtd);
nand_scan_tail(&nmtd->mtd);
s3c2410_nand_add_partition(info, nmtd, sets);
}
if (sets != NULL)
sets++;
}
err = s3c2410_nand_cpufreq_register(info);
if (err < 0) {
dev_err(&pdev->dev, "failed to init cpufreq support\n");
goto exit_error;
}
if (allow_clk_suspend(info)) {
dev_info(&pdev->dev, "clock idle support enabled\n");
s3c2410_nand_clk_set_state(info, CLOCK_SUSPEND);
}
pr_debug("initialised ok\n");
return 0;
exit_error:
s3c24xx_nand_remove(pdev);
if (err == 0)
err = -EINVAL;
return err;
}
/* PM Support */
#ifdef CONFIG_PM
static int s3c24xx_nand_suspend(struct platform_device *dev, pm_message_t pm)
{
struct s3c2410_nand_info *info = platform_get_drvdata(dev);
if (info) {
info->save_sel = readl(info->sel_reg);
/* For the moment, we must ensure nFCE is high during
* the time we are suspended. This really should be
* handled by suspending the MTDs we are using, but
* that is currently not the case. */
writel(info->save_sel | info->sel_bit, info->sel_reg);
s3c2410_nand_clk_set_state(info, CLOCK_DISABLE);
}
return 0;
}
static int s3c24xx_nand_resume(struct platform_device *dev)
{
struct s3c2410_nand_info *info = platform_get_drvdata(dev);
unsigned long sel;
if (info) {
s3c2410_nand_clk_set_state(info, CLOCK_ENABLE);
s3c2410_nand_inithw(info);
/* Restore the state of the nFCE line. */
sel = readl(info->sel_reg);
sel &= ~info->sel_bit;
sel |= info->save_sel & info->sel_bit;
writel(sel, info->sel_reg);
s3c2410_nand_clk_set_state(info, CLOCK_SUSPEND);
}
return 0;
}
#else
#define s3c24xx_nand_suspend NULL
#define s3c24xx_nand_resume NULL
#endif
/* driver device registration */
static struct platform_device_id s3c24xx_driver_ids[] = {
{
.name = "s3c2410-nand",
.driver_data = TYPE_S3C2410,
}, {
.name = "s3c2440-nand",
.driver_data = TYPE_S3C2440,
}, {
.name = "s3c2412-nand",
.driver_data = TYPE_S3C2412,
}, {
.name = "s3c6400-nand",
.driver_data = TYPE_S3C2412, /* compatible with 2412 */
},
{ }
};
MODULE_DEVICE_TABLE(platform, s3c24xx_driver_ids);
static struct platform_driver s3c24xx_nand_driver = {
.probe = s3c24xx_nand_probe,
.remove = s3c24xx_nand_remove,
.suspend = s3c24xx_nand_suspend,
.resume = s3c24xx_nand_resume,
.id_table = s3c24xx_driver_ids,
.driver = {
.name = "s3c24xx-nand",
.owner = THIS_MODULE,
},
};
static int __init s3c2410_nand_init(void)
{
printk("S3C24XX NAND Driver, (c) 2004 Simtec Electronics\n");
return platform_driver_register(&s3c24xx_nand_driver);
}
static void __exit s3c2410_nand_exit(void)
{
platform_driver_unregister(&s3c24xx_nand_driver);
}
module_init(s3c2410_nand_init);
module_exit(s3c2410_nand_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_DESCRIPTION("S3C24XX MTD NAND driver");
| gpl-2.0 |
KINGbabasula/u8500_kernel | drivers/staging/cx25821/cx25821-cards.c | 3035 | 1958 | /*
* Driver for the Conexant CX25821 PCIe bridge
*
* Copyright (C) 2009 Conexant Systems Inc.
* Authors <shu.lin@conexant.com>, <hiep.huynh@conexant.com>
* Based on Steven Toth <stoth@linuxtv.org> cx23885 driver
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/init.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <media/cx25840.h>
#include "cx25821.h"
#include "tuner-xc2028.h"
/* board config info */
struct cx25821_board cx25821_boards[] = {
[UNKNOWN_BOARD] = {
.name = "UNKNOWN/GENERIC",
/* Ensure safe default for unknown boards */
.clk_freq = 0,
},
[CX25821_BOARD] = {
.name = "CX25821",
.portb = CX25821_RAW,
.portc = CX25821_264,
.input[0].type = CX25821_VMUX_COMPOSITE,
},
};
const unsigned int cx25821_bcount = ARRAY_SIZE(cx25821_boards);
struct cx25821_subid cx25821_subids[] = {
{
.subvendor = 0x14f1,
.subdevice = 0x0920,
.card = CX25821_BOARD,
},
};
void cx25821_card_setup(struct cx25821_dev *dev)
{
static u8 eeprom[256];
if (dev->i2c_bus[0].i2c_rc == 0) {
dev->i2c_bus[0].i2c_client.addr = 0xa0 >> 1;
tveeprom_read(&dev->i2c_bus[0].i2c_client, eeprom,
sizeof(eeprom));
}
}
| gpl-2.0 |
chonix/trinity | drivers/net/sfc/tenxpress.c | 3035 | 13626 | /****************************************************************************
* Driver for Solarflare Solarstorm network controllers and boards
* Copyright 2007-2011 Solarflare Communications 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, incorporated herein by reference.
*/
#include <linux/delay.h>
#include <linux/rtnetlink.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include "efx.h"
#include "mdio_10g.h"
#include "nic.h"
#include "phy.h"
#include "workarounds.h"
/* We expect these MMDs to be in the package. */
#define TENXPRESS_REQUIRED_DEVS (MDIO_DEVS_PMAPMD | \
MDIO_DEVS_PCS | \
MDIO_DEVS_PHYXS | \
MDIO_DEVS_AN)
#define SFX7101_LOOPBACKS ((1 << LOOPBACK_PHYXS) | \
(1 << LOOPBACK_PCS) | \
(1 << LOOPBACK_PMAPMD) | \
(1 << LOOPBACK_PHYXS_WS))
/* We complain if we fail to see the link partner as 10G capable this many
* times in a row (must be > 1 as sampling the autoneg. registers is racy)
*/
#define MAX_BAD_LP_TRIES (5)
/* Extended control register */
#define PMA_PMD_XCONTROL_REG 49152
#define PMA_PMD_EXT_GMII_EN_LBN 1
#define PMA_PMD_EXT_GMII_EN_WIDTH 1
#define PMA_PMD_EXT_CLK_OUT_LBN 2
#define PMA_PMD_EXT_CLK_OUT_WIDTH 1
#define PMA_PMD_LNPGA_POWERDOWN_LBN 8
#define PMA_PMD_LNPGA_POWERDOWN_WIDTH 1
#define PMA_PMD_EXT_CLK312_WIDTH 1
#define PMA_PMD_EXT_LPOWER_LBN 12
#define PMA_PMD_EXT_LPOWER_WIDTH 1
#define PMA_PMD_EXT_ROBUST_LBN 14
#define PMA_PMD_EXT_ROBUST_WIDTH 1
#define PMA_PMD_EXT_SSR_LBN 15
#define PMA_PMD_EXT_SSR_WIDTH 1
/* extended status register */
#define PMA_PMD_XSTATUS_REG 49153
#define PMA_PMD_XSTAT_MDIX_LBN 14
#define PMA_PMD_XSTAT_FLP_LBN (12)
/* LED control register */
#define PMA_PMD_LED_CTRL_REG 49159
#define PMA_PMA_LED_ACTIVITY_LBN (3)
/* LED function override register */
#define PMA_PMD_LED_OVERR_REG 49161
/* Bit positions for different LEDs (there are more but not wired on SFE4001)*/
#define PMA_PMD_LED_LINK_LBN (0)
#define PMA_PMD_LED_SPEED_LBN (2)
#define PMA_PMD_LED_TX_LBN (4)
#define PMA_PMD_LED_RX_LBN (6)
/* Override settings */
#define PMA_PMD_LED_AUTO (0) /* H/W control */
#define PMA_PMD_LED_ON (1)
#define PMA_PMD_LED_OFF (2)
#define PMA_PMD_LED_FLASH (3)
#define PMA_PMD_LED_MASK 3
/* All LEDs under hardware control */
/* Green and Amber under hardware control, Red off */
#define SFX7101_PMA_PMD_LED_DEFAULT (PMA_PMD_LED_OFF << PMA_PMD_LED_RX_LBN)
#define PMA_PMD_SPEED_ENABLE_REG 49192
#define PMA_PMD_100TX_ADV_LBN 1
#define PMA_PMD_100TX_ADV_WIDTH 1
#define PMA_PMD_1000T_ADV_LBN 2
#define PMA_PMD_1000T_ADV_WIDTH 1
#define PMA_PMD_10000T_ADV_LBN 3
#define PMA_PMD_10000T_ADV_WIDTH 1
#define PMA_PMD_SPEED_LBN 4
#define PMA_PMD_SPEED_WIDTH 4
/* Misc register defines */
#define PCS_CLOCK_CTRL_REG 55297
#define PLL312_RST_N_LBN 2
#define PCS_SOFT_RST2_REG 55302
#define SERDES_RST_N_LBN 13
#define XGXS_RST_N_LBN 12
#define PCS_TEST_SELECT_REG 55303 /* PRM 10.5.8 */
#define CLK312_EN_LBN 3
/* PHYXS registers */
#define PHYXS_XCONTROL_REG 49152
#define PHYXS_RESET_LBN 15
#define PHYXS_RESET_WIDTH 1
#define PHYXS_TEST1 (49162)
#define LOOPBACK_NEAR_LBN (8)
#define LOOPBACK_NEAR_WIDTH (1)
/* Boot status register */
#define PCS_BOOT_STATUS_REG 53248
#define PCS_BOOT_FATAL_ERROR_LBN 0
#define PCS_BOOT_PROGRESS_LBN 1
#define PCS_BOOT_PROGRESS_WIDTH 2
#define PCS_BOOT_PROGRESS_INIT 0
#define PCS_BOOT_PROGRESS_WAIT_MDIO 1
#define PCS_BOOT_PROGRESS_CHECKSUM 2
#define PCS_BOOT_PROGRESS_JUMP 3
#define PCS_BOOT_DOWNLOAD_WAIT_LBN 3
#define PCS_BOOT_CODE_STARTED_LBN 4
/* 100M/1G PHY registers */
#define GPHY_XCONTROL_REG 49152
#define GPHY_ISOLATE_LBN 10
#define GPHY_ISOLATE_WIDTH 1
#define GPHY_DUPLEX_LBN 8
#define GPHY_DUPLEX_WIDTH 1
#define GPHY_LOOPBACK_NEAR_LBN 14
#define GPHY_LOOPBACK_NEAR_WIDTH 1
#define C22EXT_STATUS_REG 49153
#define C22EXT_STATUS_LINK_LBN 2
#define C22EXT_STATUS_LINK_WIDTH 1
#define C22EXT_MSTSLV_CTRL 49161
#define C22EXT_MSTSLV_CTRL_ADV_1000_HD_LBN 8
#define C22EXT_MSTSLV_CTRL_ADV_1000_FD_LBN 9
#define C22EXT_MSTSLV_STATUS 49162
#define C22EXT_MSTSLV_STATUS_LP_1000_HD_LBN 10
#define C22EXT_MSTSLV_STATUS_LP_1000_FD_LBN 11
/* Time to wait between powering down the LNPGA and turning off the power
* rails */
#define LNPGA_PDOWN_WAIT (HZ / 5)
struct tenxpress_phy_data {
enum efx_loopback_mode loopback_mode;
enum efx_phy_mode phy_mode;
int bad_lp_tries;
};
static int tenxpress_init(struct efx_nic *efx)
{
/* Enable 312.5 MHz clock */
efx_mdio_write(efx, MDIO_MMD_PCS, PCS_TEST_SELECT_REG,
1 << CLK312_EN_LBN);
/* Set the LEDs up as: Green = Link, Amber = Link/Act, Red = Off */
efx_mdio_set_flag(efx, MDIO_MMD_PMAPMD, PMA_PMD_LED_CTRL_REG,
1 << PMA_PMA_LED_ACTIVITY_LBN, true);
efx_mdio_write(efx, MDIO_MMD_PMAPMD, PMA_PMD_LED_OVERR_REG,
SFX7101_PMA_PMD_LED_DEFAULT);
return 0;
}
static int tenxpress_phy_probe(struct efx_nic *efx)
{
struct tenxpress_phy_data *phy_data;
/* Allocate phy private storage */
phy_data = kzalloc(sizeof(*phy_data), GFP_KERNEL);
if (!phy_data)
return -ENOMEM;
efx->phy_data = phy_data;
phy_data->phy_mode = efx->phy_mode;
efx->mdio.mmds = TENXPRESS_REQUIRED_DEVS;
efx->mdio.mode_support = MDIO_SUPPORTS_C45;
efx->loopback_modes = SFX7101_LOOPBACKS | FALCON_XMAC_LOOPBACKS;
efx->link_advertising = (ADVERTISED_TP | ADVERTISED_Autoneg |
ADVERTISED_10000baseT_Full);
return 0;
}
static int tenxpress_phy_init(struct efx_nic *efx)
{
int rc;
falcon_board(efx)->type->init_phy(efx);
if (!(efx->phy_mode & PHY_MODE_SPECIAL)) {
rc = efx_mdio_wait_reset_mmds(efx, TENXPRESS_REQUIRED_DEVS);
if (rc < 0)
return rc;
rc = efx_mdio_check_mmds(efx, TENXPRESS_REQUIRED_DEVS);
if (rc < 0)
return rc;
}
rc = tenxpress_init(efx);
if (rc < 0)
return rc;
/* Reinitialise flow control settings */
efx_link_set_wanted_fc(efx, efx->wanted_fc);
efx_mdio_an_reconfigure(efx);
schedule_timeout_uninterruptible(HZ / 5); /* 200ms */
/* Let XGXS and SerDes out of reset */
falcon_reset_xaui(efx);
return 0;
}
/* Perform a "special software reset" on the PHY. The caller is
* responsible for saving and restoring the PHY hardware registers
* properly, and masking/unmasking LASI */
static int tenxpress_special_reset(struct efx_nic *efx)
{
int rc, reg;
/* The XGMAC clock is driven from the SFX7101 312MHz clock, so
* a special software reset can glitch the XGMAC sufficiently for stats
* requests to fail. */
falcon_stop_nic_stats(efx);
/* Initiate reset */
reg = efx_mdio_read(efx, MDIO_MMD_PMAPMD, PMA_PMD_XCONTROL_REG);
reg |= (1 << PMA_PMD_EXT_SSR_LBN);
efx_mdio_write(efx, MDIO_MMD_PMAPMD, PMA_PMD_XCONTROL_REG, reg);
mdelay(200);
/* Wait for the blocks to come out of reset */
rc = efx_mdio_wait_reset_mmds(efx, TENXPRESS_REQUIRED_DEVS);
if (rc < 0)
goto out;
/* Try and reconfigure the device */
rc = tenxpress_init(efx);
if (rc < 0)
goto out;
/* Wait for the XGXS state machine to churn */
mdelay(10);
out:
falcon_start_nic_stats(efx);
return rc;
}
static void sfx7101_check_bad_lp(struct efx_nic *efx, bool link_ok)
{
struct tenxpress_phy_data *pd = efx->phy_data;
bool bad_lp;
int reg;
if (link_ok) {
bad_lp = false;
} else {
/* Check that AN has started but not completed. */
reg = efx_mdio_read(efx, MDIO_MMD_AN, MDIO_STAT1);
if (!(reg & MDIO_AN_STAT1_LPABLE))
return; /* LP status is unknown */
bad_lp = !(reg & MDIO_AN_STAT1_COMPLETE);
if (bad_lp)
pd->bad_lp_tries++;
}
/* Nothing to do if all is well and was previously so. */
if (!pd->bad_lp_tries)
return;
/* Use the RX (red) LED as an error indicator once we've seen AN
* failure several times in a row, and also log a message. */
if (!bad_lp || pd->bad_lp_tries == MAX_BAD_LP_TRIES) {
reg = efx_mdio_read(efx, MDIO_MMD_PMAPMD,
PMA_PMD_LED_OVERR_REG);
reg &= ~(PMA_PMD_LED_MASK << PMA_PMD_LED_RX_LBN);
if (!bad_lp) {
reg |= PMA_PMD_LED_OFF << PMA_PMD_LED_RX_LBN;
} else {
reg |= PMA_PMD_LED_FLASH << PMA_PMD_LED_RX_LBN;
netif_err(efx, link, efx->net_dev,
"appears to be plugged into a port"
" that is not 10GBASE-T capable. The PHY"
" supports 10GBASE-T ONLY, so no link can"
" be established\n");
}
efx_mdio_write(efx, MDIO_MMD_PMAPMD,
PMA_PMD_LED_OVERR_REG, reg);
pd->bad_lp_tries = bad_lp;
}
}
static bool sfx7101_link_ok(struct efx_nic *efx)
{
return efx_mdio_links_ok(efx,
MDIO_DEVS_PMAPMD |
MDIO_DEVS_PCS |
MDIO_DEVS_PHYXS);
}
static void tenxpress_ext_loopback(struct efx_nic *efx)
{
efx_mdio_set_flag(efx, MDIO_MMD_PHYXS, PHYXS_TEST1,
1 << LOOPBACK_NEAR_LBN,
efx->loopback_mode == LOOPBACK_PHYXS);
}
static void tenxpress_low_power(struct efx_nic *efx)
{
efx_mdio_set_mmds_lpower(
efx, !!(efx->phy_mode & PHY_MODE_LOW_POWER),
TENXPRESS_REQUIRED_DEVS);
}
static int tenxpress_phy_reconfigure(struct efx_nic *efx)
{
struct tenxpress_phy_data *phy_data = efx->phy_data;
bool phy_mode_change, loop_reset;
if (efx->phy_mode & (PHY_MODE_OFF | PHY_MODE_SPECIAL)) {
phy_data->phy_mode = efx->phy_mode;
return 0;
}
phy_mode_change = (efx->phy_mode == PHY_MODE_NORMAL &&
phy_data->phy_mode != PHY_MODE_NORMAL);
loop_reset = (LOOPBACK_OUT_OF(phy_data, efx, LOOPBACKS_EXTERNAL(efx)) ||
LOOPBACK_CHANGED(phy_data, efx, 1 << LOOPBACK_GPHY));
if (loop_reset || phy_mode_change) {
tenxpress_special_reset(efx);
falcon_reset_xaui(efx);
}
tenxpress_low_power(efx);
efx_mdio_transmit_disable(efx);
efx_mdio_phy_reconfigure(efx);
tenxpress_ext_loopback(efx);
efx_mdio_an_reconfigure(efx);
phy_data->loopback_mode = efx->loopback_mode;
phy_data->phy_mode = efx->phy_mode;
return 0;
}
static void
tenxpress_get_settings(struct efx_nic *efx, struct ethtool_cmd *ecmd);
/* Poll for link state changes */
static bool tenxpress_phy_poll(struct efx_nic *efx)
{
struct efx_link_state old_state = efx->link_state;
efx->link_state.up = sfx7101_link_ok(efx);
efx->link_state.speed = 10000;
efx->link_state.fd = true;
efx->link_state.fc = efx_mdio_get_pause(efx);
sfx7101_check_bad_lp(efx, efx->link_state.up);
return !efx_link_state_equal(&efx->link_state, &old_state);
}
static void sfx7101_phy_fini(struct efx_nic *efx)
{
int reg;
/* Power down the LNPGA */
reg = (1 << PMA_PMD_LNPGA_POWERDOWN_LBN);
efx_mdio_write(efx, MDIO_MMD_PMAPMD, PMA_PMD_XCONTROL_REG, reg);
/* Waiting here ensures that the board fini, which can turn
* off the power to the PHY, won't get run until the LNPGA
* powerdown has been given long enough to complete. */
schedule_timeout_uninterruptible(LNPGA_PDOWN_WAIT); /* 200 ms */
}
static void tenxpress_phy_remove(struct efx_nic *efx)
{
kfree(efx->phy_data);
efx->phy_data = NULL;
}
/* Override the RX, TX and link LEDs */
void tenxpress_set_id_led(struct efx_nic *efx, enum efx_led_mode mode)
{
int reg;
switch (mode) {
case EFX_LED_OFF:
reg = (PMA_PMD_LED_OFF << PMA_PMD_LED_TX_LBN) |
(PMA_PMD_LED_OFF << PMA_PMD_LED_RX_LBN) |
(PMA_PMD_LED_OFF << PMA_PMD_LED_LINK_LBN);
break;
case EFX_LED_ON:
reg = (PMA_PMD_LED_ON << PMA_PMD_LED_TX_LBN) |
(PMA_PMD_LED_ON << PMA_PMD_LED_RX_LBN) |
(PMA_PMD_LED_ON << PMA_PMD_LED_LINK_LBN);
break;
default:
reg = SFX7101_PMA_PMD_LED_DEFAULT;
break;
}
efx_mdio_write(efx, MDIO_MMD_PMAPMD, PMA_PMD_LED_OVERR_REG, reg);
}
static const char *const sfx7101_test_names[] = {
"bist"
};
static const char *sfx7101_test_name(struct efx_nic *efx, unsigned int index)
{
if (index < ARRAY_SIZE(sfx7101_test_names))
return sfx7101_test_names[index];
return NULL;
}
static int
sfx7101_run_tests(struct efx_nic *efx, int *results, unsigned flags)
{
int rc;
if (!(flags & ETH_TEST_FL_OFFLINE))
return 0;
/* BIST is automatically run after a special software reset */
rc = tenxpress_special_reset(efx);
results[0] = rc ? -1 : 1;
efx_mdio_an_reconfigure(efx);
return rc;
}
static void
tenxpress_get_settings(struct efx_nic *efx, struct ethtool_cmd *ecmd)
{
u32 adv = 0, lpa = 0;
int reg;
reg = efx_mdio_read(efx, MDIO_MMD_AN, MDIO_AN_10GBT_CTRL);
if (reg & MDIO_AN_10GBT_CTRL_ADV10G)
adv |= ADVERTISED_10000baseT_Full;
reg = efx_mdio_read(efx, MDIO_MMD_AN, MDIO_AN_10GBT_STAT);
if (reg & MDIO_AN_10GBT_STAT_LP10G)
lpa |= ADVERTISED_10000baseT_Full;
mdio45_ethtool_gset_npage(&efx->mdio, ecmd, adv, lpa);
/* In loopback, the PHY automatically brings up the correct interface,
* but doesn't advertise the correct speed. So override it */
if (LOOPBACK_EXTERNAL(efx))
ethtool_cmd_speed_set(ecmd, SPEED_10000);
}
static int tenxpress_set_settings(struct efx_nic *efx, struct ethtool_cmd *ecmd)
{
if (!ecmd->autoneg)
return -EINVAL;
return efx_mdio_set_settings(efx, ecmd);
}
static void sfx7101_set_npage_adv(struct efx_nic *efx, u32 advertising)
{
efx_mdio_set_flag(efx, MDIO_MMD_AN, MDIO_AN_10GBT_CTRL,
MDIO_AN_10GBT_CTRL_ADV10G,
advertising & ADVERTISED_10000baseT_Full);
}
const struct efx_phy_operations falcon_sfx7101_phy_ops = {
.probe = tenxpress_phy_probe,
.init = tenxpress_phy_init,
.reconfigure = tenxpress_phy_reconfigure,
.poll = tenxpress_phy_poll,
.fini = sfx7101_phy_fini,
.remove = tenxpress_phy_remove,
.get_settings = tenxpress_get_settings,
.set_settings = tenxpress_set_settings,
.set_npage_adv = sfx7101_set_npage_adv,
.test_alive = efx_mdio_test_alive,
.test_name = sfx7101_test_name,
.run_tests = sfx7101_run_tests,
};
| gpl-2.0 |
Mirsaid02/android_kernel_samsung_ms013g-2 | arch/arm/mach-msm/scm-io.c | 3547 | 1841 | /* Copyright (c) 2011, 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/module.h>
#include <linux/io.h>
#include <mach/msm_iomap.h>
#include <mach/scm.h>
#include <mach/scm-io.h>
#define SCM_IO_READ 0x1
#define SCM_IO_WRITE 0x2
#define BETWEEN(p, st, sz) ((p) >= (void __iomem *)(st) && \
(p) < ((void __iomem *)(st) + (sz)))
#define XLATE(p, pst, vst) ((u32)((p) - (vst)) + (pst))
static u32 __secure_readl(u32 addr)
{
u32 r;
r = scm_call_atomic1(SCM_SVC_IO, SCM_IO_READ, addr);
__iormb();
return r;
}
u32 secure_readl(void __iomem *c)
{
if (BETWEEN(c, MSM_MMSS_CLK_CTL_BASE, MSM_MMSS_CLK_CTL_SIZE))
return __secure_readl(XLATE(c, MSM_MMSS_CLK_CTL_PHYS,
MSM_MMSS_CLK_CTL_BASE));
else if (BETWEEN(c, MSM_TCSR_BASE, MSM_TCSR_SIZE))
return __secure_readl(XLATE(c, MSM_TCSR_PHYS, MSM_TCSR_BASE));
return readl(c);
}
EXPORT_SYMBOL(secure_readl);
static void __secure_writel(u32 v, u32 addr)
{
__iowmb();
scm_call_atomic2(SCM_SVC_IO, SCM_IO_WRITE, addr, v);
}
void secure_writel(u32 v, void __iomem *c)
{
if (BETWEEN(c, MSM_MMSS_CLK_CTL_BASE, MSM_MMSS_CLK_CTL_SIZE))
__secure_writel(v, XLATE(c, MSM_MMSS_CLK_CTL_PHYS,
MSM_MMSS_CLK_CTL_BASE));
else if (BETWEEN(c, MSM_TCSR_BASE, MSM_TCSR_SIZE))
__secure_writel(v, XLATE(c, MSM_TCSR_PHYS, MSM_TCSR_BASE));
else
writel(v, c);
}
EXPORT_SYMBOL(secure_writel);
| gpl-2.0 |
QduZ9zEVr6/kernel-msm | arch/arm/mach-exynos/pm.c | 4571 | 10775 | /* linux/arch/arm/mach-exynos4/pm.c
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* EXYNOS4210 - Power Management support
*
* Based on arch/arm/mach-s3c2410/pm.c
* Copyright (c) 2006 Simtec Electronics
* Ben Dooks <ben@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.
*/
#include <linux/init.h>
#include <linux/suspend.h>
#include <linux/syscore_ops.h>
#include <linux/io.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <asm/cacheflush.h>
#include <asm/hardware/cache-l2x0.h>
#include <asm/smp_scu.h>
#include <plat/cpu.h>
#include <plat/pm.h>
#include <plat/pll.h>
#include <plat/regs-srom.h>
#include <mach/regs-irq.h>
#include <mach/regs-gpio.h>
#include <mach/regs-clock.h>
#include <mach/regs-pmu.h>
#include <mach/pm-core.h>
#include <mach/pmu.h>
static struct sleep_save exynos4_set_clksrc[] = {
{ .reg = EXYNOS4_CLKSRC_MASK_TOP , .val = 0x00000001, },
{ .reg = EXYNOS4_CLKSRC_MASK_CAM , .val = 0x11111111, },
{ .reg = EXYNOS4_CLKSRC_MASK_TV , .val = 0x00000111, },
{ .reg = EXYNOS4_CLKSRC_MASK_LCD0 , .val = 0x00001111, },
{ .reg = EXYNOS4_CLKSRC_MASK_MAUDIO , .val = 0x00000001, },
{ .reg = EXYNOS4_CLKSRC_MASK_FSYS , .val = 0x01011111, },
{ .reg = EXYNOS4_CLKSRC_MASK_PERIL0 , .val = 0x01111111, },
{ .reg = EXYNOS4_CLKSRC_MASK_PERIL1 , .val = 0x01110111, },
{ .reg = EXYNOS4_CLKSRC_MASK_DMC , .val = 0x00010000, },
};
static struct sleep_save exynos4210_set_clksrc[] = {
{ .reg = EXYNOS4210_CLKSRC_MASK_LCD1 , .val = 0x00001111, },
};
static struct sleep_save exynos4_epll_save[] = {
SAVE_ITEM(EXYNOS4_EPLL_CON0),
SAVE_ITEM(EXYNOS4_EPLL_CON1),
};
static struct sleep_save exynos4_vpll_save[] = {
SAVE_ITEM(EXYNOS4_VPLL_CON0),
SAVE_ITEM(EXYNOS4_VPLL_CON1),
};
static struct sleep_save exynos4_core_save[] = {
/* GIC side */
SAVE_ITEM(S5P_VA_GIC_CPU + 0x000),
SAVE_ITEM(S5P_VA_GIC_CPU + 0x004),
SAVE_ITEM(S5P_VA_GIC_CPU + 0x008),
SAVE_ITEM(S5P_VA_GIC_CPU + 0x00C),
SAVE_ITEM(S5P_VA_GIC_CPU + 0x014),
SAVE_ITEM(S5P_VA_GIC_CPU + 0x018),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x000),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x004),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x100),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x104),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x108),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x300),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x304),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x308),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x400),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x404),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x408),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x40C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x410),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x414),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x418),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x41C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x420),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x424),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x428),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x42C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x430),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x434),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x438),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x43C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x440),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x444),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x448),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x44C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x450),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x454),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x458),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x45C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x800),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x804),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x808),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x80C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x810),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x814),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x818),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x81C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x820),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x824),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x828),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x82C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x830),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x834),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x838),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x83C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x840),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x844),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x848),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x84C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x850),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x854),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x858),
SAVE_ITEM(S5P_VA_GIC_DIST + 0x85C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0xC00),
SAVE_ITEM(S5P_VA_GIC_DIST + 0xC04),
SAVE_ITEM(S5P_VA_GIC_DIST + 0xC08),
SAVE_ITEM(S5P_VA_GIC_DIST + 0xC0C),
SAVE_ITEM(S5P_VA_GIC_DIST + 0xC10),
SAVE_ITEM(S5P_VA_GIC_DIST + 0xC14),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x000),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x010),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x020),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x030),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x040),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x050),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x060),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x070),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x080),
SAVE_ITEM(S5P_VA_COMBINER_BASE + 0x090),
/* SROM side */
SAVE_ITEM(S5P_SROM_BW),
SAVE_ITEM(S5P_SROM_BC0),
SAVE_ITEM(S5P_SROM_BC1),
SAVE_ITEM(S5P_SROM_BC2),
SAVE_ITEM(S5P_SROM_BC3),
};
/* For Cortex-A9 Diagnostic and Power control register */
static unsigned int save_arm_register[2];
static int exynos4_cpu_suspend(unsigned long arg)
{
outer_flush_all();
/* issue the standby signal into the pm unit. */
cpu_do_idle();
/* we should never get past here */
panic("sleep resumed to originator?");
}
static void exynos4_pm_prepare(void)
{
u32 tmp;
s3c_pm_do_save(exynos4_core_save, ARRAY_SIZE(exynos4_core_save));
s3c_pm_do_save(exynos4_epll_save, ARRAY_SIZE(exynos4_epll_save));
s3c_pm_do_save(exynos4_vpll_save, ARRAY_SIZE(exynos4_vpll_save));
tmp = __raw_readl(S5P_INFORM1);
/* Set value of power down register for sleep mode */
exynos4_sys_powerdown_conf(SYS_SLEEP);
__raw_writel(S5P_CHECK_SLEEP, S5P_INFORM1);
/* ensure at least INFORM0 has the resume address */
__raw_writel(virt_to_phys(s3c_cpu_resume), S5P_INFORM0);
/* Before enter central sequence mode, clock src register have to set */
s3c_pm_do_restore_core(exynos4_set_clksrc, ARRAY_SIZE(exynos4_set_clksrc));
if (soc_is_exynos4210())
s3c_pm_do_restore_core(exynos4210_set_clksrc, ARRAY_SIZE(exynos4210_set_clksrc));
}
static int exynos4_pm_add(struct device *dev, struct subsys_interface *sif)
{
pm_cpu_prep = exynos4_pm_prepare;
pm_cpu_sleep = exynos4_cpu_suspend;
return 0;
}
static unsigned long pll_base_rate;
static void exynos4_restore_pll(void)
{
unsigned long pll_con, locktime, lockcnt;
unsigned long pll_in_rate;
unsigned int p_div, epll_wait = 0, vpll_wait = 0;
if (pll_base_rate == 0)
return;
pll_in_rate = pll_base_rate;
/* EPLL */
pll_con = exynos4_epll_save[0].val;
if (pll_con & (1 << 31)) {
pll_con &= (PLL46XX_PDIV_MASK << PLL46XX_PDIV_SHIFT);
p_div = (pll_con >> PLL46XX_PDIV_SHIFT);
pll_in_rate /= 1000000;
locktime = (3000 / pll_in_rate) * p_div;
lockcnt = locktime * 10000 / (10000 / pll_in_rate);
__raw_writel(lockcnt, EXYNOS4_EPLL_LOCK);
s3c_pm_do_restore_core(exynos4_epll_save,
ARRAY_SIZE(exynos4_epll_save));
epll_wait = 1;
}
pll_in_rate = pll_base_rate;
/* VPLL */
pll_con = exynos4_vpll_save[0].val;
if (pll_con & (1 << 31)) {
pll_in_rate /= 1000000;
/* 750us */
locktime = 750;
lockcnt = locktime * 10000 / (10000 / pll_in_rate);
__raw_writel(lockcnt, EXYNOS4_VPLL_LOCK);
s3c_pm_do_restore_core(exynos4_vpll_save,
ARRAY_SIZE(exynos4_vpll_save));
vpll_wait = 1;
}
/* Wait PLL locking */
do {
if (epll_wait) {
pll_con = __raw_readl(EXYNOS4_EPLL_CON0);
if (pll_con & (1 << EXYNOS4_EPLLCON0_LOCKED_SHIFT))
epll_wait = 0;
}
if (vpll_wait) {
pll_con = __raw_readl(EXYNOS4_VPLL_CON0);
if (pll_con & (1 << EXYNOS4_VPLLCON0_LOCKED_SHIFT))
vpll_wait = 0;
}
} while (epll_wait || vpll_wait);
}
static struct subsys_interface exynos4_pm_interface = {
.name = "exynos4_pm",
.subsys = &exynos4_subsys,
.add_dev = exynos4_pm_add,
};
static __init int exynos4_pm_drvinit(void)
{
struct clk *pll_base;
unsigned int tmp;
s3c_pm_init();
/* All wakeup disable */
tmp = __raw_readl(S5P_WAKEUP_MASK);
tmp |= ((0xFF << 8) | (0x1F << 1));
__raw_writel(tmp, S5P_WAKEUP_MASK);
pll_base = clk_get(NULL, "xtal");
if (!IS_ERR(pll_base)) {
pll_base_rate = clk_get_rate(pll_base);
clk_put(pll_base);
}
return subsys_interface_register(&exynos4_pm_interface);
}
arch_initcall(exynos4_pm_drvinit);
static int exynos4_pm_suspend(void)
{
unsigned long tmp;
/* Setting Central Sequence Register for power down mode */
tmp = __raw_readl(S5P_CENTRAL_SEQ_CONFIGURATION);
tmp &= ~S5P_CENTRAL_LOWPWR_CFG;
__raw_writel(tmp, S5P_CENTRAL_SEQ_CONFIGURATION);
if (soc_is_exynos4212()) {
tmp = __raw_readl(S5P_CENTRAL_SEQ_OPTION);
tmp &= ~(S5P_USE_STANDBYWFI_ISP_ARM |
S5P_USE_STANDBYWFE_ISP_ARM);
__raw_writel(tmp, S5P_CENTRAL_SEQ_OPTION);
}
/* Save Power control register */
asm ("mrc p15, 0, %0, c15, c0, 0"
: "=r" (tmp) : : "cc");
save_arm_register[0] = tmp;
/* Save Diagnostic register */
asm ("mrc p15, 0, %0, c15, c0, 1"
: "=r" (tmp) : : "cc");
save_arm_register[1] = tmp;
return 0;
}
static void exynos4_pm_resume(void)
{
unsigned long tmp;
/*
* If PMU failed while entering sleep mode, WFI will be
* ignored by PMU and then exiting cpu_do_idle().
* S5P_CENTRAL_LOWPWR_CFG bit will not be set automatically
* in this situation.
*/
tmp = __raw_readl(S5P_CENTRAL_SEQ_CONFIGURATION);
if (!(tmp & S5P_CENTRAL_LOWPWR_CFG)) {
tmp |= S5P_CENTRAL_LOWPWR_CFG;
__raw_writel(tmp, S5P_CENTRAL_SEQ_CONFIGURATION);
/* No need to perform below restore code */
goto early_wakeup;
}
/* Restore Power control register */
tmp = save_arm_register[0];
asm volatile ("mcr p15, 0, %0, c15, c0, 0"
: : "r" (tmp)
: "cc");
/* Restore Diagnostic register */
tmp = save_arm_register[1];
asm volatile ("mcr p15, 0, %0, c15, c0, 1"
: : "r" (tmp)
: "cc");
/* For release retention */
__raw_writel((1 << 28), S5P_PAD_RET_MAUDIO_OPTION);
__raw_writel((1 << 28), S5P_PAD_RET_GPIO_OPTION);
__raw_writel((1 << 28), S5P_PAD_RET_UART_OPTION);
__raw_writel((1 << 28), S5P_PAD_RET_MMCA_OPTION);
__raw_writel((1 << 28), S5P_PAD_RET_MMCB_OPTION);
__raw_writel((1 << 28), S5P_PAD_RET_EBIA_OPTION);
__raw_writel((1 << 28), S5P_PAD_RET_EBIB_OPTION);
s3c_pm_do_restore_core(exynos4_core_save, ARRAY_SIZE(exynos4_core_save));
exynos4_restore_pll();
#ifdef CONFIG_SMP
scu_enable(S5P_VA_SCU);
#endif
early_wakeup:
return;
}
static struct syscore_ops exynos4_pm_syscore_ops = {
.suspend = exynos4_pm_suspend,
.resume = exynos4_pm_resume,
};
static __init int exynos4_pm_syscore_init(void)
{
register_syscore_ops(&exynos4_pm_syscore_ops);
return 0;
}
arch_initcall(exynos4_pm_syscore_init);
| gpl-2.0 |
voltagex/msm | arch/arm/mach-s5pc100/mach-smdkc100.c | 4827 | 6444 | /* linux/arch/arm/mach-s5pc100/mach-smdkc100.c
*
* Copyright 2009 Samsung Electronics Co.
* Author: Byungho Min <bhmin@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/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/fb.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/pwm_backlight.h>
#include <asm/hardware/vic.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/map.h>
#include <mach/regs-gpio.h>
#include <video/platform_lcd.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <plat/gpio-cfg.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/fb.h>
#include <plat/iic.h>
#include <plat/ata.h>
#include <plat/adc.h>
#include <plat/keypad.h>
#include <plat/ts.h>
#include <plat/audio.h>
#include <plat/backlight.h>
#include <plat/regs-fb-v4.h>
#include "common.h"
/* Following are default values for UCON, ULCON and UFCON UART registers */
#define SMDKC100_UCON_DEFAULT (S3C2410_UCON_TXILEVEL | \
S3C2410_UCON_RXILEVEL | \
S3C2410_UCON_TXIRQMODE | \
S3C2410_UCON_RXIRQMODE | \
S3C2410_UCON_RXFIFO_TOI | \
S3C2443_UCON_RXERR_IRQEN)
#define SMDKC100_ULCON_DEFAULT S3C2410_LCON_CS8
#define SMDKC100_UFCON_DEFAULT (S3C2410_UFCON_FIFOMODE | \
S3C2440_UFCON_RXTRIG8 | \
S3C2440_UFCON_TXTRIG16)
static struct s3c2410_uartcfg smdkc100_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = SMDKC100_UCON_DEFAULT,
.ulcon = SMDKC100_ULCON_DEFAULT,
.ufcon = SMDKC100_UFCON_DEFAULT,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = SMDKC100_UCON_DEFAULT,
.ulcon = SMDKC100_ULCON_DEFAULT,
.ufcon = SMDKC100_UFCON_DEFAULT,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = SMDKC100_UCON_DEFAULT,
.ulcon = SMDKC100_ULCON_DEFAULT,
.ufcon = SMDKC100_UFCON_DEFAULT,
},
[3] = {
.hwport = 3,
.flags = 0,
.ucon = SMDKC100_UCON_DEFAULT,
.ulcon = SMDKC100_ULCON_DEFAULT,
.ufcon = SMDKC100_UFCON_DEFAULT,
},
};
/* I2C0 */
static struct i2c_board_info i2c_devs0[] __initdata = {
{I2C_BOARD_INFO("wm8580", 0x1b),},
};
/* I2C1 */
static struct i2c_board_info i2c_devs1[] __initdata = {
};
/* LCD power controller */
static void smdkc100_lcd_power_set(struct plat_lcd_data *pd,
unsigned int power)
{
if (power) {
/* module reset */
gpio_direction_output(S5PC100_GPH0(6), 1);
mdelay(100);
gpio_direction_output(S5PC100_GPH0(6), 0);
mdelay(10);
gpio_direction_output(S5PC100_GPH0(6), 1);
mdelay(10);
}
}
static struct plat_lcd_data smdkc100_lcd_power_data = {
.set_power = smdkc100_lcd_power_set,
};
static struct platform_device smdkc100_lcd_powerdev = {
.name = "platform-lcd",
.dev.parent = &s3c_device_fb.dev,
.dev.platform_data = &smdkc100_lcd_power_data,
};
/* Frame Buffer */
static struct s3c_fb_pd_win smdkc100_fb_win0 = {
/* this is to ensure we use win0 */
.win_mode = {
.left_margin = 8,
.right_margin = 13,
.upper_margin = 7,
.lower_margin = 5,
.hsync_len = 3,
.vsync_len = 1,
.xres = 800,
.yres = 480,
.refresh = 80,
},
.max_bpp = 32,
.default_bpp = 16,
};
static struct s3c_fb_platdata smdkc100_lcd_pdata __initdata = {
.win[0] = &smdkc100_fb_win0,
.vidcon0 = VIDCON0_VIDOUT_RGB | VIDCON0_PNRMODE_RGB,
.vidcon1 = VIDCON1_INV_HSYNC | VIDCON1_INV_VSYNC,
.setup_gpio = s5pc100_fb_gpio_setup_24bpp,
};
static struct s3c_ide_platdata smdkc100_ide_pdata __initdata = {
.setup_gpio = s5pc100_ide_setup_gpio,
};
static uint32_t smdkc100_keymap[] __initdata = {
/* KEY(row, col, keycode) */
KEY(0, 3, KEY_1), KEY(0, 4, KEY_2), KEY(0, 5, KEY_3),
KEY(0, 6, KEY_4), KEY(0, 7, KEY_5),
KEY(1, 3, KEY_A), KEY(1, 4, KEY_B), KEY(1, 5, KEY_C),
KEY(1, 6, KEY_D), KEY(1, 7, KEY_E)
};
static struct matrix_keymap_data smdkc100_keymap_data __initdata = {
.keymap = smdkc100_keymap,
.keymap_size = ARRAY_SIZE(smdkc100_keymap),
};
static struct samsung_keypad_platdata smdkc100_keypad_data __initdata = {
.keymap_data = &smdkc100_keymap_data,
.rows = 2,
.cols = 8,
};
static struct platform_device *smdkc100_devices[] __initdata = {
&s3c_device_adc,
&s3c_device_cfcon,
&s3c_device_i2c0,
&s3c_device_i2c1,
&s3c_device_fb,
&s3c_device_hsmmc0,
&s3c_device_hsmmc1,
&s3c_device_hsmmc2,
&s3c_device_ts,
&s3c_device_wdt,
&smdkc100_lcd_powerdev,
&samsung_asoc_dma,
&s5pc100_device_iis0,
&samsung_device_keypad,
&s5pc100_device_ac97,
&s3c_device_rtc,
&s5p_device_fimc0,
&s5p_device_fimc1,
&s5p_device_fimc2,
&s5pc100_device_spdif,
};
/* LCD Backlight data */
static struct samsung_bl_gpio_info smdkc100_bl_gpio_info = {
.no = S5PC100_GPD(0),
.func = S3C_GPIO_SFN(2),
};
static struct platform_pwm_backlight_data smdkc100_bl_data = {
.pwm_id = 0,
};
static void __init smdkc100_map_io(void)
{
s5pc100_init_io(NULL, 0);
s3c24xx_init_clocks(12000000);
s3c24xx_init_uarts(smdkc100_uartcfgs, ARRAY_SIZE(smdkc100_uartcfgs));
}
static void __init smdkc100_machine_init(void)
{
s3c24xx_ts_set_platdata(NULL);
/* I2C */
s3c_i2c0_set_platdata(NULL);
s3c_i2c1_set_platdata(NULL);
i2c_register_board_info(0, i2c_devs0, ARRAY_SIZE(i2c_devs0));
i2c_register_board_info(1, i2c_devs1, ARRAY_SIZE(i2c_devs1));
s3c_fb_set_platdata(&smdkc100_lcd_pdata);
s3c_ide_set_platdata(&smdkc100_ide_pdata);
samsung_keypad_set_platdata(&smdkc100_keypad_data);
s5pc100_spdif_setup_gpio(S5PC100_SPDIF_GPD);
/* LCD init */
gpio_request(S5PC100_GPH0(6), "GPH0");
smdkc100_lcd_power_set(&smdkc100_lcd_power_data, 0);
samsung_bl_set(&smdkc100_bl_gpio_info, &smdkc100_bl_data);
platform_add_devices(smdkc100_devices, ARRAY_SIZE(smdkc100_devices));
}
MACHINE_START(SMDKC100, "SMDKC100")
/* Maintainer: Byungho Min <bhmin@samsung.com> */
.atag_offset = 0x100,
.init_irq = s5pc100_init_irq,
.handle_irq = vic_handle_irq,
.map_io = smdkc100_map_io,
.init_machine = smdkc100_machine_init,
.timer = &s3c24xx_timer,
.restart = s5pc100_restart,
MACHINE_END
| gpl-2.0 |
bilalliberty/depricated-kernel-villec2--3.4- | drivers/scsi/bfa/bfa_ioc_cb.c | 7899 | 9084 | /*
* Copyright (c) 2005-2010 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*
* Linux driver for Brocade Fibre Channel Host Bus Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) Version 2 as
* published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include "bfad_drv.h"
#include "bfa_ioc.h"
#include "bfi_reg.h"
#include "bfa_defs.h"
BFA_TRC_FILE(CNA, IOC_CB);
/*
* forward declarations
*/
static bfa_boolean_t bfa_ioc_cb_firmware_lock(struct bfa_ioc_s *ioc);
static void bfa_ioc_cb_firmware_unlock(struct bfa_ioc_s *ioc);
static void bfa_ioc_cb_reg_init(struct bfa_ioc_s *ioc);
static void bfa_ioc_cb_map_port(struct bfa_ioc_s *ioc);
static void bfa_ioc_cb_isr_mode_set(struct bfa_ioc_s *ioc, bfa_boolean_t msix);
static void bfa_ioc_cb_notify_fail(struct bfa_ioc_s *ioc);
static void bfa_ioc_cb_ownership_reset(struct bfa_ioc_s *ioc);
static bfa_boolean_t bfa_ioc_cb_sync_start(struct bfa_ioc_s *ioc);
static void bfa_ioc_cb_sync_join(struct bfa_ioc_s *ioc);
static void bfa_ioc_cb_sync_leave(struct bfa_ioc_s *ioc);
static void bfa_ioc_cb_sync_ack(struct bfa_ioc_s *ioc);
static bfa_boolean_t bfa_ioc_cb_sync_complete(struct bfa_ioc_s *ioc);
static struct bfa_ioc_hwif_s hwif_cb;
/*
* Called from bfa_ioc_attach() to map asic specific calls.
*/
void
bfa_ioc_set_cb_hwif(struct bfa_ioc_s *ioc)
{
hwif_cb.ioc_pll_init = bfa_ioc_cb_pll_init;
hwif_cb.ioc_firmware_lock = bfa_ioc_cb_firmware_lock;
hwif_cb.ioc_firmware_unlock = bfa_ioc_cb_firmware_unlock;
hwif_cb.ioc_reg_init = bfa_ioc_cb_reg_init;
hwif_cb.ioc_map_port = bfa_ioc_cb_map_port;
hwif_cb.ioc_isr_mode_set = bfa_ioc_cb_isr_mode_set;
hwif_cb.ioc_notify_fail = bfa_ioc_cb_notify_fail;
hwif_cb.ioc_ownership_reset = bfa_ioc_cb_ownership_reset;
hwif_cb.ioc_sync_start = bfa_ioc_cb_sync_start;
hwif_cb.ioc_sync_join = bfa_ioc_cb_sync_join;
hwif_cb.ioc_sync_leave = bfa_ioc_cb_sync_leave;
hwif_cb.ioc_sync_ack = bfa_ioc_cb_sync_ack;
hwif_cb.ioc_sync_complete = bfa_ioc_cb_sync_complete;
ioc->ioc_hwif = &hwif_cb;
}
/*
* Return true if firmware of current driver matches the running firmware.
*/
static bfa_boolean_t
bfa_ioc_cb_firmware_lock(struct bfa_ioc_s *ioc)
{
return BFA_TRUE;
}
static void
bfa_ioc_cb_firmware_unlock(struct bfa_ioc_s *ioc)
{
}
/*
* Notify other functions on HB failure.
*/
static void
bfa_ioc_cb_notify_fail(struct bfa_ioc_s *ioc)
{
writel(~0U, ioc->ioc_regs.err_set);
readl(ioc->ioc_regs.err_set);
}
/*
* Host to LPU mailbox message addresses
*/
static struct { u32 hfn_mbox, lpu_mbox, hfn_pgn; } iocreg_fnreg[] = {
{ HOSTFN0_LPU_MBOX0_0, LPU_HOSTFN0_MBOX0_0, HOST_PAGE_NUM_FN0 },
{ HOSTFN1_LPU_MBOX0_8, LPU_HOSTFN1_MBOX0_8, HOST_PAGE_NUM_FN1 }
};
/*
* Host <-> LPU mailbox command/status registers
*/
static struct { u32 hfn, lpu; } iocreg_mbcmd[] = {
{ HOSTFN0_LPU0_CMD_STAT, LPU0_HOSTFN0_CMD_STAT },
{ HOSTFN1_LPU1_CMD_STAT, LPU1_HOSTFN1_CMD_STAT }
};
static void
bfa_ioc_cb_reg_init(struct bfa_ioc_s *ioc)
{
void __iomem *rb;
int pcifn = bfa_ioc_pcifn(ioc);
rb = bfa_ioc_bar0(ioc);
ioc->ioc_regs.hfn_mbox = rb + iocreg_fnreg[pcifn].hfn_mbox;
ioc->ioc_regs.lpu_mbox = rb + iocreg_fnreg[pcifn].lpu_mbox;
ioc->ioc_regs.host_page_num_fn = rb + iocreg_fnreg[pcifn].hfn_pgn;
if (ioc->port_id == 0) {
ioc->ioc_regs.heartbeat = rb + BFA_IOC0_HBEAT_REG;
ioc->ioc_regs.ioc_fwstate = rb + BFA_IOC0_STATE_REG;
ioc->ioc_regs.alt_ioc_fwstate = rb + BFA_IOC1_STATE_REG;
} else {
ioc->ioc_regs.heartbeat = (rb + BFA_IOC1_HBEAT_REG);
ioc->ioc_regs.ioc_fwstate = (rb + BFA_IOC1_STATE_REG);
ioc->ioc_regs.alt_ioc_fwstate = (rb + BFA_IOC0_STATE_REG);
}
/*
* Host <-> LPU mailbox command/status registers
*/
ioc->ioc_regs.hfn_mbox_cmd = rb + iocreg_mbcmd[pcifn].hfn;
ioc->ioc_regs.lpu_mbox_cmd = rb + iocreg_mbcmd[pcifn].lpu;
/*
* PSS control registers
*/
ioc->ioc_regs.pss_ctl_reg = (rb + PSS_CTL_REG);
ioc->ioc_regs.pss_err_status_reg = (rb + PSS_ERR_STATUS_REG);
ioc->ioc_regs.app_pll_fast_ctl_reg = (rb + APP_PLL_LCLK_CTL_REG);
ioc->ioc_regs.app_pll_slow_ctl_reg = (rb + APP_PLL_SCLK_CTL_REG);
/*
* IOC semaphore registers and serialization
*/
ioc->ioc_regs.ioc_sem_reg = (rb + HOST_SEM0_REG);
ioc->ioc_regs.ioc_init_sem_reg = (rb + HOST_SEM2_REG);
/*
* sram memory access
*/
ioc->ioc_regs.smem_page_start = (rb + PSS_SMEM_PAGE_START);
ioc->ioc_regs.smem_pg0 = BFI_IOC_SMEM_PG0_CB;
/*
* err set reg : for notification of hb failure
*/
ioc->ioc_regs.err_set = (rb + ERR_SET_REG);
}
/*
* Initialize IOC to port mapping.
*/
static void
bfa_ioc_cb_map_port(struct bfa_ioc_s *ioc)
{
/*
* For crossbow, port id is same as pci function.
*/
ioc->port_id = bfa_ioc_pcifn(ioc);
bfa_trc(ioc, ioc->port_id);
}
/*
* Set interrupt mode for a function: INTX or MSIX
*/
static void
bfa_ioc_cb_isr_mode_set(struct bfa_ioc_s *ioc, bfa_boolean_t msix)
{
}
/*
* Synchronized IOC failure processing routines
*/
static bfa_boolean_t
bfa_ioc_cb_sync_start(struct bfa_ioc_s *ioc)
{
return bfa_ioc_cb_sync_complete(ioc);
}
/*
* Cleanup hw semaphore and usecnt registers
*/
static void
bfa_ioc_cb_ownership_reset(struct bfa_ioc_s *ioc)
{
/*
* Read the hw sem reg to make sure that it is locked
* before we clear it. If it is not locked, writing 1
* will lock it instead of clearing it.
*/
readl(ioc->ioc_regs.ioc_sem_reg);
writel(1, ioc->ioc_regs.ioc_sem_reg);
}
/*
* Synchronized IOC failure processing routines
*/
static void
bfa_ioc_cb_sync_join(struct bfa_ioc_s *ioc)
{
}
static void
bfa_ioc_cb_sync_leave(struct bfa_ioc_s *ioc)
{
}
static void
bfa_ioc_cb_sync_ack(struct bfa_ioc_s *ioc)
{
writel(BFI_IOC_FAIL, ioc->ioc_regs.ioc_fwstate);
}
static bfa_boolean_t
bfa_ioc_cb_sync_complete(struct bfa_ioc_s *ioc)
{
uint32_t fwstate, alt_fwstate;
fwstate = readl(ioc->ioc_regs.ioc_fwstate);
/*
* At this point, this IOC is hoding the hw sem in the
* start path (fwcheck) OR in the disable/enable path
* OR to check if the other IOC has acknowledged failure.
*
* So, this IOC can be in UNINIT, INITING, DISABLED, FAIL
* or in MEMTEST states. In a normal scenario, this IOC
* can not be in OP state when this function is called.
*
* However, this IOC could still be in OP state when
* the OS driver is starting up, if the OptROM code has
* left it in that state.
*
* If we had marked this IOC's fwstate as BFI_IOC_FAIL
* in the failure case and now, if the fwstate is not
* BFI_IOC_FAIL it implies that the other PCI fn have
* reinitialized the ASIC or this IOC got disabled, so
* return TRUE.
*/
if (fwstate == BFI_IOC_UNINIT ||
fwstate == BFI_IOC_INITING ||
fwstate == BFI_IOC_DISABLED ||
fwstate == BFI_IOC_MEMTEST ||
fwstate == BFI_IOC_OP)
return BFA_TRUE;
else {
alt_fwstate = readl(ioc->ioc_regs.alt_ioc_fwstate);
if (alt_fwstate == BFI_IOC_FAIL ||
alt_fwstate == BFI_IOC_DISABLED ||
alt_fwstate == BFI_IOC_UNINIT ||
alt_fwstate == BFI_IOC_INITING ||
alt_fwstate == BFI_IOC_MEMTEST)
return BFA_TRUE;
else
return BFA_FALSE;
}
}
bfa_status_t
bfa_ioc_cb_pll_init(void __iomem *rb, enum bfi_asic_mode fcmode)
{
u32 pll_sclk, pll_fclk;
pll_sclk = __APP_PLL_SCLK_ENABLE | __APP_PLL_SCLK_LRESETN |
__APP_PLL_SCLK_P0_1(3U) |
__APP_PLL_SCLK_JITLMT0_1(3U) |
__APP_PLL_SCLK_CNTLMT0_1(3U);
pll_fclk = __APP_PLL_LCLK_ENABLE | __APP_PLL_LCLK_LRESETN |
__APP_PLL_LCLK_RSEL200500 | __APP_PLL_LCLK_P0_1(3U) |
__APP_PLL_LCLK_JITLMT0_1(3U) |
__APP_PLL_LCLK_CNTLMT0_1(3U);
writel(BFI_IOC_UNINIT, (rb + BFA_IOC0_STATE_REG));
writel(BFI_IOC_UNINIT, (rb + BFA_IOC1_STATE_REG));
writel(0xffffffffU, (rb + HOSTFN0_INT_MSK));
writel(0xffffffffU, (rb + HOSTFN1_INT_MSK));
writel(0xffffffffU, (rb + HOSTFN0_INT_STATUS));
writel(0xffffffffU, (rb + HOSTFN1_INT_STATUS));
writel(0xffffffffU, (rb + HOSTFN0_INT_MSK));
writel(0xffffffffU, (rb + HOSTFN1_INT_MSK));
writel(__APP_PLL_SCLK_LOGIC_SOFT_RESET, rb + APP_PLL_SCLK_CTL_REG);
writel(__APP_PLL_SCLK_BYPASS | __APP_PLL_SCLK_LOGIC_SOFT_RESET,
rb + APP_PLL_SCLK_CTL_REG);
writel(__APP_PLL_LCLK_LOGIC_SOFT_RESET, rb + APP_PLL_LCLK_CTL_REG);
writel(__APP_PLL_LCLK_BYPASS | __APP_PLL_LCLK_LOGIC_SOFT_RESET,
rb + APP_PLL_LCLK_CTL_REG);
udelay(2);
writel(__APP_PLL_SCLK_LOGIC_SOFT_RESET, rb + APP_PLL_SCLK_CTL_REG);
writel(__APP_PLL_LCLK_LOGIC_SOFT_RESET, rb + APP_PLL_LCLK_CTL_REG);
writel(pll_sclk | __APP_PLL_SCLK_LOGIC_SOFT_RESET,
rb + APP_PLL_SCLK_CTL_REG);
writel(pll_fclk | __APP_PLL_LCLK_LOGIC_SOFT_RESET,
rb + APP_PLL_LCLK_CTL_REG);
udelay(2000);
writel(0xffffffffU, (rb + HOSTFN0_INT_STATUS));
writel(0xffffffffU, (rb + HOSTFN1_INT_STATUS));
writel(pll_sclk, (rb + APP_PLL_SCLK_CTL_REG));
writel(pll_fclk, (rb + APP_PLL_LCLK_CTL_REG));
return BFA_STATUS_OK;
}
| gpl-2.0 |
antaril/AGK-CM-BASED | drivers/tty/hvc/hvc_beat.c | 8667 | 3211 | /*
* Beat hypervisor console driver
*
* (C) Copyright 2006 TOSHIBA CORPORATION
*
* This code is based on drivers/char/hvc_rtas.c:
* (C) Copyright IBM Corporation 2001-2005
* (C) Copyright Red Hat, Inc. 2005
*
* 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 <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/string.h>
#include <linux/console.h>
#include <asm/prom.h>
#include <asm/hvconsole.h>
#include <asm/firmware.h>
#include "hvc_console.h"
extern int64_t beat_get_term_char(uint64_t, uint64_t *, uint64_t *, uint64_t *);
extern int64_t beat_put_term_char(uint64_t, uint64_t, uint64_t, uint64_t);
struct hvc_struct *hvc_beat_dev = NULL;
/* bug: only one queue is available regardless of vtermno */
static int hvc_beat_get_chars(uint32_t vtermno, char *buf, int cnt)
{
static unsigned char q[sizeof(unsigned long) * 2]
__attribute__((aligned(sizeof(unsigned long))));
static int qlen = 0;
u64 got;
again:
if (qlen) {
if (qlen > cnt) {
memcpy(buf, q, cnt);
qlen -= cnt;
memmove(q + cnt, q, qlen);
return cnt;
} else { /* qlen <= cnt */
int r;
memcpy(buf, q, qlen);
r = qlen;
qlen = 0;
return r;
}
}
if (beat_get_term_char(vtermno, &got,
((u64 *)q), ((u64 *)q) + 1) == 0) {
qlen = got;
goto again;
}
return 0;
}
static int hvc_beat_put_chars(uint32_t vtermno, const char *buf, int cnt)
{
unsigned long kb[2];
int rest, nlen;
for (rest = cnt; rest > 0; rest -= nlen) {
nlen = (rest > 16) ? 16 : rest;
memcpy(kb, buf, nlen);
beat_put_term_char(vtermno, nlen, kb[0], kb[1]);
buf += nlen;
}
return cnt;
}
static const struct hv_ops hvc_beat_get_put_ops = {
.get_chars = hvc_beat_get_chars,
.put_chars = hvc_beat_put_chars,
};
static int hvc_beat_useit = 1;
static int hvc_beat_config(char *p)
{
hvc_beat_useit = simple_strtoul(p, NULL, 0);
return 0;
}
static int __init hvc_beat_console_init(void)
{
if (hvc_beat_useit && of_machine_is_compatible("Beat")) {
hvc_instantiate(0, 0, &hvc_beat_get_put_ops);
}
return 0;
}
/* temp */
static int __init hvc_beat_init(void)
{
struct hvc_struct *hp;
if (!firmware_has_feature(FW_FEATURE_BEAT))
return -ENODEV;
hp = hvc_alloc(0, 0, &hvc_beat_get_put_ops, 16);
if (IS_ERR(hp))
return PTR_ERR(hp);
hvc_beat_dev = hp;
return 0;
}
static void __exit hvc_beat_exit(void)
{
if (hvc_beat_dev)
hvc_remove(hvc_beat_dev);
}
module_init(hvc_beat_init);
module_exit(hvc_beat_exit);
__setup("hvc_beat=", hvc_beat_config);
console_initcall(hvc_beat_console_init);
| gpl-2.0 |
qtekfun/kernel_htc_msm8939 | arch/xtensa/boot/lib/zmem.c | 14043 | 1984 | #include <linux/zlib.h>
/* bits taken from ppc */
extern void *avail_ram, *end_avail;
void exit (void)
{
for (;;);
}
void *zalloc(unsigned size)
{
void *p = avail_ram;
size = (size + 7) & -8;
avail_ram += size;
if (avail_ram > end_avail) {
//puts("oops... out of memory\n");
//pause();
exit ();
}
return p;
}
#define HEAD_CRC 2
#define EXTRA_FIELD 4
#define ORIG_NAME 8
#define COMMENT 0x10
#define RESERVED 0xe0
#define DEFLATED 8
void gunzip (void *dst, int dstlen, unsigned char *src, int *lenp)
{
z_stream s;
int r, i, flags;
/* skip header */
i = 10;
flags = src[3];
if (src[2] != DEFLATED || (flags & RESERVED) != 0) {
//puts("bad gzipped data\n");
exit();
}
if ((flags & EXTRA_FIELD) != 0)
i = 12 + src[10] + (src[11] << 8);
if ((flags & ORIG_NAME) != 0)
while (src[i++] != 0)
;
if ((flags & COMMENT) != 0)
while (src[i++] != 0)
;
if ((flags & HEAD_CRC) != 0)
i += 2;
if (i >= *lenp) {
//puts("gunzip: ran out of data in header\n");
exit();
}
s.workspace = zalloc(zlib_inflate_workspacesize());
r = zlib_inflateInit2(&s, -MAX_WBITS);
if (r != Z_OK) {
//puts("inflateInit2 returned "); puthex(r); puts("\n");
exit();
}
s.next_in = src + i;
s.avail_in = *lenp - i;
s.next_out = dst;
s.avail_out = dstlen;
r = zlib_inflate(&s, Z_FINISH);
if (r != Z_OK && r != Z_STREAM_END) {
//puts("inflate returned "); puthex(r); puts("\n");
exit();
}
*lenp = s.next_out - (unsigned char *) dst;
zlib_inflateEnd(&s);
}
| gpl-2.0 |
insop/sched-deadline2 | sound/core/pcm.c | 220 | 32753 | /*
* Digital Audio (PCM) abstract layer
* 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/slab.h>
#include <linux/module.h>
#include <linux/time.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/minors.h>
#include <sound/pcm.h>
#include <sound/control.h>
#include <sound/info.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>, Abramo Bagnara <abramo@alsa-project.org>");
MODULE_DESCRIPTION("Midlevel PCM code for ALSA.");
MODULE_LICENSE("GPL");
static LIST_HEAD(snd_pcm_devices);
static LIST_HEAD(snd_pcm_notify_list);
static DEFINE_MUTEX(register_mutex);
static int snd_pcm_free(struct snd_pcm *pcm);
static int snd_pcm_dev_free(struct snd_device *device);
static int snd_pcm_dev_register(struct snd_device *device);
static int snd_pcm_dev_disconnect(struct snd_device *device);
static struct snd_pcm *snd_pcm_get(struct snd_card *card, int device)
{
struct snd_pcm *pcm;
list_for_each_entry(pcm, &snd_pcm_devices, list) {
if (pcm->card == card && pcm->device == device)
return pcm;
}
return NULL;
}
static int snd_pcm_next(struct snd_card *card, int device)
{
struct snd_pcm *pcm;
list_for_each_entry(pcm, &snd_pcm_devices, list) {
if (pcm->card == card && pcm->device > device)
return pcm->device;
else if (pcm->card->number > card->number)
return -1;
}
return -1;
}
static int snd_pcm_add(struct snd_pcm *newpcm)
{
struct snd_pcm *pcm;
list_for_each_entry(pcm, &snd_pcm_devices, list) {
if (pcm->card == newpcm->card && pcm->device == newpcm->device)
return -EBUSY;
if (pcm->card->number > newpcm->card->number ||
(pcm->card == newpcm->card &&
pcm->device > newpcm->device)) {
list_add(&newpcm->list, pcm->list.prev);
return 0;
}
}
list_add_tail(&newpcm->list, &snd_pcm_devices);
return 0;
}
static int snd_pcm_control_ioctl(struct snd_card *card,
struct snd_ctl_file *control,
unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case SNDRV_CTL_IOCTL_PCM_NEXT_DEVICE:
{
int device;
if (get_user(device, (int __user *)arg))
return -EFAULT;
mutex_lock(®ister_mutex);
device = snd_pcm_next(card, device);
mutex_unlock(®ister_mutex);
if (put_user(device, (int __user *)arg))
return -EFAULT;
return 0;
}
case SNDRV_CTL_IOCTL_PCM_INFO:
{
struct snd_pcm_info __user *info;
unsigned int device, subdevice;
int stream;
struct snd_pcm *pcm;
struct snd_pcm_str *pstr;
struct snd_pcm_substream *substream;
int err;
info = (struct snd_pcm_info __user *)arg;
if (get_user(device, &info->device))
return -EFAULT;
if (get_user(stream, &info->stream))
return -EFAULT;
if (stream < 0 || stream > 1)
return -EINVAL;
if (get_user(subdevice, &info->subdevice))
return -EFAULT;
mutex_lock(®ister_mutex);
pcm = snd_pcm_get(card, device);
if (pcm == NULL) {
err = -ENXIO;
goto _error;
}
pstr = &pcm->streams[stream];
if (pstr->substream_count == 0) {
err = -ENOENT;
goto _error;
}
if (subdevice >= pstr->substream_count) {
err = -ENXIO;
goto _error;
}
for (substream = pstr->substream; substream;
substream = substream->next)
if (substream->number == (int)subdevice)
break;
if (substream == NULL) {
err = -ENXIO;
goto _error;
}
err = snd_pcm_info_user(substream, info);
_error:
mutex_unlock(®ister_mutex);
return err;
}
case SNDRV_CTL_IOCTL_PCM_PREFER_SUBDEVICE:
{
int val;
if (get_user(val, (int __user *)arg))
return -EFAULT;
control->prefer_pcm_subdevice = val;
return 0;
}
}
return -ENOIOCTLCMD;
}
#define FORMAT(v) [SNDRV_PCM_FORMAT_##v] = #v
static char *snd_pcm_format_names[] = {
FORMAT(S8),
FORMAT(U8),
FORMAT(S16_LE),
FORMAT(S16_BE),
FORMAT(U16_LE),
FORMAT(U16_BE),
FORMAT(S24_LE),
FORMAT(S24_BE),
FORMAT(U24_LE),
FORMAT(U24_BE),
FORMAT(S32_LE),
FORMAT(S32_BE),
FORMAT(U32_LE),
FORMAT(U32_BE),
FORMAT(FLOAT_LE),
FORMAT(FLOAT_BE),
FORMAT(FLOAT64_LE),
FORMAT(FLOAT64_BE),
FORMAT(IEC958_SUBFRAME_LE),
FORMAT(IEC958_SUBFRAME_BE),
FORMAT(MU_LAW),
FORMAT(A_LAW),
FORMAT(IMA_ADPCM),
FORMAT(MPEG),
FORMAT(GSM),
FORMAT(SPECIAL),
FORMAT(S24_3LE),
FORMAT(S24_3BE),
FORMAT(U24_3LE),
FORMAT(U24_3BE),
FORMAT(S20_3LE),
FORMAT(S20_3BE),
FORMAT(U20_3LE),
FORMAT(U20_3BE),
FORMAT(S18_3LE),
FORMAT(S18_3BE),
FORMAT(U18_3LE),
FORMAT(U18_3BE),
FORMAT(G723_24),
FORMAT(G723_24_1B),
FORMAT(G723_40),
FORMAT(G723_40_1B),
};
const char *snd_pcm_format_name(snd_pcm_format_t format)
{
if ((__force unsigned int)format >= ARRAY_SIZE(snd_pcm_format_names))
return "Unknown";
return snd_pcm_format_names[(__force unsigned int)format];
}
EXPORT_SYMBOL_GPL(snd_pcm_format_name);
#ifdef CONFIG_SND_VERBOSE_PROCFS
#define STATE(v) [SNDRV_PCM_STATE_##v] = #v
#define STREAM(v) [SNDRV_PCM_STREAM_##v] = #v
#define READY(v) [SNDRV_PCM_READY_##v] = #v
#define XRUN(v) [SNDRV_PCM_XRUN_##v] = #v
#define SILENCE(v) [SNDRV_PCM_SILENCE_##v] = #v
#define TSTAMP(v) [SNDRV_PCM_TSTAMP_##v] = #v
#define ACCESS(v) [SNDRV_PCM_ACCESS_##v] = #v
#define START(v) [SNDRV_PCM_START_##v] = #v
#define SUBFORMAT(v) [SNDRV_PCM_SUBFORMAT_##v] = #v
static char *snd_pcm_stream_names[] = {
STREAM(PLAYBACK),
STREAM(CAPTURE),
};
static char *snd_pcm_state_names[] = {
STATE(OPEN),
STATE(SETUP),
STATE(PREPARED),
STATE(RUNNING),
STATE(XRUN),
STATE(DRAINING),
STATE(PAUSED),
STATE(SUSPENDED),
};
static char *snd_pcm_access_names[] = {
ACCESS(MMAP_INTERLEAVED),
ACCESS(MMAP_NONINTERLEAVED),
ACCESS(MMAP_COMPLEX),
ACCESS(RW_INTERLEAVED),
ACCESS(RW_NONINTERLEAVED),
};
static char *snd_pcm_subformat_names[] = {
SUBFORMAT(STD),
};
static char *snd_pcm_tstamp_mode_names[] = {
TSTAMP(NONE),
TSTAMP(ENABLE),
};
static const char *snd_pcm_stream_name(int stream)
{
return snd_pcm_stream_names[stream];
}
static const char *snd_pcm_access_name(snd_pcm_access_t access)
{
return snd_pcm_access_names[(__force int)access];
}
static const char *snd_pcm_subformat_name(snd_pcm_subformat_t subformat)
{
return snd_pcm_subformat_names[(__force int)subformat];
}
static const char *snd_pcm_tstamp_mode_name(int mode)
{
return snd_pcm_tstamp_mode_names[mode];
}
static const char *snd_pcm_state_name(snd_pcm_state_t state)
{
return snd_pcm_state_names[(__force int)state];
}
#if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
#include <linux/soundcard.h>
static const char *snd_pcm_oss_format_name(int format)
{
switch (format) {
case AFMT_MU_LAW:
return "MU_LAW";
case AFMT_A_LAW:
return "A_LAW";
case AFMT_IMA_ADPCM:
return "IMA_ADPCM";
case AFMT_U8:
return "U8";
case AFMT_S16_LE:
return "S16_LE";
case AFMT_S16_BE:
return "S16_BE";
case AFMT_S8:
return "S8";
case AFMT_U16_LE:
return "U16_LE";
case AFMT_U16_BE:
return "U16_BE";
case AFMT_MPEG:
return "MPEG";
default:
return "unknown";
}
}
#endif
static void snd_pcm_proc_info_read(struct snd_pcm_substream *substream,
struct snd_info_buffer *buffer)
{
struct snd_pcm_info *info;
int err;
if (! substream)
return;
info = kmalloc(sizeof(*info), GFP_KERNEL);
if (! info) {
printk(KERN_DEBUG "snd_pcm_proc_info_read: cannot malloc\n");
return;
}
err = snd_pcm_info(substream, info);
if (err < 0) {
snd_iprintf(buffer, "error %d\n", err);
kfree(info);
return;
}
snd_iprintf(buffer, "card: %d\n", info->card);
snd_iprintf(buffer, "device: %d\n", info->device);
snd_iprintf(buffer, "subdevice: %d\n", info->subdevice);
snd_iprintf(buffer, "stream: %s\n", snd_pcm_stream_name(info->stream));
snd_iprintf(buffer, "id: %s\n", info->id);
snd_iprintf(buffer, "name: %s\n", info->name);
snd_iprintf(buffer, "subname: %s\n", info->subname);
snd_iprintf(buffer, "class: %d\n", info->dev_class);
snd_iprintf(buffer, "subclass: %d\n", info->dev_subclass);
snd_iprintf(buffer, "subdevices_count: %d\n", info->subdevices_count);
snd_iprintf(buffer, "subdevices_avail: %d\n", info->subdevices_avail);
kfree(info);
}
static void snd_pcm_stream_proc_info_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
snd_pcm_proc_info_read(((struct snd_pcm_str *)entry->private_data)->substream,
buffer);
}
static void snd_pcm_substream_proc_info_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
snd_pcm_proc_info_read(entry->private_data, buffer);
}
static void snd_pcm_substream_proc_hw_params_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm_substream *substream = entry->private_data;
struct snd_pcm_runtime *runtime;
mutex_lock(&substream->pcm->open_mutex);
runtime = substream->runtime;
if (!runtime) {
snd_iprintf(buffer, "closed\n");
goto unlock;
}
if (runtime->status->state == SNDRV_PCM_STATE_OPEN) {
snd_iprintf(buffer, "no setup\n");
goto unlock;
}
snd_iprintf(buffer, "access: %s\n", snd_pcm_access_name(runtime->access));
snd_iprintf(buffer, "format: %s\n", snd_pcm_format_name(runtime->format));
snd_iprintf(buffer, "subformat: %s\n", snd_pcm_subformat_name(runtime->subformat));
snd_iprintf(buffer, "channels: %u\n", runtime->channels);
snd_iprintf(buffer, "rate: %u (%u/%u)\n", runtime->rate, runtime->rate_num, runtime->rate_den);
snd_iprintf(buffer, "period_size: %lu\n", runtime->period_size);
snd_iprintf(buffer, "buffer_size: %lu\n", runtime->buffer_size);
#if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
if (substream->oss.oss) {
snd_iprintf(buffer, "OSS format: %s\n", snd_pcm_oss_format_name(runtime->oss.format));
snd_iprintf(buffer, "OSS channels: %u\n", runtime->oss.channels);
snd_iprintf(buffer, "OSS rate: %u\n", runtime->oss.rate);
snd_iprintf(buffer, "OSS period bytes: %lu\n", (unsigned long)runtime->oss.period_bytes);
snd_iprintf(buffer, "OSS periods: %u\n", runtime->oss.periods);
snd_iprintf(buffer, "OSS period frames: %lu\n", (unsigned long)runtime->oss.period_frames);
}
#endif
unlock:
mutex_unlock(&substream->pcm->open_mutex);
}
static void snd_pcm_substream_proc_sw_params_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm_substream *substream = entry->private_data;
struct snd_pcm_runtime *runtime;
mutex_lock(&substream->pcm->open_mutex);
runtime = substream->runtime;
if (!runtime) {
snd_iprintf(buffer, "closed\n");
goto unlock;
}
if (runtime->status->state == SNDRV_PCM_STATE_OPEN) {
snd_iprintf(buffer, "no setup\n");
goto unlock;
}
snd_iprintf(buffer, "tstamp_mode: %s\n", snd_pcm_tstamp_mode_name(runtime->tstamp_mode));
snd_iprintf(buffer, "period_step: %u\n", runtime->period_step);
snd_iprintf(buffer, "avail_min: %lu\n", runtime->control->avail_min);
snd_iprintf(buffer, "start_threshold: %lu\n", runtime->start_threshold);
snd_iprintf(buffer, "stop_threshold: %lu\n", runtime->stop_threshold);
snd_iprintf(buffer, "silence_threshold: %lu\n", runtime->silence_threshold);
snd_iprintf(buffer, "silence_size: %lu\n", runtime->silence_size);
snd_iprintf(buffer, "boundary: %lu\n", runtime->boundary);
unlock:
mutex_unlock(&substream->pcm->open_mutex);
}
static void snd_pcm_substream_proc_status_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm_substream *substream = entry->private_data;
struct snd_pcm_runtime *runtime;
struct snd_pcm_status status;
int err;
mutex_lock(&substream->pcm->open_mutex);
runtime = substream->runtime;
if (!runtime) {
snd_iprintf(buffer, "closed\n");
goto unlock;
}
memset(&status, 0, sizeof(status));
err = snd_pcm_status(substream, &status);
if (err < 0) {
snd_iprintf(buffer, "error %d\n", err);
goto unlock;
}
snd_iprintf(buffer, "state: %s\n", snd_pcm_state_name(status.state));
snd_iprintf(buffer, "owner_pid : %d\n", pid_vnr(substream->pid));
snd_iprintf(buffer, "trigger_time: %ld.%09ld\n",
status.trigger_tstamp.tv_sec, status.trigger_tstamp.tv_nsec);
snd_iprintf(buffer, "tstamp : %ld.%09ld\n",
status.tstamp.tv_sec, status.tstamp.tv_nsec);
snd_iprintf(buffer, "delay : %ld\n", status.delay);
snd_iprintf(buffer, "avail : %ld\n", status.avail);
snd_iprintf(buffer, "avail_max : %ld\n", status.avail_max);
snd_iprintf(buffer, "-----\n");
snd_iprintf(buffer, "hw_ptr : %ld\n", runtime->status->hw_ptr);
snd_iprintf(buffer, "appl_ptr : %ld\n", runtime->control->appl_ptr);
unlock:
mutex_unlock(&substream->pcm->open_mutex);
}
#ifdef CONFIG_SND_PCM_XRUN_DEBUG
static void snd_pcm_xrun_debug_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm_str *pstr = entry->private_data;
snd_iprintf(buffer, "%d\n", pstr->xrun_debug);
}
static void snd_pcm_xrun_debug_write(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm_str *pstr = entry->private_data;
char line[64];
if (!snd_info_get_line(buffer, line, sizeof(line)))
pstr->xrun_debug = simple_strtoul(line, NULL, 10);
}
#endif
static int snd_pcm_stream_proc_init(struct snd_pcm_str *pstr)
{
struct snd_pcm *pcm = pstr->pcm;
struct snd_info_entry *entry;
char name[16];
sprintf(name, "pcm%i%c", pcm->device,
pstr->stream == SNDRV_PCM_STREAM_PLAYBACK ? 'p' : 'c');
if ((entry = snd_info_create_card_entry(pcm->card, name, pcm->card->proc_root)) == NULL)
return -ENOMEM;
entry->mode = S_IFDIR | S_IRUGO | S_IXUGO;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
return -ENOMEM;
}
pstr->proc_root = entry;
if ((entry = snd_info_create_card_entry(pcm->card, "info", pstr->proc_root)) != NULL) {
snd_info_set_text_ops(entry, pstr, snd_pcm_stream_proc_info_read);
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
pstr->proc_info_entry = entry;
#ifdef CONFIG_SND_PCM_XRUN_DEBUG
if ((entry = snd_info_create_card_entry(pcm->card, "xrun_debug",
pstr->proc_root)) != NULL) {
entry->c.text.read = snd_pcm_xrun_debug_read;
entry->c.text.write = snd_pcm_xrun_debug_write;
entry->mode |= S_IWUSR;
entry->private_data = pstr;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
pstr->proc_xrun_debug_entry = entry;
#endif
return 0;
}
static int snd_pcm_stream_proc_done(struct snd_pcm_str *pstr)
{
#ifdef CONFIG_SND_PCM_XRUN_DEBUG
snd_info_free_entry(pstr->proc_xrun_debug_entry);
pstr->proc_xrun_debug_entry = NULL;
#endif
snd_info_free_entry(pstr->proc_info_entry);
pstr->proc_info_entry = NULL;
snd_info_free_entry(pstr->proc_root);
pstr->proc_root = NULL;
return 0;
}
static int snd_pcm_substream_proc_init(struct snd_pcm_substream *substream)
{
struct snd_info_entry *entry;
struct snd_card *card;
char name[16];
card = substream->pcm->card;
sprintf(name, "sub%i", substream->number);
if ((entry = snd_info_create_card_entry(card, name, substream->pstr->proc_root)) == NULL)
return -ENOMEM;
entry->mode = S_IFDIR | S_IRUGO | S_IXUGO;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
return -ENOMEM;
}
substream->proc_root = entry;
if ((entry = snd_info_create_card_entry(card, "info", substream->proc_root)) != NULL) {
snd_info_set_text_ops(entry, substream,
snd_pcm_substream_proc_info_read);
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
substream->proc_info_entry = entry;
if ((entry = snd_info_create_card_entry(card, "hw_params", substream->proc_root)) != NULL) {
snd_info_set_text_ops(entry, substream,
snd_pcm_substream_proc_hw_params_read);
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
substream->proc_hw_params_entry = entry;
if ((entry = snd_info_create_card_entry(card, "sw_params", substream->proc_root)) != NULL) {
snd_info_set_text_ops(entry, substream,
snd_pcm_substream_proc_sw_params_read);
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
substream->proc_sw_params_entry = entry;
if ((entry = snd_info_create_card_entry(card, "status", substream->proc_root)) != NULL) {
snd_info_set_text_ops(entry, substream,
snd_pcm_substream_proc_status_read);
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
substream->proc_status_entry = entry;
return 0;
}
static int snd_pcm_substream_proc_done(struct snd_pcm_substream *substream)
{
snd_info_free_entry(substream->proc_info_entry);
substream->proc_info_entry = NULL;
snd_info_free_entry(substream->proc_hw_params_entry);
substream->proc_hw_params_entry = NULL;
snd_info_free_entry(substream->proc_sw_params_entry);
substream->proc_sw_params_entry = NULL;
snd_info_free_entry(substream->proc_status_entry);
substream->proc_status_entry = NULL;
snd_info_free_entry(substream->proc_root);
substream->proc_root = NULL;
return 0;
}
#else /* !CONFIG_SND_VERBOSE_PROCFS */
static inline int snd_pcm_stream_proc_init(struct snd_pcm_str *pstr) { return 0; }
static inline int snd_pcm_stream_proc_done(struct snd_pcm_str *pstr) { return 0; }
static inline int snd_pcm_substream_proc_init(struct snd_pcm_substream *substream) { return 0; }
static inline int snd_pcm_substream_proc_done(struct snd_pcm_substream *substream) { return 0; }
#endif /* CONFIG_SND_VERBOSE_PROCFS */
/**
* snd_pcm_new_stream - create a new PCM stream
* @pcm: the pcm instance
* @stream: the stream direction, SNDRV_PCM_STREAM_XXX
* @substream_count: the number of substreams
*
* Creates a new stream for the pcm.
* The corresponding stream on the pcm must have been empty before
* calling this, i.e. zero must be given to the argument of
* snd_pcm_new().
*
* Returns zero if successful, or a negative error code on failure.
*/
int snd_pcm_new_stream(struct snd_pcm *pcm, int stream, int substream_count)
{
int idx, err;
struct snd_pcm_str *pstr = &pcm->streams[stream];
struct snd_pcm_substream *substream, *prev;
#if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
mutex_init(&pstr->oss.setup_mutex);
#endif
pstr->stream = stream;
pstr->pcm = pcm;
pstr->substream_count = substream_count;
if (substream_count > 0) {
err = snd_pcm_stream_proc_init(pstr);
if (err < 0) {
snd_printk(KERN_ERR "Error in snd_pcm_stream_proc_init\n");
return err;
}
}
prev = NULL;
for (idx = 0, prev = NULL; idx < substream_count; idx++) {
substream = kzalloc(sizeof(*substream), GFP_KERNEL);
if (substream == NULL) {
snd_printk(KERN_ERR "Cannot allocate PCM substream\n");
return -ENOMEM;
}
substream->pcm = pcm;
substream->pstr = pstr;
substream->number = idx;
substream->stream = stream;
sprintf(substream->name, "subdevice #%i", idx);
substream->buffer_bytes_max = UINT_MAX;
if (prev == NULL)
pstr->substream = substream;
else
prev->next = substream;
err = snd_pcm_substream_proc_init(substream);
if (err < 0) {
snd_printk(KERN_ERR "Error in snd_pcm_stream_proc_init\n");
if (prev == NULL)
pstr->substream = NULL;
else
prev->next = NULL;
kfree(substream);
return err;
}
substream->group = &substream->self_group;
spin_lock_init(&substream->self_group.lock);
INIT_LIST_HEAD(&substream->self_group.substreams);
list_add_tail(&substream->link_list, &substream->self_group.substreams);
atomic_set(&substream->mmap_count, 0);
prev = substream;
}
return 0;
}
EXPORT_SYMBOL(snd_pcm_new_stream);
/**
* snd_pcm_new - create a new PCM instance
* @card: the card instance
* @id: the id string
* @device: the device index (zero based)
* @playback_count: the number of substreams for playback
* @capture_count: the number of substreams for capture
* @rpcm: the pointer to store the new pcm instance
*
* Creates a new PCM instance.
*
* The pcm operators have to be set afterwards to the new instance
* via snd_pcm_set_ops().
*
* Returns zero if successful, or a negative error code on failure.
*/
int snd_pcm_new(struct snd_card *card, const char *id, int device,
int playback_count, int capture_count,
struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_pcm_dev_free,
.dev_register = snd_pcm_dev_register,
.dev_disconnect = snd_pcm_dev_disconnect,
};
if (snd_BUG_ON(!card))
return -ENXIO;
if (rpcm)
*rpcm = NULL;
pcm = kzalloc(sizeof(*pcm), GFP_KERNEL);
if (pcm == NULL) {
snd_printk(KERN_ERR "Cannot allocate PCM\n");
return -ENOMEM;
}
pcm->card = card;
pcm->device = device;
if (id)
strlcpy(pcm->id, id, sizeof(pcm->id));
if ((err = snd_pcm_new_stream(pcm, SNDRV_PCM_STREAM_PLAYBACK, playback_count)) < 0) {
snd_pcm_free(pcm);
return err;
}
if ((err = snd_pcm_new_stream(pcm, SNDRV_PCM_STREAM_CAPTURE, capture_count)) < 0) {
snd_pcm_free(pcm);
return err;
}
mutex_init(&pcm->open_mutex);
init_waitqueue_head(&pcm->open_wait);
if ((err = snd_device_new(card, SNDRV_DEV_PCM, pcm, &ops)) < 0) {
snd_pcm_free(pcm);
return err;
}
if (rpcm)
*rpcm = pcm;
return 0;
}
EXPORT_SYMBOL(snd_pcm_new);
static void snd_pcm_free_stream(struct snd_pcm_str * pstr)
{
struct snd_pcm_substream *substream, *substream_next;
#if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
struct snd_pcm_oss_setup *setup, *setupn;
#endif
substream = pstr->substream;
while (substream) {
substream_next = substream->next;
snd_pcm_timer_done(substream);
snd_pcm_substream_proc_done(substream);
kfree(substream);
substream = substream_next;
}
snd_pcm_stream_proc_done(pstr);
#if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
for (setup = pstr->oss.setup_list; setup; setup = setupn) {
setupn = setup->next;
kfree(setup->task_name);
kfree(setup);
}
#endif
}
static int snd_pcm_free(struct snd_pcm *pcm)
{
struct snd_pcm_notify *notify;
if (!pcm)
return 0;
list_for_each_entry(notify, &snd_pcm_notify_list, list) {
notify->n_unregister(pcm);
}
if (pcm->private_free)
pcm->private_free(pcm);
snd_pcm_lib_preallocate_free_for_all(pcm);
snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_PLAYBACK]);
snd_pcm_free_stream(&pcm->streams[SNDRV_PCM_STREAM_CAPTURE]);
kfree(pcm);
return 0;
}
static int snd_pcm_dev_free(struct snd_device *device)
{
struct snd_pcm *pcm = device->device_data;
return snd_pcm_free(pcm);
}
int snd_pcm_attach_substream(struct snd_pcm *pcm, int stream,
struct file *file,
struct snd_pcm_substream **rsubstream)
{
struct snd_pcm_str * pstr;
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
struct snd_ctl_file *kctl;
struct snd_card *card;
int prefer_subdevice = -1;
size_t size;
if (snd_BUG_ON(!pcm || !rsubstream))
return -ENXIO;
*rsubstream = NULL;
pstr = &pcm->streams[stream];
if (pstr->substream == NULL || pstr->substream_count == 0)
return -ENODEV;
card = pcm->card;
read_lock(&card->ctl_files_rwlock);
list_for_each_entry(kctl, &card->ctl_files, list) {
if (kctl->pid == task_pid(current)) {
prefer_subdevice = kctl->prefer_pcm_subdevice;
if (prefer_subdevice != -1)
break;
}
}
read_unlock(&card->ctl_files_rwlock);
switch (stream) {
case SNDRV_PCM_STREAM_PLAYBACK:
if (pcm->info_flags & SNDRV_PCM_INFO_HALF_DUPLEX) {
for (substream = pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream; substream; substream = substream->next) {
if (SUBSTREAM_BUSY(substream))
return -EAGAIN;
}
}
break;
case SNDRV_PCM_STREAM_CAPTURE:
if (pcm->info_flags & SNDRV_PCM_INFO_HALF_DUPLEX) {
for (substream = pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream; substream; substream = substream->next) {
if (SUBSTREAM_BUSY(substream))
return -EAGAIN;
}
}
break;
default:
return -EINVAL;
}
if (file->f_flags & O_APPEND) {
if (prefer_subdevice < 0) {
if (pstr->substream_count > 1)
return -EINVAL; /* must be unique */
substream = pstr->substream;
} else {
for (substream = pstr->substream; substream;
substream = substream->next)
if (substream->number == prefer_subdevice)
break;
}
if (! substream)
return -ENODEV;
if (! SUBSTREAM_BUSY(substream))
return -EBADFD;
substream->ref_count++;
*rsubstream = substream;
return 0;
}
if (prefer_subdevice >= 0) {
for (substream = pstr->substream; substream; substream = substream->next)
if (!SUBSTREAM_BUSY(substream) && substream->number == prefer_subdevice)
goto __ok;
}
for (substream = pstr->substream; substream; substream = substream->next)
if (!SUBSTREAM_BUSY(substream))
break;
__ok:
if (substream == NULL)
return -EAGAIN;
runtime = kzalloc(sizeof(*runtime), GFP_KERNEL);
if (runtime == NULL)
return -ENOMEM;
size = PAGE_ALIGN(sizeof(struct snd_pcm_mmap_status));
runtime->status = snd_malloc_pages(size, GFP_KERNEL);
if (runtime->status == NULL) {
kfree(runtime);
return -ENOMEM;
}
memset((void*)runtime->status, 0, size);
size = PAGE_ALIGN(sizeof(struct snd_pcm_mmap_control));
runtime->control = snd_malloc_pages(size, GFP_KERNEL);
if (runtime->control == NULL) {
snd_free_pages((void*)runtime->status,
PAGE_ALIGN(sizeof(struct snd_pcm_mmap_status)));
kfree(runtime);
return -ENOMEM;
}
memset((void*)runtime->control, 0, size);
init_waitqueue_head(&runtime->sleep);
init_waitqueue_head(&runtime->tsleep);
runtime->status->state = SNDRV_PCM_STATE_OPEN;
substream->runtime = runtime;
substream->private_data = pcm->private_data;
substream->ref_count = 1;
substream->f_flags = file->f_flags;
substream->pid = get_pid(task_pid(current));
pstr->substream_opened++;
*rsubstream = substream;
return 0;
}
void snd_pcm_detach_substream(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime;
if (PCM_RUNTIME_CHECK(substream))
return;
runtime = substream->runtime;
if (runtime->private_free != NULL)
runtime->private_free(runtime);
snd_free_pages((void*)runtime->status,
PAGE_ALIGN(sizeof(struct snd_pcm_mmap_status)));
snd_free_pages((void*)runtime->control,
PAGE_ALIGN(sizeof(struct snd_pcm_mmap_control)));
kfree(runtime->hw_constraints.rules);
#ifdef CONFIG_SND_PCM_XRUN_DEBUG
if (runtime->hwptr_log)
kfree(runtime->hwptr_log);
#endif
kfree(runtime);
substream->runtime = NULL;
put_pid(substream->pid);
substream->pid = NULL;
substream->pstr->substream_opened--;
}
static ssize_t show_pcm_class(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct snd_pcm *pcm;
const char *str;
static const char *strs[SNDRV_PCM_CLASS_LAST + 1] = {
[SNDRV_PCM_CLASS_GENERIC] = "generic",
[SNDRV_PCM_CLASS_MULTI] = "multi",
[SNDRV_PCM_CLASS_MODEM] = "modem",
[SNDRV_PCM_CLASS_DIGITIZER] = "digitizer",
};
if (! (pcm = dev_get_drvdata(dev)) ||
pcm->dev_class > SNDRV_PCM_CLASS_LAST)
str = "none";
else
str = strs[pcm->dev_class];
return snprintf(buf, PAGE_SIZE, "%s\n", str);
}
static struct device_attribute pcm_attrs =
__ATTR(pcm_class, S_IRUGO, show_pcm_class, NULL);
static int snd_pcm_dev_register(struct snd_device *device)
{
int cidx, err;
struct snd_pcm_substream *substream;
struct snd_pcm_notify *notify;
char str[16];
struct snd_pcm *pcm;
struct device *dev;
if (snd_BUG_ON(!device || !device->device_data))
return -ENXIO;
pcm = device->device_data;
mutex_lock(®ister_mutex);
err = snd_pcm_add(pcm);
if (err) {
mutex_unlock(®ister_mutex);
return err;
}
for (cidx = 0; cidx < 2; cidx++) {
int devtype = -1;
if (pcm->streams[cidx].substream == NULL)
continue;
switch (cidx) {
case SNDRV_PCM_STREAM_PLAYBACK:
sprintf(str, "pcmC%iD%ip", pcm->card->number, pcm->device);
devtype = SNDRV_DEVICE_TYPE_PCM_PLAYBACK;
break;
case SNDRV_PCM_STREAM_CAPTURE:
sprintf(str, "pcmC%iD%ic", pcm->card->number, pcm->device);
devtype = SNDRV_DEVICE_TYPE_PCM_CAPTURE;
break;
}
/* device pointer to use, pcm->dev takes precedence if
* it is assigned, otherwise fall back to card's device
* if possible */
dev = pcm->dev;
if (!dev)
dev = snd_card_get_device_link(pcm->card);
/* register pcm */
err = snd_register_device_for_dev(devtype, pcm->card,
pcm->device,
&snd_pcm_f_ops[cidx],
pcm, str, dev);
if (err < 0) {
list_del(&pcm->list);
mutex_unlock(®ister_mutex);
return err;
}
snd_add_device_sysfs_file(devtype, pcm->card, pcm->device,
&pcm_attrs);
for (substream = pcm->streams[cidx].substream; substream; substream = substream->next)
snd_pcm_timer_init(substream);
}
list_for_each_entry(notify, &snd_pcm_notify_list, list)
notify->n_register(pcm);
mutex_unlock(®ister_mutex);
return 0;
}
static int snd_pcm_dev_disconnect(struct snd_device *device)
{
struct snd_pcm *pcm = device->device_data;
struct snd_pcm_notify *notify;
struct snd_pcm_substream *substream;
int cidx, devtype;
mutex_lock(®ister_mutex);
if (list_empty(&pcm->list))
goto unlock;
list_del_init(&pcm->list);
for (cidx = 0; cidx < 2; cidx++)
for (substream = pcm->streams[cidx].substream; substream; substream = substream->next)
if (substream->runtime)
substream->runtime->status->state = SNDRV_PCM_STATE_DISCONNECTED;
list_for_each_entry(notify, &snd_pcm_notify_list, list) {
notify->n_disconnect(pcm);
}
for (cidx = 0; cidx < 2; cidx++) {
devtype = -1;
switch (cidx) {
case SNDRV_PCM_STREAM_PLAYBACK:
devtype = SNDRV_DEVICE_TYPE_PCM_PLAYBACK;
break;
case SNDRV_PCM_STREAM_CAPTURE:
devtype = SNDRV_DEVICE_TYPE_PCM_CAPTURE;
break;
}
snd_unregister_device(devtype, pcm->card, pcm->device);
}
unlock:
mutex_unlock(®ister_mutex);
return 0;
}
int snd_pcm_notify(struct snd_pcm_notify *notify, int nfree)
{
struct snd_pcm *pcm;
if (snd_BUG_ON(!notify ||
!notify->n_register ||
!notify->n_unregister ||
!notify->n_disconnect))
return -EINVAL;
mutex_lock(®ister_mutex);
if (nfree) {
list_del(¬ify->list);
list_for_each_entry(pcm, &snd_pcm_devices, list)
notify->n_unregister(pcm);
} else {
list_add_tail(¬ify->list, &snd_pcm_notify_list);
list_for_each_entry(pcm, &snd_pcm_devices, list)
notify->n_register(pcm);
}
mutex_unlock(®ister_mutex);
return 0;
}
EXPORT_SYMBOL(snd_pcm_notify);
#ifdef CONFIG_PROC_FS
/*
* Info interface
*/
static void snd_pcm_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_pcm *pcm;
mutex_lock(®ister_mutex);
list_for_each_entry(pcm, &snd_pcm_devices, list) {
snd_iprintf(buffer, "%02i-%02i: %s : %s",
pcm->card->number, pcm->device, pcm->id, pcm->name);
if (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream)
snd_iprintf(buffer, " : playback %i",
pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream_count);
if (pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream)
snd_iprintf(buffer, " : capture %i",
pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream_count);
snd_iprintf(buffer, "\n");
}
mutex_unlock(®ister_mutex);
}
static struct snd_info_entry *snd_pcm_proc_entry;
static void snd_pcm_proc_init(void)
{
struct snd_info_entry *entry;
if ((entry = snd_info_create_module_entry(THIS_MODULE, "pcm", NULL)) != NULL) {
snd_info_set_text_ops(entry, NULL, snd_pcm_proc_read);
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
snd_pcm_proc_entry = entry;
}
static void snd_pcm_proc_done(void)
{
snd_info_free_entry(snd_pcm_proc_entry);
}
#else /* !CONFIG_PROC_FS */
#define snd_pcm_proc_init()
#define snd_pcm_proc_done()
#endif /* CONFIG_PROC_FS */
/*
* ENTRY functions
*/
static int __init alsa_pcm_init(void)
{
snd_ctl_register_ioctl(snd_pcm_control_ioctl);
snd_ctl_register_ioctl_compat(snd_pcm_control_ioctl);
snd_pcm_proc_init();
return 0;
}
static void __exit alsa_pcm_exit(void)
{
snd_ctl_unregister_ioctl(snd_pcm_control_ioctl);
snd_ctl_unregister_ioctl_compat(snd_pcm_control_ioctl);
snd_pcm_proc_done();
}
module_init(alsa_pcm_init)
module_exit(alsa_pcm_exit)
| gpl-2.0 |
mathur/rohan.kernel.op3 | sound/soc/pxa/ttc-dkb.c | 476 | 4959 | /*
* linux/sound/soc/pxa/ttc_dkb.c
*
* Copyright (C) 2012 Marvell International Ltd.
*
* 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/module.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/jack.h>
#include <asm/mach-types.h>
#include <sound/pcm_params.h>
#include "../codecs/88pm860x-codec.h"
static struct snd_soc_jack hs_jack, mic_jack;
static struct snd_soc_jack_pin hs_jack_pins[] = {
{ .pin = "Headset Stereophone", .mask = SND_JACK_HEADPHONE, },
};
static struct snd_soc_jack_pin mic_jack_pins[] = {
{ .pin = "Headset Mic 2", .mask = SND_JACK_MICROPHONE, },
};
/* ttc machine dapm widgets */
static const struct snd_soc_dapm_widget ttc_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headset Stereophone", NULL),
SND_SOC_DAPM_LINE("Lineout Out 1", NULL),
SND_SOC_DAPM_LINE("Lineout Out 2", NULL),
SND_SOC_DAPM_SPK("Ext Speaker", NULL),
SND_SOC_DAPM_MIC("Ext Mic 1", NULL),
SND_SOC_DAPM_MIC("Headset Mic 2", NULL),
SND_SOC_DAPM_MIC("Ext Mic 3", NULL),
};
/* ttc machine audio map */
static const struct snd_soc_dapm_route ttc_audio_map[] = {
{"Headset Stereophone", NULL, "HS1"},
{"Headset Stereophone", NULL, "HS2"},
{"Ext Speaker", NULL, "LSP"},
{"Ext Speaker", NULL, "LSN"},
{"Lineout Out 1", NULL, "LINEOUT1"},
{"Lineout Out 2", NULL, "LINEOUT2"},
{"MIC1P", NULL, "Mic1 Bias"},
{"MIC1N", NULL, "Mic1 Bias"},
{"Mic1 Bias", NULL, "Ext Mic 1"},
{"MIC2P", NULL, "Mic1 Bias"},
{"MIC2N", NULL, "Mic1 Bias"},
{"Mic1 Bias", NULL, "Headset Mic 2"},
{"MIC3P", NULL, "Mic3 Bias"},
{"MIC3N", NULL, "Mic3 Bias"},
{"Mic3 Bias", NULL, "Ext Mic 3"},
};
static int ttc_pm860x_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_dapm_disable_pin(dapm, "Headset Mic 2");
snd_soc_dapm_disable_pin(dapm, "Headset Stereophone");
/* Headset jack detection */
snd_soc_jack_new(codec, "Headphone Jack", SND_JACK_HEADPHONE
| SND_JACK_BTN_0 | SND_JACK_BTN_1 | SND_JACK_BTN_2,
&hs_jack);
snd_soc_jack_add_pins(&hs_jack, ARRAY_SIZE(hs_jack_pins),
hs_jack_pins);
snd_soc_jack_new(codec, "Microphone Jack", SND_JACK_MICROPHONE,
&mic_jack);
snd_soc_jack_add_pins(&mic_jack, ARRAY_SIZE(mic_jack_pins),
mic_jack_pins);
/* headphone, microphone detection & headset short detection */
pm860x_hs_jack_detect(codec, &hs_jack, SND_JACK_HEADPHONE,
SND_JACK_BTN_0, SND_JACK_BTN_1, SND_JACK_BTN_2);
pm860x_mic_jack_detect(codec, &hs_jack, SND_JACK_MICROPHONE);
return 0;
}
/* ttc/td-dkb digital audio interface glue - connects codec <--> CPU */
static struct snd_soc_dai_link ttc_pm860x_hifi_dai[] = {
{
.name = "88pm860x i2s",
.stream_name = "audio playback",
.codec_name = "88pm860x-codec",
.platform_name = "mmp-pcm-audio",
.cpu_dai_name = "pxa-ssp-dai.1",
.codec_dai_name = "88pm860x-i2s",
.dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBM_CFM,
.init = ttc_pm860x_init,
},
};
/* ttc/td audio machine driver */
static struct snd_soc_card ttc_dkb_card = {
.name = "ttc-dkb-hifi",
.owner = THIS_MODULE,
.dai_link = ttc_pm860x_hifi_dai,
.num_links = ARRAY_SIZE(ttc_pm860x_hifi_dai),
.dapm_widgets = ttc_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(ttc_dapm_widgets),
.dapm_routes = ttc_audio_map,
.num_dapm_routes = ARRAY_SIZE(ttc_audio_map),
};
static int ttc_dkb_probe(struct platform_device *pdev)
{
struct snd_soc_card *card = &ttc_dkb_card;
int ret;
card->dev = &pdev->dev;
ret = snd_soc_register_card(card);
if (ret)
dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n",
ret);
return ret;
}
static int ttc_dkb_remove(struct platform_device *pdev)
{
struct snd_soc_card *card = platform_get_drvdata(pdev);
snd_soc_unregister_card(card);
return 0;
}
static struct platform_driver ttc_dkb_driver = {
.driver = {
.name = "ttc-dkb-audio",
.owner = THIS_MODULE,
.pm = &snd_soc_pm_ops,
},
.probe = ttc_dkb_probe,
.remove = ttc_dkb_remove,
};
module_platform_driver(ttc_dkb_driver);
/* Module information */
MODULE_AUTHOR("Qiao Zhou, <zhouqiao@marvell.com>");
MODULE_DESCRIPTION("ALSA SoC TTC DKB");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:ttc-dkb-audio");
| gpl-2.0 |
GAXUSXX/GalaxyS7edge_G935F_Kernel | drivers/staging/skein/skein.c | 476 | 29952 | /***********************************************************************
**
** Implementation of the Skein hash function.
**
** Source code author: Doug Whiting, 2008.
**
** This algorithm and source code is released to the public domain.
**
************************************************************************/
#define SKEIN_PORT_CODE /* instantiate any code in skein_port.h */
#include <linux/string.h> /* get the memcpy/memset functions */
#include "skein.h" /* get the Skein API definitions */
#include "skein_iv.h" /* get precomputed IVs */
#include "skein_block.h"
/*****************************************************************/
/* 256-bit Skein */
/*****************************************************************/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a straight hashing operation */
int skein_256_init(struct skein_256_ctx *ctx, size_t hash_bit_len)
{
union {
u8 b[SKEIN_256_STATE_BYTES];
u64 w[SKEIN_256_STATE_WORDS];
} cfg; /* config block */
skein_assert_ret(hash_bit_len > 0, SKEIN_BAD_HASHLEN);
ctx->h.hash_bit_len = hash_bit_len; /* output hash bit count */
switch (hash_bit_len) { /* use pre-computed values, where available */
case 256:
memcpy(ctx->x, SKEIN_256_IV_256, sizeof(ctx->x));
break;
case 224:
memcpy(ctx->x, SKEIN_256_IV_224, sizeof(ctx->x));
break;
case 160:
memcpy(ctx->x, SKEIN_256_IV_160, sizeof(ctx->x));
break;
case 128:
memcpy(ctx->x, SKEIN_256_IV_128, sizeof(ctx->x));
break;
default:
/* here if there is no precomputed IV value available */
/*
* build/process the config block, type == CONFIG (could be
* precomputed)
*/
/* set tweaks: T0=0; T1=CFG | FINAL */
skein_start_new_type(ctx, CFG_FINAL);
/* set the schema, version */
cfg.w[0] = skein_swap64(SKEIN_SCHEMA_VER);
/* hash result length in bits */
cfg.w[1] = skein_swap64(hash_bit_len);
cfg.w[2] = skein_swap64(SKEIN_CFG_TREE_INFO_SEQUENTIAL);
/* zero pad config block */
memset(&cfg.w[3], 0, sizeof(cfg) - 3*sizeof(cfg.w[0]));
/* compute the initial chaining values from config block */
/* zero the chaining variables */
memset(ctx->x, 0, sizeof(ctx->x));
skein_256_process_block(ctx, cfg.b, 1, SKEIN_CFG_STR_LEN);
break;
}
/* The chaining vars ctx->x are now initialized for hash_bit_len. */
/* Set up to process the data message portion of the hash (default) */
skein_start_new_type(ctx, MSG); /* T0=0, T1= MSG type */
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a MAC and/or tree hash operation */
/* [identical to skein_256_init() when key_bytes == 0 && \
* tree_info == SKEIN_CFG_TREE_INFO_SEQUENTIAL] */
int skein_256_init_ext(struct skein_256_ctx *ctx, size_t hash_bit_len,
u64 tree_info, const u8 *key, size_t key_bytes)
{
union {
u8 b[SKEIN_256_STATE_BYTES];
u64 w[SKEIN_256_STATE_WORDS];
} cfg; /* config block */
skein_assert_ret(hash_bit_len > 0, SKEIN_BAD_HASHLEN);
skein_assert_ret(key_bytes == 0 || key != NULL, SKEIN_FAIL);
/* compute the initial chaining values ctx->x[], based on key */
if (key_bytes == 0) { /* is there a key? */
/* no key: use all zeroes as key for config block */
memset(ctx->x, 0, sizeof(ctx->x));
} else { /* here to pre-process a key */
skein_assert(sizeof(cfg.b) >= sizeof(ctx->x));
/* do a mini-Init right here */
/* set output hash bit count = state size */
ctx->h.hash_bit_len = 8*sizeof(ctx->x);
/* set tweaks: T0 = 0; T1 = KEY type */
skein_start_new_type(ctx, KEY);
/* zero the initial chaining variables */
memset(ctx->x, 0, sizeof(ctx->x));
/* hash the key */
skein_256_update(ctx, key, key_bytes);
/* put result into cfg.b[] */
skein_256_final_pad(ctx, cfg.b);
/* copy over into ctx->x[] */
memcpy(ctx->x, cfg.b, sizeof(cfg.b));
}
/*
* build/process the config block, type == CONFIG (could be
* precomputed for each key)
*/
/* output hash bit count */
ctx->h.hash_bit_len = hash_bit_len;
skein_start_new_type(ctx, CFG_FINAL);
/* pre-pad cfg.w[] with zeroes */
memset(&cfg.w, 0, sizeof(cfg.w));
cfg.w[0] = skein_swap64(SKEIN_SCHEMA_VER);
/* hash result length in bits */
cfg.w[1] = skein_swap64(hash_bit_len);
/* tree hash config info (or SKEIN_CFG_TREE_INFO_SEQUENTIAL) */
cfg.w[2] = skein_swap64(tree_info);
skein_show_key(256, &ctx->h, key, key_bytes);
/* compute the initial chaining values from config block */
skein_256_process_block(ctx, cfg.b, 1, SKEIN_CFG_STR_LEN);
/* The chaining vars ctx->x are now initialized */
/* Set up to process the data message portion of the hash (default) */
skein_start_new_type(ctx, MSG);
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* process the input bytes */
int skein_256_update(struct skein_256_ctx *ctx, const u8 *msg,
size_t msg_byte_cnt)
{
size_t n;
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_256_BLOCK_BYTES, SKEIN_FAIL);
/* process full blocks, if any */
if (msg_byte_cnt + ctx->h.b_cnt > SKEIN_256_BLOCK_BYTES) {
/* finish up any buffered message data */
if (ctx->h.b_cnt) {
/* # bytes free in buffer b[] */
n = SKEIN_256_BLOCK_BYTES - ctx->h.b_cnt;
if (n) {
/* check on our logic here */
skein_assert(n < msg_byte_cnt);
memcpy(&ctx->b[ctx->h.b_cnt], msg, n);
msg_byte_cnt -= n;
msg += n;
ctx->h.b_cnt += n;
}
skein_assert(ctx->h.b_cnt == SKEIN_256_BLOCK_BYTES);
skein_256_process_block(ctx, ctx->b, 1,
SKEIN_256_BLOCK_BYTES);
ctx->h.b_cnt = 0;
}
/*
* now process any remaining full blocks, directly from input
* message data
*/
if (msg_byte_cnt > SKEIN_256_BLOCK_BYTES) {
/* number of full blocks to process */
n = (msg_byte_cnt-1) / SKEIN_256_BLOCK_BYTES;
skein_256_process_block(ctx, msg, n,
SKEIN_256_BLOCK_BYTES);
msg_byte_cnt -= n * SKEIN_256_BLOCK_BYTES;
msg += n * SKEIN_256_BLOCK_BYTES;
}
skein_assert(ctx->h.b_cnt == 0);
}
/* copy any remaining source message data bytes into b[] */
if (msg_byte_cnt) {
skein_assert(msg_byte_cnt + ctx->h.b_cnt <=
SKEIN_256_BLOCK_BYTES);
memcpy(&ctx->b[ctx->h.b_cnt], msg, msg_byte_cnt);
ctx->h.b_cnt += msg_byte_cnt;
}
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the result */
int skein_256_final(struct skein_256_ctx *ctx, u8 *hash_val)
{
size_t i, n, byte_cnt;
u64 x[SKEIN_256_STATE_WORDS];
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_256_BLOCK_BYTES, SKEIN_FAIL);
/* tag as the final block */
ctx->h.tweak[1] |= SKEIN_T1_FLAG_FINAL;
/* zero pad b[] if necessary */
if (ctx->h.b_cnt < SKEIN_256_BLOCK_BYTES)
memset(&ctx->b[ctx->h.b_cnt], 0,
SKEIN_256_BLOCK_BYTES - ctx->h.b_cnt);
/* process the final block */
skein_256_process_block(ctx, ctx->b, 1, ctx->h.b_cnt);
/* now output the result */
/* total number of output bytes */
byte_cnt = (ctx->h.hash_bit_len + 7) >> 3;
/* run Threefish in "counter mode" to generate output */
/* zero out b[], so it can hold the counter */
memset(ctx->b, 0, sizeof(ctx->b));
/* keep a local copy of counter mode "key" */
memcpy(x, ctx->x, sizeof(x));
for (i = 0; i*SKEIN_256_BLOCK_BYTES < byte_cnt; i++) {
/* build the counter block */
((u64 *)ctx->b)[0] = skein_swap64((u64) i);
skein_start_new_type(ctx, OUT_FINAL);
/* run "counter mode" */
skein_256_process_block(ctx, ctx->b, 1, sizeof(u64));
/* number of output bytes left to go */
n = byte_cnt - i*SKEIN_256_BLOCK_BYTES;
if (n >= SKEIN_256_BLOCK_BYTES)
n = SKEIN_256_BLOCK_BYTES;
/* "output" the ctr mode bytes */
skein_put64_lsb_first(hash_val+i*SKEIN_256_BLOCK_BYTES, ctx->x,
n);
skein_show_final(256, &ctx->h, n,
hash_val+i*SKEIN_256_BLOCK_BYTES);
/* restore the counter mode key for next time */
memcpy(ctx->x, x, sizeof(x));
}
return SKEIN_SUCCESS;
}
/*****************************************************************/
/* 512-bit Skein */
/*****************************************************************/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a straight hashing operation */
int skein_512_init(struct skein_512_ctx *ctx, size_t hash_bit_len)
{
union {
u8 b[SKEIN_512_STATE_BYTES];
u64 w[SKEIN_512_STATE_WORDS];
} cfg; /* config block */
skein_assert_ret(hash_bit_len > 0, SKEIN_BAD_HASHLEN);
ctx->h.hash_bit_len = hash_bit_len; /* output hash bit count */
switch (hash_bit_len) { /* use pre-computed values, where available */
case 512:
memcpy(ctx->x, SKEIN_512_IV_512, sizeof(ctx->x));
break;
case 384:
memcpy(ctx->x, SKEIN_512_IV_384, sizeof(ctx->x));
break;
case 256:
memcpy(ctx->x, SKEIN_512_IV_256, sizeof(ctx->x));
break;
case 224:
memcpy(ctx->x, SKEIN_512_IV_224, sizeof(ctx->x));
break;
default:
/* here if there is no precomputed IV value available */
/*
* build/process the config block, type == CONFIG (could be
* precomputed)
*/
/* set tweaks: T0=0; T1=CFG | FINAL */
skein_start_new_type(ctx, CFG_FINAL);
/* set the schema, version */
cfg.w[0] = skein_swap64(SKEIN_SCHEMA_VER);
/* hash result length in bits */
cfg.w[1] = skein_swap64(hash_bit_len);
cfg.w[2] = skein_swap64(SKEIN_CFG_TREE_INFO_SEQUENTIAL);
/* zero pad config block */
memset(&cfg.w[3], 0, sizeof(cfg) - 3*sizeof(cfg.w[0]));
/* compute the initial chaining values from config block */
/* zero the chaining variables */
memset(ctx->x, 0, sizeof(ctx->x));
skein_512_process_block(ctx, cfg.b, 1, SKEIN_CFG_STR_LEN);
break;
}
/*
* The chaining vars ctx->x are now initialized for the given
* hash_bit_len.
*/
/* Set up to process the data message portion of the hash (default) */
skein_start_new_type(ctx, MSG); /* T0=0, T1= MSG type */
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a MAC and/or tree hash operation */
/* [identical to skein_512_init() when key_bytes == 0 && \
* tree_info == SKEIN_CFG_TREE_INFO_SEQUENTIAL] */
int skein_512_init_ext(struct skein_512_ctx *ctx, size_t hash_bit_len,
u64 tree_info, const u8 *key, size_t key_bytes)
{
union {
u8 b[SKEIN_512_STATE_BYTES];
u64 w[SKEIN_512_STATE_WORDS];
} cfg; /* config block */
skein_assert_ret(hash_bit_len > 0, SKEIN_BAD_HASHLEN);
skein_assert_ret(key_bytes == 0 || key != NULL, SKEIN_FAIL);
/* compute the initial chaining values ctx->x[], based on key */
if (key_bytes == 0) { /* is there a key? */
/* no key: use all zeroes as key for config block */
memset(ctx->x, 0, sizeof(ctx->x));
} else { /* here to pre-process a key */
skein_assert(sizeof(cfg.b) >= sizeof(ctx->x));
/* do a mini-Init right here */
/* set output hash bit count = state size */
ctx->h.hash_bit_len = 8*sizeof(ctx->x);
/* set tweaks: T0 = 0; T1 = KEY type */
skein_start_new_type(ctx, KEY);
/* zero the initial chaining variables */
memset(ctx->x, 0, sizeof(ctx->x));
/* hash the key */
skein_512_update(ctx, key, key_bytes);
/* put result into cfg.b[] */
skein_512_final_pad(ctx, cfg.b);
/* copy over into ctx->x[] */
memcpy(ctx->x, cfg.b, sizeof(cfg.b));
}
/*
* build/process the config block, type == CONFIG (could be
* precomputed for each key)
*/
ctx->h.hash_bit_len = hash_bit_len; /* output hash bit count */
skein_start_new_type(ctx, CFG_FINAL);
/* pre-pad cfg.w[] with zeroes */
memset(&cfg.w, 0, sizeof(cfg.w));
cfg.w[0] = skein_swap64(SKEIN_SCHEMA_VER);
/* hash result length in bits */
cfg.w[1] = skein_swap64(hash_bit_len);
/* tree hash config info (or SKEIN_CFG_TREE_INFO_SEQUENTIAL) */
cfg.w[2] = skein_swap64(tree_info);
skein_show_key(512, &ctx->h, key, key_bytes);
/* compute the initial chaining values from config block */
skein_512_process_block(ctx, cfg.b, 1, SKEIN_CFG_STR_LEN);
/* The chaining vars ctx->x are now initialized */
/* Set up to process the data message portion of the hash (default) */
skein_start_new_type(ctx, MSG);
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* process the input bytes */
int skein_512_update(struct skein_512_ctx *ctx, const u8 *msg,
size_t msg_byte_cnt)
{
size_t n;
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_512_BLOCK_BYTES, SKEIN_FAIL);
/* process full blocks, if any */
if (msg_byte_cnt + ctx->h.b_cnt > SKEIN_512_BLOCK_BYTES) {
/* finish up any buffered message data */
if (ctx->h.b_cnt) {
/* # bytes free in buffer b[] */
n = SKEIN_512_BLOCK_BYTES - ctx->h.b_cnt;
if (n) {
/* check on our logic here */
skein_assert(n < msg_byte_cnt);
memcpy(&ctx->b[ctx->h.b_cnt], msg, n);
msg_byte_cnt -= n;
msg += n;
ctx->h.b_cnt += n;
}
skein_assert(ctx->h.b_cnt == SKEIN_512_BLOCK_BYTES);
skein_512_process_block(ctx, ctx->b, 1,
SKEIN_512_BLOCK_BYTES);
ctx->h.b_cnt = 0;
}
/*
* now process any remaining full blocks, directly from input
* message data
*/
if (msg_byte_cnt > SKEIN_512_BLOCK_BYTES) {
/* number of full blocks to process */
n = (msg_byte_cnt-1) / SKEIN_512_BLOCK_BYTES;
skein_512_process_block(ctx, msg, n,
SKEIN_512_BLOCK_BYTES);
msg_byte_cnt -= n * SKEIN_512_BLOCK_BYTES;
msg += n * SKEIN_512_BLOCK_BYTES;
}
skein_assert(ctx->h.b_cnt == 0);
}
/* copy any remaining source message data bytes into b[] */
if (msg_byte_cnt) {
skein_assert(msg_byte_cnt + ctx->h.b_cnt <=
SKEIN_512_BLOCK_BYTES);
memcpy(&ctx->b[ctx->h.b_cnt], msg, msg_byte_cnt);
ctx->h.b_cnt += msg_byte_cnt;
}
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the result */
int skein_512_final(struct skein_512_ctx *ctx, u8 *hash_val)
{
size_t i, n, byte_cnt;
u64 x[SKEIN_512_STATE_WORDS];
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_512_BLOCK_BYTES, SKEIN_FAIL);
/* tag as the final block */
ctx->h.tweak[1] |= SKEIN_T1_FLAG_FINAL;
/* zero pad b[] if necessary */
if (ctx->h.b_cnt < SKEIN_512_BLOCK_BYTES)
memset(&ctx->b[ctx->h.b_cnt], 0,
SKEIN_512_BLOCK_BYTES - ctx->h.b_cnt);
/* process the final block */
skein_512_process_block(ctx, ctx->b, 1, ctx->h.b_cnt);
/* now output the result */
/* total number of output bytes */
byte_cnt = (ctx->h.hash_bit_len + 7) >> 3;
/* run Threefish in "counter mode" to generate output */
/* zero out b[], so it can hold the counter */
memset(ctx->b, 0, sizeof(ctx->b));
/* keep a local copy of counter mode "key" */
memcpy(x, ctx->x, sizeof(x));
for (i = 0; i*SKEIN_512_BLOCK_BYTES < byte_cnt; i++) {
/* build the counter block */
((u64 *)ctx->b)[0] = skein_swap64((u64) i);
skein_start_new_type(ctx, OUT_FINAL);
/* run "counter mode" */
skein_512_process_block(ctx, ctx->b, 1, sizeof(u64));
/* number of output bytes left to go */
n = byte_cnt - i*SKEIN_512_BLOCK_BYTES;
if (n >= SKEIN_512_BLOCK_BYTES)
n = SKEIN_512_BLOCK_BYTES;
/* "output" the ctr mode bytes */
skein_put64_lsb_first(hash_val+i*SKEIN_512_BLOCK_BYTES, ctx->x,
n);
skein_show_final(512, &ctx->h, n,
hash_val+i*SKEIN_512_BLOCK_BYTES);
/* restore the counter mode key for next time */
memcpy(ctx->x, x, sizeof(x));
}
return SKEIN_SUCCESS;
}
/*****************************************************************/
/* 1024-bit Skein */
/*****************************************************************/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a straight hashing operation */
int skein_1024_init(struct skein_1024_ctx *ctx, size_t hash_bit_len)
{
union {
u8 b[SKEIN_1024_STATE_BYTES];
u64 w[SKEIN_1024_STATE_WORDS];
} cfg; /* config block */
skein_assert_ret(hash_bit_len > 0, SKEIN_BAD_HASHLEN);
ctx->h.hash_bit_len = hash_bit_len; /* output hash bit count */
switch (hash_bit_len) { /* use pre-computed values, where available */
case 512:
memcpy(ctx->x, SKEIN_1024_IV_512, sizeof(ctx->x));
break;
case 384:
memcpy(ctx->x, SKEIN_1024_IV_384, sizeof(ctx->x));
break;
case 1024:
memcpy(ctx->x, SKEIN_1024_IV_1024, sizeof(ctx->x));
break;
default:
/* here if there is no precomputed IV value available */
/*
* build/process the config block, type == CONFIG
* (could be precomputed)
*/
/* set tweaks: T0=0; T1=CFG | FINAL */
skein_start_new_type(ctx, CFG_FINAL);
/* set the schema, version */
cfg.w[0] = skein_swap64(SKEIN_SCHEMA_VER);
/* hash result length in bits */
cfg.w[1] = skein_swap64(hash_bit_len);
cfg.w[2] = skein_swap64(SKEIN_CFG_TREE_INFO_SEQUENTIAL);
/* zero pad config block */
memset(&cfg.w[3], 0, sizeof(cfg) - 3*sizeof(cfg.w[0]));
/* compute the initial chaining values from config block */
/* zero the chaining variables */
memset(ctx->x, 0, sizeof(ctx->x));
skein_1024_process_block(ctx, cfg.b, 1, SKEIN_CFG_STR_LEN);
break;
}
/* The chaining vars ctx->x are now initialized for the hash_bit_len. */
/* Set up to process the data message portion of the hash (default) */
skein_start_new_type(ctx, MSG); /* T0=0, T1= MSG type */
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a MAC and/or tree hash operation */
/* [identical to skein_1024_init() when key_bytes == 0 && \
* tree_info == SKEIN_CFG_TREE_INFO_SEQUENTIAL] */
int skein_1024_init_ext(struct skein_1024_ctx *ctx, size_t hash_bit_len,
u64 tree_info, const u8 *key, size_t key_bytes)
{
union {
u8 b[SKEIN_1024_STATE_BYTES];
u64 w[SKEIN_1024_STATE_WORDS];
} cfg; /* config block */
skein_assert_ret(hash_bit_len > 0, SKEIN_BAD_HASHLEN);
skein_assert_ret(key_bytes == 0 || key != NULL, SKEIN_FAIL);
/* compute the initial chaining values ctx->x[], based on key */
if (key_bytes == 0) { /* is there a key? */
/* no key: use all zeroes as key for config block */
memset(ctx->x, 0, sizeof(ctx->x));
} else { /* here to pre-process a key */
skein_assert(sizeof(cfg.b) >= sizeof(ctx->x));
/* do a mini-Init right here */
/* set output hash bit count = state size */
ctx->h.hash_bit_len = 8*sizeof(ctx->x);
/* set tweaks: T0 = 0; T1 = KEY type */
skein_start_new_type(ctx, KEY);
/* zero the initial chaining variables */
memset(ctx->x, 0, sizeof(ctx->x));
/* hash the key */
skein_1024_update(ctx, key, key_bytes);
/* put result into cfg.b[] */
skein_1024_final_pad(ctx, cfg.b);
/* copy over into ctx->x[] */
memcpy(ctx->x, cfg.b, sizeof(cfg.b));
}
/*
* build/process the config block, type == CONFIG (could be
* precomputed for each key)
*/
/* output hash bit count */
ctx->h.hash_bit_len = hash_bit_len;
skein_start_new_type(ctx, CFG_FINAL);
/* pre-pad cfg.w[] with zeroes */
memset(&cfg.w, 0, sizeof(cfg.w));
cfg.w[0] = skein_swap64(SKEIN_SCHEMA_VER);
/* hash result length in bits */
cfg.w[1] = skein_swap64(hash_bit_len);
/* tree hash config info (or SKEIN_CFG_TREE_INFO_SEQUENTIAL) */
cfg.w[2] = skein_swap64(tree_info);
skein_show_key(1024, &ctx->h, key, key_bytes);
/* compute the initial chaining values from config block */
skein_1024_process_block(ctx, cfg.b, 1, SKEIN_CFG_STR_LEN);
/* The chaining vars ctx->x are now initialized */
/* Set up to process the data message portion of the hash (default) */
skein_start_new_type(ctx, MSG);
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* process the input bytes */
int skein_1024_update(struct skein_1024_ctx *ctx, const u8 *msg,
size_t msg_byte_cnt)
{
size_t n;
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_1024_BLOCK_BYTES, SKEIN_FAIL);
/* process full blocks, if any */
if (msg_byte_cnt + ctx->h.b_cnt > SKEIN_1024_BLOCK_BYTES) {
/* finish up any buffered message data */
if (ctx->h.b_cnt) {
/* # bytes free in buffer b[] */
n = SKEIN_1024_BLOCK_BYTES - ctx->h.b_cnt;
if (n) {
/* check on our logic here */
skein_assert(n < msg_byte_cnt);
memcpy(&ctx->b[ctx->h.b_cnt], msg, n);
msg_byte_cnt -= n;
msg += n;
ctx->h.b_cnt += n;
}
skein_assert(ctx->h.b_cnt == SKEIN_1024_BLOCK_BYTES);
skein_1024_process_block(ctx, ctx->b, 1,
SKEIN_1024_BLOCK_BYTES);
ctx->h.b_cnt = 0;
}
/*
* now process any remaining full blocks, directly from input
* message data
*/
if (msg_byte_cnt > SKEIN_1024_BLOCK_BYTES) {
/* number of full blocks to process */
n = (msg_byte_cnt-1) / SKEIN_1024_BLOCK_BYTES;
skein_1024_process_block(ctx, msg, n,
SKEIN_1024_BLOCK_BYTES);
msg_byte_cnt -= n * SKEIN_1024_BLOCK_BYTES;
msg += n * SKEIN_1024_BLOCK_BYTES;
}
skein_assert(ctx->h.b_cnt == 0);
}
/* copy any remaining source message data bytes into b[] */
if (msg_byte_cnt) {
skein_assert(msg_byte_cnt + ctx->h.b_cnt <=
SKEIN_1024_BLOCK_BYTES);
memcpy(&ctx->b[ctx->h.b_cnt], msg, msg_byte_cnt);
ctx->h.b_cnt += msg_byte_cnt;
}
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the result */
int skein_1024_final(struct skein_1024_ctx *ctx, u8 *hash_val)
{
size_t i, n, byte_cnt;
u64 x[SKEIN_1024_STATE_WORDS];
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_1024_BLOCK_BYTES, SKEIN_FAIL);
/* tag as the final block */
ctx->h.tweak[1] |= SKEIN_T1_FLAG_FINAL;
/* zero pad b[] if necessary */
if (ctx->h.b_cnt < SKEIN_1024_BLOCK_BYTES)
memset(&ctx->b[ctx->h.b_cnt], 0,
SKEIN_1024_BLOCK_BYTES - ctx->h.b_cnt);
/* process the final block */
skein_1024_process_block(ctx, ctx->b, 1, ctx->h.b_cnt);
/* now output the result */
/* total number of output bytes */
byte_cnt = (ctx->h.hash_bit_len + 7) >> 3;
/* run Threefish in "counter mode" to generate output */
/* zero out b[], so it can hold the counter */
memset(ctx->b, 0, sizeof(ctx->b));
/* keep a local copy of counter mode "key" */
memcpy(x, ctx->x, sizeof(x));
for (i = 0; i*SKEIN_1024_BLOCK_BYTES < byte_cnt; i++) {
/* build the counter block */
((u64 *)ctx->b)[0] = skein_swap64((u64) i);
skein_start_new_type(ctx, OUT_FINAL);
/* run "counter mode" */
skein_1024_process_block(ctx, ctx->b, 1, sizeof(u64));
/* number of output bytes left to go */
n = byte_cnt - i*SKEIN_1024_BLOCK_BYTES;
if (n >= SKEIN_1024_BLOCK_BYTES)
n = SKEIN_1024_BLOCK_BYTES;
/* "output" the ctr mode bytes */
skein_put64_lsb_first(hash_val+i*SKEIN_1024_BLOCK_BYTES, ctx->x,
n);
skein_show_final(1024, &ctx->h, n,
hash_val+i*SKEIN_1024_BLOCK_BYTES);
/* restore the counter mode key for next time */
memcpy(ctx->x, x, sizeof(x));
}
return SKEIN_SUCCESS;
}
/**************** Functions to support MAC/tree hashing ***************/
/* (this code is identical for Optimized and Reference versions) */
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the block, no OUTPUT stage */
int skein_256_final_pad(struct skein_256_ctx *ctx, u8 *hash_val)
{
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_256_BLOCK_BYTES, SKEIN_FAIL);
/* tag as the final block */
ctx->h.tweak[1] |= SKEIN_T1_FLAG_FINAL;
/* zero pad b[] if necessary */
if (ctx->h.b_cnt < SKEIN_256_BLOCK_BYTES)
memset(&ctx->b[ctx->h.b_cnt], 0,
SKEIN_256_BLOCK_BYTES - ctx->h.b_cnt);
/* process the final block */
skein_256_process_block(ctx, ctx->b, 1, ctx->h.b_cnt);
/* "output" the state bytes */
skein_put64_lsb_first(hash_val, ctx->x, SKEIN_256_BLOCK_BYTES);
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the block, no OUTPUT stage */
int skein_512_final_pad(struct skein_512_ctx *ctx, u8 *hash_val)
{
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_512_BLOCK_BYTES, SKEIN_FAIL);
/* tag as the final block */
ctx->h.tweak[1] |= SKEIN_T1_FLAG_FINAL;
/* zero pad b[] if necessary */
if (ctx->h.b_cnt < SKEIN_512_BLOCK_BYTES)
memset(&ctx->b[ctx->h.b_cnt], 0,
SKEIN_512_BLOCK_BYTES - ctx->h.b_cnt);
/* process the final block */
skein_512_process_block(ctx, ctx->b, 1, ctx->h.b_cnt);
/* "output" the state bytes */
skein_put64_lsb_first(hash_val, ctx->x, SKEIN_512_BLOCK_BYTES);
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the block, no OUTPUT stage */
int skein_1024_final_pad(struct skein_1024_ctx *ctx, u8 *hash_val)
{
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_1024_BLOCK_BYTES, SKEIN_FAIL);
/* tag as the final block */
ctx->h.tweak[1] |= SKEIN_T1_FLAG_FINAL;
/* zero pad b[] if necessary */
if (ctx->h.b_cnt < SKEIN_1024_BLOCK_BYTES)
memset(&ctx->b[ctx->h.b_cnt], 0,
SKEIN_1024_BLOCK_BYTES - ctx->h.b_cnt);
/* process the final block */
skein_1024_process_block(ctx, ctx->b, 1, ctx->h.b_cnt);
/* "output" the state bytes */
skein_put64_lsb_first(hash_val, ctx->x, SKEIN_1024_BLOCK_BYTES);
return SKEIN_SUCCESS;
}
#if SKEIN_TREE_HASH
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* just do the OUTPUT stage */
int skein_256_output(struct skein_256_ctx *ctx, u8 *hash_val)
{
size_t i, n, byte_cnt;
u64 x[SKEIN_256_STATE_WORDS];
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_256_BLOCK_BYTES, SKEIN_FAIL);
/* now output the result */
/* total number of output bytes */
byte_cnt = (ctx->h.hash_bit_len + 7) >> 3;
/* run Threefish in "counter mode" to generate output */
/* zero out b[], so it can hold the counter */
memset(ctx->b, 0, sizeof(ctx->b));
/* keep a local copy of counter mode "key" */
memcpy(x, ctx->x, sizeof(x));
for (i = 0; i*SKEIN_256_BLOCK_BYTES < byte_cnt; i++) {
/* build the counter block */
((u64 *)ctx->b)[0] = skein_swap64((u64) i);
skein_start_new_type(ctx, OUT_FINAL);
/* run "counter mode" */
skein_256_process_block(ctx, ctx->b, 1, sizeof(u64));
/* number of output bytes left to go */
n = byte_cnt - i*SKEIN_256_BLOCK_BYTES;
if (n >= SKEIN_256_BLOCK_BYTES)
n = SKEIN_256_BLOCK_BYTES;
/* "output" the ctr mode bytes */
skein_put64_lsb_first(hash_val+i*SKEIN_256_BLOCK_BYTES, ctx->x,
n);
skein_show_final(256, &ctx->h, n,
hash_val+i*SKEIN_256_BLOCK_BYTES);
/* restore the counter mode key for next time */
memcpy(ctx->x, x, sizeof(x));
}
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* just do the OUTPUT stage */
int skein_512_output(struct skein_512_ctx *ctx, u8 *hash_val)
{
size_t i, n, byte_cnt;
u64 x[SKEIN_512_STATE_WORDS];
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_512_BLOCK_BYTES, SKEIN_FAIL);
/* now output the result */
/* total number of output bytes */
byte_cnt = (ctx->h.hash_bit_len + 7) >> 3;
/* run Threefish in "counter mode" to generate output */
/* zero out b[], so it can hold the counter */
memset(ctx->b, 0, sizeof(ctx->b));
/* keep a local copy of counter mode "key" */
memcpy(x, ctx->x, sizeof(x));
for (i = 0; i*SKEIN_512_BLOCK_BYTES < byte_cnt; i++) {
/* build the counter block */
((u64 *)ctx->b)[0] = skein_swap64((u64) i);
skein_start_new_type(ctx, OUT_FINAL);
/* run "counter mode" */
skein_512_process_block(ctx, ctx->b, 1, sizeof(u64));
/* number of output bytes left to go */
n = byte_cnt - i*SKEIN_512_BLOCK_BYTES;
if (n >= SKEIN_512_BLOCK_BYTES)
n = SKEIN_512_BLOCK_BYTES;
/* "output" the ctr mode bytes */
skein_put64_lsb_first(hash_val+i*SKEIN_512_BLOCK_BYTES, ctx->x,
n);
skein_show_final(256, &ctx->h, n,
hash_val+i*SKEIN_512_BLOCK_BYTES);
/* restore the counter mode key for next time */
memcpy(ctx->x, x, sizeof(x));
}
return SKEIN_SUCCESS;
}
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* just do the OUTPUT stage */
int skein_1024_output(struct skein_1024_ctx *ctx, u8 *hash_val)
{
size_t i, n, byte_cnt;
u64 x[SKEIN_1024_STATE_WORDS];
/* catch uninitialized context */
skein_assert_ret(ctx->h.b_cnt <= SKEIN_1024_BLOCK_BYTES, SKEIN_FAIL);
/* now output the result */
/* total number of output bytes */
byte_cnt = (ctx->h.hash_bit_len + 7) >> 3;
/* run Threefish in "counter mode" to generate output */
/* zero out b[], so it can hold the counter */
memset(ctx->b, 0, sizeof(ctx->b));
/* keep a local copy of counter mode "key" */
memcpy(x, ctx->x, sizeof(x));
for (i = 0; i*SKEIN_1024_BLOCK_BYTES < byte_cnt; i++) {
/* build the counter block */
((u64 *)ctx->b)[0] = skein_swap64((u64) i);
skein_start_new_type(ctx, OUT_FINAL);
/* run "counter mode" */
skein_1024_process_block(ctx, ctx->b, 1, sizeof(u64));
/* number of output bytes left to go */
n = byte_cnt - i*SKEIN_1024_BLOCK_BYTES;
if (n >= SKEIN_1024_BLOCK_BYTES)
n = SKEIN_1024_BLOCK_BYTES;
/* "output" the ctr mode bytes */
skein_put64_lsb_first(hash_val+i*SKEIN_1024_BLOCK_BYTES, ctx->x,
n);
skein_show_final(256, &ctx->h, n,
hash_val+i*SKEIN_1024_BLOCK_BYTES);
/* restore the counter mode key for next time */
memcpy(ctx->x, x, sizeof(x));
}
return SKEIN_SUCCESS;
}
#endif
| gpl-2.0 |
mayli/unionfs-latest | drivers/net/ethernet/intel/e1000e/82571.c | 732 | 55540 | /* Intel PRO/1000 Linux driver
* Copyright(c) 1999 - 2014 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.
*
* The full GNU General Public License is included in this distribution in
* the file called "COPYING".
*
* Contact Information:
* Linux NICS <linux.nics@intel.com>
* e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*/
/* 82571EB Gigabit Ethernet Controller
* 82571EB Gigabit Ethernet Controller (Copper)
* 82571EB Gigabit Ethernet Controller (Fiber)
* 82571EB Dual Port Gigabit Mezzanine Adapter
* 82571EB Quad Port Gigabit Mezzanine Adapter
* 82571PT Gigabit PT Quad Port Server ExpressModule
* 82572EI Gigabit Ethernet Controller (Copper)
* 82572EI Gigabit Ethernet Controller (Fiber)
* 82572EI Gigabit Ethernet Controller
* 82573V Gigabit Ethernet Controller (Copper)
* 82573E Gigabit Ethernet Controller (Copper)
* 82573L Gigabit Ethernet Controller
* 82574L Gigabit Network Connection
* 82583V Gigabit Network Connection
*/
#include "e1000.h"
static s32 e1000_get_phy_id_82571(struct e1000_hw *hw);
static s32 e1000_setup_copper_link_82571(struct e1000_hw *hw);
static s32 e1000_setup_fiber_serdes_link_82571(struct e1000_hw *hw);
static s32 e1000_check_for_serdes_link_82571(struct e1000_hw *hw);
static s32 e1000_write_nvm_eewr_82571(struct e1000_hw *hw, u16 offset,
u16 words, u16 *data);
static s32 e1000_fix_nvm_checksum_82571(struct e1000_hw *hw);
static void e1000_initialize_hw_bits_82571(struct e1000_hw *hw);
static void e1000_clear_hw_cntrs_82571(struct e1000_hw *hw);
static bool e1000_check_mng_mode_82574(struct e1000_hw *hw);
static s32 e1000_led_on_82574(struct e1000_hw *hw);
static void e1000_put_hw_semaphore_82571(struct e1000_hw *hw);
static void e1000_power_down_phy_copper_82571(struct e1000_hw *hw);
static void e1000_put_hw_semaphore_82573(struct e1000_hw *hw);
static s32 e1000_get_hw_semaphore_82574(struct e1000_hw *hw);
static void e1000_put_hw_semaphore_82574(struct e1000_hw *hw);
static s32 e1000_set_d0_lplu_state_82574(struct e1000_hw *hw, bool active);
static s32 e1000_set_d3_lplu_state_82574(struct e1000_hw *hw, bool active);
/**
* e1000_init_phy_params_82571 - Init PHY func ptrs.
* @hw: pointer to the HW structure
**/
static s32 e1000_init_phy_params_82571(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val;
if (hw->phy.media_type != e1000_media_type_copper) {
phy->type = e1000_phy_none;
return 0;
}
phy->addr = 1;
phy->autoneg_mask = AUTONEG_ADVERTISE_SPEED_DEFAULT;
phy->reset_delay_us = 100;
phy->ops.power_up = e1000_power_up_phy_copper;
phy->ops.power_down = e1000_power_down_phy_copper_82571;
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
phy->type = e1000_phy_igp_2;
break;
case e1000_82573:
phy->type = e1000_phy_m88;
break;
case e1000_82574:
case e1000_82583:
phy->type = e1000_phy_bm;
phy->ops.acquire = e1000_get_hw_semaphore_82574;
phy->ops.release = e1000_put_hw_semaphore_82574;
phy->ops.set_d0_lplu_state = e1000_set_d0_lplu_state_82574;
phy->ops.set_d3_lplu_state = e1000_set_d3_lplu_state_82574;
break;
default:
return -E1000_ERR_PHY;
}
/* This can only be done after all function pointers are setup. */
ret_val = e1000_get_phy_id_82571(hw);
if (ret_val) {
e_dbg("Error getting PHY ID\n");
return ret_val;
}
/* Verify phy id */
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
if (phy->id != IGP01E1000_I_PHY_ID)
ret_val = -E1000_ERR_PHY;
break;
case e1000_82573:
if (phy->id != M88E1111_I_PHY_ID)
ret_val = -E1000_ERR_PHY;
break;
case e1000_82574:
case e1000_82583:
if (phy->id != BME1000_E_PHY_ID_R2)
ret_val = -E1000_ERR_PHY;
break;
default:
ret_val = -E1000_ERR_PHY;
break;
}
if (ret_val)
e_dbg("PHY ID unknown: type = 0x%08x\n", phy->id);
return ret_val;
}
/**
* e1000_init_nvm_params_82571 - Init NVM func ptrs.
* @hw: pointer to the HW structure
**/
static s32 e1000_init_nvm_params_82571(struct e1000_hw *hw)
{
struct e1000_nvm_info *nvm = &hw->nvm;
u32 eecd = er32(EECD);
u16 size;
nvm->opcode_bits = 8;
nvm->delay_usec = 1;
switch (nvm->override) {
case e1000_nvm_override_spi_large:
nvm->page_size = 32;
nvm->address_bits = 16;
break;
case e1000_nvm_override_spi_small:
nvm->page_size = 8;
nvm->address_bits = 8;
break;
default:
nvm->page_size = eecd & E1000_EECD_ADDR_BITS ? 32 : 8;
nvm->address_bits = eecd & E1000_EECD_ADDR_BITS ? 16 : 8;
break;
}
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
if (((eecd >> 15) & 0x3) == 0x3) {
nvm->type = e1000_nvm_flash_hw;
nvm->word_size = 2048;
/* Autonomous Flash update bit must be cleared due
* to Flash update issue.
*/
eecd &= ~E1000_EECD_AUPDEN;
ew32(EECD, eecd);
break;
}
/* Fall Through */
default:
nvm->type = e1000_nvm_eeprom_spi;
size = (u16)((eecd & E1000_EECD_SIZE_EX_MASK) >>
E1000_EECD_SIZE_EX_SHIFT);
/* Added to a constant, "size" becomes the left-shift value
* for setting word_size.
*/
size += NVM_WORD_SIZE_BASE_SHIFT;
/* EEPROM access above 16k is unsupported */
if (size > 14)
size = 14;
nvm->word_size = 1 << size;
break;
}
/* Function Pointers */
switch (hw->mac.type) {
case e1000_82574:
case e1000_82583:
nvm->ops.acquire = e1000_get_hw_semaphore_82574;
nvm->ops.release = e1000_put_hw_semaphore_82574;
break;
default:
break;
}
return 0;
}
/**
* e1000_init_mac_params_82571 - Init MAC func ptrs.
* @hw: pointer to the HW structure
**/
static s32 e1000_init_mac_params_82571(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 swsm = 0;
u32 swsm2 = 0;
bool force_clear_smbi = false;
/* Set media type and media-dependent function pointers */
switch (hw->adapter->pdev->device) {
case E1000_DEV_ID_82571EB_FIBER:
case E1000_DEV_ID_82572EI_FIBER:
case E1000_DEV_ID_82571EB_QUAD_FIBER:
hw->phy.media_type = e1000_media_type_fiber;
mac->ops.setup_physical_interface =
e1000_setup_fiber_serdes_link_82571;
mac->ops.check_for_link = e1000e_check_for_fiber_link;
mac->ops.get_link_up_info =
e1000e_get_speed_and_duplex_fiber_serdes;
break;
case E1000_DEV_ID_82571EB_SERDES:
case E1000_DEV_ID_82571EB_SERDES_DUAL:
case E1000_DEV_ID_82571EB_SERDES_QUAD:
case E1000_DEV_ID_82572EI_SERDES:
hw->phy.media_type = e1000_media_type_internal_serdes;
mac->ops.setup_physical_interface =
e1000_setup_fiber_serdes_link_82571;
mac->ops.check_for_link = e1000_check_for_serdes_link_82571;
mac->ops.get_link_up_info =
e1000e_get_speed_and_duplex_fiber_serdes;
break;
default:
hw->phy.media_type = e1000_media_type_copper;
mac->ops.setup_physical_interface =
e1000_setup_copper_link_82571;
mac->ops.check_for_link = e1000e_check_for_copper_link;
mac->ops.get_link_up_info = e1000e_get_speed_and_duplex_copper;
break;
}
/* Set mta register count */
mac->mta_reg_count = 128;
/* Set rar entry count */
mac->rar_entry_count = E1000_RAR_ENTRIES;
/* Adaptive IFS supported */
mac->adaptive_ifs = true;
/* MAC-specific function pointers */
switch (hw->mac.type) {
case e1000_82573:
mac->ops.set_lan_id = e1000_set_lan_id_single_port;
mac->ops.check_mng_mode = e1000e_check_mng_mode_generic;
mac->ops.led_on = e1000e_led_on_generic;
mac->ops.blink_led = e1000e_blink_led_generic;
/* FWSM register */
mac->has_fwsm = true;
/* ARC supported; valid only if manageability features are
* enabled.
*/
mac->arc_subsystem_valid = !!(er32(FWSM) &
E1000_FWSM_MODE_MASK);
break;
case e1000_82574:
case e1000_82583:
mac->ops.set_lan_id = e1000_set_lan_id_single_port;
mac->ops.check_mng_mode = e1000_check_mng_mode_82574;
mac->ops.led_on = e1000_led_on_82574;
break;
default:
mac->ops.check_mng_mode = e1000e_check_mng_mode_generic;
mac->ops.led_on = e1000e_led_on_generic;
mac->ops.blink_led = e1000e_blink_led_generic;
/* FWSM register */
mac->has_fwsm = true;
break;
}
/* Ensure that the inter-port SWSM.SMBI lock bit is clear before
* first NVM or PHY access. This should be done for single-port
* devices, and for one port only on dual-port devices so that
* for those devices we can still use the SMBI lock to synchronize
* inter-port accesses to the PHY & NVM.
*/
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
swsm2 = er32(SWSM2);
if (!(swsm2 & E1000_SWSM2_LOCK)) {
/* Only do this for the first interface on this card */
ew32(SWSM2, swsm2 | E1000_SWSM2_LOCK);
force_clear_smbi = true;
} else {
force_clear_smbi = false;
}
break;
default:
force_clear_smbi = true;
break;
}
if (force_clear_smbi) {
/* Make sure SWSM.SMBI is clear */
swsm = er32(SWSM);
if (swsm & E1000_SWSM_SMBI) {
/* This bit should not be set on a first interface, and
* indicates that the bootagent or EFI code has
* improperly left this bit enabled
*/
e_dbg("Please update your 82571 Bootagent\n");
}
ew32(SWSM, swsm & ~E1000_SWSM_SMBI);
}
/* Initialize device specific counter of SMBI acquisition timeouts. */
hw->dev_spec.e82571.smb_counter = 0;
return 0;
}
static s32 e1000_get_variants_82571(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
static int global_quad_port_a; /* global port a indication */
struct pci_dev *pdev = adapter->pdev;
int is_port_b = er32(STATUS) & E1000_STATUS_FUNC_1;
s32 rc;
rc = e1000_init_mac_params_82571(hw);
if (rc)
return rc;
rc = e1000_init_nvm_params_82571(hw);
if (rc)
return rc;
rc = e1000_init_phy_params_82571(hw);
if (rc)
return rc;
/* tag quad port adapters first, it's used below */
switch (pdev->device) {
case E1000_DEV_ID_82571EB_QUAD_COPPER:
case E1000_DEV_ID_82571EB_QUAD_FIBER:
case E1000_DEV_ID_82571EB_QUAD_COPPER_LP:
case E1000_DEV_ID_82571PT_QUAD_COPPER:
adapter->flags |= FLAG_IS_QUAD_PORT;
/* mark the first port */
if (global_quad_port_a == 0)
adapter->flags |= FLAG_IS_QUAD_PORT_A;
/* Reset for multiple quad port adapters */
global_quad_port_a++;
if (global_quad_port_a == 4)
global_quad_port_a = 0;
break;
default:
break;
}
switch (adapter->hw.mac.type) {
case e1000_82571:
/* these dual ports don't have WoL on port B at all */
if (((pdev->device == E1000_DEV_ID_82571EB_FIBER) ||
(pdev->device == E1000_DEV_ID_82571EB_SERDES) ||
(pdev->device == E1000_DEV_ID_82571EB_COPPER)) &&
(is_port_b))
adapter->flags &= ~FLAG_HAS_WOL;
/* quad ports only support WoL on port A */
if (adapter->flags & FLAG_IS_QUAD_PORT &&
(!(adapter->flags & FLAG_IS_QUAD_PORT_A)))
adapter->flags &= ~FLAG_HAS_WOL;
/* Does not support WoL on any port */
if (pdev->device == E1000_DEV_ID_82571EB_SERDES_QUAD)
adapter->flags &= ~FLAG_HAS_WOL;
break;
case e1000_82573:
if (pdev->device == E1000_DEV_ID_82573L) {
adapter->flags |= FLAG_HAS_JUMBO_FRAMES;
adapter->max_hw_frame_size = DEFAULT_JUMBO;
}
break;
default:
break;
}
return 0;
}
/**
* e1000_get_phy_id_82571 - Retrieve the PHY ID and revision
* @hw: pointer to the HW structure
*
* Reads the PHY registers and stores the PHY ID and possibly the PHY
* revision in the hardware structure.
**/
static s32 e1000_get_phy_id_82571(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val;
u16 phy_id = 0;
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
/* The 82571 firmware may still be configuring the PHY.
* In this case, we cannot access the PHY until the
* configuration is done. So we explicitly set the
* PHY ID.
*/
phy->id = IGP01E1000_I_PHY_ID;
break;
case e1000_82573:
return e1000e_get_phy_id(hw);
case e1000_82574:
case e1000_82583:
ret_val = e1e_rphy(hw, MII_PHYSID1, &phy_id);
if (ret_val)
return ret_val;
phy->id = (u32)(phy_id << 16);
usleep_range(20, 40);
ret_val = e1e_rphy(hw, MII_PHYSID2, &phy_id);
if (ret_val)
return ret_val;
phy->id |= (u32)(phy_id);
phy->revision = (u32)(phy_id & ~PHY_REVISION_MASK);
break;
default:
return -E1000_ERR_PHY;
}
return 0;
}
/**
* e1000_get_hw_semaphore_82571 - Acquire hardware semaphore
* @hw: pointer to the HW structure
*
* Acquire the HW semaphore to access the PHY or NVM
**/
static s32 e1000_get_hw_semaphore_82571(struct e1000_hw *hw)
{
u32 swsm;
s32 sw_timeout = hw->nvm.word_size + 1;
s32 fw_timeout = hw->nvm.word_size + 1;
s32 i = 0;
/* If we have timedout 3 times on trying to acquire
* the inter-port SMBI semaphore, there is old code
* operating on the other port, and it is not
* releasing SMBI. Modify the number of times that
* we try for the semaphore to interwork with this
* older code.
*/
if (hw->dev_spec.e82571.smb_counter > 2)
sw_timeout = 1;
/* Get the SW semaphore */
while (i < sw_timeout) {
swsm = er32(SWSM);
if (!(swsm & E1000_SWSM_SMBI))
break;
usleep_range(50, 100);
i++;
}
if (i == sw_timeout) {
e_dbg("Driver can't access device - SMBI bit is set.\n");
hw->dev_spec.e82571.smb_counter++;
}
/* Get the FW semaphore. */
for (i = 0; i < fw_timeout; i++) {
swsm = er32(SWSM);
ew32(SWSM, swsm | E1000_SWSM_SWESMBI);
/* Semaphore acquired if bit latched */
if (er32(SWSM) & E1000_SWSM_SWESMBI)
break;
usleep_range(50, 100);
}
if (i == fw_timeout) {
/* Release semaphores */
e1000_put_hw_semaphore_82571(hw);
e_dbg("Driver can't access the NVM\n");
return -E1000_ERR_NVM;
}
return 0;
}
/**
* e1000_put_hw_semaphore_82571 - Release hardware semaphore
* @hw: pointer to the HW structure
*
* Release hardware semaphore used to access the PHY or NVM
**/
static void e1000_put_hw_semaphore_82571(struct e1000_hw *hw)
{
u32 swsm;
swsm = er32(SWSM);
swsm &= ~(E1000_SWSM_SMBI | E1000_SWSM_SWESMBI);
ew32(SWSM, swsm);
}
/**
* e1000_get_hw_semaphore_82573 - Acquire hardware semaphore
* @hw: pointer to the HW structure
*
* Acquire the HW semaphore during reset.
*
**/
static s32 e1000_get_hw_semaphore_82573(struct e1000_hw *hw)
{
u32 extcnf_ctrl;
s32 i = 0;
extcnf_ctrl = er32(EXTCNF_CTRL);
do {
extcnf_ctrl |= E1000_EXTCNF_CTRL_MDIO_SW_OWNERSHIP;
ew32(EXTCNF_CTRL, extcnf_ctrl);
extcnf_ctrl = er32(EXTCNF_CTRL);
if (extcnf_ctrl & E1000_EXTCNF_CTRL_MDIO_SW_OWNERSHIP)
break;
usleep_range(2000, 4000);
i++;
} while (i < MDIO_OWNERSHIP_TIMEOUT);
if (i == MDIO_OWNERSHIP_TIMEOUT) {
/* Release semaphores */
e1000_put_hw_semaphore_82573(hw);
e_dbg("Driver can't access the PHY\n");
return -E1000_ERR_PHY;
}
return 0;
}
/**
* e1000_put_hw_semaphore_82573 - Release hardware semaphore
* @hw: pointer to the HW structure
*
* Release hardware semaphore used during reset.
*
**/
static void e1000_put_hw_semaphore_82573(struct e1000_hw *hw)
{
u32 extcnf_ctrl;
extcnf_ctrl = er32(EXTCNF_CTRL);
extcnf_ctrl &= ~E1000_EXTCNF_CTRL_MDIO_SW_OWNERSHIP;
ew32(EXTCNF_CTRL, extcnf_ctrl);
}
static DEFINE_MUTEX(swflag_mutex);
/**
* e1000_get_hw_semaphore_82574 - Acquire hardware semaphore
* @hw: pointer to the HW structure
*
* Acquire the HW semaphore to access the PHY or NVM.
*
**/
static s32 e1000_get_hw_semaphore_82574(struct e1000_hw *hw)
{
s32 ret_val;
mutex_lock(&swflag_mutex);
ret_val = e1000_get_hw_semaphore_82573(hw);
if (ret_val)
mutex_unlock(&swflag_mutex);
return ret_val;
}
/**
* e1000_put_hw_semaphore_82574 - Release hardware semaphore
* @hw: pointer to the HW structure
*
* Release hardware semaphore used to access the PHY or NVM
*
**/
static void e1000_put_hw_semaphore_82574(struct e1000_hw *hw)
{
e1000_put_hw_semaphore_82573(hw);
mutex_unlock(&swflag_mutex);
}
/**
* e1000_set_d0_lplu_state_82574 - Set Low Power Linkup D0 state
* @hw: pointer to the HW structure
* @active: true to enable LPLU, false to disable
*
* Sets the LPLU D0 state according to the active flag.
* LPLU will not be activated unless the
* device autonegotiation advertisement meets standards of
* either 10 or 10/100 or 10/100/1000 at all duplexes.
* This is a function pointer entry point only called by
* PHY setup routines.
**/
static s32 e1000_set_d0_lplu_state_82574(struct e1000_hw *hw, bool active)
{
u32 data = er32(POEMB);
if (active)
data |= E1000_PHY_CTRL_D0A_LPLU;
else
data &= ~E1000_PHY_CTRL_D0A_LPLU;
ew32(POEMB, data);
return 0;
}
/**
* e1000_set_d3_lplu_state_82574 - Sets low power link up state for D3
* @hw: pointer to the HW structure
* @active: boolean used to enable/disable lplu
*
* The low power link up (lplu) state is set to the power management level D3
* when active is true, else clear lplu for D3. LPLU
* is used during Dx states where the power conservation is most important.
* During driver activity, SmartSpeed should be enabled so performance is
* maintained.
**/
static s32 e1000_set_d3_lplu_state_82574(struct e1000_hw *hw, bool active)
{
u32 data = er32(POEMB);
if (!active) {
data &= ~E1000_PHY_CTRL_NOND0A_LPLU;
} else if ((hw->phy.autoneg_advertised == E1000_ALL_SPEED_DUPLEX) ||
(hw->phy.autoneg_advertised == E1000_ALL_NOT_GIG) ||
(hw->phy.autoneg_advertised == E1000_ALL_10_SPEED)) {
data |= E1000_PHY_CTRL_NOND0A_LPLU;
}
ew32(POEMB, data);
return 0;
}
/**
* e1000_acquire_nvm_82571 - Request for access to the EEPROM
* @hw: pointer to the HW structure
*
* To gain access to the EEPROM, first we must obtain a hardware semaphore.
* Then for non-82573 hardware, set the EEPROM access request bit and wait
* for EEPROM access grant bit. If the access grant bit is not set, release
* hardware semaphore.
**/
static s32 e1000_acquire_nvm_82571(struct e1000_hw *hw)
{
s32 ret_val;
ret_val = e1000_get_hw_semaphore_82571(hw);
if (ret_val)
return ret_val;
switch (hw->mac.type) {
case e1000_82573:
break;
default:
ret_val = e1000e_acquire_nvm(hw);
break;
}
if (ret_val)
e1000_put_hw_semaphore_82571(hw);
return ret_val;
}
/**
* e1000_release_nvm_82571 - Release exclusive access to EEPROM
* @hw: pointer to the HW structure
*
* Stop any current commands to the EEPROM and clear the EEPROM request bit.
**/
static void e1000_release_nvm_82571(struct e1000_hw *hw)
{
e1000e_release_nvm(hw);
e1000_put_hw_semaphore_82571(hw);
}
/**
* e1000_write_nvm_82571 - Write to EEPROM using appropriate interface
* @hw: pointer to the HW structure
* @offset: offset within the EEPROM to be written to
* @words: number of words to write
* @data: 16 bit word(s) to be written to the EEPROM
*
* For non-82573 silicon, write data to EEPROM at offset using SPI interface.
*
* If e1000e_update_nvm_checksum is not called after this function, the
* EEPROM will most likely contain an invalid checksum.
**/
static s32 e1000_write_nvm_82571(struct e1000_hw *hw, u16 offset, u16 words,
u16 *data)
{
s32 ret_val;
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
ret_val = e1000_write_nvm_eewr_82571(hw, offset, words, data);
break;
case e1000_82571:
case e1000_82572:
ret_val = e1000e_write_nvm_spi(hw, offset, words, data);
break;
default:
ret_val = -E1000_ERR_NVM;
break;
}
return ret_val;
}
/**
* e1000_update_nvm_checksum_82571 - Update EEPROM checksum
* @hw: pointer to the HW structure
*
* Updates the EEPROM checksum by reading/adding each word of the EEPROM
* up to the checksum. Then calculates the EEPROM checksum and writes the
* value to the EEPROM.
**/
static s32 e1000_update_nvm_checksum_82571(struct e1000_hw *hw)
{
u32 eecd;
s32 ret_val;
u16 i;
ret_val = e1000e_update_nvm_checksum_generic(hw);
if (ret_val)
return ret_val;
/* If our nvm is an EEPROM, then we're done
* otherwise, commit the checksum to the flash NVM.
*/
if (hw->nvm.type != e1000_nvm_flash_hw)
return 0;
/* Check for pending operations. */
for (i = 0; i < E1000_FLASH_UPDATES; i++) {
usleep_range(1000, 2000);
if (!(er32(EECD) & E1000_EECD_FLUPD))
break;
}
if (i == E1000_FLASH_UPDATES)
return -E1000_ERR_NVM;
/* Reset the firmware if using STM opcode. */
if ((er32(FLOP) & 0xFF00) == E1000_STM_OPCODE) {
/* The enabling of and the actual reset must be done
* in two write cycles.
*/
ew32(HICR, E1000_HICR_FW_RESET_ENABLE);
e1e_flush();
ew32(HICR, E1000_HICR_FW_RESET);
}
/* Commit the write to flash */
eecd = er32(EECD) | E1000_EECD_FLUPD;
ew32(EECD, eecd);
for (i = 0; i < E1000_FLASH_UPDATES; i++) {
usleep_range(1000, 2000);
if (!(er32(EECD) & E1000_EECD_FLUPD))
break;
}
if (i == E1000_FLASH_UPDATES)
return -E1000_ERR_NVM;
return 0;
}
/**
* e1000_validate_nvm_checksum_82571 - Validate EEPROM checksum
* @hw: pointer to the HW structure
*
* Calculates the EEPROM checksum by reading/adding each word of the EEPROM
* and then verifies that the sum of the EEPROM is equal to 0xBABA.
**/
static s32 e1000_validate_nvm_checksum_82571(struct e1000_hw *hw)
{
if (hw->nvm.type == e1000_nvm_flash_hw)
e1000_fix_nvm_checksum_82571(hw);
return e1000e_validate_nvm_checksum_generic(hw);
}
/**
* e1000_write_nvm_eewr_82571 - Write to EEPROM for 82573 silicon
* @hw: pointer to the HW structure
* @offset: offset within the EEPROM to be written to
* @words: number of words to write
* @data: 16 bit word(s) to be written to the EEPROM
*
* After checking for invalid values, poll the EEPROM to ensure the previous
* command has completed before trying to write the next word. After write
* poll for completion.
*
* If e1000e_update_nvm_checksum is not called after this function, the
* EEPROM will most likely contain an invalid checksum.
**/
static s32 e1000_write_nvm_eewr_82571(struct e1000_hw *hw, u16 offset,
u16 words, u16 *data)
{
struct e1000_nvm_info *nvm = &hw->nvm;
u32 i, eewr = 0;
s32 ret_val = 0;
/* A check for invalid values: offset too large, too many words,
* and not enough words.
*/
if ((offset >= nvm->word_size) || (words > (nvm->word_size - offset)) ||
(words == 0)) {
e_dbg("nvm parameter(s) out of bounds\n");
return -E1000_ERR_NVM;
}
for (i = 0; i < words; i++) {
eewr = ((data[i] << E1000_NVM_RW_REG_DATA) |
((offset + i) << E1000_NVM_RW_ADDR_SHIFT) |
E1000_NVM_RW_REG_START);
ret_val = e1000e_poll_eerd_eewr_done(hw, E1000_NVM_POLL_WRITE);
if (ret_val)
break;
ew32(EEWR, eewr);
ret_val = e1000e_poll_eerd_eewr_done(hw, E1000_NVM_POLL_WRITE);
if (ret_val)
break;
}
return ret_val;
}
/**
* e1000_get_cfg_done_82571 - Poll for configuration done
* @hw: pointer to the HW structure
*
* Reads the management control register for the config done bit to be set.
**/
static s32 e1000_get_cfg_done_82571(struct e1000_hw *hw)
{
s32 timeout = PHY_CFG_TIMEOUT;
while (timeout) {
if (er32(EEMNGCTL) & E1000_NVM_CFG_DONE_PORT_0)
break;
usleep_range(1000, 2000);
timeout--;
}
if (!timeout) {
e_dbg("MNG configuration cycle has not completed.\n");
return -E1000_ERR_RESET;
}
return 0;
}
/**
* e1000_set_d0_lplu_state_82571 - Set Low Power Linkup D0 state
* @hw: pointer to the HW structure
* @active: true to enable LPLU, false to disable
*
* Sets the LPLU D0 state according to the active flag. When activating LPLU
* this function also disables smart speed and vice versa. LPLU will not be
* activated unless the device autonegotiation advertisement meets standards
* of either 10 or 10/100 or 10/100/1000 at all duplexes. This is a function
* pointer entry point only called by PHY setup routines.
**/
static s32 e1000_set_d0_lplu_state_82571(struct e1000_hw *hw, bool active)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val;
u16 data;
ret_val = e1e_rphy(hw, IGP02E1000_PHY_POWER_MGMT, &data);
if (ret_val)
return ret_val;
if (active) {
data |= IGP02E1000_PM_D0_LPLU;
ret_val = e1e_wphy(hw, IGP02E1000_PHY_POWER_MGMT, data);
if (ret_val)
return ret_val;
/* When LPLU is enabled, we should disable SmartSpeed */
ret_val = e1e_rphy(hw, IGP01E1000_PHY_PORT_CONFIG, &data);
if (ret_val)
return ret_val;
data &= ~IGP01E1000_PSCFR_SMART_SPEED;
ret_val = e1e_wphy(hw, IGP01E1000_PHY_PORT_CONFIG, data);
if (ret_val)
return ret_val;
} else {
data &= ~IGP02E1000_PM_D0_LPLU;
ret_val = e1e_wphy(hw, IGP02E1000_PHY_POWER_MGMT, data);
/* LPLU and SmartSpeed are mutually exclusive. LPLU is used
* during Dx states where the power conservation is most
* important. During driver activity we should enable
* SmartSpeed, so performance is maintained.
*/
if (phy->smart_speed == e1000_smart_speed_on) {
ret_val = e1e_rphy(hw, IGP01E1000_PHY_PORT_CONFIG,
&data);
if (ret_val)
return ret_val;
data |= IGP01E1000_PSCFR_SMART_SPEED;
ret_val = e1e_wphy(hw, IGP01E1000_PHY_PORT_CONFIG,
data);
if (ret_val)
return ret_val;
} else if (phy->smart_speed == e1000_smart_speed_off) {
ret_val = e1e_rphy(hw, IGP01E1000_PHY_PORT_CONFIG,
&data);
if (ret_val)
return ret_val;
data &= ~IGP01E1000_PSCFR_SMART_SPEED;
ret_val = e1e_wphy(hw, IGP01E1000_PHY_PORT_CONFIG,
data);
if (ret_val)
return ret_val;
}
}
return 0;
}
/**
* e1000_reset_hw_82571 - Reset hardware
* @hw: pointer to the HW structure
*
* This resets the hardware into a known state.
**/
static s32 e1000_reset_hw_82571(struct e1000_hw *hw)
{
u32 ctrl, ctrl_ext, eecd, tctl;
s32 ret_val;
/* Prevent the PCI-E bus from sticking if there is no TLP connection
* on the last TLP read/write transaction when MAC is reset.
*/
ret_val = e1000e_disable_pcie_master(hw);
if (ret_val)
e_dbg("PCI-E Master disable polling has failed.\n");
e_dbg("Masking off all interrupts\n");
ew32(IMC, 0xffffffff);
ew32(RCTL, 0);
tctl = er32(TCTL);
tctl &= ~E1000_TCTL_EN;
ew32(TCTL, tctl);
e1e_flush();
usleep_range(10000, 20000);
/* Must acquire the MDIO ownership before MAC reset.
* Ownership defaults to firmware after a reset.
*/
switch (hw->mac.type) {
case e1000_82573:
ret_val = e1000_get_hw_semaphore_82573(hw);
break;
case e1000_82574:
case e1000_82583:
ret_val = e1000_get_hw_semaphore_82574(hw);
break;
default:
break;
}
ctrl = er32(CTRL);
e_dbg("Issuing a global reset to MAC\n");
ew32(CTRL, ctrl | E1000_CTRL_RST);
/* Must release MDIO ownership and mutex after MAC reset. */
switch (hw->mac.type) {
case e1000_82573:
/* Release mutex only if the hw semaphore is acquired */
if (!ret_val)
e1000_put_hw_semaphore_82573(hw);
break;
case e1000_82574:
case e1000_82583:
/* Release mutex only if the hw semaphore is acquired */
if (!ret_val)
e1000_put_hw_semaphore_82574(hw);
break;
default:
break;
}
if (hw->nvm.type == e1000_nvm_flash_hw) {
usleep_range(10, 20);
ctrl_ext = er32(CTRL_EXT);
ctrl_ext |= E1000_CTRL_EXT_EE_RST;
ew32(CTRL_EXT, ctrl_ext);
e1e_flush();
}
ret_val = e1000e_get_auto_rd_done(hw);
if (ret_val)
/* We don't want to continue accessing MAC registers. */
return ret_val;
/* Phy configuration from NVM just starts after EECD_AUTO_RD is set.
* Need to wait for Phy configuration completion before accessing
* NVM and Phy.
*/
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
/* REQ and GNT bits need to be cleared when using AUTO_RD
* to access the EEPROM.
*/
eecd = er32(EECD);
eecd &= ~(E1000_EECD_REQ | E1000_EECD_GNT);
ew32(EECD, eecd);
break;
case e1000_82573:
case e1000_82574:
case e1000_82583:
msleep(25);
break;
default:
break;
}
/* Clear any pending interrupt events. */
ew32(IMC, 0xffffffff);
er32(ICR);
if (hw->mac.type == e1000_82571) {
/* Install any alternate MAC address into RAR0 */
ret_val = e1000_check_alt_mac_addr_generic(hw);
if (ret_val)
return ret_val;
e1000e_set_laa_state_82571(hw, true);
}
/* Reinitialize the 82571 serdes link state machine */
if (hw->phy.media_type == e1000_media_type_internal_serdes)
hw->mac.serdes_link_state = e1000_serdes_link_down;
return 0;
}
/**
* e1000_init_hw_82571 - Initialize hardware
* @hw: pointer to the HW structure
*
* This inits the hardware readying it for operation.
**/
static s32 e1000_init_hw_82571(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 reg_data;
s32 ret_val;
u16 i, rar_count = mac->rar_entry_count;
e1000_initialize_hw_bits_82571(hw);
/* Initialize identification LED */
ret_val = mac->ops.id_led_init(hw);
/* An error is not fatal and we should not stop init due to this */
if (ret_val)
e_dbg("Error initializing identification LED\n");
/* Disabling VLAN filtering */
e_dbg("Initializing the IEEE VLAN\n");
mac->ops.clear_vfta(hw);
/* Setup the receive address.
* If, however, a locally administered address was assigned to the
* 82571, we must reserve a RAR for it to work around an issue where
* resetting one port will reload the MAC on the other port.
*/
if (e1000e_get_laa_state_82571(hw))
rar_count--;
e1000e_init_rx_addrs(hw, rar_count);
/* Zero out the Multicast HASH table */
e_dbg("Zeroing the MTA\n");
for (i = 0; i < mac->mta_reg_count; i++)
E1000_WRITE_REG_ARRAY(hw, E1000_MTA, i, 0);
/* Setup link and flow control */
ret_val = mac->ops.setup_link(hw);
/* Set the transmit descriptor write-back policy */
reg_data = er32(TXDCTL(0));
reg_data = ((reg_data & ~E1000_TXDCTL_WTHRESH) |
E1000_TXDCTL_FULL_TX_DESC_WB | E1000_TXDCTL_COUNT_DESC);
ew32(TXDCTL(0), reg_data);
/* ...for both queues. */
switch (mac->type) {
case e1000_82573:
e1000e_enable_tx_pkt_filtering(hw);
/* fall through */
case e1000_82574:
case e1000_82583:
reg_data = er32(GCR);
reg_data |= E1000_GCR_L1_ACT_WITHOUT_L0S_RX;
ew32(GCR, reg_data);
break;
default:
reg_data = er32(TXDCTL(1));
reg_data = ((reg_data & ~E1000_TXDCTL_WTHRESH) |
E1000_TXDCTL_FULL_TX_DESC_WB |
E1000_TXDCTL_COUNT_DESC);
ew32(TXDCTL(1), reg_data);
break;
}
/* Clear all of the statistics registers (clear on read). It is
* important that we do this after we have tried to establish link
* because the symbol error count will increment wildly if there
* is no link.
*/
e1000_clear_hw_cntrs_82571(hw);
return ret_val;
}
/**
* e1000_initialize_hw_bits_82571 - Initialize hardware-dependent bits
* @hw: pointer to the HW structure
*
* Initializes required hardware-dependent bits needed for normal operation.
**/
static void e1000_initialize_hw_bits_82571(struct e1000_hw *hw)
{
u32 reg;
/* Transmit Descriptor Control 0 */
reg = er32(TXDCTL(0));
reg |= (1 << 22);
ew32(TXDCTL(0), reg);
/* Transmit Descriptor Control 1 */
reg = er32(TXDCTL(1));
reg |= (1 << 22);
ew32(TXDCTL(1), reg);
/* Transmit Arbitration Control 0 */
reg = er32(TARC(0));
reg &= ~(0xF << 27); /* 30:27 */
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
reg |= (1 << 23) | (1 << 24) | (1 << 25) | (1 << 26);
break;
case e1000_82574:
case e1000_82583:
reg |= (1 << 26);
break;
default:
break;
}
ew32(TARC(0), reg);
/* Transmit Arbitration Control 1 */
reg = er32(TARC(1));
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
reg &= ~((1 << 29) | (1 << 30));
reg |= (1 << 22) | (1 << 24) | (1 << 25) | (1 << 26);
if (er32(TCTL) & E1000_TCTL_MULR)
reg &= ~(1 << 28);
else
reg |= (1 << 28);
ew32(TARC(1), reg);
break;
default:
break;
}
/* Device Control */
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
reg = er32(CTRL);
reg &= ~(1 << 29);
ew32(CTRL, reg);
break;
default:
break;
}
/* Extended Device Control */
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
reg = er32(CTRL_EXT);
reg &= ~(1 << 23);
reg |= (1 << 22);
ew32(CTRL_EXT, reg);
break;
default:
break;
}
if (hw->mac.type == e1000_82571) {
reg = er32(PBA_ECC);
reg |= E1000_PBA_ECC_CORR_EN;
ew32(PBA_ECC, reg);
}
/* Workaround for hardware errata.
* Ensure that DMA Dynamic Clock gating is disabled on 82571 and 82572
*/
if ((hw->mac.type == e1000_82571) || (hw->mac.type == e1000_82572)) {
reg = er32(CTRL_EXT);
reg &= ~E1000_CTRL_EXT_DMA_DYN_CLK_EN;
ew32(CTRL_EXT, reg);
}
/* Disable IPv6 extension header parsing because some malformed
* IPv6 headers can hang the Rx.
*/
if (hw->mac.type <= e1000_82573) {
reg = er32(RFCTL);
reg |= (E1000_RFCTL_IPV6_EX_DIS | E1000_RFCTL_NEW_IPV6_EXT_DIS);
ew32(RFCTL, reg);
}
/* PCI-Ex Control Registers */
switch (hw->mac.type) {
case e1000_82574:
case e1000_82583:
reg = er32(GCR);
reg |= (1 << 22);
ew32(GCR, reg);
/* Workaround for hardware errata.
* apply workaround for hardware errata documented in errata
* docs Fixes issue where some error prone or unreliable PCIe
* completions are occurring, particularly with ASPM enabled.
* Without fix, issue can cause Tx timeouts.
*/
reg = er32(GCR2);
reg |= 1;
ew32(GCR2, reg);
break;
default:
break;
}
}
/**
* e1000_clear_vfta_82571 - Clear VLAN filter table
* @hw: pointer to the HW structure
*
* Clears the register array which contains the VLAN filter table by
* setting all the values to 0.
**/
static void e1000_clear_vfta_82571(struct e1000_hw *hw)
{
u32 offset;
u32 vfta_value = 0;
u32 vfta_offset = 0;
u32 vfta_bit_in_reg = 0;
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
if (hw->mng_cookie.vlan_id != 0) {
/* The VFTA is a 4096b bit-field, each identifying
* a single VLAN ID. The following operations
* determine which 32b entry (i.e. offset) into the
* array we want to set the VLAN ID (i.e. bit) of
* the manageability unit.
*/
vfta_offset = (hw->mng_cookie.vlan_id >>
E1000_VFTA_ENTRY_SHIFT) &
E1000_VFTA_ENTRY_MASK;
vfta_bit_in_reg =
1 << (hw->mng_cookie.vlan_id &
E1000_VFTA_ENTRY_BIT_SHIFT_MASK);
}
break;
default:
break;
}
for (offset = 0; offset < E1000_VLAN_FILTER_TBL_SIZE; offset++) {
/* If the offset we want to clear is the same offset of the
* manageability VLAN ID, then clear all bits except that of
* the manageability unit.
*/
vfta_value = (offset == vfta_offset) ? vfta_bit_in_reg : 0;
E1000_WRITE_REG_ARRAY(hw, E1000_VFTA, offset, vfta_value);
e1e_flush();
}
}
/**
* e1000_check_mng_mode_82574 - Check manageability is enabled
* @hw: pointer to the HW structure
*
* Reads the NVM Initialization Control Word 2 and returns true
* (>0) if any manageability is enabled, else false (0).
**/
static bool e1000_check_mng_mode_82574(struct e1000_hw *hw)
{
u16 data;
e1000_read_nvm(hw, NVM_INIT_CONTROL2_REG, 1, &data);
return (data & E1000_NVM_INIT_CTRL2_MNGM) != 0;
}
/**
* e1000_led_on_82574 - Turn LED on
* @hw: pointer to the HW structure
*
* Turn LED on.
**/
static s32 e1000_led_on_82574(struct e1000_hw *hw)
{
u32 ctrl;
u32 i;
ctrl = hw->mac.ledctl_mode2;
if (!(E1000_STATUS_LU & er32(STATUS))) {
/* If no link, then turn LED on by setting the invert bit
* for each LED that's "on" (0x0E) in ledctl_mode2.
*/
for (i = 0; i < 4; i++)
if (((hw->mac.ledctl_mode2 >> (i * 8)) & 0xFF) ==
E1000_LEDCTL_MODE_LED_ON)
ctrl |= (E1000_LEDCTL_LED0_IVRT << (i * 8));
}
ew32(LEDCTL, ctrl);
return 0;
}
/**
* e1000_check_phy_82574 - check 82574 phy hung state
* @hw: pointer to the HW structure
*
* Returns whether phy is hung or not
**/
bool e1000_check_phy_82574(struct e1000_hw *hw)
{
u16 status_1kbt = 0;
u16 receive_errors = 0;
s32 ret_val;
/* Read PHY Receive Error counter first, if its is max - all F's then
* read the Base1000T status register If both are max then PHY is hung.
*/
ret_val = e1e_rphy(hw, E1000_RECEIVE_ERROR_COUNTER, &receive_errors);
if (ret_val)
return false;
if (receive_errors == E1000_RECEIVE_ERROR_MAX) {
ret_val = e1e_rphy(hw, E1000_BASE1000T_STATUS, &status_1kbt);
if (ret_val)
return false;
if ((status_1kbt & E1000_IDLE_ERROR_COUNT_MASK) ==
E1000_IDLE_ERROR_COUNT_MASK)
return true;
}
return false;
}
/**
* e1000_setup_link_82571 - Setup flow control and link settings
* @hw: pointer to the HW structure
*
* Determines which flow control settings to use, then configures flow
* control. Calls the appropriate media-specific link configuration
* function. Assuming the adapter has a valid link partner, a valid link
* should be established. Assumes the hardware has previously been reset
* and the transmitter and receiver are not enabled.
**/
static s32 e1000_setup_link_82571(struct e1000_hw *hw)
{
/* 82573 does not have a word in the NVM to determine
* the default flow control setting, so we explicitly
* set it to full.
*/
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
if (hw->fc.requested_mode == e1000_fc_default)
hw->fc.requested_mode = e1000_fc_full;
break;
default:
break;
}
return e1000e_setup_link_generic(hw);
}
/**
* e1000_setup_copper_link_82571 - Configure copper link settings
* @hw: pointer to the HW structure
*
* Configures the link for auto-neg or forced speed and duplex. Then we check
* for link, once link is established calls to configure collision distance
* and flow control are called.
**/
static s32 e1000_setup_copper_link_82571(struct e1000_hw *hw)
{
u32 ctrl;
s32 ret_val;
ctrl = er32(CTRL);
ctrl |= E1000_CTRL_SLU;
ctrl &= ~(E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX);
ew32(CTRL, ctrl);
switch (hw->phy.type) {
case e1000_phy_m88:
case e1000_phy_bm:
ret_val = e1000e_copper_link_setup_m88(hw);
break;
case e1000_phy_igp_2:
ret_val = e1000e_copper_link_setup_igp(hw);
break;
default:
return -E1000_ERR_PHY;
}
if (ret_val)
return ret_val;
return e1000e_setup_copper_link(hw);
}
/**
* e1000_setup_fiber_serdes_link_82571 - Setup link for fiber/serdes
* @hw: pointer to the HW structure
*
* Configures collision distance and flow control for fiber and serdes links.
* Upon successful setup, poll for link.
**/
static s32 e1000_setup_fiber_serdes_link_82571(struct e1000_hw *hw)
{
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
/* If SerDes loopback mode is entered, there is no form
* of reset to take the adapter out of that mode. So we
* have to explicitly take the adapter out of loopback
* mode. This prevents drivers from twiddling their thumbs
* if another tool failed to take it out of loopback mode.
*/
ew32(SCTL, E1000_SCTL_DISABLE_SERDES_LOOPBACK);
break;
default:
break;
}
return e1000e_setup_fiber_serdes_link(hw);
}
/**
* e1000_check_for_serdes_link_82571 - Check for link (Serdes)
* @hw: pointer to the HW structure
*
* Reports the link state as up or down.
*
* If autonegotiation is supported by the link partner, the link state is
* determined by the result of autonegotiation. This is the most likely case.
* If autonegotiation is not supported by the link partner, and the link
* has a valid signal, force the link up.
*
* The link state is represented internally here by 4 states:
*
* 1) down
* 2) autoneg_progress
* 3) autoneg_complete (the link successfully autonegotiated)
* 4) forced_up (the link has been forced up, it did not autonegotiate)
*
**/
static s32 e1000_check_for_serdes_link_82571(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 rxcw;
u32 ctrl;
u32 status;
u32 txcw;
u32 i;
s32 ret_val = 0;
ctrl = er32(CTRL);
status = er32(STATUS);
er32(RXCW);
/* SYNCH bit and IV bit are sticky */
usleep_range(10, 20);
rxcw = er32(RXCW);
if ((rxcw & E1000_RXCW_SYNCH) && !(rxcw & E1000_RXCW_IV)) {
/* Receiver is synchronized with no invalid bits. */
switch (mac->serdes_link_state) {
case e1000_serdes_link_autoneg_complete:
if (!(status & E1000_STATUS_LU)) {
/* We have lost link, retry autoneg before
* reporting link failure
*/
mac->serdes_link_state =
e1000_serdes_link_autoneg_progress;
mac->serdes_has_link = false;
e_dbg("AN_UP -> AN_PROG\n");
} else {
mac->serdes_has_link = true;
}
break;
case e1000_serdes_link_forced_up:
/* If we are receiving /C/ ordered sets, re-enable
* auto-negotiation in the TXCW register and disable
* forced link in the Device Control register in an
* attempt to auto-negotiate with our link partner.
*/
if (rxcw & E1000_RXCW_C) {
/* Enable autoneg, and unforce link up */
ew32(TXCW, mac->txcw);
ew32(CTRL, (ctrl & ~E1000_CTRL_SLU));
mac->serdes_link_state =
e1000_serdes_link_autoneg_progress;
mac->serdes_has_link = false;
e_dbg("FORCED_UP -> AN_PROG\n");
} else {
mac->serdes_has_link = true;
}
break;
case e1000_serdes_link_autoneg_progress:
if (rxcw & E1000_RXCW_C) {
/* We received /C/ ordered sets, meaning the
* link partner has autonegotiated, and we can
* trust the Link Up (LU) status bit.
*/
if (status & E1000_STATUS_LU) {
mac->serdes_link_state =
e1000_serdes_link_autoneg_complete;
e_dbg("AN_PROG -> AN_UP\n");
mac->serdes_has_link = true;
} else {
/* Autoneg completed, but failed. */
mac->serdes_link_state =
e1000_serdes_link_down;
e_dbg("AN_PROG -> DOWN\n");
}
} else {
/* The link partner did not autoneg.
* Force link up and full duplex, and change
* state to forced.
*/
ew32(TXCW, (mac->txcw & ~E1000_TXCW_ANE));
ctrl |= (E1000_CTRL_SLU | E1000_CTRL_FD);
ew32(CTRL, ctrl);
/* Configure Flow Control after link up. */
ret_val = e1000e_config_fc_after_link_up(hw);
if (ret_val) {
e_dbg("Error config flow control\n");
break;
}
mac->serdes_link_state =
e1000_serdes_link_forced_up;
mac->serdes_has_link = true;
e_dbg("AN_PROG -> FORCED_UP\n");
}
break;
case e1000_serdes_link_down:
default:
/* The link was down but the receiver has now gained
* valid sync, so lets see if we can bring the link
* up.
*/
ew32(TXCW, mac->txcw);
ew32(CTRL, (ctrl & ~E1000_CTRL_SLU));
mac->serdes_link_state =
e1000_serdes_link_autoneg_progress;
mac->serdes_has_link = false;
e_dbg("DOWN -> AN_PROG\n");
break;
}
} else {
if (!(rxcw & E1000_RXCW_SYNCH)) {
mac->serdes_has_link = false;
mac->serdes_link_state = e1000_serdes_link_down;
e_dbg("ANYSTATE -> DOWN\n");
} else {
/* Check several times, if SYNCH bit and CONFIG
* bit both are consistently 1 then simply ignore
* the IV bit and restart Autoneg
*/
for (i = 0; i < AN_RETRY_COUNT; i++) {
usleep_range(10, 20);
rxcw = er32(RXCW);
if ((rxcw & E1000_RXCW_SYNCH) &&
(rxcw & E1000_RXCW_C))
continue;
if (rxcw & E1000_RXCW_IV) {
mac->serdes_has_link = false;
mac->serdes_link_state =
e1000_serdes_link_down;
e_dbg("ANYSTATE -> DOWN\n");
break;
}
}
if (i == AN_RETRY_COUNT) {
txcw = er32(TXCW);
txcw |= E1000_TXCW_ANE;
ew32(TXCW, txcw);
mac->serdes_link_state =
e1000_serdes_link_autoneg_progress;
mac->serdes_has_link = false;
e_dbg("ANYSTATE -> AN_PROG\n");
}
}
}
return ret_val;
}
/**
* e1000_valid_led_default_82571 - Verify a valid default LED config
* @hw: pointer to the HW structure
* @data: pointer to the NVM (EEPROM)
*
* Read the EEPROM for the current default LED configuration. If the
* LED configuration is not valid, set to a valid LED configuration.
**/
static s32 e1000_valid_led_default_82571(struct e1000_hw *hw, u16 *data)
{
s32 ret_val;
ret_val = e1000_read_nvm(hw, NVM_ID_LED_SETTINGS, 1, data);
if (ret_val) {
e_dbg("NVM Read Error\n");
return ret_val;
}
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
if (*data == ID_LED_RESERVED_F746)
*data = ID_LED_DEFAULT_82573;
break;
default:
if (*data == ID_LED_RESERVED_0000 ||
*data == ID_LED_RESERVED_FFFF)
*data = ID_LED_DEFAULT;
break;
}
return 0;
}
/**
* e1000e_get_laa_state_82571 - Get locally administered address state
* @hw: pointer to the HW structure
*
* Retrieve and return the current locally administered address state.
**/
bool e1000e_get_laa_state_82571(struct e1000_hw *hw)
{
if (hw->mac.type != e1000_82571)
return false;
return hw->dev_spec.e82571.laa_is_present;
}
/**
* e1000e_set_laa_state_82571 - Set locally administered address state
* @hw: pointer to the HW structure
* @state: enable/disable locally administered address
*
* Enable/Disable the current locally administered address state.
**/
void e1000e_set_laa_state_82571(struct e1000_hw *hw, bool state)
{
if (hw->mac.type != e1000_82571)
return;
hw->dev_spec.e82571.laa_is_present = state;
/* If workaround is activated... */
if (state)
/* Hold a copy of the LAA in RAR[14] This is done so that
* between the time RAR[0] gets clobbered and the time it
* gets fixed, the actual LAA is in one of the RARs and no
* incoming packets directed to this port are dropped.
* Eventually the LAA will be in RAR[0] and RAR[14].
*/
hw->mac.ops.rar_set(hw, hw->mac.addr,
hw->mac.rar_entry_count - 1);
}
/**
* e1000_fix_nvm_checksum_82571 - Fix EEPROM checksum
* @hw: pointer to the HW structure
*
* Verifies that the EEPROM has completed the update. After updating the
* EEPROM, we need to check bit 15 in work 0x23 for the checksum fix. If
* the checksum fix is not implemented, we need to set the bit and update
* the checksum. Otherwise, if bit 15 is set and the checksum is incorrect,
* we need to return bad checksum.
**/
static s32 e1000_fix_nvm_checksum_82571(struct e1000_hw *hw)
{
struct e1000_nvm_info *nvm = &hw->nvm;
s32 ret_val;
u16 data;
if (nvm->type != e1000_nvm_flash_hw)
return 0;
/* Check bit 4 of word 10h. If it is 0, firmware is done updating
* 10h-12h. Checksum may need to be fixed.
*/
ret_val = e1000_read_nvm(hw, 0x10, 1, &data);
if (ret_val)
return ret_val;
if (!(data & 0x10)) {
/* Read 0x23 and check bit 15. This bit is a 1
* when the checksum has already been fixed. If
* the checksum is still wrong and this bit is a
* 1, we need to return bad checksum. Otherwise,
* we need to set this bit to a 1 and update the
* checksum.
*/
ret_val = e1000_read_nvm(hw, 0x23, 1, &data);
if (ret_val)
return ret_val;
if (!(data & 0x8000)) {
data |= 0x8000;
ret_val = e1000_write_nvm(hw, 0x23, 1, &data);
if (ret_val)
return ret_val;
ret_val = e1000e_update_nvm_checksum(hw);
if (ret_val)
return ret_val;
}
}
return 0;
}
/**
* e1000_read_mac_addr_82571 - Read device MAC address
* @hw: pointer to the HW structure
**/
static s32 e1000_read_mac_addr_82571(struct e1000_hw *hw)
{
if (hw->mac.type == e1000_82571) {
s32 ret_val;
/* If there's an alternate MAC address place it in RAR0
* so that it will override the Si installed default perm
* address.
*/
ret_val = e1000_check_alt_mac_addr_generic(hw);
if (ret_val)
return ret_val;
}
return e1000_read_mac_addr_generic(hw);
}
/**
* e1000_power_down_phy_copper_82571 - Remove link during PHY power down
* @hw: pointer to the HW structure
*
* In the case of a PHY power down to save power, or to turn off link during a
* driver unload, or wake on lan is not enabled, remove the link.
**/
static void e1000_power_down_phy_copper_82571(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
struct e1000_mac_info *mac = &hw->mac;
if (!phy->ops.check_reset_block)
return;
/* If the management interface is not enabled, then power down */
if (!(mac->ops.check_mng_mode(hw) || phy->ops.check_reset_block(hw)))
e1000_power_down_phy_copper(hw);
}
/**
* e1000_clear_hw_cntrs_82571 - Clear device specific hardware counters
* @hw: pointer to the HW structure
*
* Clears the hardware counters by reading the counter registers.
**/
static void e1000_clear_hw_cntrs_82571(struct e1000_hw *hw)
{
e1000e_clear_hw_cntrs_base(hw);
er32(PRC64);
er32(PRC127);
er32(PRC255);
er32(PRC511);
er32(PRC1023);
er32(PRC1522);
er32(PTC64);
er32(PTC127);
er32(PTC255);
er32(PTC511);
er32(PTC1023);
er32(PTC1522);
er32(ALGNERRC);
er32(RXERRC);
er32(TNCRS);
er32(CEXTERR);
er32(TSCTC);
er32(TSCTFC);
er32(MGTPRC);
er32(MGTPDC);
er32(MGTPTC);
er32(IAC);
er32(ICRXOC);
er32(ICRXPTC);
er32(ICRXATC);
er32(ICTXPTC);
er32(ICTXATC);
er32(ICTXQEC);
er32(ICTXQMTC);
er32(ICRXDMTC);
}
static const struct e1000_mac_operations e82571_mac_ops = {
/* .check_mng_mode: mac type dependent */
/* .check_for_link: media type dependent */
.id_led_init = e1000e_id_led_init_generic,
.cleanup_led = e1000e_cleanup_led_generic,
.clear_hw_cntrs = e1000_clear_hw_cntrs_82571,
.get_bus_info = e1000e_get_bus_info_pcie,
.set_lan_id = e1000_set_lan_id_multi_port_pcie,
/* .get_link_up_info: media type dependent */
/* .led_on: mac type dependent */
.led_off = e1000e_led_off_generic,
.update_mc_addr_list = e1000e_update_mc_addr_list_generic,
.write_vfta = e1000_write_vfta_generic,
.clear_vfta = e1000_clear_vfta_82571,
.reset_hw = e1000_reset_hw_82571,
.init_hw = e1000_init_hw_82571,
.setup_link = e1000_setup_link_82571,
/* .setup_physical_interface: media type dependent */
.setup_led = e1000e_setup_led_generic,
.config_collision_dist = e1000e_config_collision_dist_generic,
.read_mac_addr = e1000_read_mac_addr_82571,
.rar_set = e1000e_rar_set_generic,
.rar_get_count = e1000e_rar_get_count_generic,
};
static const struct e1000_phy_operations e82_phy_ops_igp = {
.acquire = e1000_get_hw_semaphore_82571,
.check_polarity = e1000_check_polarity_igp,
.check_reset_block = e1000e_check_reset_block_generic,
.commit = NULL,
.force_speed_duplex = e1000e_phy_force_speed_duplex_igp,
.get_cfg_done = e1000_get_cfg_done_82571,
.get_cable_length = e1000e_get_cable_length_igp_2,
.get_info = e1000e_get_phy_info_igp,
.read_reg = e1000e_read_phy_reg_igp,
.release = e1000_put_hw_semaphore_82571,
.reset = e1000e_phy_hw_reset_generic,
.set_d0_lplu_state = e1000_set_d0_lplu_state_82571,
.set_d3_lplu_state = e1000e_set_d3_lplu_state,
.write_reg = e1000e_write_phy_reg_igp,
.cfg_on_link_up = NULL,
};
static const struct e1000_phy_operations e82_phy_ops_m88 = {
.acquire = e1000_get_hw_semaphore_82571,
.check_polarity = e1000_check_polarity_m88,
.check_reset_block = e1000e_check_reset_block_generic,
.commit = e1000e_phy_sw_reset,
.force_speed_duplex = e1000e_phy_force_speed_duplex_m88,
.get_cfg_done = e1000e_get_cfg_done_generic,
.get_cable_length = e1000e_get_cable_length_m88,
.get_info = e1000e_get_phy_info_m88,
.read_reg = e1000e_read_phy_reg_m88,
.release = e1000_put_hw_semaphore_82571,
.reset = e1000e_phy_hw_reset_generic,
.set_d0_lplu_state = e1000_set_d0_lplu_state_82571,
.set_d3_lplu_state = e1000e_set_d3_lplu_state,
.write_reg = e1000e_write_phy_reg_m88,
.cfg_on_link_up = NULL,
};
static const struct e1000_phy_operations e82_phy_ops_bm = {
.acquire = e1000_get_hw_semaphore_82571,
.check_polarity = e1000_check_polarity_m88,
.check_reset_block = e1000e_check_reset_block_generic,
.commit = e1000e_phy_sw_reset,
.force_speed_duplex = e1000e_phy_force_speed_duplex_m88,
.get_cfg_done = e1000e_get_cfg_done_generic,
.get_cable_length = e1000e_get_cable_length_m88,
.get_info = e1000e_get_phy_info_m88,
.read_reg = e1000e_read_phy_reg_bm2,
.release = e1000_put_hw_semaphore_82571,
.reset = e1000e_phy_hw_reset_generic,
.set_d0_lplu_state = e1000_set_d0_lplu_state_82571,
.set_d3_lplu_state = e1000e_set_d3_lplu_state,
.write_reg = e1000e_write_phy_reg_bm2,
.cfg_on_link_up = NULL,
};
static const struct e1000_nvm_operations e82571_nvm_ops = {
.acquire = e1000_acquire_nvm_82571,
.read = e1000e_read_nvm_eerd,
.release = e1000_release_nvm_82571,
.reload = e1000e_reload_nvm_generic,
.update = e1000_update_nvm_checksum_82571,
.valid_led_default = e1000_valid_led_default_82571,
.validate = e1000_validate_nvm_checksum_82571,
.write = e1000_write_nvm_82571,
};
const struct e1000_info e1000_82571_info = {
.mac = e1000_82571,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_JUMBO_FRAMES
| FLAG_HAS_WOL
| FLAG_APME_IN_CTRL3
| FLAG_HAS_CTRLEXT_ON_LOAD
| FLAG_HAS_SMART_POWER_DOWN
| FLAG_RESET_OVERWRITES_LAA /* errata */
| FLAG_TARC_SPEED_MODE_BIT /* errata */
| FLAG_APME_CHECK_PORT_B,
.flags2 = FLAG2_DISABLE_ASPM_L1 /* errata 13 */
| FLAG2_DMA_BURST,
.pba = 38,
.max_hw_frame_size = DEFAULT_JUMBO,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_igp,
.nvm_ops = &e82571_nvm_ops,
};
const struct e1000_info e1000_82572_info = {
.mac = e1000_82572,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_JUMBO_FRAMES
| FLAG_HAS_WOL
| FLAG_APME_IN_CTRL3
| FLAG_HAS_CTRLEXT_ON_LOAD
| FLAG_TARC_SPEED_MODE_BIT, /* errata */
.flags2 = FLAG2_DISABLE_ASPM_L1 /* errata 13 */
| FLAG2_DMA_BURST,
.pba = 38,
.max_hw_frame_size = DEFAULT_JUMBO,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_igp,
.nvm_ops = &e82571_nvm_ops,
};
const struct e1000_info e1000_82573_info = {
.mac = e1000_82573,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_WOL
| FLAG_APME_IN_CTRL3
| FLAG_HAS_SMART_POWER_DOWN
| FLAG_HAS_AMT
| FLAG_HAS_SWSM_ON_LOAD,
.flags2 = FLAG2_DISABLE_ASPM_L1
| FLAG2_DISABLE_ASPM_L0S,
.pba = 20,
.max_hw_frame_size = ETH_FRAME_LEN + ETH_FCS_LEN,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_m88,
.nvm_ops = &e82571_nvm_ops,
};
const struct e1000_info e1000_82574_info = {
.mac = e1000_82574,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_MSIX
| FLAG_HAS_JUMBO_FRAMES
| FLAG_HAS_WOL
| FLAG_HAS_HW_TIMESTAMP
| FLAG_APME_IN_CTRL3
| FLAG_HAS_SMART_POWER_DOWN
| FLAG_HAS_AMT
| FLAG_HAS_CTRLEXT_ON_LOAD,
.flags2 = FLAG2_CHECK_PHY_HANG
| FLAG2_DISABLE_ASPM_L0S
| FLAG2_DISABLE_ASPM_L1
| FLAG2_NO_DISABLE_RX
| FLAG2_DMA_BURST,
.pba = 32,
.max_hw_frame_size = DEFAULT_JUMBO,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_bm,
.nvm_ops = &e82571_nvm_ops,
};
const struct e1000_info e1000_82583_info = {
.mac = e1000_82583,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_WOL
| FLAG_HAS_HW_TIMESTAMP
| FLAG_APME_IN_CTRL3
| FLAG_HAS_SMART_POWER_DOWN
| FLAG_HAS_AMT
| FLAG_HAS_JUMBO_FRAMES
| FLAG_HAS_CTRLEXT_ON_LOAD,
.flags2 = FLAG2_DISABLE_ASPM_L0S
| FLAG2_DISABLE_ASPM_L1
| FLAG2_NO_DISABLE_RX,
.pba = 32,
.max_hw_frame_size = DEFAULT_JUMBO,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_bm,
.nvm_ops = &e82571_nvm_ops,
};
| gpl-2.0 |
psyke83/android_kernel_samsung_msm-codeaurora | drivers/media/video/usbvision/usbvision-cards.c | 1756 | 31842 | /*
* usbvision-cards.c
* usbvision cards definition file
*
* Copyright (c) 1999-2005 Joerg Heckenbach <joerg@heckenbach-aw.de>
*
* This module is part of usbvision driver project.
* Updates to driver completed by Dwaine P. Garden
*
* 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/list.h>
#include <media/v4l2-dev.h>
#include <media/tuner.h>
#include "usbvision.h"
#include "usbvision-cards.h"
/* Supported Devices: A table for usbvision.c*/
struct usbvision_device_data_st usbvision_device_data[] = {
[XANBOO] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 4,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Xanboo",
},
[BELKIN_VIDEOBUS_II] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Belkin USB VideoBus II Adapter",
},
[BELKIN_VIDEOBUS] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Belkin Components USB VideoBus",
},
[BELKIN_USB_VIDEOBUS_II] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Belkin USB VideoBus II",
},
[ECHOFX_INTERVIEW_LITE] = {
.Interface = 0,
.Codec = CODEC_SAA7111,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 0,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = -1,
.Y_Offset = -1,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "echoFX InterView Lite",
},
[USBGEAR_USBG_V1] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "USBGear USBG-V1 resp. HAMA USB",
},
[D_LINK_V100] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 4,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 0,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "D-Link V100",
},
[X10_USB_CAMERA] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "X10 USB Camera",
},
[HPG_WINTV_LIVE_PAL_BG] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = -1,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Live (PAL B/G)",
},
[HPG_WINTV_LIVE_PRO_NTSC_MN] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 0,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Live Pro (NTSC M/N)",
},
[ZORAN_PMD_NOGATECH] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 2,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Zoran Co. PMD (Nogatech) AV-grabber Manhattan",
},
[NOGATECH_USB_TV_NTSC_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = -1,
.Y_Offset = 20,
.ModelString = "Nogatech USB-TV (NTSC) FM",
},
[PNY_USB_TV_NTSC_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = -1,
.Y_Offset = 20,
.ModelString = "PNY USB-TV (NTSC) FM",
},
[PV_PLAYTV_USB_PRO_PAL_FM] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "PixelView PlayTv-USB PRO (PAL) FM",
},
[ZT_721] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "ZTV ZT-721 2.4GHz USB A/V Receiver",
},
[HPG_WINTV_NTSC_MN] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = -1,
.Y_Offset = 20,
.ModelString = "Hauppauge WinTV USB (NTSC M/N)",
},
[HPG_WINTV_PAL_BG] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Hauppauge WinTV USB (PAL B/G)",
},
[HPG_WINTV_PAL_I] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Hauppauge WinTV USB (PAL I)",
},
[HPG_WINTV_PAL_SECAM_L] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_SECAM,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_SECAM,
.X_Offset = 0x80,
.Y_Offset = 0x16,
.ModelString = "Hauppauge WinTV USB (PAL/SECAM L)",
},
[HPG_WINTV_PAL_D_K] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Hauppauge WinTV USB (PAL D/K)",
},
[HPG_WINTV_NTSC_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Hauppauge WinTV USB (NTSC FM)",
},
[HPG_WINTV_PAL_BG_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Hauppauge WinTV USB (PAL B/G FM)",
},
[HPG_WINTV_PAL_I_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Hauppauge WinTV USB (PAL I FM)",
},
[HPG_WINTV_PAL_D_K_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Hauppauge WinTV USB (PAL D/K FM)",
},
[HPG_WINTV_PRO_NTSC_MN] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_MICROTUNE_4049FM5,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (NTSC M/N)",
},
[HPG_WINTV_PRO_NTSC_MN_V2] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_MICROTUNE_4049FM5,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (NTSC M/N) V2",
},
[HPG_WINTV_PRO_PAL] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_FM1216ME_MK3,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL/SECAM B/G/I/D/K/L)",
},
[HPG_WINTV_PRO_NTSC_MN_V3] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (NTSC M/N) V3",
},
[HPG_WINTV_PRO_PAL_BG] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL B/G)",
},
[HPG_WINTV_PRO_PAL_I] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL I)",
},
[HPG_WINTV_PRO_PAL_SECAM_L] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_SECAM,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_SECAM,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL/SECAM L)",
},
[HPG_WINTV_PRO_PAL_D_K] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL D/K)",
},
[HPG_WINTV_PRO_PAL_SECAM] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_SECAM,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_SECAM,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL/SECAM BGDK/I/L)",
},
[HPG_WINTV_PRO_PAL_SECAM_V2] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_SECAM,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_SECAM,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL/SECAM BGDK/I/L) V2",
},
[HPG_WINTV_PRO_PAL_BG_V2] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_ALPS_TSBE1_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL B/G) V2",
},
[HPG_WINTV_PRO_PAL_BG_D_K] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_ALPS_TSBE1_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL B/G,D/K)",
},
[HPG_WINTV_PRO_PAL_I_D_K] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_LG_PAL_NEW_TAPC,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL I,D/K)",
},
[HPG_WINTV_PRO_NTSC_MN_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (NTSC M/N FM)",
},
[HPG_WINTV_PRO_PAL_BG_FM] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL B/G FM)",
},
[HPG_WINTV_PRO_PAL_I_FM] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL I FM)",
},
[HPG_WINTV_PRO_PAL_D_K_FM] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL D/K FM)",
},
[HPG_WINTV_PRO_TEMIC_PAL_FM] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_MICROTUNE_4049FM5,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (Temic PAL/SECAM B/G/I/D/K/L FM)",
},
[HPG_WINTV_PRO_TEMIC_PAL_BG_FM] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_MICROTUNE_4049FM5,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (Temic PAL B/G FM)",
},
[HPG_WINTV_PRO_PAL_FM] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_FM1216ME_MK3,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (PAL/SECAM B/G/I/D/K/L FM)",
},
[HPG_WINTV_PRO_NTSC_MN_FM_V2] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Hauppauge WinTV USB Pro (NTSC M/N FM) V2",
},
[CAMTEL_TVB330] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = 5,
.Y_Offset = 5,
.ModelString = "Camtel Technology USB TV Genie Pro FM Model TVB330",
},
[DIGITAL_VIDEO_CREATOR_I] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 0,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Digital Video Creator I",
},
[GLOBAL_VILLAGE_GV_007_NTSC] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 0,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 82,
.Y_Offset = 20,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Global Village GV-007 (NTSC)",
},
[DAZZLE_DVC_50_REV_1_NTSC] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 0,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Dazzle Fusion Model DVC-50 Rev 1 (NTSC)",
},
[DAZZLE_DVC_80_REV_1_PAL] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 0,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Dazzle Fusion Model DVC-80 Rev 1 (PAL)",
},
[DAZZLE_DVC_90_REV_1_SECAM] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_SECAM,
.AudioChannels = 0,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Dazzle Fusion Model DVC-90 Rev 1 (SECAM)",
},
[ESKAPE_LABS_MYTV2GO] = {
.Interface = 0,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_FM1216ME_MK3,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Eskape Labs MyTV2Go",
},
[PINNA_PCTV_USB_PAL] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 0,
.Tuner = 1,
.TunerType = TUNER_TEMIC_4066FY5_PAL_I,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Pinnacle Studio PCTV USB (PAL)",
},
[PINNA_PCTV_USB_SECAM] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_SECAM,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_SECAM,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Pinnacle Studio PCTV USB (SECAM)",
},
[PINNA_PCTV_USB_PAL_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = 128,
.Y_Offset = 23,
.ModelString = "Pinnacle Studio PCTV USB (PAL) FM",
},
[MIRO_PCTV_USB] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_PAL,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Miro PCTV USB",
},
[PINNA_PCTV_USB_NTSC_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Pinnacle Studio PCTV USB (NTSC) FM",
},
[PINNA_PCTV_USB_NTSC_FM_V3] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Pinnacle Studio PCTV USB (NTSC) FM V3",
},
[PINNA_PCTV_USB_PAL_FM_V2] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_TEMIC_4009FR5_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Pinnacle Studio PCTV USB (PAL) FM V2",
},
[PINNA_PCTV_USB_NTSC_FM_V2] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_TEMIC_4039FR5_NTSC,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Pinnacle Studio PCTV USB (NTSC) FM V2",
},
[PINNA_PCTV_USB_PAL_FM_V3] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_TEMIC_4009FR5_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Pinnacle Studio PCTV USB (PAL) FM V3",
},
[PINNA_LINX_VD_IN_CAB_NTSC] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Pinnacle Studio Linx Video input cable (NTSC)",
},
[PINNA_LINX_VD_IN_CAB_PAL] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 2,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 0,
.TunerType = 0,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Pinnacle Studio Linx Video input cable (PAL)",
},
[PINNA_PCTV_BUNGEE_PAL_FM] = {
.Interface = -1,
.Codec = CODEC_SAA7113,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_PAL,
.AudioChannels = 1,
.Radio = 1,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_TEMIC_4009FR5_PAL,
.X_Offset = 0,
.Y_Offset = 3,
.Dvi_yuv_override = 1,
.Dvi_yuv = 7,
.ModelString = "Pinnacle PCTV Bungee USB (PAL) FM",
},
[HPG_WINTV] = {
.Interface = -1,
.Codec = CODEC_SAA7111,
.VideoChannels = 3,
.VideoNorm = V4L2_STD_NTSC,
.AudioChannels = 1,
.Radio = 0,
.vbi = 1,
.Tuner = 1,
.TunerType = TUNER_PHILIPS_NTSC_M,
.X_Offset = -1,
.Y_Offset = -1,
.ModelString = "Hauppauge WinTv-USB",
},
};
const int usbvision_device_data_size=ARRAY_SIZE(usbvision_device_data);
/* Supported Devices */
struct usb_device_id usbvision_table [] = {
{ USB_DEVICE(0x0a6f, 0x0400), .driver_info=XANBOO },
{ USB_DEVICE(0x050d, 0x0106), .driver_info=BELKIN_VIDEOBUS_II },
{ USB_DEVICE(0x050d, 0x0207), .driver_info=BELKIN_VIDEOBUS },
{ USB_DEVICE(0x050d, 0x0208), .driver_info=BELKIN_USB_VIDEOBUS_II },
{ USB_DEVICE(0x0571, 0x0002), .driver_info=ECHOFX_INTERVIEW_LITE },
{ USB_DEVICE(0x0573, 0x0003), .driver_info=USBGEAR_USBG_V1 },
{ USB_DEVICE(0x0573, 0x0400), .driver_info=D_LINK_V100 },
{ USB_DEVICE(0x0573, 0x2000), .driver_info=X10_USB_CAMERA },
{ USB_DEVICE(0x0573, 0x2d00), .driver_info=HPG_WINTV_LIVE_PAL_BG },
{ USB_DEVICE(0x0573, 0x2d01), .driver_info=HPG_WINTV_LIVE_PRO_NTSC_MN },
{ USB_DEVICE(0x0573, 0x2101), .driver_info=ZORAN_PMD_NOGATECH },
{ USB_DEVICE(0x0573, 0x4100), .driver_info=NOGATECH_USB_TV_NTSC_FM },
{ USB_DEVICE(0x0573, 0x4110), .driver_info=PNY_USB_TV_NTSC_FM },
{ USB_DEVICE(0x0573, 0x4450), .driver_info=PV_PLAYTV_USB_PRO_PAL_FM },
{ USB_DEVICE(0x0573, 0x4550), .driver_info=ZT_721 },
{ USB_DEVICE(0x0573, 0x4d00), .driver_info=HPG_WINTV_NTSC_MN },
{ USB_DEVICE(0x0573, 0x4d01), .driver_info=HPG_WINTV_PAL_BG },
{ USB_DEVICE(0x0573, 0x4d02), .driver_info=HPG_WINTV_PAL_I },
{ USB_DEVICE(0x0573, 0x4d03), .driver_info=HPG_WINTV_PAL_SECAM_L },
{ USB_DEVICE(0x0573, 0x4d04), .driver_info=HPG_WINTV_PAL_D_K },
{ USB_DEVICE(0x0573, 0x4d10), .driver_info=HPG_WINTV_NTSC_FM },
{ USB_DEVICE(0x0573, 0x4d11), .driver_info=HPG_WINTV_PAL_BG_FM },
{ USB_DEVICE(0x0573, 0x4d12), .driver_info=HPG_WINTV_PAL_I_FM },
{ USB_DEVICE(0x0573, 0x4d14), .driver_info=HPG_WINTV_PAL_D_K_FM },
{ USB_DEVICE(0x0573, 0x4d2a), .driver_info=HPG_WINTV_PRO_NTSC_MN },
{ USB_DEVICE(0x0573, 0x4d2b), .driver_info=HPG_WINTV_PRO_NTSC_MN_V2 },
{ USB_DEVICE(0x0573, 0x4d2c), .driver_info=HPG_WINTV_PRO_PAL },
{ USB_DEVICE(0x0573, 0x4d20), .driver_info = HPG_WINTV_PRO_NTSC_MN_V3 },
{ USB_DEVICE(0x0573, 0x4d21), .driver_info=HPG_WINTV_PRO_PAL_BG },
{ USB_DEVICE(0x0573, 0x4d22), .driver_info=HPG_WINTV_PRO_PAL_I },
{ USB_DEVICE(0x0573, 0x4d23), .driver_info=HPG_WINTV_PRO_PAL_SECAM_L },
{ USB_DEVICE(0x0573, 0x4d24), .driver_info=HPG_WINTV_PRO_PAL_D_K },
{ USB_DEVICE(0x0573, 0x4d25), .driver_info=HPG_WINTV_PRO_PAL_SECAM },
{ USB_DEVICE(0x0573, 0x4d26), .driver_info=HPG_WINTV_PRO_PAL_SECAM_V2 },
{ USB_DEVICE(0x0573, 0x4d27), .driver_info=HPG_WINTV_PRO_PAL_BG_V2 },
{ USB_DEVICE(0x0573, 0x4d28), .driver_info=HPG_WINTV_PRO_PAL_BG_D_K },
{ USB_DEVICE(0x0573, 0x4d29), .driver_info=HPG_WINTV_PRO_PAL_I_D_K },
{ USB_DEVICE(0x0573, 0x4d30), .driver_info=HPG_WINTV_PRO_NTSC_MN_FM },
{ USB_DEVICE(0x0573, 0x4d31), .driver_info=HPG_WINTV_PRO_PAL_BG_FM },
{ USB_DEVICE(0x0573, 0x4d32), .driver_info=HPG_WINTV_PRO_PAL_I_FM },
{ USB_DEVICE(0x0573, 0x4d34), .driver_info=HPG_WINTV_PRO_PAL_D_K_FM },
{ USB_DEVICE(0x0573, 0x4d35), .driver_info=HPG_WINTV_PRO_TEMIC_PAL_FM },
{ USB_DEVICE(0x0573, 0x4d36), .driver_info=HPG_WINTV_PRO_TEMIC_PAL_BG_FM },
{ USB_DEVICE(0x0573, 0x4d37), .driver_info=HPG_WINTV_PRO_PAL_FM },
{ USB_DEVICE(0x0573, 0x4d38), .driver_info=HPG_WINTV_PRO_NTSC_MN_FM_V2 },
{ USB_DEVICE(0x0768, 0x0006), .driver_info=CAMTEL_TVB330 },
{ USB_DEVICE(0x07d0, 0x0001), .driver_info=DIGITAL_VIDEO_CREATOR_I },
{ USB_DEVICE(0x07d0, 0x0002), .driver_info=GLOBAL_VILLAGE_GV_007_NTSC },
{ USB_DEVICE(0x07d0, 0x0003), .driver_info=DAZZLE_DVC_50_REV_1_NTSC },
{ USB_DEVICE(0x07d0, 0x0004), .driver_info=DAZZLE_DVC_80_REV_1_PAL },
{ USB_DEVICE(0x07d0, 0x0005), .driver_info=DAZZLE_DVC_90_REV_1_SECAM },
{ USB_DEVICE(0x07f8, 0x9104), .driver_info=ESKAPE_LABS_MYTV2GO },
{ USB_DEVICE(0x2304, 0x010d), .driver_info=PINNA_PCTV_USB_PAL },
{ USB_DEVICE(0x2304, 0x0109), .driver_info=PINNA_PCTV_USB_SECAM },
{ USB_DEVICE(0x2304, 0x0110), .driver_info=PINNA_PCTV_USB_PAL_FM },
{ USB_DEVICE(0x2304, 0x0111), .driver_info=MIRO_PCTV_USB },
{ USB_DEVICE(0x2304, 0x0112), .driver_info=PINNA_PCTV_USB_NTSC_FM },
{ USB_DEVICE(0x2304, 0x0113),
.driver_info = PINNA_PCTV_USB_NTSC_FM_V3 },
{ USB_DEVICE(0x2304, 0x0210), .driver_info=PINNA_PCTV_USB_PAL_FM_V2 },
{ USB_DEVICE(0x2304, 0x0212), .driver_info=PINNA_PCTV_USB_NTSC_FM_V2 },
{ USB_DEVICE(0x2304, 0x0214), .driver_info=PINNA_PCTV_USB_PAL_FM_V3 },
{ USB_DEVICE(0x2304, 0x0300), .driver_info=PINNA_LINX_VD_IN_CAB_NTSC },
{ USB_DEVICE(0x2304, 0x0301), .driver_info=PINNA_LINX_VD_IN_CAB_PAL },
{ USB_DEVICE(0x2304, 0x0419), .driver_info=PINNA_PCTV_BUNGEE_PAL_FM },
{ USB_DEVICE(0x2400, 0x4200), .driver_info=HPG_WINTV },
{ }, /* terminate list */
};
MODULE_DEVICE_TABLE (usb, usbvision_table);
| gpl-2.0 |
shakalaca/ASUS_ZenFone_ZX551ML | linux/kernel/drivers/gpu/drm/nouveau/core/subdev/fb/nv46.c | 2268 | 2539 | /*
* Copyright (C) 2010 Francisco Jerez.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <subdev/fb.h>
struct nv46_fb_priv {
struct nouveau_fb base;
};
void
nv46_fb_tile_init(struct nouveau_fb *pfb, int i, u32 addr, u32 size, u32 pitch,
u32 flags, struct nouveau_fb_tile *tile)
{
/* for performance, select alternate bank offset for zeta */
if (!(flags & 4)) tile->addr = (0 << 3);
else tile->addr = (1 << 3);
tile->addr |= 0x00000001; /* mode = vram */
tile->addr |= addr;
tile->limit = max(1u, addr + size) - 1;
tile->pitch = pitch;
}
static int
nv46_fb_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nv46_fb_priv *priv;
int ret;
ret = nouveau_fb_create(parent, engine, oclass, &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
priv->base.memtype_valid = nv04_fb_memtype_valid;
priv->base.ram.init = nv44_fb_vram_init;
priv->base.tile.regions = 15;
priv->base.tile.init = nv46_fb_tile_init;
priv->base.tile.fini = nv20_fb_tile_fini;
priv->base.tile.prog = nv44_fb_tile_prog;
return nouveau_fb_preinit(&priv->base);
}
struct nouveau_oclass
nv46_fb_oclass = {
.handle = NV_SUBDEV(FB, 0x46),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nv46_fb_ctor,
.dtor = _nouveau_fb_dtor,
.init = nv44_fb_init,
.fini = _nouveau_fb_fini,
},
};
| gpl-2.0 |
dukie/sun4i-kernel | drivers/usb/storage/realtek_cr.c | 2524 | 16101 | /* Driver for Realtek RTS51xx USB card reader
*
* Copyright(c) 2009 Realtek Semiconductor Corp. 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, 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/>.
*
* Author:
* wwang (wei_wang@realsil.com.cn)
* No. 450, Shenhu Road, Suzhou Industry Park, Suzhou, China
*/
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/workqueue.h>
#include <linux/kernel.h>
#include <linux/version.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <linux/cdrom.h>
#include <linux/usb.h>
#include <linux/slab.h>
#include <linux/usb_usual.h>
#include "usb.h"
#include "transport.h"
#include "protocol.h"
#include "debug.h"
MODULE_DESCRIPTION("Driver for Realtek USB Card Reader");
MODULE_AUTHOR("wwang <wei_wang@realsil.com.cn>");
MODULE_LICENSE("GPL");
MODULE_VERSION("1.03");
static int auto_delink_en = 1;
module_param(auto_delink_en, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(auto_delink_en, "enable auto delink");
struct rts51x_status {
u16 vid;
u16 pid;
u8 cur_lun;
u8 card_type;
u8 total_lun;
u16 fw_ver;
u8 phy_exist;
u8 multi_flag;
u8 multi_card;
u8 log_exist;
union {
u8 detailed_type1;
u8 detailed_type2;
} detailed_type;
u8 function[2];
};
struct rts51x_chip {
u16 vendor_id;
u16 product_id;
char max_lun;
struct rts51x_status *status;
int status_len;
u32 flag;
};
/* flag definition */
#define FLIDX_AUTO_DELINK 0x01
#define SCSI_LUN(srb) ((srb)->device->lun)
/* Bit Operation */
#define SET_BIT(data, idx) ((data) |= 1 << (idx))
#define CLR_BIT(data, idx) ((data) &= ~(1 << (idx)))
#define CHK_BIT(data, idx) ((data) & (1 << (idx)))
#define SET_AUTO_DELINK(chip) ((chip)->flag |= FLIDX_AUTO_DELINK)
#define CLR_AUTO_DELINK(chip) ((chip)->flag &= ~FLIDX_AUTO_DELINK)
#define CHK_AUTO_DELINK(chip) ((chip)->flag & FLIDX_AUTO_DELINK)
#define RTS51X_GET_VID(chip) ((chip)->vendor_id)
#define RTS51X_GET_PID(chip) ((chip)->product_id)
#define FW_VERSION(chip) ((chip)->status[0].fw_ver)
#define STATUS_LEN(chip) ((chip)->status_len)
/* Check card reader function */
#define SUPPORT_DETAILED_TYPE1(chip) \
CHK_BIT((chip)->status[0].function[0], 1)
#define SUPPORT_OT(chip) \
CHK_BIT((chip)->status[0].function[0], 2)
#define SUPPORT_OC(chip) \
CHK_BIT((chip)->status[0].function[0], 3)
#define SUPPORT_AUTO_DELINK(chip) \
CHK_BIT((chip)->status[0].function[0], 4)
#define SUPPORT_SDIO(chip) \
CHK_BIT((chip)->status[0].function[1], 0)
#define SUPPORT_DETAILED_TYPE2(chip) \
CHK_BIT((chip)->status[0].function[1], 1)
#define CHECK_PID(chip, pid) (RTS51X_GET_PID(chip) == (pid))
#define CHECK_FW_VER(chip, fw_ver) (FW_VERSION(chip) == (fw_ver))
#define CHECK_ID(chip, pid, fw_ver) \
(CHECK_PID((chip), (pid)) && CHECK_FW_VER((chip), (fw_ver)))
#define wait_timeout_x(task_state, msecs) \
do { \
set_current_state((task_state)); \
schedule_timeout((msecs) * HZ / 1000); \
} while (0)
#define wait_timeout(msecs) \
wait_timeout_x(TASK_INTERRUPTIBLE, (msecs))
static int init_realtek_cr(struct us_data *us);
/*
* The table of devices
*/
#define UNUSUAL_DEV(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax, \
vendorName, productName, useProtocol, useTransport, \
initFunction, flags) \
{\
USB_DEVICE_VER(id_vendor, id_product, bcdDeviceMin, bcdDeviceMax), \
.driver_info = (flags)|(USB_US_TYPE_STOR<<24)\
}
static const struct usb_device_id realtek_cr_ids[] = {
# include "unusual_realtek.h"
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, realtek_cr_ids);
#undef UNUSUAL_DEV
/*
* The flags table
*/
#define UNUSUAL_DEV(idVendor, idProduct, bcdDeviceMin, bcdDeviceMax, \
vendor_name, product_name, use_protocol, use_transport, \
init_function, Flags) \
{ \
.vendorName = vendor_name, \
.productName = product_name, \
.useProtocol = use_protocol, \
.useTransport = use_transport, \
.initFunction = init_function, \
}
static struct us_unusual_dev realtek_cr_unusual_dev_list[] = {
# include "unusual_realtek.h"
{ } /* Terminating entry */
};
#undef UNUSUAL_DEV
static int rts51x_bulk_transport(struct us_data *us, u8 lun,
u8 *cmd, int cmd_len, u8 *buf, int buf_len,
enum dma_data_direction dir, int *act_len)
{
struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap *) us->iobuf;
struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap *) us->iobuf;
int result;
unsigned int residue;
unsigned int cswlen;
unsigned int cbwlen = US_BULK_CB_WRAP_LEN;
/* set up the command wrapper */
bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN);
bcb->DataTransferLength = cpu_to_le32(buf_len);
bcb->Flags = (dir == DMA_FROM_DEVICE) ? 1 << 7 : 0;
bcb->Tag = ++us->tag;
bcb->Lun = lun;
bcb->Length = cmd_len;
/* copy the command payload */
memset(bcb->CDB, 0, sizeof(bcb->CDB));
memcpy(bcb->CDB, cmd, bcb->Length);
/* send it to out endpoint */
result = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe,
bcb, cbwlen, NULL);
if (result != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
/* DATA STAGE */
/* send/receive data payload, if there is any */
if (buf && buf_len) {
unsigned int pipe = (dir == DMA_FROM_DEVICE) ?
us->recv_bulk_pipe : us->send_bulk_pipe;
result = usb_stor_bulk_transfer_buf(us, pipe,
buf, buf_len, NULL);
if (result == USB_STOR_XFER_ERROR)
return USB_STOR_TRANSPORT_ERROR;
}
/* get CSW for device status */
result = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe,
bcs, US_BULK_CS_WRAP_LEN, &cswlen);
if (result != USB_STOR_XFER_GOOD)
return USB_STOR_TRANSPORT_ERROR;
/* check bulk status */
if (bcs->Signature != cpu_to_le32(US_BULK_CS_SIGN)) {
US_DEBUGP("Signature mismatch: got %08X, expecting %08X\n",
le32_to_cpu(bcs->Signature),
US_BULK_CS_SIGN);
return USB_STOR_TRANSPORT_ERROR;
}
residue = bcs->Residue;
if (bcs->Tag != us->tag)
return USB_STOR_TRANSPORT_ERROR;
/* try to compute the actual residue, based on how much data
* was really transferred and what the device tells us */
if (residue)
residue = residue < buf_len ? residue : buf_len;
if (act_len)
*act_len = buf_len - residue;
/* based on the status code, we report good or bad */
switch (bcs->Status) {
case US_BULK_STAT_OK:
/* command good -- note that data could be short */
return USB_STOR_TRANSPORT_GOOD;
case US_BULK_STAT_FAIL:
/* command failed */
return USB_STOR_TRANSPORT_FAILED;
case US_BULK_STAT_PHASE:
/* phase error -- note that a transport reset will be
* invoked by the invoke_transport() function
*/
return USB_STOR_TRANSPORT_ERROR;
}
/* we should never get here, but if we do, we're in trouble */
return USB_STOR_TRANSPORT_ERROR;
}
/* Determine what the maximum LUN supported is */
static int rts51x_get_max_lun(struct us_data *us)
{
int result;
/* issue the command */
us->iobuf[0] = 0;
result = usb_stor_control_msg(us, us->recv_ctrl_pipe,
US_BULK_GET_MAX_LUN,
USB_DIR_IN | USB_TYPE_CLASS |
USB_RECIP_INTERFACE,
0, us->ifnum, us->iobuf, 1, 10*HZ);
US_DEBUGP("GetMaxLUN command result is %d, data is %d\n",
result, us->iobuf[0]);
/* if we have a successful request, return the result */
if (result > 0)
return us->iobuf[0];
return 0;
}
static int rts51x_read_mem(struct us_data *us, u16 addr, u8 *data, u16 len)
{
int retval;
u8 cmnd[12] = {0};
US_DEBUGP("%s, addr = 0x%x, len = %d\n", __func__, addr, len);
cmnd[0] = 0xF0;
cmnd[1] = 0x0D;
cmnd[2] = (u8)(addr >> 8);
cmnd[3] = (u8)addr;
cmnd[4] = (u8)(len >> 8);
cmnd[5] = (u8)len;
retval = rts51x_bulk_transport(us, 0, cmnd, 12,
data, len, DMA_FROM_DEVICE, NULL);
if (retval != USB_STOR_TRANSPORT_GOOD)
return -EIO;
return 0;
}
static int rts51x_write_mem(struct us_data *us, u16 addr, u8 *data, u16 len)
{
int retval;
u8 cmnd[12] = {0};
US_DEBUGP("%s, addr = 0x%x, len = %d\n", __func__, addr, len);
cmnd[0] = 0xF0;
cmnd[1] = 0x0E;
cmnd[2] = (u8)(addr >> 8);
cmnd[3] = (u8)addr;
cmnd[4] = (u8)(len >> 8);
cmnd[5] = (u8)len;
retval = rts51x_bulk_transport(us, 0, cmnd, 12,
data, len, DMA_TO_DEVICE, NULL);
if (retval != USB_STOR_TRANSPORT_GOOD)
return -EIO;
return 0;
}
static int rts51x_read_status(struct us_data *us,
u8 lun, u8 *status, int len, int *actlen)
{
int retval;
u8 cmnd[12] = {0};
US_DEBUGP("%s, lun = %d\n", __func__, lun);
cmnd[0] = 0xF0;
cmnd[1] = 0x09;
retval = rts51x_bulk_transport(us, lun, cmnd, 12,
status, len, DMA_FROM_DEVICE, actlen);
if (retval != USB_STOR_TRANSPORT_GOOD)
return -EIO;
return 0;
}
static int rts51x_check_status(struct us_data *us, u8 lun)
{
struct rts51x_chip *chip = (struct rts51x_chip *)(us->extra);
int retval;
u8 buf[16];
retval = rts51x_read_status(us, lun, buf, 16, &(chip->status_len));
if (retval < 0)
return -EIO;
US_DEBUGP("chip->status_len = %d\n", chip->status_len);
chip->status[lun].vid = ((u16)buf[0] << 8) | buf[1];
chip->status[lun].pid = ((u16)buf[2] << 8) | buf[3];
chip->status[lun].cur_lun = buf[4];
chip->status[lun].card_type = buf[5];
chip->status[lun].total_lun = buf[6];
chip->status[lun].fw_ver = ((u16)buf[7] << 8) | buf[8];
chip->status[lun].phy_exist = buf[9];
chip->status[lun].multi_flag = buf[10];
chip->status[lun].multi_card = buf[11];
chip->status[lun].log_exist = buf[12];
if (chip->status_len == 16) {
chip->status[lun].detailed_type.detailed_type1 = buf[13];
chip->status[lun].function[0] = buf[14];
chip->status[lun].function[1] = buf[15];
}
return 0;
}
static int enable_oscillator(struct us_data *us)
{
int retval;
u8 value;
retval = rts51x_read_mem(us, 0xFE77, &value, 1);
if (retval < 0)
return -EIO;
value |= 0x04;
retval = rts51x_write_mem(us, 0xFE77, &value, 1);
if (retval < 0)
return -EIO;
retval = rts51x_read_mem(us, 0xFE77, &value, 1);
if (retval < 0)
return -EIO;
if (!(value & 0x04))
return -EIO;
return 0;
}
static int do_config_autodelink(struct us_data *us, int enable, int force)
{
int retval;
u8 value;
retval = rts51x_read_mem(us, 0xFE47, &value, 1);
if (retval < 0)
return -EIO;
if (enable) {
if (force)
value |= 0x03;
else
value |= 0x01;
} else {
value &= ~0x03;
}
US_DEBUGP("In %s,set 0xfe47 to 0x%x\n", __func__, value);
retval = rts51x_write_mem(us, 0xFE47, &value, 1);
if (retval < 0)
return -EIO;
return 0;
}
static int config_autodelink_after_power_on(struct us_data *us)
{
struct rts51x_chip *chip = (struct rts51x_chip *)(us->extra);
int retval;
u8 value;
if (!CHK_AUTO_DELINK(chip))
return 0;
retval = rts51x_read_mem(us, 0xFE47, &value, 1);
if (retval < 0)
return -EIO;
if (auto_delink_en) {
CLR_BIT(value, 0);
CLR_BIT(value, 1);
SET_BIT(value, 2);
if (CHECK_ID(chip, 0x0138, 0x3882))
CLR_BIT(value, 2);
SET_BIT(value, 7);
retval = rts51x_write_mem(us, 0xFE47, &value, 1);
if (retval < 0)
return -EIO;
retval = enable_oscillator(us);
if (retval == 0)
(void)do_config_autodelink(us, 1, 0);
} else {
/* Autodelink controlled by firmware */
SET_BIT(value, 2);
if (CHECK_ID(chip, 0x0138, 0x3882))
CLR_BIT(value, 2);
if (CHECK_ID(chip, 0x0159, 0x5889) ||
CHECK_ID(chip, 0x0138, 0x3880)) {
CLR_BIT(value, 0);
CLR_BIT(value, 7);
}
retval = rts51x_write_mem(us, 0xFE47, &value, 1);
if (retval < 0)
return -EIO;
if (CHECK_ID(chip, 0x0159, 0x5888)) {
value = 0xFF;
retval = rts51x_write_mem(us, 0xFE79, &value, 1);
if (retval < 0)
return -EIO;
value = 0x01;
retval = rts51x_write_mem(us, 0x48, &value, 1);
if (retval < 0)
return -EIO;
}
}
return 0;
}
static int config_autodelink_before_power_down(struct us_data *us)
{
struct rts51x_chip *chip = (struct rts51x_chip *)(us->extra);
int retval;
u8 value;
if (!CHK_AUTO_DELINK(chip))
return 0;
if (auto_delink_en) {
retval = rts51x_read_mem(us, 0xFE77, &value, 1);
if (retval < 0)
return -EIO;
SET_BIT(value, 2);
retval = rts51x_write_mem(us, 0xFE77, &value, 1);
if (retval < 0)
return -EIO;
if (CHECK_ID(chip, 0x0159, 0x5888)) {
value = 0x01;
retval = rts51x_write_mem(us, 0x48, &value, 1);
if (retval < 0)
return -EIO;
}
retval = rts51x_read_mem(us, 0xFE47, &value, 1);
if (retval < 0)
return -EIO;
SET_BIT(value, 0);
if (CHECK_ID(chip, 0x0138, 0x3882))
SET_BIT(value, 2);
retval = rts51x_write_mem(us, 0xFE77, &value, 1);
if (retval < 0)
return -EIO;
} else {
if (CHECK_ID(chip, 0x0159, 0x5889) ||
CHECK_ID(chip, 0x0138, 0x3880) ||
CHECK_ID(chip, 0x0138, 0x3882)) {
retval = rts51x_read_mem(us, 0xFE47, &value, 1);
if (retval < 0)
return -EIO;
if (CHECK_ID(chip, 0x0159, 0x5889) ||
CHECK_ID(chip, 0x0138, 0x3880)) {
SET_BIT(value, 0);
SET_BIT(value, 7);
}
if (CHECK_ID(chip, 0x0138, 0x3882))
SET_BIT(value, 2);
retval = rts51x_write_mem(us, 0xFE47, &value, 1);
if (retval < 0)
return -EIO;
}
if (CHECK_ID(chip, 0x0159, 0x5888)) {
value = 0x01;
retval = rts51x_write_mem(us, 0x48, &value, 1);
if (retval < 0)
return -EIO;
}
}
return 0;
}
static void realtek_cr_destructor(void *extra)
{
struct rts51x_chip *chip = (struct rts51x_chip *)extra;
if (!chip)
return;
kfree(chip->status);
}
#ifdef CONFIG_PM
static void realtek_pm_hook(struct us_data *us, int pm_state)
{
if (pm_state == US_SUSPEND)
(void)config_autodelink_before_power_down(us);
}
#endif
static int init_realtek_cr(struct us_data *us)
{
struct rts51x_chip *chip;
int size, i, retval;
chip = kzalloc(sizeof(struct rts51x_chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
us->extra = chip;
us->extra_destructor = realtek_cr_destructor;
#ifdef CONFIG_PM
us->suspend_resume_hook = realtek_pm_hook;
#endif
us->max_lun = chip->max_lun = rts51x_get_max_lun(us);
US_DEBUGP("chip->max_lun = %d\n", chip->max_lun);
size = (chip->max_lun + 1) * sizeof(struct rts51x_status);
chip->status = kzalloc(size, GFP_KERNEL);
if (!chip->status)
goto INIT_FAIL;
for (i = 0; i <= (int)(chip->max_lun); i++) {
retval = rts51x_check_status(us, (u8)i);
if (retval < 0)
goto INIT_FAIL;
}
if (CHECK_FW_VER(chip, 0x5888) || CHECK_FW_VER(chip, 0x5889) ||
CHECK_FW_VER(chip, 0x5901))
SET_AUTO_DELINK(chip);
if (STATUS_LEN(chip) == 16) {
if (SUPPORT_AUTO_DELINK(chip))
SET_AUTO_DELINK(chip);
}
US_DEBUGP("chip->flag = 0x%x\n", chip->flag);
(void)config_autodelink_after_power_on(us);
return 0;
INIT_FAIL:
if (us->extra) {
kfree(chip->status);
kfree(us->extra);
us->extra = NULL;
}
return -EIO;
}
static int realtek_cr_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct us_data *us;
int result;
US_DEBUGP("Probe Realtek Card Reader!\n");
result = usb_stor_probe1(&us, intf, id,
(id - realtek_cr_ids) + realtek_cr_unusual_dev_list);
if (result)
return result;
result = usb_stor_probe2(us);
return result;
}
static struct usb_driver realtek_cr_driver = {
.name = "ums-realtek",
.probe = realtek_cr_probe,
.disconnect = usb_stor_disconnect,
.suspend = usb_stor_suspend,
.resume = usb_stor_resume,
.reset_resume = usb_stor_reset_resume,
.pre_reset = usb_stor_pre_reset,
.post_reset = usb_stor_post_reset,
.id_table = realtek_cr_ids,
.soft_unbind = 1,
};
static int __init realtek_cr_init(void)
{
return usb_register(&realtek_cr_driver);
}
static void __exit realtek_cr_exit(void)
{
usb_deregister(&realtek_cr_driver);
}
module_init(realtek_cr_init);
module_exit(realtek_cr_exit);
| gpl-2.0 |
budi79/deka-kernel-msm7x30-3.0 | drivers/scsi/lpfc/lpfc_vport.c | 2780 | 25287 | /*******************************************************************
* This file is part of the Emulex Linux Device Driver for *
* Fibre Channel Host Bus Adapters. *
* Copyright (C) 2004-2008 Emulex. All rights reserved. *
* EMULEX and SLI are trademarks of Emulex. *
* www.emulex.com *
* Portions Copyright (C) 2004-2005 Christoph Hellwig *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of version 2 of the GNU General *
* Public License as published by the Free Software Foundation. *
* This program is distributed in the hope that it will be useful. *
* ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND *
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE *
* DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD *
* TO BE LEGALLY INVALID. See the GNU General Public License for *
* more details, a copy of which can be found in the file COPYING *
* included with this package. *
*******************************************************************/
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/idr.h>
#include <linux/interrupt.h>
#include <linux/kthread.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <scsi/scsi.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_transport_fc.h>
#include "lpfc_hw4.h"
#include "lpfc_hw.h"
#include "lpfc_sli.h"
#include "lpfc_sli4.h"
#include "lpfc_nl.h"
#include "lpfc_disc.h"
#include "lpfc_scsi.h"
#include "lpfc.h"
#include "lpfc_logmsg.h"
#include "lpfc_crtn.h"
#include "lpfc_version.h"
#include "lpfc_vport.h"
inline void lpfc_vport_set_state(struct lpfc_vport *vport,
enum fc_vport_state new_state)
{
struct fc_vport *fc_vport = vport->fc_vport;
if (fc_vport) {
/*
* When the transport defines fc_vport_set state we will replace
* this code with the following line
*/
/* fc_vport_set_state(fc_vport, new_state); */
if (new_state != FC_VPORT_INITIALIZING)
fc_vport->vport_last_state = fc_vport->vport_state;
fc_vport->vport_state = new_state;
}
/* for all the error states we will set the invternal state to FAILED */
switch (new_state) {
case FC_VPORT_NO_FABRIC_SUPP:
case FC_VPORT_NO_FABRIC_RSCS:
case FC_VPORT_FABRIC_LOGOUT:
case FC_VPORT_FABRIC_REJ_WWN:
case FC_VPORT_FAILED:
vport->port_state = LPFC_VPORT_FAILED;
break;
case FC_VPORT_LINKDOWN:
vport->port_state = LPFC_VPORT_UNKNOWN;
break;
default:
/* do nothing */
break;
}
}
static int
lpfc_alloc_vpi(struct lpfc_hba *phba)
{
unsigned long vpi;
spin_lock_irq(&phba->hbalock);
/* Start at bit 1 because vpi zero is reserved for the physical port */
vpi = find_next_zero_bit(phba->vpi_bmask, (phba->max_vpi + 1), 1);
if (vpi > phba->max_vpi)
vpi = 0;
else
set_bit(vpi, phba->vpi_bmask);
if (phba->sli_rev == LPFC_SLI_REV4)
phba->sli4_hba.max_cfg_param.vpi_used++;
spin_unlock_irq(&phba->hbalock);
return vpi;
}
static void
lpfc_free_vpi(struct lpfc_hba *phba, int vpi)
{
if (vpi == 0)
return;
spin_lock_irq(&phba->hbalock);
clear_bit(vpi, phba->vpi_bmask);
if (phba->sli_rev == LPFC_SLI_REV4)
phba->sli4_hba.max_cfg_param.vpi_used--;
spin_unlock_irq(&phba->hbalock);
}
static int
lpfc_vport_sparm(struct lpfc_hba *phba, struct lpfc_vport *vport)
{
LPFC_MBOXQ_t *pmb;
MAILBOX_t *mb;
struct lpfc_dmabuf *mp;
int rc;
pmb = mempool_alloc(phba->mbox_mem_pool, GFP_KERNEL);
if (!pmb) {
return -ENOMEM;
}
mb = &pmb->u.mb;
rc = lpfc_read_sparam(phba, pmb, vport->vpi);
if (rc) {
mempool_free(pmb, phba->mbox_mem_pool);
return -ENOMEM;
}
/*
* Grab buffer pointer and clear context1 so we can use
* lpfc_sli_issue_box_wait
*/
mp = (struct lpfc_dmabuf *) pmb->context1;
pmb->context1 = NULL;
pmb->vport = vport;
rc = lpfc_sli_issue_mbox_wait(phba, pmb, phba->fc_ratov * 2);
if (rc != MBX_SUCCESS) {
if (signal_pending(current)) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_INIT | LOG_VPORT,
"1830 Signal aborted mbxCmd x%x\n",
mb->mbxCommand);
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
if (rc != MBX_TIMEOUT)
mempool_free(pmb, phba->mbox_mem_pool);
return -EINTR;
} else {
lpfc_printf_vlog(vport, KERN_ERR, LOG_INIT | LOG_VPORT,
"1818 VPort failed init, mbxCmd x%x "
"READ_SPARM mbxStatus x%x, rc = x%x\n",
mb->mbxCommand, mb->mbxStatus, rc);
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
if (rc != MBX_TIMEOUT)
mempool_free(pmb, phba->mbox_mem_pool);
return -EIO;
}
}
memcpy(&vport->fc_sparam, mp->virt, sizeof (struct serv_parm));
memcpy(&vport->fc_nodename, &vport->fc_sparam.nodeName,
sizeof (struct lpfc_name));
memcpy(&vport->fc_portname, &vport->fc_sparam.portName,
sizeof (struct lpfc_name));
lpfc_mbuf_free(phba, mp->virt, mp->phys);
kfree(mp);
mempool_free(pmb, phba->mbox_mem_pool);
return 0;
}
static int
lpfc_valid_wwn_format(struct lpfc_hba *phba, struct lpfc_name *wwn,
const char *name_type)
{
/* ensure that IEEE format 1 addresses
* contain zeros in bits 59-48
*/
if (!((wwn->u.wwn[0] >> 4) == 1 &&
((wwn->u.wwn[0] & 0xf) != 0 || (wwn->u.wwn[1] & 0xf) != 0)))
return 1;
lpfc_printf_log(phba, KERN_ERR, LOG_VPORT,
"1822 Invalid %s: %02x:%02x:%02x:%02x:"
"%02x:%02x:%02x:%02x\n",
name_type,
wwn->u.wwn[0], wwn->u.wwn[1],
wwn->u.wwn[2], wwn->u.wwn[3],
wwn->u.wwn[4], wwn->u.wwn[5],
wwn->u.wwn[6], wwn->u.wwn[7]);
return 0;
}
static int
lpfc_unique_wwpn(struct lpfc_hba *phba, struct lpfc_vport *new_vport)
{
struct lpfc_vport *vport;
unsigned long flags;
spin_lock_irqsave(&phba->hbalock, flags);
list_for_each_entry(vport, &phba->port_list, listentry) {
if (vport == new_vport)
continue;
/* If they match, return not unique */
if (memcmp(&vport->fc_sparam.portName,
&new_vport->fc_sparam.portName,
sizeof(struct lpfc_name)) == 0) {
spin_unlock_irqrestore(&phba->hbalock, flags);
return 0;
}
}
spin_unlock_irqrestore(&phba->hbalock, flags);
return 1;
}
/**
* lpfc_discovery_wait - Wait for driver discovery to quiesce
* @vport: The virtual port for which this call is being executed.
*
* This driver calls this routine specifically from lpfc_vport_delete
* to enforce a synchronous execution of vport
* delete relative to discovery activities. The
* lpfc_vport_delete routine should not return until it
* can reasonably guarantee that discovery has quiesced.
* Post FDISC LOGO, the driver must wait until its SAN teardown is
* complete and all resources recovered before allowing
* cleanup.
*
* This routine does not require any locks held.
**/
static void lpfc_discovery_wait(struct lpfc_vport *vport)
{
struct lpfc_hba *phba = vport->phba;
uint32_t wait_flags = 0;
unsigned long wait_time_max;
unsigned long start_time;
wait_flags = FC_RSCN_MODE | FC_RSCN_DISCOVERY | FC_NLP_MORE |
FC_RSCN_DEFERRED | FC_NDISC_ACTIVE | FC_DISC_TMO;
/*
* The time constraint on this loop is a balance between the
* fabric RA_TOV value and dev_loss tmo. The driver's
* devloss_tmo is 10 giving this loop a 3x multiplier minimally.
*/
wait_time_max = msecs_to_jiffies(((phba->fc_ratov * 3) + 3) * 1000);
wait_time_max += jiffies;
start_time = jiffies;
while (time_before(jiffies, wait_time_max)) {
if ((vport->num_disc_nodes > 0) ||
(vport->fc_flag & wait_flags) ||
((vport->port_state > LPFC_VPORT_FAILED) &&
(vport->port_state < LPFC_VPORT_READY))) {
lpfc_printf_vlog(vport, KERN_INFO, LOG_VPORT,
"1833 Vport discovery quiesce Wait:"
" state x%x fc_flags x%x"
" num_nodes x%x, waiting 1000 msecs"
" total wait msecs x%x\n",
vport->port_state, vport->fc_flag,
vport->num_disc_nodes,
jiffies_to_msecs(jiffies - start_time));
msleep(1000);
} else {
/* Base case. Wait variants satisfied. Break out */
lpfc_printf_vlog(vport, KERN_INFO, LOG_VPORT,
"1834 Vport discovery quiesced:"
" state x%x fc_flags x%x"
" wait msecs x%x\n",
vport->port_state, vport->fc_flag,
jiffies_to_msecs(jiffies
- start_time));
break;
}
}
if (time_after(jiffies, wait_time_max))
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1835 Vport discovery quiesce failed:"
" state x%x fc_flags x%x wait msecs x%x\n",
vport->port_state, vport->fc_flag,
jiffies_to_msecs(jiffies - start_time));
}
int
lpfc_vport_create(struct fc_vport *fc_vport, bool disable)
{
struct lpfc_nodelist *ndlp;
struct Scsi_Host *shost = fc_vport->shost;
struct lpfc_vport *pport = (struct lpfc_vport *) shost->hostdata;
struct lpfc_hba *phba = pport->phba;
struct lpfc_vport *vport = NULL;
int instance;
int vpi;
int rc = VPORT_ERROR;
int status;
if ((phba->sli_rev < 3) || !(phba->cfg_enable_npiv)) {
lpfc_printf_log(phba, KERN_ERR, LOG_VPORT,
"1808 Create VPORT failed: "
"NPIV is not enabled: SLImode:%d\n",
phba->sli_rev);
rc = VPORT_INVAL;
goto error_out;
}
vpi = lpfc_alloc_vpi(phba);
if (vpi == 0) {
lpfc_printf_log(phba, KERN_ERR, LOG_VPORT,
"1809 Create VPORT failed: "
"Max VPORTs (%d) exceeded\n",
phba->max_vpi);
rc = VPORT_NORESOURCES;
goto error_out;
}
/* Assign an unused board number */
if ((instance = lpfc_get_instance()) < 0) {
lpfc_printf_log(phba, KERN_ERR, LOG_VPORT,
"1810 Create VPORT failed: Cannot get "
"instance number\n");
lpfc_free_vpi(phba, vpi);
rc = VPORT_NORESOURCES;
goto error_out;
}
vport = lpfc_create_port(phba, instance, &fc_vport->dev);
if (!vport) {
lpfc_printf_log(phba, KERN_ERR, LOG_VPORT,
"1811 Create VPORT failed: vpi x%x\n", vpi);
lpfc_free_vpi(phba, vpi);
rc = VPORT_NORESOURCES;
goto error_out;
}
vport->vpi = vpi;
lpfc_debugfs_initialize(vport);
if ((status = lpfc_vport_sparm(phba, vport))) {
if (status == -EINTR) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1831 Create VPORT Interrupted.\n");
rc = VPORT_ERROR;
} else {
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1813 Create VPORT failed. "
"Cannot get sparam\n");
rc = VPORT_NORESOURCES;
}
lpfc_free_vpi(phba, vpi);
destroy_port(vport);
goto error_out;
}
u64_to_wwn(fc_vport->node_name, vport->fc_nodename.u.wwn);
u64_to_wwn(fc_vport->port_name, vport->fc_portname.u.wwn);
memcpy(&vport->fc_sparam.portName, vport->fc_portname.u.wwn, 8);
memcpy(&vport->fc_sparam.nodeName, vport->fc_nodename.u.wwn, 8);
if (!lpfc_valid_wwn_format(phba, &vport->fc_sparam.nodeName, "WWNN") ||
!lpfc_valid_wwn_format(phba, &vport->fc_sparam.portName, "WWPN")) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1821 Create VPORT failed. "
"Invalid WWN format\n");
lpfc_free_vpi(phba, vpi);
destroy_port(vport);
rc = VPORT_INVAL;
goto error_out;
}
if (!lpfc_unique_wwpn(phba, vport)) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1823 Create VPORT failed. "
"Duplicate WWN on HBA\n");
lpfc_free_vpi(phba, vpi);
destroy_port(vport);
rc = VPORT_INVAL;
goto error_out;
}
/* Create binary sysfs attribute for vport */
lpfc_alloc_sysfs_attr(vport);
*(struct lpfc_vport **)fc_vport->dd_data = vport;
vport->fc_vport = fc_vport;
/*
* In SLI4, the vpi must be activated before it can be used
* by the port.
*/
if ((phba->sli_rev == LPFC_SLI_REV4) &&
(pport->fc_flag & FC_VFI_REGISTERED)) {
rc = lpfc_sli4_init_vpi(vport);
if (rc) {
lpfc_printf_log(phba, KERN_ERR, LOG_VPORT,
"1838 Failed to INIT_VPI on vpi %d "
"status %d\n", vpi, rc);
rc = VPORT_NORESOURCES;
lpfc_free_vpi(phba, vpi);
goto error_out;
}
} else if (phba->sli_rev == LPFC_SLI_REV4) {
/*
* Driver cannot INIT_VPI now. Set the flags to
* init_vpi when reg_vfi complete.
*/
vport->fc_flag |= FC_VPORT_NEEDS_INIT_VPI;
lpfc_vport_set_state(vport, FC_VPORT_LINKDOWN);
rc = VPORT_OK;
goto out;
}
if ((phba->link_state < LPFC_LINK_UP) ||
(pport->port_state < LPFC_FABRIC_CFG_LINK) ||
(phba->fc_topology == LPFC_TOPOLOGY_LOOP)) {
lpfc_vport_set_state(vport, FC_VPORT_LINKDOWN);
rc = VPORT_OK;
goto out;
}
if (disable) {
lpfc_vport_set_state(vport, FC_VPORT_DISABLED);
rc = VPORT_OK;
goto out;
}
/* Use the Physical nodes Fabric NDLP to determine if the link is
* up and ready to FDISC.
*/
ndlp = lpfc_findnode_did(phba->pport, Fabric_DID);
if (ndlp && NLP_CHK_NODE_ACT(ndlp) &&
ndlp->nlp_state == NLP_STE_UNMAPPED_NODE) {
if (phba->link_flag & LS_NPIV_FAB_SUPPORTED) {
lpfc_set_disctmo(vport);
lpfc_initial_fdisc(vport);
} else {
lpfc_vport_set_state(vport, FC_VPORT_NO_FABRIC_SUPP);
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0262 No NPIV Fabric support\n");
}
} else {
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
}
rc = VPORT_OK;
out:
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1825 Vport Created.\n");
lpfc_host_attrib_init(lpfc_shost_from_vport(vport));
error_out:
return rc;
}
static int
disable_vport(struct fc_vport *fc_vport)
{
struct lpfc_vport *vport = *(struct lpfc_vport **)fc_vport->dd_data;
struct lpfc_hba *phba = vport->phba;
struct lpfc_nodelist *ndlp = NULL, *next_ndlp = NULL;
long timeout;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
ndlp = lpfc_findnode_did(vport, Fabric_DID);
if (ndlp && NLP_CHK_NODE_ACT(ndlp)
&& phba->link_state >= LPFC_LINK_UP) {
vport->unreg_vpi_cmpl = VPORT_INVAL;
timeout = msecs_to_jiffies(phba->fc_ratov * 2000);
if (!lpfc_issue_els_npiv_logo(vport, ndlp))
while (vport->unreg_vpi_cmpl == VPORT_INVAL && timeout)
timeout = schedule_timeout(timeout);
}
lpfc_sli_host_down(vport);
/* Mark all nodes for discovery so we can remove them by
* calling lpfc_cleanup_rpis(vport, 1)
*/
list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
if (!NLP_CHK_NODE_ACT(ndlp))
continue;
if (ndlp->nlp_state == NLP_STE_UNUSED_NODE)
continue;
lpfc_disc_state_machine(vport, ndlp, NULL,
NLP_EVT_DEVICE_RECOVERY);
}
lpfc_cleanup_rpis(vport, 1);
lpfc_stop_vport_timers(vport);
lpfc_unreg_all_rpis(vport);
lpfc_unreg_default_rpis(vport);
/*
* Completion of unreg_vpi (lpfc_mbx_cmpl_unreg_vpi) does the
* scsi_host_put() to release the vport.
*/
lpfc_mbx_unreg_vpi(vport);
spin_lock_irq(shost->host_lock);
vport->fc_flag |= FC_VPORT_NEEDS_INIT_VPI;
spin_unlock_irq(shost->host_lock);
lpfc_vport_set_state(vport, FC_VPORT_DISABLED);
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1826 Vport Disabled.\n");
return VPORT_OK;
}
static int
enable_vport(struct fc_vport *fc_vport)
{
struct lpfc_vport *vport = *(struct lpfc_vport **)fc_vport->dd_data;
struct lpfc_hba *phba = vport->phba;
struct lpfc_nodelist *ndlp = NULL;
struct Scsi_Host *shost = lpfc_shost_from_vport(vport);
if ((phba->link_state < LPFC_LINK_UP) ||
(phba->fc_topology == LPFC_TOPOLOGY_LOOP)) {
lpfc_vport_set_state(vport, FC_VPORT_LINKDOWN);
return VPORT_OK;
}
spin_lock_irq(shost->host_lock);
vport->load_flag |= FC_LOADING;
vport->fc_flag |= FC_VPORT_NEEDS_REG_VPI;
spin_unlock_irq(shost->host_lock);
/* Use the Physical nodes Fabric NDLP to determine if the link is
* up and ready to FDISC.
*/
ndlp = lpfc_findnode_did(phba->pport, Fabric_DID);
if (ndlp && NLP_CHK_NODE_ACT(ndlp)
&& ndlp->nlp_state == NLP_STE_UNMAPPED_NODE) {
if (phba->link_flag & LS_NPIV_FAB_SUPPORTED) {
lpfc_set_disctmo(vport);
lpfc_initial_fdisc(vport);
} else {
lpfc_vport_set_state(vport, FC_VPORT_NO_FABRIC_SUPP);
lpfc_printf_vlog(vport, KERN_ERR, LOG_ELS,
"0264 No NPIV Fabric support\n");
}
} else {
lpfc_vport_set_state(vport, FC_VPORT_FAILED);
}
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1827 Vport Enabled.\n");
return VPORT_OK;
}
int
lpfc_vport_disable(struct fc_vport *fc_vport, bool disable)
{
if (disable)
return disable_vport(fc_vport);
else
return enable_vport(fc_vport);
}
int
lpfc_vport_delete(struct fc_vport *fc_vport)
{
struct lpfc_nodelist *ndlp = NULL;
struct Scsi_Host *shost = (struct Scsi_Host *) fc_vport->shost;
struct lpfc_vport *vport = *(struct lpfc_vport **)fc_vport->dd_data;
struct lpfc_hba *phba = vport->phba;
long timeout;
if (vport->port_type == LPFC_PHYSICAL_PORT) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1812 vport_delete failed: Cannot delete "
"physical host\n");
return VPORT_ERROR;
}
/* If the vport is a static vport fail the deletion. */
if ((vport->vport_flag & STATIC_VPORT) &&
!(phba->pport->load_flag & FC_UNLOADING)) {
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1837 vport_delete failed: Cannot delete "
"static vport.\n");
return VPORT_ERROR;
}
spin_lock_irq(&phba->hbalock);
vport->load_flag |= FC_UNLOADING;
spin_unlock_irq(&phba->hbalock);
/*
* If we are not unloading the driver then prevent the vport_delete
* from happening until after this vport's discovery is finished.
*/
if (!(phba->pport->load_flag & FC_UNLOADING)) {
int check_count = 0;
while (check_count < ((phba->fc_ratov * 3) + 3) &&
vport->port_state > LPFC_VPORT_FAILED &&
vport->port_state < LPFC_VPORT_READY) {
check_count++;
msleep(1000);
}
if (vport->port_state > LPFC_VPORT_FAILED &&
vport->port_state < LPFC_VPORT_READY)
return -EAGAIN;
}
/*
* This is a bit of a mess. We want to ensure the shost doesn't get
* torn down until we're done with the embedded lpfc_vport structure.
*
* Beyond holding a reference for this function, we also need a
* reference for outstanding I/O requests we schedule during delete
* processing. But once we scsi_remove_host() we can no longer obtain
* a reference through scsi_host_get().
*
* So we take two references here. We release one reference at the
* bottom of the function -- after delinking the vport. And we
* release the other at the completion of the unreg_vpi that get's
* initiated after we've disposed of all other resources associated
* with the port.
*/
if (!scsi_host_get(shost))
return VPORT_INVAL;
if (!scsi_host_get(shost)) {
scsi_host_put(shost);
return VPORT_INVAL;
}
lpfc_free_sysfs_attr(vport);
lpfc_debugfs_terminate(vport);
/* Remove FC host and then SCSI host with the vport */
fc_remove_host(lpfc_shost_from_vport(vport));
scsi_remove_host(lpfc_shost_from_vport(vport));
ndlp = lpfc_findnode_did(phba->pport, Fabric_DID);
/* In case of driver unload, we shall not perform fabric logo as the
* worker thread already stopped at this stage and, in this case, we
* can safely skip the fabric logo.
*/
if (phba->pport->load_flag & FC_UNLOADING) {
if (ndlp && NLP_CHK_NODE_ACT(ndlp) &&
ndlp->nlp_state == NLP_STE_UNMAPPED_NODE &&
phba->link_state >= LPFC_LINK_UP) {
/* First look for the Fabric ndlp */
ndlp = lpfc_findnode_did(vport, Fabric_DID);
if (!ndlp)
goto skip_logo;
else if (!NLP_CHK_NODE_ACT(ndlp)) {
ndlp = lpfc_enable_node(vport, ndlp,
NLP_STE_UNUSED_NODE);
if (!ndlp)
goto skip_logo;
}
/* Remove ndlp from vport npld list */
lpfc_dequeue_node(vport, ndlp);
/* Indicate free memory when release */
spin_lock_irq(&phba->ndlp_lock);
NLP_SET_FREE_REQ(ndlp);
spin_unlock_irq(&phba->ndlp_lock);
/* Kick off release ndlp when it can be safely done */
lpfc_nlp_put(ndlp);
}
goto skip_logo;
}
/* Otherwise, we will perform fabric logo as needed */
if (ndlp && NLP_CHK_NODE_ACT(ndlp) &&
ndlp->nlp_state == NLP_STE_UNMAPPED_NODE &&
phba->link_state >= LPFC_LINK_UP &&
phba->fc_topology != LPFC_TOPOLOGY_LOOP) {
if (vport->cfg_enable_da_id) {
timeout = msecs_to_jiffies(phba->fc_ratov * 2000);
if (!lpfc_ns_cmd(vport, SLI_CTNS_DA_ID, 0, 0))
while (vport->ct_flags && timeout)
timeout = schedule_timeout(timeout);
else
lpfc_printf_log(vport->phba, KERN_WARNING,
LOG_VPORT,
"1829 CT command failed to "
"delete objects on fabric\n");
}
/* First look for the Fabric ndlp */
ndlp = lpfc_findnode_did(vport, Fabric_DID);
if (!ndlp) {
/* Cannot find existing Fabric ndlp, allocate one */
ndlp = mempool_alloc(phba->nlp_mem_pool, GFP_KERNEL);
if (!ndlp)
goto skip_logo;
lpfc_nlp_init(vport, ndlp, Fabric_DID);
/* Indicate free memory when release */
NLP_SET_FREE_REQ(ndlp);
} else {
if (!NLP_CHK_NODE_ACT(ndlp))
ndlp = lpfc_enable_node(vport, ndlp,
NLP_STE_UNUSED_NODE);
if (!ndlp)
goto skip_logo;
/* Remove ndlp from vport npld list */
lpfc_dequeue_node(vport, ndlp);
spin_lock_irq(&phba->ndlp_lock);
if (!NLP_CHK_FREE_REQ(ndlp))
/* Indicate free memory when release */
NLP_SET_FREE_REQ(ndlp);
else {
/* Skip this if ndlp is already in free mode */
spin_unlock_irq(&phba->ndlp_lock);
goto skip_logo;
}
spin_unlock_irq(&phba->ndlp_lock);
}
if (!(vport->vpi_state & LPFC_VPI_REGISTERED))
goto skip_logo;
vport->unreg_vpi_cmpl = VPORT_INVAL;
timeout = msecs_to_jiffies(phba->fc_ratov * 2000);
if (!lpfc_issue_els_npiv_logo(vport, ndlp))
while (vport->unreg_vpi_cmpl == VPORT_INVAL && timeout)
timeout = schedule_timeout(timeout);
}
if (!(phba->pport->load_flag & FC_UNLOADING))
lpfc_discovery_wait(vport);
skip_logo:
lpfc_cleanup(vport);
lpfc_sli_host_down(vport);
lpfc_stop_vport_timers(vport);
if (!(phba->pport->load_flag & FC_UNLOADING)) {
lpfc_unreg_all_rpis(vport);
lpfc_unreg_default_rpis(vport);
/*
* Completion of unreg_vpi (lpfc_mbx_cmpl_unreg_vpi)
* does the scsi_host_put() to release the vport.
*/
if (lpfc_mbx_unreg_vpi(vport))
scsi_host_put(shost);
} else
scsi_host_put(shost);
lpfc_free_vpi(phba, vport->vpi);
vport->work_port_events = 0;
spin_lock_irq(&phba->hbalock);
list_del_init(&vport->listentry);
spin_unlock_irq(&phba->hbalock);
lpfc_printf_vlog(vport, KERN_ERR, LOG_VPORT,
"1828 Vport Deleted.\n");
scsi_host_put(shost);
return VPORT_OK;
}
struct lpfc_vport **
lpfc_create_vport_work_array(struct lpfc_hba *phba)
{
struct lpfc_vport *port_iterator;
struct lpfc_vport **vports;
int index = 0;
vports = kzalloc((phba->max_vports + 1) * sizeof(struct lpfc_vport *),
GFP_KERNEL);
if (vports == NULL)
return NULL;
spin_lock_irq(&phba->hbalock);
list_for_each_entry(port_iterator, &phba->port_list, listentry) {
if (!scsi_host_get(lpfc_shost_from_vport(port_iterator))) {
if (!(port_iterator->load_flag & FC_UNLOADING))
lpfc_printf_vlog(port_iterator, KERN_ERR,
LOG_VPORT,
"1801 Create vport work array FAILED: "
"cannot do scsi_host_get\n");
continue;
}
vports[index++] = port_iterator;
}
spin_unlock_irq(&phba->hbalock);
return vports;
}
void
lpfc_destroy_vport_work_array(struct lpfc_hba *phba, struct lpfc_vport **vports)
{
int i;
if (vports == NULL)
return;
for (i = 0; i <= phba->max_vports && vports[i] != NULL; i++)
scsi_host_put(lpfc_shost_from_vport(vports[i]));
kfree(vports);
}
/**
* lpfc_vport_reset_stat_data - Reset the statistical data for the vport
* @vport: Pointer to vport object.
*
* This function resets the statistical data for the vport. This function
* is called with the host_lock held
**/
void
lpfc_vport_reset_stat_data(struct lpfc_vport *vport)
{
struct lpfc_nodelist *ndlp = NULL, *next_ndlp = NULL;
list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
if (!NLP_CHK_NODE_ACT(ndlp))
continue;
if (ndlp->lat_data)
memset(ndlp->lat_data, 0, LPFC_MAX_BUCKET_COUNT *
sizeof(struct lpfc_scsicmd_bkt));
}
}
/**
* lpfc_alloc_bucket - Allocate data buffer required for statistical data
* @vport: Pointer to vport object.
*
* This function allocates data buffer required for all the FC
* nodes of the vport to collect statistical data.
**/
void
lpfc_alloc_bucket(struct lpfc_vport *vport)
{
struct lpfc_nodelist *ndlp = NULL, *next_ndlp = NULL;
list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
if (!NLP_CHK_NODE_ACT(ndlp))
continue;
kfree(ndlp->lat_data);
ndlp->lat_data = NULL;
if (ndlp->nlp_state == NLP_STE_MAPPED_NODE) {
ndlp->lat_data = kcalloc(LPFC_MAX_BUCKET_COUNT,
sizeof(struct lpfc_scsicmd_bkt),
GFP_ATOMIC);
if (!ndlp->lat_data)
lpfc_printf_vlog(vport, KERN_ERR, LOG_NODE,
"0287 lpfc_alloc_bucket failed to "
"allocate statistical data buffer DID "
"0x%x\n", ndlp->nlp_DID);
}
}
}
/**
* lpfc_free_bucket - Free data buffer required for statistical data
* @vport: Pointer to vport object.
*
* Th function frees statistical data buffer of all the FC
* nodes of the vport.
**/
void
lpfc_free_bucket(struct lpfc_vport *vport)
{
struct lpfc_nodelist *ndlp = NULL, *next_ndlp = NULL;
list_for_each_entry_safe(ndlp, next_ndlp, &vport->fc_nodes, nlp_listp) {
if (!NLP_CHK_NODE_ACT(ndlp))
continue;
kfree(ndlp->lat_data);
ndlp->lat_data = NULL;
}
}
| gpl-2.0 |
os2sd/android_kernel_lge_msm7x27-3.0.x | drivers/mtd/maps/vmu-flash.c | 3036 | 20009 | /* vmu-flash.c
* Driver for SEGA Dreamcast Visual Memory Unit
*
* Copyright (c) Adrian McMenamin 2002 - 2009
* Copyright (c) Paul Mundt 2001
*
* Licensed under version 2 of the
* GNU General Public Licence
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/maple.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
struct vmu_cache {
unsigned char *buffer; /* Cache */
unsigned int block; /* Which block was cached */
unsigned long jiffies_atc; /* When was it cached? */
int valid;
};
struct mdev_part {
struct maple_device *mdev;
int partition;
};
struct vmupart {
u16 user_blocks;
u16 root_block;
u16 numblocks;
char *name;
struct vmu_cache *pcache;
};
struct memcard {
u16 tempA;
u16 tempB;
u32 partitions;
u32 blocklen;
u32 writecnt;
u32 readcnt;
u32 removeable;
int partition;
int read;
unsigned char *blockread;
struct vmupart *parts;
struct mtd_info *mtd;
};
struct vmu_block {
unsigned int num; /* block number */
unsigned int ofs; /* block offset */
};
static struct vmu_block *ofs_to_block(unsigned long src_ofs,
struct mtd_info *mtd, int partition)
{
struct vmu_block *vblock;
struct maple_device *mdev;
struct memcard *card;
struct mdev_part *mpart;
int num;
mpart = mtd->priv;
mdev = mpart->mdev;
card = maple_get_drvdata(mdev);
if (src_ofs >= card->parts[partition].numblocks * card->blocklen)
goto failed;
num = src_ofs / card->blocklen;
if (num > card->parts[partition].numblocks)
goto failed;
vblock = kmalloc(sizeof(struct vmu_block), GFP_KERNEL);
if (!vblock)
goto failed;
vblock->num = num;
vblock->ofs = src_ofs % card->blocklen;
return vblock;
failed:
return NULL;
}
/* Maple bus callback function for reads */
static void vmu_blockread(struct mapleq *mq)
{
struct maple_device *mdev;
struct memcard *card;
mdev = mq->dev;
card = maple_get_drvdata(mdev);
/* copy the read in data */
if (unlikely(!card->blockread))
return;
memcpy(card->blockread, mq->recvbuf->buf + 12,
card->blocklen/card->readcnt);
}
/* Interface with maple bus to read blocks
* caching the results so that other parts
* of the driver can access block reads */
static int maple_vmu_read_block(unsigned int num, unsigned char *buf,
struct mtd_info *mtd)
{
struct memcard *card;
struct mdev_part *mpart;
struct maple_device *mdev;
int partition, error = 0, x, wait;
unsigned char *blockread = NULL;
struct vmu_cache *pcache;
__be32 sendbuf;
mpart = mtd->priv;
mdev = mpart->mdev;
partition = mpart->partition;
card = maple_get_drvdata(mdev);
pcache = card->parts[partition].pcache;
pcache->valid = 0;
/* prepare the cache for this block */
if (!pcache->buffer) {
pcache->buffer = kmalloc(card->blocklen, GFP_KERNEL);
if (!pcache->buffer) {
dev_err(&mdev->dev, "VMU at (%d, %d) - read fails due"
" to lack of memory\n", mdev->port,
mdev->unit);
error = -ENOMEM;
goto outB;
}
}
/*
* Reads may be phased - again the hardware spec
* supports this - though may not be any devices in
* the wild that implement it, but we will here
*/
for (x = 0; x < card->readcnt; x++) {
sendbuf = cpu_to_be32(partition << 24 | x << 16 | num);
if (atomic_read(&mdev->busy) == 1) {
wait_event_interruptible_timeout(mdev->maple_wait,
atomic_read(&mdev->busy) == 0, HZ);
if (atomic_read(&mdev->busy) == 1) {
dev_notice(&mdev->dev, "VMU at (%d, %d)"
" is busy\n", mdev->port, mdev->unit);
error = -EAGAIN;
goto outB;
}
}
atomic_set(&mdev->busy, 1);
blockread = kmalloc(card->blocklen/card->readcnt, GFP_KERNEL);
if (!blockread) {
error = -ENOMEM;
atomic_set(&mdev->busy, 0);
goto outB;
}
card->blockread = blockread;
maple_getcond_callback(mdev, vmu_blockread, 0,
MAPLE_FUNC_MEMCARD);
error = maple_add_packet(mdev, MAPLE_FUNC_MEMCARD,
MAPLE_COMMAND_BREAD, 2, &sendbuf);
/* Very long timeouts seem to be needed when box is stressed */
wait = wait_event_interruptible_timeout(mdev->maple_wait,
(atomic_read(&mdev->busy) == 0 ||
atomic_read(&mdev->busy) == 2), HZ * 3);
/*
* MTD layer does not handle hotplugging well
* so have to return errors when VMU is unplugged
* in the middle of a read (busy == 2)
*/
if (error || atomic_read(&mdev->busy) == 2) {
if (atomic_read(&mdev->busy) == 2)
error = -ENXIO;
atomic_set(&mdev->busy, 0);
card->blockread = NULL;
goto outA;
}
if (wait == 0 || wait == -ERESTARTSYS) {
card->blockread = NULL;
atomic_set(&mdev->busy, 0);
error = -EIO;
list_del_init(&(mdev->mq->list));
kfree(mdev->mq->sendbuf);
mdev->mq->sendbuf = NULL;
if (wait == -ERESTARTSYS) {
dev_warn(&mdev->dev, "VMU read on (%d, %d)"
" interrupted on block 0x%X\n",
mdev->port, mdev->unit, num);
} else
dev_notice(&mdev->dev, "VMU read on (%d, %d)"
" timed out on block 0x%X\n",
mdev->port, mdev->unit, num);
goto outA;
}
memcpy(buf + (card->blocklen/card->readcnt) * x, blockread,
card->blocklen/card->readcnt);
memcpy(pcache->buffer + (card->blocklen/card->readcnt) * x,
card->blockread, card->blocklen/card->readcnt);
card->blockread = NULL;
pcache->block = num;
pcache->jiffies_atc = jiffies;
pcache->valid = 1;
kfree(blockread);
}
return error;
outA:
kfree(blockread);
outB:
return error;
}
/* communicate with maple bus for phased writing */
static int maple_vmu_write_block(unsigned int num, const unsigned char *buf,
struct mtd_info *mtd)
{
struct memcard *card;
struct mdev_part *mpart;
struct maple_device *mdev;
int partition, error, locking, x, phaselen, wait;
__be32 *sendbuf;
mpart = mtd->priv;
mdev = mpart->mdev;
partition = mpart->partition;
card = maple_get_drvdata(mdev);
phaselen = card->blocklen/card->writecnt;
sendbuf = kmalloc(phaselen + 4, GFP_KERNEL);
if (!sendbuf) {
error = -ENOMEM;
goto fail_nosendbuf;
}
for (x = 0; x < card->writecnt; x++) {
sendbuf[0] = cpu_to_be32(partition << 24 | x << 16 | num);
memcpy(&sendbuf[1], buf + phaselen * x, phaselen);
/* wait until the device is not busy doing something else
* or 1 second - which ever is longer */
if (atomic_read(&mdev->busy) == 1) {
wait_event_interruptible_timeout(mdev->maple_wait,
atomic_read(&mdev->busy) == 0, HZ);
if (atomic_read(&mdev->busy) == 1) {
error = -EBUSY;
dev_notice(&mdev->dev, "VMU write at (%d, %d)"
"failed - device is busy\n",
mdev->port, mdev->unit);
goto fail_nolock;
}
}
atomic_set(&mdev->busy, 1);
locking = maple_add_packet(mdev, MAPLE_FUNC_MEMCARD,
MAPLE_COMMAND_BWRITE, phaselen / 4 + 2, sendbuf);
wait = wait_event_interruptible_timeout(mdev->maple_wait,
atomic_read(&mdev->busy) == 0, HZ/10);
if (locking) {
error = -EIO;
atomic_set(&mdev->busy, 0);
goto fail_nolock;
}
if (atomic_read(&mdev->busy) == 2) {
atomic_set(&mdev->busy, 0);
} else if (wait == 0 || wait == -ERESTARTSYS) {
error = -EIO;
dev_warn(&mdev->dev, "Write at (%d, %d) of block"
" 0x%X at phase %d failed: could not"
" communicate with VMU", mdev->port,
mdev->unit, num, x);
atomic_set(&mdev->busy, 0);
kfree(mdev->mq->sendbuf);
mdev->mq->sendbuf = NULL;
list_del_init(&(mdev->mq->list));
goto fail_nolock;
}
}
kfree(sendbuf);
return card->blocklen;
fail_nolock:
kfree(sendbuf);
fail_nosendbuf:
dev_err(&mdev->dev, "VMU (%d, %d): write failed\n", mdev->port,
mdev->unit);
return error;
}
/* mtd function to simulate reading byte by byte */
static unsigned char vmu_flash_read_char(unsigned long ofs, int *retval,
struct mtd_info *mtd)
{
struct vmu_block *vblock;
struct memcard *card;
struct mdev_part *mpart;
struct maple_device *mdev;
unsigned char *buf, ret;
int partition, error;
mpart = mtd->priv;
mdev = mpart->mdev;
partition = mpart->partition;
card = maple_get_drvdata(mdev);
*retval = 0;
buf = kmalloc(card->blocklen, GFP_KERNEL);
if (!buf) {
*retval = 1;
ret = -ENOMEM;
goto finish;
}
vblock = ofs_to_block(ofs, mtd, partition);
if (!vblock) {
*retval = 3;
ret = -ENOMEM;
goto out_buf;
}
error = maple_vmu_read_block(vblock->num, buf, mtd);
if (error) {
ret = error;
*retval = 2;
goto out_vblock;
}
ret = buf[vblock->ofs];
out_vblock:
kfree(vblock);
out_buf:
kfree(buf);
finish:
return ret;
}
/* mtd higher order function to read flash */
static int vmu_flash_read(struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, u_char *buf)
{
struct maple_device *mdev;
struct memcard *card;
struct mdev_part *mpart;
struct vmu_cache *pcache;
struct vmu_block *vblock;
int index = 0, retval, partition, leftover, numblocks;
unsigned char cx;
if (len < 1)
return -EIO;
mpart = mtd->priv;
mdev = mpart->mdev;
partition = mpart->partition;
card = maple_get_drvdata(mdev);
numblocks = card->parts[partition].numblocks;
if (from + len > numblocks * card->blocklen)
len = numblocks * card->blocklen - from;
if (len == 0)
return -EIO;
/* Have we cached this bit already? */
pcache = card->parts[partition].pcache;
do {
vblock = ofs_to_block(from + index, mtd, partition);
if (!vblock)
return -ENOMEM;
/* Have we cached this and is the cache valid and timely? */
if (pcache->valid &&
time_before(jiffies, pcache->jiffies_atc + HZ) &&
(pcache->block == vblock->num)) {
/* we have cached it, so do necessary copying */
leftover = card->blocklen - vblock->ofs;
if (vblock->ofs + len - index < card->blocklen) {
/* only a bit of this block to copy */
memcpy(buf + index,
pcache->buffer + vblock->ofs,
len - index);
index = len;
} else {
/* otherwise copy remainder of whole block */
memcpy(buf + index, pcache->buffer +
vblock->ofs, leftover);
index += leftover;
}
} else {
/*
* Not cached so read one byte -
* but cache the rest of the block
*/
cx = vmu_flash_read_char(from + index, &retval, mtd);
if (retval) {
*retlen = index;
kfree(vblock);
return cx;
}
memset(buf + index, cx, 1);
index++;
}
kfree(vblock);
} while (len > index);
*retlen = index;
return 0;
}
static int vmu_flash_write(struct mtd_info *mtd, loff_t to, size_t len,
size_t *retlen, const u_char *buf)
{
struct maple_device *mdev;
struct memcard *card;
struct mdev_part *mpart;
int index = 0, partition, error = 0, numblocks;
struct vmu_cache *pcache;
struct vmu_block *vblock;
unsigned char *buffer;
mpart = mtd->priv;
mdev = mpart->mdev;
partition = mpart->partition;
card = maple_get_drvdata(mdev);
/* simple sanity checks */
if (len < 1) {
error = -EIO;
goto failed;
}
numblocks = card->parts[partition].numblocks;
if (to + len > numblocks * card->blocklen)
len = numblocks * card->blocklen - to;
if (len == 0) {
error = -EIO;
goto failed;
}
vblock = ofs_to_block(to, mtd, partition);
if (!vblock) {
error = -ENOMEM;
goto failed;
}
buffer = kmalloc(card->blocklen, GFP_KERNEL);
if (!buffer) {
error = -ENOMEM;
goto fail_buffer;
}
do {
/* Read in the block we are to write to */
error = maple_vmu_read_block(vblock->num, buffer, mtd);
if (error)
goto fail_io;
do {
buffer[vblock->ofs] = buf[index];
vblock->ofs++;
index++;
if (index >= len)
break;
} while (vblock->ofs < card->blocklen);
/* write out new buffer */
error = maple_vmu_write_block(vblock->num, buffer, mtd);
/* invalidate the cache */
pcache = card->parts[partition].pcache;
pcache->valid = 0;
if (error != card->blocklen)
goto fail_io;
vblock->num++;
vblock->ofs = 0;
} while (len > index);
kfree(buffer);
*retlen = index;
kfree(vblock);
return 0;
fail_io:
kfree(buffer);
fail_buffer:
kfree(vblock);
failed:
dev_err(&mdev->dev, "VMU write failing with error %d\n", error);
return error;
}
static void vmu_flash_sync(struct mtd_info *mtd)
{
/* Do nothing here */
}
/* Maple bus callback function to recursively query hardware details */
static void vmu_queryblocks(struct mapleq *mq)
{
struct maple_device *mdev;
unsigned short *res;
struct memcard *card;
__be32 partnum;
struct vmu_cache *pcache;
struct mdev_part *mpart;
struct mtd_info *mtd_cur;
struct vmupart *part_cur;
int error;
mdev = mq->dev;
card = maple_get_drvdata(mdev);
res = (unsigned short *) (mq->recvbuf->buf);
card->tempA = res[12];
card->tempB = res[6];
dev_info(&mdev->dev, "VMU device at partition %d has %d user "
"blocks with a root block at %d\n", card->partition,
card->tempA, card->tempB);
part_cur = &card->parts[card->partition];
part_cur->user_blocks = card->tempA;
part_cur->root_block = card->tempB;
part_cur->numblocks = card->tempB + 1;
part_cur->name = kmalloc(12, GFP_KERNEL);
if (!part_cur->name)
goto fail_name;
sprintf(part_cur->name, "vmu%d.%d.%d",
mdev->port, mdev->unit, card->partition);
mtd_cur = &card->mtd[card->partition];
mtd_cur->name = part_cur->name;
mtd_cur->type = 8;
mtd_cur->flags = MTD_WRITEABLE|MTD_NO_ERASE;
mtd_cur->size = part_cur->numblocks * card->blocklen;
mtd_cur->erasesize = card->blocklen;
mtd_cur->write = vmu_flash_write;
mtd_cur->read = vmu_flash_read;
mtd_cur->sync = vmu_flash_sync;
mtd_cur->writesize = card->blocklen;
mpart = kmalloc(sizeof(struct mdev_part), GFP_KERNEL);
if (!mpart)
goto fail_mpart;
mpart->mdev = mdev;
mpart->partition = card->partition;
mtd_cur->priv = mpart;
mtd_cur->owner = THIS_MODULE;
pcache = kzalloc(sizeof(struct vmu_cache), GFP_KERNEL);
if (!pcache)
goto fail_cache_create;
part_cur->pcache = pcache;
error = mtd_device_register(mtd_cur, NULL, 0);
if (error)
goto fail_mtd_register;
maple_getcond_callback(mdev, NULL, 0,
MAPLE_FUNC_MEMCARD);
/*
* Set up a recursive call to the (probably theoretical)
* second or more partition
*/
if (++card->partition < card->partitions) {
partnum = cpu_to_be32(card->partition << 24);
maple_getcond_callback(mdev, vmu_queryblocks, 0,
MAPLE_FUNC_MEMCARD);
maple_add_packet(mdev, MAPLE_FUNC_MEMCARD,
MAPLE_COMMAND_GETMINFO, 2, &partnum);
}
return;
fail_mtd_register:
dev_err(&mdev->dev, "Could not register maple device at (%d, %d)"
"error is 0x%X\n", mdev->port, mdev->unit, error);
for (error = 0; error <= card->partition; error++) {
kfree(((card->parts)[error]).pcache);
((card->parts)[error]).pcache = NULL;
}
fail_cache_create:
fail_mpart:
for (error = 0; error <= card->partition; error++) {
kfree(((card->mtd)[error]).priv);
((card->mtd)[error]).priv = NULL;
}
maple_getcond_callback(mdev, NULL, 0,
MAPLE_FUNC_MEMCARD);
kfree(part_cur->name);
fail_name:
return;
}
/* Handles very basic info about the flash, queries for details */
static int __devinit vmu_connect(struct maple_device *mdev)
{
unsigned long test_flash_data, basic_flash_data;
int c, error;
struct memcard *card;
u32 partnum = 0;
test_flash_data = be32_to_cpu(mdev->devinfo.function);
/* Need to count how many bits are set - to find out which
* function_data element has details of the memory card
*/
c = hweight_long(test_flash_data);
basic_flash_data = be32_to_cpu(mdev->devinfo.function_data[c - 1]);
card = kmalloc(sizeof(struct memcard), GFP_KERNEL);
if (!card) {
error = -ENOMEM;
goto fail_nomem;
}
card->partitions = (basic_flash_data >> 24 & 0xFF) + 1;
card->blocklen = ((basic_flash_data >> 16 & 0xFF) + 1) << 5;
card->writecnt = basic_flash_data >> 12 & 0xF;
card->readcnt = basic_flash_data >> 8 & 0xF;
card->removeable = basic_flash_data >> 7 & 1;
card->partition = 0;
/*
* Not sure there are actually any multi-partition devices in the
* real world, but the hardware supports them, so, so will we
*/
card->parts = kmalloc(sizeof(struct vmupart) * card->partitions,
GFP_KERNEL);
if (!card->parts) {
error = -ENOMEM;
goto fail_partitions;
}
card->mtd = kmalloc(sizeof(struct mtd_info) * card->partitions,
GFP_KERNEL);
if (!card->mtd) {
error = -ENOMEM;
goto fail_mtd_info;
}
maple_set_drvdata(mdev, card);
/*
* We want to trap meminfo not get cond
* so set interval to zero, but rely on maple bus
* driver to pass back the results of the meminfo
*/
maple_getcond_callback(mdev, vmu_queryblocks, 0,
MAPLE_FUNC_MEMCARD);
/* Make sure we are clear to go */
if (atomic_read(&mdev->busy) == 1) {
wait_event_interruptible_timeout(mdev->maple_wait,
atomic_read(&mdev->busy) == 0, HZ);
if (atomic_read(&mdev->busy) == 1) {
dev_notice(&mdev->dev, "VMU at (%d, %d) is busy\n",
mdev->port, mdev->unit);
error = -EAGAIN;
goto fail_device_busy;
}
}
atomic_set(&mdev->busy, 1);
/*
* Set up the minfo call: vmu_queryblocks will handle
* the information passed back
*/
error = maple_add_packet(mdev, MAPLE_FUNC_MEMCARD,
MAPLE_COMMAND_GETMINFO, 2, &partnum);
if (error) {
dev_err(&mdev->dev, "Could not lock VMU at (%d, %d)"
" error is 0x%X\n", mdev->port, mdev->unit, error);
goto fail_mtd_info;
}
return 0;
fail_device_busy:
kfree(card->mtd);
fail_mtd_info:
kfree(card->parts);
fail_partitions:
kfree(card);
fail_nomem:
return error;
}
static void __devexit vmu_disconnect(struct maple_device *mdev)
{
struct memcard *card;
struct mdev_part *mpart;
int x;
mdev->callback = NULL;
card = maple_get_drvdata(mdev);
for (x = 0; x < card->partitions; x++) {
mpart = ((card->mtd)[x]).priv;
mpart->mdev = NULL;
mtd_device_unregister(&((card->mtd)[x]));
kfree(((card->parts)[x]).name);
}
kfree(card->parts);
kfree(card->mtd);
kfree(card);
}
/* Callback to handle eccentricities of both mtd subsystem
* and general flakyness of Dreamcast VMUs
*/
static int vmu_can_unload(struct maple_device *mdev)
{
struct memcard *card;
int x;
struct mtd_info *mtd;
card = maple_get_drvdata(mdev);
for (x = 0; x < card->partitions; x++) {
mtd = &((card->mtd)[x]);
if (mtd->usecount > 0)
return 0;
}
return 1;
}
#define ERRSTR "VMU at (%d, %d) file error -"
static void vmu_file_error(struct maple_device *mdev, void *recvbuf)
{
enum maple_file_errors error = ((int *)recvbuf)[1];
switch (error) {
case MAPLE_FILEERR_INVALID_PARTITION:
dev_notice(&mdev->dev, ERRSTR " invalid partition number\n",
mdev->port, mdev->unit);
break;
case MAPLE_FILEERR_PHASE_ERROR:
dev_notice(&mdev->dev, ERRSTR " phase error\n",
mdev->port, mdev->unit);
break;
case MAPLE_FILEERR_INVALID_BLOCK:
dev_notice(&mdev->dev, ERRSTR " invalid block number\n",
mdev->port, mdev->unit);
break;
case MAPLE_FILEERR_WRITE_ERROR:
dev_notice(&mdev->dev, ERRSTR " write error\n",
mdev->port, mdev->unit);
break;
case MAPLE_FILEERR_INVALID_WRITE_LENGTH:
dev_notice(&mdev->dev, ERRSTR " invalid write length\n",
mdev->port, mdev->unit);
break;
case MAPLE_FILEERR_BAD_CRC:
dev_notice(&mdev->dev, ERRSTR " bad CRC\n",
mdev->port, mdev->unit);
break;
default:
dev_notice(&mdev->dev, ERRSTR " 0x%X\n",
mdev->port, mdev->unit, error);
}
}
static int __devinit probe_maple_vmu(struct device *dev)
{
int error;
struct maple_device *mdev = to_maple_dev(dev);
struct maple_driver *mdrv = to_maple_driver(dev->driver);
mdev->can_unload = vmu_can_unload;
mdev->fileerr_handler = vmu_file_error;
mdev->driver = mdrv;
error = vmu_connect(mdev);
if (error)
return error;
return 0;
}
static int __devexit remove_maple_vmu(struct device *dev)
{
struct maple_device *mdev = to_maple_dev(dev);
vmu_disconnect(mdev);
return 0;
}
static struct maple_driver vmu_flash_driver = {
.function = MAPLE_FUNC_MEMCARD,
.drv = {
.name = "Dreamcast_visual_memory",
.probe = probe_maple_vmu,
.remove = __devexit_p(remove_maple_vmu),
},
};
static int __init vmu_flash_map_init(void)
{
return maple_driver_register(&vmu_flash_driver);
}
static void __exit vmu_flash_map_exit(void)
{
maple_driver_unregister(&vmu_flash_driver);
}
module_init(vmu_flash_map_init);
module_exit(vmu_flash_map_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Adrian McMenamin");
MODULE_DESCRIPTION("Flash mapping for Sega Dreamcast visual memory");
| gpl-2.0 |
kularny/GeniSys.Kernel | fs/coda/upcall.c | 3292 | 23315 | /*
* Mostly platform independent upcall operations to Venus:
* -- upcalls
* -- upcall routines
*
* Linux 2.0 version
* Copyright (C) 1996 Peter J. Braam <braam@maths.ox.ac.uk>,
* Michael Callahan <callahan@maths.ox.ac.uk>
*
* Redone for Linux 2.1
* Copyright (C) 1997 Carnegie Mellon University
*
* Carnegie Mellon University encourages users of this code to contribute
* improvements to the Coda project. Contact Peter Braam <coda@cs.cmu.edu>.
*/
#include <asm/system.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/stat.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <linux/vmalloc.h>
#include <linux/vfs.h>
#include <linux/coda.h>
#include <linux/coda_psdev.h>
#include "coda_linux.h"
#include "coda_cache.h"
#include "coda_int.h"
static int coda_upcall(struct venus_comm *vc, int inSize, int *outSize,
union inputArgs *buffer);
static void *alloc_upcall(int opcode, int size)
{
union inputArgs *inp;
CODA_ALLOC(inp, union inputArgs *, size);
if (!inp)
return ERR_PTR(-ENOMEM);
inp->ih.opcode = opcode;
inp->ih.pid = current->pid;
inp->ih.pgid = task_pgrp_nr(current);
inp->ih.uid = current_fsuid();
return (void*)inp;
}
#define UPARG(op)\
do {\
inp = (union inputArgs *)alloc_upcall(op, insize); \
if (IS_ERR(inp)) { return PTR_ERR(inp); }\
outp = (union outputArgs *)(inp); \
outsize = insize; \
} while (0)
#define INSIZE(tag) sizeof(struct coda_ ## tag ## _in)
#define OUTSIZE(tag) sizeof(struct coda_ ## tag ## _out)
#define SIZE(tag) max_t(unsigned int, INSIZE(tag), OUTSIZE(tag))
/* the upcalls */
int venus_rootfid(struct super_block *sb, struct CodaFid *fidp)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
insize = SIZE(root);
UPARG(CODA_ROOT);
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
if (!error)
*fidp = outp->coda_root.VFid;
CODA_FREE(inp, insize);
return error;
}
int venus_getattr(struct super_block *sb, struct CodaFid *fid,
struct coda_vattr *attr)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
insize = SIZE(getattr);
UPARG(CODA_GETATTR);
inp->coda_getattr.VFid = *fid;
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
if (!error)
*attr = outp->coda_getattr.attr;
CODA_FREE(inp, insize);
return error;
}
int venus_setattr(struct super_block *sb, struct CodaFid *fid,
struct coda_vattr *vattr)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
insize = SIZE(setattr);
UPARG(CODA_SETATTR);
inp->coda_setattr.VFid = *fid;
inp->coda_setattr.attr = *vattr;
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
CODA_FREE(inp, insize);
return error;
}
int venus_lookup(struct super_block *sb, struct CodaFid *fid,
const char *name, int length, int * type,
struct CodaFid *resfid)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
int offset;
offset = INSIZE(lookup);
insize = max_t(unsigned int, offset + length +1, OUTSIZE(lookup));
UPARG(CODA_LOOKUP);
inp->coda_lookup.VFid = *fid;
inp->coda_lookup.name = offset;
inp->coda_lookup.flags = CLU_CASE_SENSITIVE;
/* send Venus a null terminated string */
memcpy((char *)(inp) + offset, name, length);
*((char *)inp + offset + length) = '\0';
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
if (!error) {
*resfid = outp->coda_lookup.VFid;
*type = outp->coda_lookup.vtype;
}
CODA_FREE(inp, insize);
return error;
}
int venus_close(struct super_block *sb, struct CodaFid *fid, int flags,
vuid_t uid)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
insize = SIZE(release);
UPARG(CODA_CLOSE);
inp->ih.uid = uid;
inp->coda_close.VFid = *fid;
inp->coda_close.flags = flags;
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
CODA_FREE(inp, insize);
return error;
}
int venus_open(struct super_block *sb, struct CodaFid *fid,
int flags, struct file **fh)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
insize = SIZE(open_by_fd);
UPARG(CODA_OPEN_BY_FD);
inp->coda_open_by_fd.VFid = *fid;
inp->coda_open_by_fd.flags = flags;
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
if (!error)
*fh = outp->coda_open_by_fd.fh;
CODA_FREE(inp, insize);
return error;
}
int venus_mkdir(struct super_block *sb, struct CodaFid *dirfid,
const char *name, int length,
struct CodaFid *newfid, struct coda_vattr *attrs)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
int offset;
offset = INSIZE(mkdir);
insize = max_t(unsigned int, offset + length + 1, OUTSIZE(mkdir));
UPARG(CODA_MKDIR);
inp->coda_mkdir.VFid = *dirfid;
inp->coda_mkdir.attr = *attrs;
inp->coda_mkdir.name = offset;
/* Venus must get null terminated string */
memcpy((char *)(inp) + offset, name, length);
*((char *)inp + offset + length) = '\0';
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
if (!error) {
*attrs = outp->coda_mkdir.attr;
*newfid = outp->coda_mkdir.VFid;
}
CODA_FREE(inp, insize);
return error;
}
int venus_rename(struct super_block *sb, struct CodaFid *old_fid,
struct CodaFid *new_fid, size_t old_length,
size_t new_length, const char *old_name,
const char *new_name)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
int offset, s;
offset = INSIZE(rename);
insize = max_t(unsigned int, offset + new_length + old_length + 8,
OUTSIZE(rename));
UPARG(CODA_RENAME);
inp->coda_rename.sourceFid = *old_fid;
inp->coda_rename.destFid = *new_fid;
inp->coda_rename.srcname = offset;
/* Venus must receive an null terminated string */
s = ( old_length & ~0x3) +4; /* round up to word boundary */
memcpy((char *)(inp) + offset, old_name, old_length);
*((char *)inp + offset + old_length) = '\0';
/* another null terminated string for Venus */
offset += s;
inp->coda_rename.destname = offset;
s = ( new_length & ~0x3) +4; /* round up to word boundary */
memcpy((char *)(inp) + offset, new_name, new_length);
*((char *)inp + offset + new_length) = '\0';
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
CODA_FREE(inp, insize);
return error;
}
int venus_create(struct super_block *sb, struct CodaFid *dirfid,
const char *name, int length, int excl, int mode,
struct CodaFid *newfid, struct coda_vattr *attrs)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
int offset;
offset = INSIZE(create);
insize = max_t(unsigned int, offset + length + 1, OUTSIZE(create));
UPARG(CODA_CREATE);
inp->coda_create.VFid = *dirfid;
inp->coda_create.attr.va_mode = mode;
inp->coda_create.excl = excl;
inp->coda_create.mode = mode;
inp->coda_create.name = offset;
/* Venus must get null terminated string */
memcpy((char *)(inp) + offset, name, length);
*((char *)inp + offset + length) = '\0';
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
if (!error) {
*attrs = outp->coda_create.attr;
*newfid = outp->coda_create.VFid;
}
CODA_FREE(inp, insize);
return error;
}
int venus_rmdir(struct super_block *sb, struct CodaFid *dirfid,
const char *name, int length)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
int offset;
offset = INSIZE(rmdir);
insize = max_t(unsigned int, offset + length + 1, OUTSIZE(rmdir));
UPARG(CODA_RMDIR);
inp->coda_rmdir.VFid = *dirfid;
inp->coda_rmdir.name = offset;
memcpy((char *)(inp) + offset, name, length);
*((char *)inp + offset + length) = '\0';
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
CODA_FREE(inp, insize);
return error;
}
int venus_remove(struct super_block *sb, struct CodaFid *dirfid,
const char *name, int length)
{
union inputArgs *inp;
union outputArgs *outp;
int error=0, insize, outsize, offset;
offset = INSIZE(remove);
insize = max_t(unsigned int, offset + length + 1, OUTSIZE(remove));
UPARG(CODA_REMOVE);
inp->coda_remove.VFid = *dirfid;
inp->coda_remove.name = offset;
memcpy((char *)(inp) + offset, name, length);
*((char *)inp + offset + length) = '\0';
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
CODA_FREE(inp, insize);
return error;
}
int venus_readlink(struct super_block *sb, struct CodaFid *fid,
char *buffer, int *length)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
int retlen;
char *result;
insize = max_t(unsigned int,
INSIZE(readlink), OUTSIZE(readlink)+ *length + 1);
UPARG(CODA_READLINK);
inp->coda_readlink.VFid = *fid;
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
if (!error) {
retlen = outp->coda_readlink.count;
if ( retlen > *length )
retlen = *length;
*length = retlen;
result = (char *)outp + (long)outp->coda_readlink.data;
memcpy(buffer, result, retlen);
*(buffer + retlen) = '\0';
}
CODA_FREE(inp, insize);
return error;
}
int venus_link(struct super_block *sb, struct CodaFid *fid,
struct CodaFid *dirfid, const char *name, int len )
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
int offset;
offset = INSIZE(link);
insize = max_t(unsigned int, offset + len + 1, OUTSIZE(link));
UPARG(CODA_LINK);
inp->coda_link.sourceFid = *fid;
inp->coda_link.destFid = *dirfid;
inp->coda_link.tname = offset;
/* make sure strings are null terminated */
memcpy((char *)(inp) + offset, name, len);
*((char *)inp + offset + len) = '\0';
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
CODA_FREE(inp, insize);
return error;
}
int venus_symlink(struct super_block *sb, struct CodaFid *fid,
const char *name, int len,
const char *symname, int symlen)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
int offset, s;
offset = INSIZE(symlink);
insize = max_t(unsigned int, offset + len + symlen + 8, OUTSIZE(symlink));
UPARG(CODA_SYMLINK);
/* inp->coda_symlink.attr = *tva; XXXXXX */
inp->coda_symlink.VFid = *fid;
/* Round up to word boundary and null terminate */
inp->coda_symlink.srcname = offset;
s = ( symlen & ~0x3 ) + 4;
memcpy((char *)(inp) + offset, symname, symlen);
*((char *)inp + offset + symlen) = '\0';
/* Round up to word boundary and null terminate */
offset += s;
inp->coda_symlink.tname = offset;
s = (len & ~0x3) + 4;
memcpy((char *)(inp) + offset, name, len);
*((char *)inp + offset + len) = '\0';
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
CODA_FREE(inp, insize);
return error;
}
int venus_fsync(struct super_block *sb, struct CodaFid *fid)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
insize=SIZE(fsync);
UPARG(CODA_FSYNC);
inp->coda_fsync.VFid = *fid;
error = coda_upcall(coda_vcp(sb), sizeof(union inputArgs),
&outsize, inp);
CODA_FREE(inp, insize);
return error;
}
int venus_access(struct super_block *sb, struct CodaFid *fid, int mask)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
insize = SIZE(access);
UPARG(CODA_ACCESS);
inp->coda_access.VFid = *fid;
inp->coda_access.flags = mask;
error = coda_upcall(coda_vcp(sb), insize, &outsize, inp);
CODA_FREE(inp, insize);
return error;
}
int venus_pioctl(struct super_block *sb, struct CodaFid *fid,
unsigned int cmd, struct PioctlData *data)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
int iocsize;
insize = VC_MAXMSGSIZE;
UPARG(CODA_IOCTL);
/* build packet for Venus */
if (data->vi.in_size > VC_MAXDATASIZE) {
error = -EINVAL;
goto exit;
}
if (data->vi.out_size > VC_MAXDATASIZE) {
error = -EINVAL;
goto exit;
}
inp->coda_ioctl.VFid = *fid;
/* the cmd field was mutated by increasing its size field to
* reflect the path and follow args. We need to subtract that
* out before sending the command to Venus. */
inp->coda_ioctl.cmd = (cmd & ~(PIOCPARM_MASK << 16));
iocsize = ((cmd >> 16) & PIOCPARM_MASK) - sizeof(char *) - sizeof(int);
inp->coda_ioctl.cmd |= (iocsize & PIOCPARM_MASK) << 16;
/* in->coda_ioctl.rwflag = flag; */
inp->coda_ioctl.len = data->vi.in_size;
inp->coda_ioctl.data = (char *)(INSIZE(ioctl));
/* get the data out of user space */
if ( copy_from_user((char*)inp + (long)inp->coda_ioctl.data,
data->vi.in, data->vi.in_size) ) {
error = -EINVAL;
goto exit;
}
error = coda_upcall(coda_vcp(sb), SIZE(ioctl) + data->vi.in_size,
&outsize, inp);
if (error) {
printk("coda_pioctl: Venus returns: %d for %s\n",
error, coda_f2s(fid));
goto exit;
}
if (outsize < (long)outp->coda_ioctl.data + outp->coda_ioctl.len) {
error = -EINVAL;
goto exit;
}
/* Copy out the OUT buffer. */
if (outp->coda_ioctl.len > data->vi.out_size) {
error = -EINVAL;
goto exit;
}
/* Copy out the OUT buffer. */
if (copy_to_user(data->vi.out,
(char *)outp + (long)outp->coda_ioctl.data,
outp->coda_ioctl.len)) {
error = -EFAULT;
goto exit;
}
exit:
CODA_FREE(inp, insize);
return error;
}
int venus_statfs(struct dentry *dentry, struct kstatfs *sfs)
{
union inputArgs *inp;
union outputArgs *outp;
int insize, outsize, error;
insize = max_t(unsigned int, INSIZE(statfs), OUTSIZE(statfs));
UPARG(CODA_STATFS);
error = coda_upcall(coda_vcp(dentry->d_sb), insize, &outsize, inp);
if (!error) {
sfs->f_blocks = outp->coda_statfs.stat.f_blocks;
sfs->f_bfree = outp->coda_statfs.stat.f_bfree;
sfs->f_bavail = outp->coda_statfs.stat.f_bavail;
sfs->f_files = outp->coda_statfs.stat.f_files;
sfs->f_ffree = outp->coda_statfs.stat.f_ffree;
}
CODA_FREE(inp, insize);
return error;
}
/*
* coda_upcall and coda_downcall routines.
*/
static void coda_block_signals(sigset_t *old)
{
spin_lock_irq(¤t->sighand->siglock);
*old = current->blocked;
sigfillset(¤t->blocked);
sigdelset(¤t->blocked, SIGKILL);
sigdelset(¤t->blocked, SIGSTOP);
sigdelset(¤t->blocked, SIGINT);
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
}
static void coda_unblock_signals(sigset_t *old)
{
spin_lock_irq(¤t->sighand->siglock);
current->blocked = *old;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
}
/* Don't allow signals to interrupt the following upcalls before venus
* has seen them,
* - CODA_CLOSE or CODA_RELEASE upcall (to avoid reference count problems)
* - CODA_STORE (to avoid data loss)
*/
#define CODA_INTERRUPTIBLE(r) (!coda_hard && \
(((r)->uc_opcode != CODA_CLOSE && \
(r)->uc_opcode != CODA_STORE && \
(r)->uc_opcode != CODA_RELEASE) || \
(r)->uc_flags & CODA_REQ_READ))
static inline void coda_waitfor_upcall(struct venus_comm *vcp,
struct upc_req *req)
{
DECLARE_WAITQUEUE(wait, current);
unsigned long timeout = jiffies + coda_timeout * HZ;
sigset_t old;
int blocked;
coda_block_signals(&old);
blocked = 1;
add_wait_queue(&req->uc_sleep, &wait);
for (;;) {
if (CODA_INTERRUPTIBLE(req))
set_current_state(TASK_INTERRUPTIBLE);
else
set_current_state(TASK_UNINTERRUPTIBLE);
/* got a reply */
if (req->uc_flags & (CODA_REQ_WRITE | CODA_REQ_ABORT))
break;
if (blocked && time_after(jiffies, timeout) &&
CODA_INTERRUPTIBLE(req))
{
coda_unblock_signals(&old);
blocked = 0;
}
if (signal_pending(current)) {
list_del(&req->uc_chain);
break;
}
mutex_unlock(&vcp->vc_mutex);
if (blocked)
schedule_timeout(HZ);
else
schedule();
mutex_lock(&vcp->vc_mutex);
}
if (blocked)
coda_unblock_signals(&old);
remove_wait_queue(&req->uc_sleep, &wait);
set_current_state(TASK_RUNNING);
}
/*
* coda_upcall will return an error in the case of
* failed communication with Venus _or_ will peek at Venus
* reply and return Venus' error.
*
* As venus has 2 types of errors, normal errors (positive) and internal
* errors (negative), normal errors are negated, while internal errors
* are all mapped to -EINTR, while showing a nice warning message. (jh)
*/
static int coda_upcall(struct venus_comm *vcp,
int inSize, int *outSize,
union inputArgs *buffer)
{
union outputArgs *out;
union inputArgs *sig_inputArgs;
struct upc_req *req = NULL, *sig_req;
int error;
mutex_lock(&vcp->vc_mutex);
if (!vcp->vc_inuse) {
printk(KERN_NOTICE "coda: Venus dead, not sending upcall\n");
error = -ENXIO;
goto exit;
}
/* Format the request message. */
req = kmalloc(sizeof(struct upc_req), GFP_KERNEL);
if (!req) {
error = -ENOMEM;
goto exit;
}
req->uc_data = (void *)buffer;
req->uc_flags = 0;
req->uc_inSize = inSize;
req->uc_outSize = *outSize ? *outSize : inSize;
req->uc_opcode = ((union inputArgs *)buffer)->ih.opcode;
req->uc_unique = ++vcp->vc_seq;
init_waitqueue_head(&req->uc_sleep);
/* Fill in the common input args. */
((union inputArgs *)buffer)->ih.unique = req->uc_unique;
/* Append msg to pending queue and poke Venus. */
list_add_tail(&req->uc_chain, &vcp->vc_pending);
wake_up_interruptible(&vcp->vc_waitq);
/* We can be interrupted while we wait for Venus to process
* our request. If the interrupt occurs before Venus has read
* the request, we dequeue and return. If it occurs after the
* read but before the reply, we dequeue, send a signal
* message, and return. If it occurs after the reply we ignore
* it. In no case do we want to restart the syscall. If it
* was interrupted by a venus shutdown (psdev_close), return
* ENODEV. */
/* Go to sleep. Wake up on signals only after the timeout. */
coda_waitfor_upcall(vcp, req);
/* Op went through, interrupt or not... */
if (req->uc_flags & CODA_REQ_WRITE) {
out = (union outputArgs *)req->uc_data;
/* here we map positive Venus errors to kernel errors */
error = -out->oh.result;
*outSize = req->uc_outSize;
goto exit;
}
error = -EINTR;
if ((req->uc_flags & CODA_REQ_ABORT) || !signal_pending(current)) {
printk(KERN_WARNING "coda: Unexpected interruption.\n");
goto exit;
}
/* Interrupted before venus read it. */
if (!(req->uc_flags & CODA_REQ_READ))
goto exit;
/* Venus saw the upcall, make sure we can send interrupt signal */
if (!vcp->vc_inuse) {
printk(KERN_INFO "coda: Venus dead, not sending signal.\n");
goto exit;
}
error = -ENOMEM;
sig_req = kmalloc(sizeof(struct upc_req), GFP_KERNEL);
if (!sig_req) goto exit;
CODA_ALLOC((sig_req->uc_data), char *, sizeof(struct coda_in_hdr));
if (!sig_req->uc_data) {
kfree(sig_req);
goto exit;
}
error = -EINTR;
sig_inputArgs = (union inputArgs *)sig_req->uc_data;
sig_inputArgs->ih.opcode = CODA_SIGNAL;
sig_inputArgs->ih.unique = req->uc_unique;
sig_req->uc_flags = CODA_REQ_ASYNC;
sig_req->uc_opcode = sig_inputArgs->ih.opcode;
sig_req->uc_unique = sig_inputArgs->ih.unique;
sig_req->uc_inSize = sizeof(struct coda_in_hdr);
sig_req->uc_outSize = sizeof(struct coda_in_hdr);
/* insert at head of queue! */
list_add(&(sig_req->uc_chain), &vcp->vc_pending);
wake_up_interruptible(&vcp->vc_waitq);
exit:
kfree(req);
mutex_unlock(&vcp->vc_mutex);
return error;
}
/*
The statements below are part of the Coda opportunistic
programming -- taken from the Mach/BSD kernel code for Coda.
You don't get correct semantics by stating what needs to be
done without guaranteeing the invariants needed for it to happen.
When will be have time to find out what exactly is going on? (pjb)
*/
/*
* There are 7 cases where cache invalidations occur. The semantics
* of each is listed here:
*
* CODA_FLUSH -- flush all entries from the name cache and the cnode cache.
* CODA_PURGEUSER -- flush all entries from the name cache for a specific user
* This call is a result of token expiration.
*
* The next arise as the result of callbacks on a file or directory.
* CODA_ZAPFILE -- flush the cached attributes for a file.
* CODA_ZAPDIR -- flush the attributes for the dir and
* force a new lookup for all the children
of this dir.
*
* The next is a result of Venus detecting an inconsistent file.
* CODA_PURGEFID -- flush the attribute for the file
* purge it and its children from the dcache
*
* The last allows Venus to replace local fids with global ones
* during reintegration.
*
* CODA_REPLACE -- replace one CodaFid with another throughout the name cache */
int coda_downcall(struct venus_comm *vcp, int opcode, union outputArgs *out)
{
struct inode *inode = NULL;
struct CodaFid *fid = NULL, *newfid;
struct super_block *sb;
/* Handle invalidation requests. */
mutex_lock(&vcp->vc_mutex);
sb = vcp->vc_sb;
if (!sb || !sb->s_root)
goto unlock_out;
switch (opcode) {
case CODA_FLUSH:
coda_cache_clear_all(sb);
shrink_dcache_sb(sb);
if (sb->s_root->d_inode)
coda_flag_inode(sb->s_root->d_inode, C_FLUSH);
break;
case CODA_PURGEUSER:
coda_cache_clear_all(sb);
break;
case CODA_ZAPDIR:
fid = &out->coda_zapdir.CodaFid;
break;
case CODA_ZAPFILE:
fid = &out->coda_zapfile.CodaFid;
break;
case CODA_PURGEFID:
fid = &out->coda_purgefid.CodaFid;
break;
case CODA_REPLACE:
fid = &out->coda_replace.OldFid;
break;
}
if (fid)
inode = coda_fid_to_inode(fid, sb);
unlock_out:
mutex_unlock(&vcp->vc_mutex);
if (!inode)
return 0;
switch (opcode) {
case CODA_ZAPDIR:
coda_flag_inode_children(inode, C_PURGE);
coda_flag_inode(inode, C_VATTR);
break;
case CODA_ZAPFILE:
coda_flag_inode(inode, C_VATTR);
break;
case CODA_PURGEFID:
coda_flag_inode_children(inode, C_PURGE);
/* catch the dentries later if some are still busy */
coda_flag_inode(inode, C_PURGE);
d_prune_aliases(inode);
break;
case CODA_REPLACE:
newfid = &out->coda_replace.NewFid;
coda_replace_fid(inode, fid, newfid);
break;
}
iput(inode);
return 0;
}
| gpl-2.0 |
jeboo/kernel-msm | arch/arm/mach-omap1/i2c.c | 3548 | 2525 | /*
* Helper module for board specific I2C bus registration
*
* Copyright (C) 2009 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
*
*/
#include <linux/i2c-omap.h>
#include <mach/mux.h>
#include "soc.h"
#include <plat/i2c.h>
#define OMAP_I2C_SIZE 0x3f
#define OMAP1_I2C_BASE 0xfffb3800
#define OMAP1_INT_I2C (32 + 4)
static const char name[] = "omap_i2c";
static struct resource i2c_resources[2] = {
};
static struct platform_device omap_i2c_devices[1] = {
};
static void __init omap1_i2c_mux_pins(int bus_id)
{
if (cpu_is_omap7xx()) {
omap_cfg_reg(I2C_7XX_SDA);
omap_cfg_reg(I2C_7XX_SCL);
} else {
omap_cfg_reg(I2C_SDA);
omap_cfg_reg(I2C_SCL);
}
}
int __init omap_i2c_add_bus(struct omap_i2c_bus_platform_data *pdata,
int bus_id)
{
struct platform_device *pdev;
struct resource *res;
if (bus_id > 1)
return -EINVAL;
omap1_i2c_mux_pins(bus_id);
pdev = &omap_i2c_devices[bus_id - 1];
pdev->id = bus_id;
pdev->name = name;
pdev->num_resources = ARRAY_SIZE(i2c_resources);
res = i2c_resources;
res[0].start = OMAP1_I2C_BASE;
res[0].end = res[0].start + OMAP_I2C_SIZE;
res[0].flags = IORESOURCE_MEM;
res[1].start = OMAP1_INT_I2C;
res[1].flags = IORESOURCE_IRQ;
pdev->resource = res;
/* all OMAP1 have IP version 1 register set */
pdata->rev = OMAP_I2C_IP_VERSION_1;
/* all OMAP1 I2C are implemented like this */
pdata->flags = OMAP_I2C_FLAG_NO_FIFO |
OMAP_I2C_FLAG_SIMPLE_CLOCK |
OMAP_I2C_FLAG_16BIT_DATA_REG |
OMAP_I2C_FLAG_ALWAYS_ARMXOR_CLK;
/* how the cpu bus is wired up differs for 7xx only */
if (cpu_is_omap7xx())
pdata->flags |= OMAP_I2C_FLAG_BUS_SHIFT_1;
else
pdata->flags |= OMAP_I2C_FLAG_BUS_SHIFT_2;
pdev->dev.platform_data = pdata;
return platform_device_register(pdev);
}
static int __init omap_i2c_cmdline(void)
{
return omap_register_i2c_bus_cmdline();
}
subsys_initcall(omap_i2c_cmdline);
| gpl-2.0 |
DirtyUnicorns/android_kernel_samsung_ks01lte | fs/ioprio.c | 3804 | 4924 | /*
* fs/ioprio.c
*
* Copyright (C) 2004 Jens Axboe <axboe@kernel.dk>
*
* Helper functions for setting/querying io priorities of processes. The
* system calls closely mimmick getpriority/setpriority, see the man page for
* those. The prio argument is a composite of prio class and prio data, where
* the data argument has meaning within that class. The standard scheduling
* classes have 8 distinct prio levels, with 0 being the highest prio and 7
* being the lowest.
*
* IOW, setting BE scheduling class with prio 2 is done ala:
*
* unsigned int prio = (IOPRIO_CLASS_BE << IOPRIO_CLASS_SHIFT) | 2;
*
* ioprio_set(PRIO_PROCESS, pid, prio);
*
* See also Documentation/block/ioprio.txt
*
*/
#include <linux/gfp.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/ioprio.h>
#include <linux/blkdev.h>
#include <linux/capability.h>
#include <linux/syscalls.h>
#include <linux/security.h>
#include <linux/pid_namespace.h>
int set_task_ioprio(struct task_struct *task, int ioprio)
{
int err;
struct io_context *ioc;
const struct cred *cred = current_cred(), *tcred;
rcu_read_lock();
tcred = __task_cred(task);
if (tcred->uid != cred->euid &&
tcred->uid != cred->uid && !capable(CAP_SYS_NICE)) {
rcu_read_unlock();
return -EPERM;
}
rcu_read_unlock();
err = security_task_setioprio(task, ioprio);
if (err)
return err;
ioc = get_task_io_context(task, GFP_ATOMIC, NUMA_NO_NODE);
if (ioc) {
ioc_ioprio_changed(ioc, ioprio);
put_io_context(ioc);
}
return err;
}
EXPORT_SYMBOL_GPL(set_task_ioprio);
SYSCALL_DEFINE3(ioprio_set, int, which, int, who, int, ioprio)
{
int class = IOPRIO_PRIO_CLASS(ioprio);
int data = IOPRIO_PRIO_DATA(ioprio);
struct task_struct *p, *g;
struct user_struct *user;
struct pid *pgrp;
int ret;
switch (class) {
case IOPRIO_CLASS_RT:
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
/* fall through, rt has prio field too */
case IOPRIO_CLASS_BE:
if (data >= IOPRIO_BE_NR || data < 0)
return -EINVAL;
break;
case IOPRIO_CLASS_IDLE:
break;
case IOPRIO_CLASS_NONE:
if (data)
return -EINVAL;
break;
default:
return -EINVAL;
}
ret = -ESRCH;
rcu_read_lock();
switch (which) {
case IOPRIO_WHO_PROCESS:
if (!who)
p = current;
else
p = find_task_by_vpid(who);
if (p)
ret = set_task_ioprio(p, ioprio);
break;
case IOPRIO_WHO_PGRP:
if (!who)
pgrp = task_pgrp(current);
else
pgrp = find_vpid(who);
do_each_pid_thread(pgrp, PIDTYPE_PGID, p) {
ret = set_task_ioprio(p, ioprio);
if (ret)
break;
} while_each_pid_thread(pgrp, PIDTYPE_PGID, p);
break;
case IOPRIO_WHO_USER:
if (!who)
user = current_user();
else
user = find_user(who);
if (!user)
break;
do_each_thread(g, p) {
if (__task_cred(p)->uid != who)
continue;
ret = set_task_ioprio(p, ioprio);
if (ret)
goto free_uid;
} while_each_thread(g, p);
free_uid:
if (who)
free_uid(user);
break;
default:
ret = -EINVAL;
}
rcu_read_unlock();
return ret;
}
static int get_task_ioprio(struct task_struct *p)
{
int ret;
ret = security_task_getioprio(p);
if (ret)
goto out;
ret = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, IOPRIO_NORM);
if (p->io_context)
ret = p->io_context->ioprio;
out:
return ret;
}
int ioprio_best(unsigned short aprio, unsigned short bprio)
{
unsigned short aclass = IOPRIO_PRIO_CLASS(aprio);
unsigned short bclass = IOPRIO_PRIO_CLASS(bprio);
if (aclass == IOPRIO_CLASS_NONE)
aclass = IOPRIO_CLASS_BE;
if (bclass == IOPRIO_CLASS_NONE)
bclass = IOPRIO_CLASS_BE;
if (aclass == bclass)
return min(aprio, bprio);
if (aclass > bclass)
return bprio;
else
return aprio;
}
SYSCALL_DEFINE2(ioprio_get, int, which, int, who)
{
struct task_struct *g, *p;
struct user_struct *user;
struct pid *pgrp;
int ret = -ESRCH;
int tmpio;
rcu_read_lock();
switch (which) {
case IOPRIO_WHO_PROCESS:
if (!who)
p = current;
else
p = find_task_by_vpid(who);
if (p)
ret = get_task_ioprio(p);
break;
case IOPRIO_WHO_PGRP:
if (!who)
pgrp = task_pgrp(current);
else
pgrp = find_vpid(who);
do_each_pid_thread(pgrp, PIDTYPE_PGID, p) {
tmpio = get_task_ioprio(p);
if (tmpio < 0)
continue;
if (ret == -ESRCH)
ret = tmpio;
else
ret = ioprio_best(ret, tmpio);
} while_each_pid_thread(pgrp, PIDTYPE_PGID, p);
break;
case IOPRIO_WHO_USER:
if (!who)
user = current_user();
else
user = find_user(who);
if (!user)
break;
do_each_thread(g, p) {
if (__task_cred(p)->uid != user->uid)
continue;
tmpio = get_task_ioprio(p);
if (tmpio < 0)
continue;
if (ret == -ESRCH)
ret = tmpio;
else
ret = ioprio_best(ret, tmpio);
} while_each_thread(g, p);
if (who)
free_uid(user);
break;
default:
ret = -EINVAL;
}
rcu_read_unlock();
return ret;
}
| gpl-2.0 |
snishanth512/linux | drivers/media/dvb-frontends/tda8261.c | 4316 | 6001 | /*
TDA8261 8PSK/QPSK tuner driver
Copyright (C) Manu Abraham (abraham.manu@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "dvb_frontend.h"
#include "tda8261.h"
struct tda8261_state {
struct dvb_frontend *fe;
struct i2c_adapter *i2c;
const struct tda8261_config *config;
/* state cache */
u32 frequency;
u32 bandwidth;
};
static int tda8261_read(struct tda8261_state *state, u8 *buf)
{
const struct tda8261_config *config = state->config;
int err = 0;
struct i2c_msg msg = { .addr = config->addr, .flags = I2C_M_RD,.buf = buf, .len = 1 };
if ((err = i2c_transfer(state->i2c, &msg, 1)) != 1)
pr_err("%s: read error, err=%d\n", __func__, err);
return err;
}
static int tda8261_write(struct tda8261_state *state, u8 *buf)
{
const struct tda8261_config *config = state->config;
int err = 0;
struct i2c_msg msg = { .addr = config->addr, .flags = 0, .buf = buf, .len = 4 };
if ((err = i2c_transfer(state->i2c, &msg, 1)) != 1)
pr_err("%s: write error, err=%d\n", __func__, err);
return err;
}
static int tda8261_get_status(struct dvb_frontend *fe, u32 *status)
{
struct tda8261_state *state = fe->tuner_priv;
u8 result = 0;
int err = 0;
*status = 0;
if ((err = tda8261_read(state, &result)) < 0) {
pr_err("%s: I/O Error\n", __func__);
return err;
}
if ((result >> 6) & 0x01) {
pr_debug("%s: Tuner Phase Locked\n", __func__);
*status = 1;
}
return err;
}
static const u32 div_tab[] = { 2000, 1000, 500, 250, 125 }; /* kHz */
static const u8 ref_div[] = { 0x00, 0x01, 0x02, 0x05, 0x07 };
static int tda8261_get_state(struct dvb_frontend *fe,
enum tuner_param param,
struct tuner_state *tstate)
{
struct tda8261_state *state = fe->tuner_priv;
int err = 0;
switch (param) {
case DVBFE_TUNER_FREQUENCY:
tstate->frequency = state->frequency;
break;
case DVBFE_TUNER_BANDWIDTH:
tstate->bandwidth = 40000000; /* FIXME! need to calculate Bandwidth */
break;
default:
pr_err("%s: Unknown parameter (param=%d)\n", __func__, param);
err = -EINVAL;
break;
}
return err;
}
static int tda8261_set_state(struct dvb_frontend *fe,
enum tuner_param param,
struct tuner_state *tstate)
{
struct tda8261_state *state = fe->tuner_priv;
const struct tda8261_config *config = state->config;
u32 frequency, N, status = 0;
u8 buf[4];
int err = 0;
if (param & DVBFE_TUNER_FREQUENCY) {
/**
* N = Max VCO Frequency / Channel Spacing
* Max VCO Frequency = VCO frequency + (channel spacing - 1)
* (to account for half channel spacing on either side)
*/
frequency = tstate->frequency;
if ((frequency < 950000) || (frequency > 2150000)) {
pr_warn("%s: Frequency beyond limits, frequency=%d\n", __func__, frequency);
return -EINVAL;
}
N = (frequency + (div_tab[config->step_size] - 1)) / div_tab[config->step_size];
pr_debug("%s: Step size=%d, Divider=%d, PG=0x%02x (%d)\n",
__func__, config->step_size, div_tab[config->step_size], N, N);
buf[0] = (N >> 8) & 0xff;
buf[1] = N & 0xff;
buf[2] = (0x01 << 7) | ((ref_div[config->step_size] & 0x07) << 1);
if (frequency < 1450000)
buf[3] = 0x00;
else if (frequency < 2000000)
buf[3] = 0x40;
else if (frequency < 2150000)
buf[3] = 0x80;
/* Set params */
if ((err = tda8261_write(state, buf)) < 0) {
pr_err("%s: I/O Error\n", __func__);
return err;
}
/* sleep for some time */
pr_debug("%s: Waiting to Phase LOCK\n", __func__);
msleep(20);
/* check status */
if ((err = tda8261_get_status(fe, &status)) < 0) {
pr_err("%s: I/O Error\n", __func__);
return err;
}
if (status == 1) {
pr_debug("%s: Tuner Phase locked: status=%d\n", __func__, status);
state->frequency = frequency; /* cache successful state */
} else {
pr_debug("%s: No Phase lock: status=%d\n", __func__, status);
}
} else {
pr_err("%s: Unknown parameter (param=%d)\n", __func__, param);
return -EINVAL;
}
return 0;
}
static int tda8261_release(struct dvb_frontend *fe)
{
struct tda8261_state *state = fe->tuner_priv;
fe->tuner_priv = NULL;
kfree(state);
return 0;
}
static struct dvb_tuner_ops tda8261_ops = {
.info = {
.name = "TDA8261",
// .tuner_name = NULL,
.frequency_min = 950000,
.frequency_max = 2150000,
.frequency_step = 0
},
.set_state = tda8261_set_state,
.get_state = tda8261_get_state,
.get_status = tda8261_get_status,
.release = tda8261_release
};
struct dvb_frontend *tda8261_attach(struct dvb_frontend *fe,
const struct tda8261_config *config,
struct i2c_adapter *i2c)
{
struct tda8261_state *state = NULL;
if ((state = kzalloc(sizeof (struct tda8261_state), GFP_KERNEL)) == NULL)
goto exit;
state->config = config;
state->i2c = i2c;
state->fe = fe;
fe->tuner_priv = state;
fe->ops.tuner_ops = tda8261_ops;
fe->ops.tuner_ops.info.frequency_step = div_tab[config->step_size];
// fe->ops.tuner_ops.tuner_name = &config->buf;
// printk("%s: Attaching %s TDA8261 8PSK/QPSK tuner\n",
// __func__, fe->ops.tuner_ops.tuner_name);
pr_info("%s: Attaching TDA8261 8PSK/QPSK tuner\n", __func__);
return fe;
exit:
kfree(state);
return NULL;
}
EXPORT_SYMBOL(tda8261_attach);
MODULE_AUTHOR("Manu Abraham");
MODULE_DESCRIPTION("TDA8261 8PSK/QPSK Tuner");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Beeko/android_kernel_htc_msm8960 | drivers/media/common/tuners/tda18271-maps.c | 4828 | 45788 | /*
tda18271-maps.c - driver for the Philips / NXP TDA18271 silicon tuner
Copyright (C) 2007, 2008 Michael Krufky <mkrufky@linuxtv.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "tda18271-priv.h"
struct tda18271_pll_map {
u32 lomax;
u8 pd; /* post div */
u8 d; /* div */
};
struct tda18271_map {
u32 rfmax;
u8 val;
};
/*---------------------------------------------------------------------*/
static struct tda18271_pll_map tda18271c1_main_pll[] = {
{ .lomax = 32000, .pd = 0x5f, .d = 0xf0 },
{ .lomax = 35000, .pd = 0x5e, .d = 0xe0 },
{ .lomax = 37000, .pd = 0x5d, .d = 0xd0 },
{ .lomax = 41000, .pd = 0x5c, .d = 0xc0 },
{ .lomax = 44000, .pd = 0x5b, .d = 0xb0 },
{ .lomax = 49000, .pd = 0x5a, .d = 0xa0 },
{ .lomax = 54000, .pd = 0x59, .d = 0x90 },
{ .lomax = 61000, .pd = 0x58, .d = 0x80 },
{ .lomax = 65000, .pd = 0x4f, .d = 0x78 },
{ .lomax = 70000, .pd = 0x4e, .d = 0x70 },
{ .lomax = 75000, .pd = 0x4d, .d = 0x68 },
{ .lomax = 82000, .pd = 0x4c, .d = 0x60 },
{ .lomax = 89000, .pd = 0x4b, .d = 0x58 },
{ .lomax = 98000, .pd = 0x4a, .d = 0x50 },
{ .lomax = 109000, .pd = 0x49, .d = 0x48 },
{ .lomax = 123000, .pd = 0x48, .d = 0x40 },
{ .lomax = 131000, .pd = 0x3f, .d = 0x3c },
{ .lomax = 141000, .pd = 0x3e, .d = 0x38 },
{ .lomax = 151000, .pd = 0x3d, .d = 0x34 },
{ .lomax = 164000, .pd = 0x3c, .d = 0x30 },
{ .lomax = 179000, .pd = 0x3b, .d = 0x2c },
{ .lomax = 197000, .pd = 0x3a, .d = 0x28 },
{ .lomax = 219000, .pd = 0x39, .d = 0x24 },
{ .lomax = 246000, .pd = 0x38, .d = 0x20 },
{ .lomax = 263000, .pd = 0x2f, .d = 0x1e },
{ .lomax = 282000, .pd = 0x2e, .d = 0x1c },
{ .lomax = 303000, .pd = 0x2d, .d = 0x1a },
{ .lomax = 329000, .pd = 0x2c, .d = 0x18 },
{ .lomax = 359000, .pd = 0x2b, .d = 0x16 },
{ .lomax = 395000, .pd = 0x2a, .d = 0x14 },
{ .lomax = 438000, .pd = 0x29, .d = 0x12 },
{ .lomax = 493000, .pd = 0x28, .d = 0x10 },
{ .lomax = 526000, .pd = 0x1f, .d = 0x0f },
{ .lomax = 564000, .pd = 0x1e, .d = 0x0e },
{ .lomax = 607000, .pd = 0x1d, .d = 0x0d },
{ .lomax = 658000, .pd = 0x1c, .d = 0x0c },
{ .lomax = 718000, .pd = 0x1b, .d = 0x0b },
{ .lomax = 790000, .pd = 0x1a, .d = 0x0a },
{ .lomax = 877000, .pd = 0x19, .d = 0x09 },
{ .lomax = 987000, .pd = 0x18, .d = 0x08 },
{ .lomax = 0, .pd = 0x00, .d = 0x00 }, /* end */
};
static struct tda18271_pll_map tda18271c2_main_pll[] = {
{ .lomax = 33125, .pd = 0x57, .d = 0xf0 },
{ .lomax = 35500, .pd = 0x56, .d = 0xe0 },
{ .lomax = 38188, .pd = 0x55, .d = 0xd0 },
{ .lomax = 41375, .pd = 0x54, .d = 0xc0 },
{ .lomax = 45125, .pd = 0x53, .d = 0xb0 },
{ .lomax = 49688, .pd = 0x52, .d = 0xa0 },
{ .lomax = 55188, .pd = 0x51, .d = 0x90 },
{ .lomax = 62125, .pd = 0x50, .d = 0x80 },
{ .lomax = 66250, .pd = 0x47, .d = 0x78 },
{ .lomax = 71000, .pd = 0x46, .d = 0x70 },
{ .lomax = 76375, .pd = 0x45, .d = 0x68 },
{ .lomax = 82750, .pd = 0x44, .d = 0x60 },
{ .lomax = 90250, .pd = 0x43, .d = 0x58 },
{ .lomax = 99375, .pd = 0x42, .d = 0x50 },
{ .lomax = 110375, .pd = 0x41, .d = 0x48 },
{ .lomax = 124250, .pd = 0x40, .d = 0x40 },
{ .lomax = 132500, .pd = 0x37, .d = 0x3c },
{ .lomax = 142000, .pd = 0x36, .d = 0x38 },
{ .lomax = 152750, .pd = 0x35, .d = 0x34 },
{ .lomax = 165500, .pd = 0x34, .d = 0x30 },
{ .lomax = 180500, .pd = 0x33, .d = 0x2c },
{ .lomax = 198750, .pd = 0x32, .d = 0x28 },
{ .lomax = 220750, .pd = 0x31, .d = 0x24 },
{ .lomax = 248500, .pd = 0x30, .d = 0x20 },
{ .lomax = 265000, .pd = 0x27, .d = 0x1e },
{ .lomax = 284000, .pd = 0x26, .d = 0x1c },
{ .lomax = 305500, .pd = 0x25, .d = 0x1a },
{ .lomax = 331000, .pd = 0x24, .d = 0x18 },
{ .lomax = 361000, .pd = 0x23, .d = 0x16 },
{ .lomax = 397500, .pd = 0x22, .d = 0x14 },
{ .lomax = 441500, .pd = 0x21, .d = 0x12 },
{ .lomax = 497000, .pd = 0x20, .d = 0x10 },
{ .lomax = 530000, .pd = 0x17, .d = 0x0f },
{ .lomax = 568000, .pd = 0x16, .d = 0x0e },
{ .lomax = 611000, .pd = 0x15, .d = 0x0d },
{ .lomax = 662000, .pd = 0x14, .d = 0x0c },
{ .lomax = 722000, .pd = 0x13, .d = 0x0b },
{ .lomax = 795000, .pd = 0x12, .d = 0x0a },
{ .lomax = 883000, .pd = 0x11, .d = 0x09 },
{ .lomax = 994000, .pd = 0x10, .d = 0x08 },
{ .lomax = 0, .pd = 0x00, .d = 0x00 }, /* end */
};
static struct tda18271_pll_map tda18271c1_cal_pll[] = {
{ .lomax = 33000, .pd = 0xdd, .d = 0xd0 },
{ .lomax = 36000, .pd = 0xdc, .d = 0xc0 },
{ .lomax = 40000, .pd = 0xdb, .d = 0xb0 },
{ .lomax = 44000, .pd = 0xda, .d = 0xa0 },
{ .lomax = 49000, .pd = 0xd9, .d = 0x90 },
{ .lomax = 55000, .pd = 0xd8, .d = 0x80 },
{ .lomax = 63000, .pd = 0xd3, .d = 0x70 },
{ .lomax = 67000, .pd = 0xcd, .d = 0x68 },
{ .lomax = 73000, .pd = 0xcc, .d = 0x60 },
{ .lomax = 80000, .pd = 0xcb, .d = 0x58 },
{ .lomax = 88000, .pd = 0xca, .d = 0x50 },
{ .lomax = 98000, .pd = 0xc9, .d = 0x48 },
{ .lomax = 110000, .pd = 0xc8, .d = 0x40 },
{ .lomax = 126000, .pd = 0xc3, .d = 0x38 },
{ .lomax = 135000, .pd = 0xbd, .d = 0x34 },
{ .lomax = 147000, .pd = 0xbc, .d = 0x30 },
{ .lomax = 160000, .pd = 0xbb, .d = 0x2c },
{ .lomax = 176000, .pd = 0xba, .d = 0x28 },
{ .lomax = 196000, .pd = 0xb9, .d = 0x24 },
{ .lomax = 220000, .pd = 0xb8, .d = 0x20 },
{ .lomax = 252000, .pd = 0xb3, .d = 0x1c },
{ .lomax = 271000, .pd = 0xad, .d = 0x1a },
{ .lomax = 294000, .pd = 0xac, .d = 0x18 },
{ .lomax = 321000, .pd = 0xab, .d = 0x16 },
{ .lomax = 353000, .pd = 0xaa, .d = 0x14 },
{ .lomax = 392000, .pd = 0xa9, .d = 0x12 },
{ .lomax = 441000, .pd = 0xa8, .d = 0x10 },
{ .lomax = 505000, .pd = 0xa3, .d = 0x0e },
{ .lomax = 543000, .pd = 0x9d, .d = 0x0d },
{ .lomax = 589000, .pd = 0x9c, .d = 0x0c },
{ .lomax = 642000, .pd = 0x9b, .d = 0x0b },
{ .lomax = 707000, .pd = 0x9a, .d = 0x0a },
{ .lomax = 785000, .pd = 0x99, .d = 0x09 },
{ .lomax = 883000, .pd = 0x98, .d = 0x08 },
{ .lomax = 1010000, .pd = 0x93, .d = 0x07 },
{ .lomax = 0, .pd = 0x00, .d = 0x00 }, /* end */
};
static struct tda18271_pll_map tda18271c2_cal_pll[] = {
{ .lomax = 33813, .pd = 0xdd, .d = 0xd0 },
{ .lomax = 36625, .pd = 0xdc, .d = 0xc0 },
{ .lomax = 39938, .pd = 0xdb, .d = 0xb0 },
{ .lomax = 43938, .pd = 0xda, .d = 0xa0 },
{ .lomax = 48813, .pd = 0xd9, .d = 0x90 },
{ .lomax = 54938, .pd = 0xd8, .d = 0x80 },
{ .lomax = 62813, .pd = 0xd3, .d = 0x70 },
{ .lomax = 67625, .pd = 0xcd, .d = 0x68 },
{ .lomax = 73250, .pd = 0xcc, .d = 0x60 },
{ .lomax = 79875, .pd = 0xcb, .d = 0x58 },
{ .lomax = 87875, .pd = 0xca, .d = 0x50 },
{ .lomax = 97625, .pd = 0xc9, .d = 0x48 },
{ .lomax = 109875, .pd = 0xc8, .d = 0x40 },
{ .lomax = 125625, .pd = 0xc3, .d = 0x38 },
{ .lomax = 135250, .pd = 0xbd, .d = 0x34 },
{ .lomax = 146500, .pd = 0xbc, .d = 0x30 },
{ .lomax = 159750, .pd = 0xbb, .d = 0x2c },
{ .lomax = 175750, .pd = 0xba, .d = 0x28 },
{ .lomax = 195250, .pd = 0xb9, .d = 0x24 },
{ .lomax = 219750, .pd = 0xb8, .d = 0x20 },
{ .lomax = 251250, .pd = 0xb3, .d = 0x1c },
{ .lomax = 270500, .pd = 0xad, .d = 0x1a },
{ .lomax = 293000, .pd = 0xac, .d = 0x18 },
{ .lomax = 319500, .pd = 0xab, .d = 0x16 },
{ .lomax = 351500, .pd = 0xaa, .d = 0x14 },
{ .lomax = 390500, .pd = 0xa9, .d = 0x12 },
{ .lomax = 439500, .pd = 0xa8, .d = 0x10 },
{ .lomax = 502500, .pd = 0xa3, .d = 0x0e },
{ .lomax = 541000, .pd = 0x9d, .d = 0x0d },
{ .lomax = 586000, .pd = 0x9c, .d = 0x0c },
{ .lomax = 639000, .pd = 0x9b, .d = 0x0b },
{ .lomax = 703000, .pd = 0x9a, .d = 0x0a },
{ .lomax = 781000, .pd = 0x99, .d = 0x09 },
{ .lomax = 879000, .pd = 0x98, .d = 0x08 },
{ .lomax = 0, .pd = 0x00, .d = 0x00 }, /* end */
};
static struct tda18271_map tda18271_bp_filter[] = {
{ .rfmax = 62000, .val = 0x00 },
{ .rfmax = 84000, .val = 0x01 },
{ .rfmax = 100000, .val = 0x02 },
{ .rfmax = 140000, .val = 0x03 },
{ .rfmax = 170000, .val = 0x04 },
{ .rfmax = 180000, .val = 0x05 },
{ .rfmax = 865000, .val = 0x06 },
{ .rfmax = 0, .val = 0x00 }, /* end */
};
static struct tda18271_map tda18271c1_km[] = {
{ .rfmax = 61100, .val = 0x74 },
{ .rfmax = 350000, .val = 0x40 },
{ .rfmax = 720000, .val = 0x30 },
{ .rfmax = 865000, .val = 0x40 },
{ .rfmax = 0, .val = 0x00 }, /* end */
};
static struct tda18271_map tda18271c2_km[] = {
{ .rfmax = 47900, .val = 0x38 },
{ .rfmax = 61100, .val = 0x44 },
{ .rfmax = 350000, .val = 0x30 },
{ .rfmax = 720000, .val = 0x24 },
{ .rfmax = 865000, .val = 0x3c },
{ .rfmax = 0, .val = 0x00 }, /* end */
};
static struct tda18271_map tda18271_rf_band[] = {
{ .rfmax = 47900, .val = 0x00 },
{ .rfmax = 61100, .val = 0x01 },
{ .rfmax = 152600, .val = 0x02 },
{ .rfmax = 164700, .val = 0x03 },
{ .rfmax = 203500, .val = 0x04 },
{ .rfmax = 457800, .val = 0x05 },
{ .rfmax = 865000, .val = 0x06 },
{ .rfmax = 0, .val = 0x00 }, /* end */
};
static struct tda18271_map tda18271_gain_taper[] = {
{ .rfmax = 45400, .val = 0x1f },
{ .rfmax = 45800, .val = 0x1e },
{ .rfmax = 46200, .val = 0x1d },
{ .rfmax = 46700, .val = 0x1c },
{ .rfmax = 47100, .val = 0x1b },
{ .rfmax = 47500, .val = 0x1a },
{ .rfmax = 47900, .val = 0x19 },
{ .rfmax = 49600, .val = 0x17 },
{ .rfmax = 51200, .val = 0x16 },
{ .rfmax = 52900, .val = 0x15 },
{ .rfmax = 54500, .val = 0x14 },
{ .rfmax = 56200, .val = 0x13 },
{ .rfmax = 57800, .val = 0x12 },
{ .rfmax = 59500, .val = 0x11 },
{ .rfmax = 61100, .val = 0x10 },
{ .rfmax = 67600, .val = 0x0d },
{ .rfmax = 74200, .val = 0x0c },
{ .rfmax = 80700, .val = 0x0b },
{ .rfmax = 87200, .val = 0x0a },
{ .rfmax = 93800, .val = 0x09 },
{ .rfmax = 100300, .val = 0x08 },
{ .rfmax = 106900, .val = 0x07 },
{ .rfmax = 113400, .val = 0x06 },
{ .rfmax = 119900, .val = 0x05 },
{ .rfmax = 126500, .val = 0x04 },
{ .rfmax = 133000, .val = 0x03 },
{ .rfmax = 139500, .val = 0x02 },
{ .rfmax = 146100, .val = 0x01 },
{ .rfmax = 152600, .val = 0x00 },
{ .rfmax = 154300, .val = 0x1f },
{ .rfmax = 156100, .val = 0x1e },
{ .rfmax = 157800, .val = 0x1d },
{ .rfmax = 159500, .val = 0x1c },
{ .rfmax = 161200, .val = 0x1b },
{ .rfmax = 163000, .val = 0x1a },
{ .rfmax = 164700, .val = 0x19 },
{ .rfmax = 170200, .val = 0x17 },
{ .rfmax = 175800, .val = 0x16 },
{ .rfmax = 181300, .val = 0x15 },
{ .rfmax = 186900, .val = 0x14 },
{ .rfmax = 192400, .val = 0x13 },
{ .rfmax = 198000, .val = 0x12 },
{ .rfmax = 203500, .val = 0x11 },
{ .rfmax = 216200, .val = 0x14 },
{ .rfmax = 228900, .val = 0x13 },
{ .rfmax = 241600, .val = 0x12 },
{ .rfmax = 254400, .val = 0x11 },
{ .rfmax = 267100, .val = 0x10 },
{ .rfmax = 279800, .val = 0x0f },
{ .rfmax = 292500, .val = 0x0e },
{ .rfmax = 305200, .val = 0x0d },
{ .rfmax = 317900, .val = 0x0c },
{ .rfmax = 330700, .val = 0x0b },
{ .rfmax = 343400, .val = 0x0a },
{ .rfmax = 356100, .val = 0x09 },
{ .rfmax = 368800, .val = 0x08 },
{ .rfmax = 381500, .val = 0x07 },
{ .rfmax = 394200, .val = 0x06 },
{ .rfmax = 406900, .val = 0x05 },
{ .rfmax = 419700, .val = 0x04 },
{ .rfmax = 432400, .val = 0x03 },
{ .rfmax = 445100, .val = 0x02 },
{ .rfmax = 457800, .val = 0x01 },
{ .rfmax = 476300, .val = 0x19 },
{ .rfmax = 494800, .val = 0x18 },
{ .rfmax = 513300, .val = 0x17 },
{ .rfmax = 531800, .val = 0x16 },
{ .rfmax = 550300, .val = 0x15 },
{ .rfmax = 568900, .val = 0x14 },
{ .rfmax = 587400, .val = 0x13 },
{ .rfmax = 605900, .val = 0x12 },
{ .rfmax = 624400, .val = 0x11 },
{ .rfmax = 642900, .val = 0x10 },
{ .rfmax = 661400, .val = 0x0f },
{ .rfmax = 679900, .val = 0x0e },
{ .rfmax = 698400, .val = 0x0d },
{ .rfmax = 716900, .val = 0x0c },
{ .rfmax = 735400, .val = 0x0b },
{ .rfmax = 753900, .val = 0x0a },
{ .rfmax = 772500, .val = 0x09 },
{ .rfmax = 791000, .val = 0x08 },
{ .rfmax = 809500, .val = 0x07 },
{ .rfmax = 828000, .val = 0x06 },
{ .rfmax = 846500, .val = 0x05 },
{ .rfmax = 865000, .val = 0x04 },
{ .rfmax = 0, .val = 0x00 }, /* end */
};
static struct tda18271_map tda18271c1_rf_cal[] = {
{ .rfmax = 41000, .val = 0x1e },
{ .rfmax = 43000, .val = 0x30 },
{ .rfmax = 45000, .val = 0x43 },
{ .rfmax = 46000, .val = 0x4d },
{ .rfmax = 47000, .val = 0x54 },
{ .rfmax = 47900, .val = 0x64 },
{ .rfmax = 49100, .val = 0x20 },
{ .rfmax = 50000, .val = 0x22 },
{ .rfmax = 51000, .val = 0x2a },
{ .rfmax = 53000, .val = 0x32 },
{ .rfmax = 55000, .val = 0x35 },
{ .rfmax = 56000, .val = 0x3c },
{ .rfmax = 57000, .val = 0x3f },
{ .rfmax = 58000, .val = 0x48 },
{ .rfmax = 59000, .val = 0x4d },
{ .rfmax = 60000, .val = 0x58 },
{ .rfmax = 61100, .val = 0x5f },
{ .rfmax = 0, .val = 0x00 }, /* end */
};
static struct tda18271_map tda18271c2_rf_cal[] = {
{ .rfmax = 41000, .val = 0x0f },
{ .rfmax = 43000, .val = 0x1c },
{ .rfmax = 45000, .val = 0x2f },
{ .rfmax = 46000, .val = 0x39 },
{ .rfmax = 47000, .val = 0x40 },
{ .rfmax = 47900, .val = 0x50 },
{ .rfmax = 49100, .val = 0x16 },
{ .rfmax = 50000, .val = 0x18 },
{ .rfmax = 51000, .val = 0x20 },
{ .rfmax = 53000, .val = 0x28 },
{ .rfmax = 55000, .val = 0x2b },
{ .rfmax = 56000, .val = 0x32 },
{ .rfmax = 57000, .val = 0x35 },
{ .rfmax = 58000, .val = 0x3e },
{ .rfmax = 59000, .val = 0x43 },
{ .rfmax = 60000, .val = 0x4e },
{ .rfmax = 61100, .val = 0x55 },
{ .rfmax = 63000, .val = 0x0f },
{ .rfmax = 64000, .val = 0x11 },
{ .rfmax = 65000, .val = 0x12 },
{ .rfmax = 66000, .val = 0x15 },
{ .rfmax = 67000, .val = 0x16 },
{ .rfmax = 68000, .val = 0x17 },
{ .rfmax = 70000, .val = 0x19 },
{ .rfmax = 71000, .val = 0x1c },
{ .rfmax = 72000, .val = 0x1d },
{ .rfmax = 73000, .val = 0x1f },
{ .rfmax = 74000, .val = 0x20 },
{ .rfmax = 75000, .val = 0x21 },
{ .rfmax = 76000, .val = 0x24 },
{ .rfmax = 77000, .val = 0x25 },
{ .rfmax = 78000, .val = 0x27 },
{ .rfmax = 80000, .val = 0x28 },
{ .rfmax = 81000, .val = 0x29 },
{ .rfmax = 82000, .val = 0x2d },
{ .rfmax = 83000, .val = 0x2e },
{ .rfmax = 84000, .val = 0x2f },
{ .rfmax = 85000, .val = 0x31 },
{ .rfmax = 86000, .val = 0x33 },
{ .rfmax = 87000, .val = 0x34 },
{ .rfmax = 88000, .val = 0x35 },
{ .rfmax = 89000, .val = 0x37 },
{ .rfmax = 90000, .val = 0x38 },
{ .rfmax = 91000, .val = 0x39 },
{ .rfmax = 93000, .val = 0x3c },
{ .rfmax = 94000, .val = 0x3e },
{ .rfmax = 95000, .val = 0x3f },
{ .rfmax = 96000, .val = 0x40 },
{ .rfmax = 97000, .val = 0x42 },
{ .rfmax = 99000, .val = 0x45 },
{ .rfmax = 100000, .val = 0x46 },
{ .rfmax = 102000, .val = 0x48 },
{ .rfmax = 103000, .val = 0x4a },
{ .rfmax = 105000, .val = 0x4d },
{ .rfmax = 106000, .val = 0x4e },
{ .rfmax = 107000, .val = 0x50 },
{ .rfmax = 108000, .val = 0x51 },
{ .rfmax = 110000, .val = 0x54 },
{ .rfmax = 111000, .val = 0x56 },
{ .rfmax = 112000, .val = 0x57 },
{ .rfmax = 113000, .val = 0x58 },
{ .rfmax = 114000, .val = 0x59 },
{ .rfmax = 115000, .val = 0x5c },
{ .rfmax = 116000, .val = 0x5d },
{ .rfmax = 117000, .val = 0x5f },
{ .rfmax = 119000, .val = 0x60 },
{ .rfmax = 120000, .val = 0x64 },
{ .rfmax = 121000, .val = 0x65 },
{ .rfmax = 122000, .val = 0x66 },
{ .rfmax = 123000, .val = 0x68 },
{ .rfmax = 124000, .val = 0x69 },
{ .rfmax = 125000, .val = 0x6c },
{ .rfmax = 126000, .val = 0x6d },
{ .rfmax = 127000, .val = 0x6e },
{ .rfmax = 128000, .val = 0x70 },
{ .rfmax = 129000, .val = 0x71 },
{ .rfmax = 130000, .val = 0x75 },
{ .rfmax = 131000, .val = 0x77 },
{ .rfmax = 132000, .val = 0x78 },
{ .rfmax = 133000, .val = 0x7b },
{ .rfmax = 134000, .val = 0x7e },
{ .rfmax = 135000, .val = 0x81 },
{ .rfmax = 136000, .val = 0x82 },
{ .rfmax = 137000, .val = 0x87 },
{ .rfmax = 138000, .val = 0x88 },
{ .rfmax = 139000, .val = 0x8d },
{ .rfmax = 140000, .val = 0x8e },
{ .rfmax = 141000, .val = 0x91 },
{ .rfmax = 142000, .val = 0x95 },
{ .rfmax = 143000, .val = 0x9a },
{ .rfmax = 144000, .val = 0x9d },
{ .rfmax = 145000, .val = 0xa1 },
{ .rfmax = 146000, .val = 0xa2 },
{ .rfmax = 147000, .val = 0xa4 },
{ .rfmax = 148000, .val = 0xa9 },
{ .rfmax = 149000, .val = 0xae },
{ .rfmax = 150000, .val = 0xb0 },
{ .rfmax = 151000, .val = 0xb1 },
{ .rfmax = 152000, .val = 0xb7 },
{ .rfmax = 152600, .val = 0xbd },
{ .rfmax = 154000, .val = 0x20 },
{ .rfmax = 155000, .val = 0x22 },
{ .rfmax = 156000, .val = 0x24 },
{ .rfmax = 157000, .val = 0x25 },
{ .rfmax = 158000, .val = 0x27 },
{ .rfmax = 159000, .val = 0x29 },
{ .rfmax = 160000, .val = 0x2c },
{ .rfmax = 161000, .val = 0x2d },
{ .rfmax = 163000, .val = 0x2e },
{ .rfmax = 164000, .val = 0x2f },
{ .rfmax = 164700, .val = 0x30 },
{ .rfmax = 166000, .val = 0x11 },
{ .rfmax = 167000, .val = 0x12 },
{ .rfmax = 168000, .val = 0x13 },
{ .rfmax = 169000, .val = 0x14 },
{ .rfmax = 170000, .val = 0x15 },
{ .rfmax = 172000, .val = 0x16 },
{ .rfmax = 173000, .val = 0x17 },
{ .rfmax = 174000, .val = 0x18 },
{ .rfmax = 175000, .val = 0x1a },
{ .rfmax = 176000, .val = 0x1b },
{ .rfmax = 178000, .val = 0x1d },
{ .rfmax = 179000, .val = 0x1e },
{ .rfmax = 180000, .val = 0x1f },
{ .rfmax = 181000, .val = 0x20 },
{ .rfmax = 182000, .val = 0x21 },
{ .rfmax = 183000, .val = 0x22 },
{ .rfmax = 184000, .val = 0x24 },
{ .rfmax = 185000, .val = 0x25 },
{ .rfmax = 186000, .val = 0x26 },
{ .rfmax = 187000, .val = 0x27 },
{ .rfmax = 188000, .val = 0x29 },
{ .rfmax = 189000, .val = 0x2a },
{ .rfmax = 190000, .val = 0x2c },
{ .rfmax = 191000, .val = 0x2d },
{ .rfmax = 192000, .val = 0x2e },
{ .rfmax = 193000, .val = 0x2f },
{ .rfmax = 194000, .val = 0x30 },
{ .rfmax = 195000, .val = 0x33 },
{ .rfmax = 196000, .val = 0x35 },
{ .rfmax = 198000, .val = 0x36 },
{ .rfmax = 200000, .val = 0x38 },
{ .rfmax = 201000, .val = 0x3c },
{ .rfmax = 202000, .val = 0x3d },
{ .rfmax = 203500, .val = 0x3e },
{ .rfmax = 206000, .val = 0x0e },
{ .rfmax = 208000, .val = 0x0f },
{ .rfmax = 212000, .val = 0x10 },
{ .rfmax = 216000, .val = 0x11 },
{ .rfmax = 217000, .val = 0x12 },
{ .rfmax = 218000, .val = 0x13 },
{ .rfmax = 220000, .val = 0x14 },
{ .rfmax = 222000, .val = 0x15 },
{ .rfmax = 225000, .val = 0x16 },
{ .rfmax = 228000, .val = 0x17 },
{ .rfmax = 231000, .val = 0x18 },
{ .rfmax = 234000, .val = 0x19 },
{ .rfmax = 235000, .val = 0x1a },
{ .rfmax = 236000, .val = 0x1b },
{ .rfmax = 237000, .val = 0x1c },
{ .rfmax = 240000, .val = 0x1d },
{ .rfmax = 242000, .val = 0x1e },
{ .rfmax = 244000, .val = 0x1f },
{ .rfmax = 247000, .val = 0x20 },
{ .rfmax = 249000, .val = 0x21 },
{ .rfmax = 252000, .val = 0x22 },
{ .rfmax = 253000, .val = 0x23 },
{ .rfmax = 254000, .val = 0x24 },
{ .rfmax = 256000, .val = 0x25 },
{ .rfmax = 259000, .val = 0x26 },
{ .rfmax = 262000, .val = 0x27 },
{ .rfmax = 264000, .val = 0x28 },
{ .rfmax = 267000, .val = 0x29 },
{ .rfmax = 269000, .val = 0x2a },
{ .rfmax = 271000, .val = 0x2b },
{ .rfmax = 273000, .val = 0x2c },
{ .rfmax = 275000, .val = 0x2d },
{ .rfmax = 277000, .val = 0x2e },
{ .rfmax = 279000, .val = 0x2f },
{ .rfmax = 282000, .val = 0x30 },
{ .rfmax = 284000, .val = 0x31 },
{ .rfmax = 286000, .val = 0x32 },
{ .rfmax = 287000, .val = 0x33 },
{ .rfmax = 290000, .val = 0x34 },
{ .rfmax = 293000, .val = 0x35 },
{ .rfmax = 295000, .val = 0x36 },
{ .rfmax = 297000, .val = 0x37 },
{ .rfmax = 300000, .val = 0x38 },
{ .rfmax = 303000, .val = 0x39 },
{ .rfmax = 305000, .val = 0x3a },
{ .rfmax = 306000, .val = 0x3b },
{ .rfmax = 307000, .val = 0x3c },
{ .rfmax = 310000, .val = 0x3d },
{ .rfmax = 312000, .val = 0x3e },
{ .rfmax = 315000, .val = 0x3f },
{ .rfmax = 318000, .val = 0x40 },
{ .rfmax = 320000, .val = 0x41 },
{ .rfmax = 323000, .val = 0x42 },
{ .rfmax = 324000, .val = 0x43 },
{ .rfmax = 325000, .val = 0x44 },
{ .rfmax = 327000, .val = 0x45 },
{ .rfmax = 331000, .val = 0x46 },
{ .rfmax = 334000, .val = 0x47 },
{ .rfmax = 337000, .val = 0x48 },
{ .rfmax = 339000, .val = 0x49 },
{ .rfmax = 340000, .val = 0x4a },
{ .rfmax = 341000, .val = 0x4b },
{ .rfmax = 343000, .val = 0x4c },
{ .rfmax = 345000, .val = 0x4d },
{ .rfmax = 349000, .val = 0x4e },
{ .rfmax = 352000, .val = 0x4f },
{ .rfmax = 353000, .val = 0x50 },
{ .rfmax = 355000, .val = 0x51 },
{ .rfmax = 357000, .val = 0x52 },
{ .rfmax = 359000, .val = 0x53 },
{ .rfmax = 361000, .val = 0x54 },
{ .rfmax = 362000, .val = 0x55 },
{ .rfmax = 364000, .val = 0x56 },
{ .rfmax = 368000, .val = 0x57 },
{ .rfmax = 370000, .val = 0x58 },
{ .rfmax = 372000, .val = 0x59 },
{ .rfmax = 375000, .val = 0x5a },
{ .rfmax = 376000, .val = 0x5b },
{ .rfmax = 377000, .val = 0x5c },
{ .rfmax = 379000, .val = 0x5d },
{ .rfmax = 382000, .val = 0x5e },
{ .rfmax = 384000, .val = 0x5f },
{ .rfmax = 385000, .val = 0x60 },
{ .rfmax = 386000, .val = 0x61 },
{ .rfmax = 388000, .val = 0x62 },
{ .rfmax = 390000, .val = 0x63 },
{ .rfmax = 393000, .val = 0x64 },
{ .rfmax = 394000, .val = 0x65 },
{ .rfmax = 396000, .val = 0x66 },
{ .rfmax = 397000, .val = 0x67 },
{ .rfmax = 398000, .val = 0x68 },
{ .rfmax = 400000, .val = 0x69 },
{ .rfmax = 402000, .val = 0x6a },
{ .rfmax = 403000, .val = 0x6b },
{ .rfmax = 407000, .val = 0x6c },
{ .rfmax = 408000, .val = 0x6d },
{ .rfmax = 409000, .val = 0x6e },
{ .rfmax = 410000, .val = 0x6f },
{ .rfmax = 411000, .val = 0x70 },
{ .rfmax = 412000, .val = 0x71 },
{ .rfmax = 413000, .val = 0x72 },
{ .rfmax = 414000, .val = 0x73 },
{ .rfmax = 417000, .val = 0x74 },
{ .rfmax = 418000, .val = 0x75 },
{ .rfmax = 420000, .val = 0x76 },
{ .rfmax = 422000, .val = 0x77 },
{ .rfmax = 423000, .val = 0x78 },
{ .rfmax = 424000, .val = 0x79 },
{ .rfmax = 427000, .val = 0x7a },
{ .rfmax = 428000, .val = 0x7b },
{ .rfmax = 429000, .val = 0x7d },
{ .rfmax = 432000, .val = 0x7f },
{ .rfmax = 434000, .val = 0x80 },
{ .rfmax = 435000, .val = 0x81 },
{ .rfmax = 436000, .val = 0x83 },
{ .rfmax = 437000, .val = 0x84 },
{ .rfmax = 438000, .val = 0x85 },
{ .rfmax = 439000, .val = 0x86 },
{ .rfmax = 440000, .val = 0x87 },
{ .rfmax = 441000, .val = 0x88 },
{ .rfmax = 442000, .val = 0x89 },
{ .rfmax = 445000, .val = 0x8a },
{ .rfmax = 446000, .val = 0x8b },
{ .rfmax = 447000, .val = 0x8c },
{ .rfmax = 448000, .val = 0x8e },
{ .rfmax = 449000, .val = 0x8f },
{ .rfmax = 450000, .val = 0x90 },
{ .rfmax = 452000, .val = 0x91 },
{ .rfmax = 453000, .val = 0x93 },
{ .rfmax = 454000, .val = 0x94 },
{ .rfmax = 456000, .val = 0x96 },
{ .rfmax = 457800, .val = 0x98 },
{ .rfmax = 461000, .val = 0x11 },
{ .rfmax = 468000, .val = 0x12 },
{ .rfmax = 472000, .val = 0x13 },
{ .rfmax = 473000, .val = 0x14 },
{ .rfmax = 474000, .val = 0x15 },
{ .rfmax = 481000, .val = 0x16 },
{ .rfmax = 486000, .val = 0x17 },
{ .rfmax = 491000, .val = 0x18 },
{ .rfmax = 498000, .val = 0x19 },
{ .rfmax = 499000, .val = 0x1a },
{ .rfmax = 501000, .val = 0x1b },
{ .rfmax = 506000, .val = 0x1c },
{ .rfmax = 511000, .val = 0x1d },
{ .rfmax = 516000, .val = 0x1e },
{ .rfmax = 520000, .val = 0x1f },
{ .rfmax = 521000, .val = 0x20 },
{ .rfmax = 525000, .val = 0x21 },
{ .rfmax = 529000, .val = 0x22 },
{ .rfmax = 533000, .val = 0x23 },
{ .rfmax = 539000, .val = 0x24 },
{ .rfmax = 541000, .val = 0x25 },
{ .rfmax = 547000, .val = 0x26 },
{ .rfmax = 549000, .val = 0x27 },
{ .rfmax = 551000, .val = 0x28 },
{ .rfmax = 556000, .val = 0x29 },
{ .rfmax = 561000, .val = 0x2a },
{ .rfmax = 563000, .val = 0x2b },
{ .rfmax = 565000, .val = 0x2c },
{ .rfmax = 569000, .val = 0x2d },
{ .rfmax = 571000, .val = 0x2e },
{ .rfmax = 577000, .val = 0x2f },
{ .rfmax = 580000, .val = 0x30 },
{ .rfmax = 582000, .val = 0x31 },
{ .rfmax = 584000, .val = 0x32 },
{ .rfmax = 588000, .val = 0x33 },
{ .rfmax = 591000, .val = 0x34 },
{ .rfmax = 596000, .val = 0x35 },
{ .rfmax = 598000, .val = 0x36 },
{ .rfmax = 603000, .val = 0x37 },
{ .rfmax = 604000, .val = 0x38 },
{ .rfmax = 606000, .val = 0x39 },
{ .rfmax = 612000, .val = 0x3a },
{ .rfmax = 615000, .val = 0x3b },
{ .rfmax = 617000, .val = 0x3c },
{ .rfmax = 621000, .val = 0x3d },
{ .rfmax = 622000, .val = 0x3e },
{ .rfmax = 625000, .val = 0x3f },
{ .rfmax = 632000, .val = 0x40 },
{ .rfmax = 633000, .val = 0x41 },
{ .rfmax = 634000, .val = 0x42 },
{ .rfmax = 642000, .val = 0x43 },
{ .rfmax = 643000, .val = 0x44 },
{ .rfmax = 647000, .val = 0x45 },
{ .rfmax = 650000, .val = 0x46 },
{ .rfmax = 652000, .val = 0x47 },
{ .rfmax = 657000, .val = 0x48 },
{ .rfmax = 661000, .val = 0x49 },
{ .rfmax = 662000, .val = 0x4a },
{ .rfmax = 665000, .val = 0x4b },
{ .rfmax = 667000, .val = 0x4c },
{ .rfmax = 670000, .val = 0x4d },
{ .rfmax = 673000, .val = 0x4e },
{ .rfmax = 676000, .val = 0x4f },
{ .rfmax = 677000, .val = 0x50 },
{ .rfmax = 681000, .val = 0x51 },
{ .rfmax = 683000, .val = 0x52 },
{ .rfmax = 686000, .val = 0x53 },
{ .rfmax = 688000, .val = 0x54 },
{ .rfmax = 689000, .val = 0x55 },
{ .rfmax = 691000, .val = 0x56 },
{ .rfmax = 695000, .val = 0x57 },
{ .rfmax = 698000, .val = 0x58 },
{ .rfmax = 703000, .val = 0x59 },
{ .rfmax = 704000, .val = 0x5a },
{ .rfmax = 705000, .val = 0x5b },
{ .rfmax = 707000, .val = 0x5c },
{ .rfmax = 710000, .val = 0x5d },
{ .rfmax = 712000, .val = 0x5e },
{ .rfmax = 717000, .val = 0x5f },
{ .rfmax = 718000, .val = 0x60 },
{ .rfmax = 721000, .val = 0x61 },
{ .rfmax = 722000, .val = 0x62 },
{ .rfmax = 723000, .val = 0x63 },
{ .rfmax = 725000, .val = 0x64 },
{ .rfmax = 727000, .val = 0x65 },
{ .rfmax = 730000, .val = 0x66 },
{ .rfmax = 732000, .val = 0x67 },
{ .rfmax = 735000, .val = 0x68 },
{ .rfmax = 740000, .val = 0x69 },
{ .rfmax = 741000, .val = 0x6a },
{ .rfmax = 742000, .val = 0x6b },
{ .rfmax = 743000, .val = 0x6c },
{ .rfmax = 745000, .val = 0x6d },
{ .rfmax = 747000, .val = 0x6e },
{ .rfmax = 748000, .val = 0x6f },
{ .rfmax = 750000, .val = 0x70 },
{ .rfmax = 752000, .val = 0x71 },
{ .rfmax = 754000, .val = 0x72 },
{ .rfmax = 757000, .val = 0x73 },
{ .rfmax = 758000, .val = 0x74 },
{ .rfmax = 760000, .val = 0x75 },
{ .rfmax = 763000, .val = 0x76 },
{ .rfmax = 764000, .val = 0x77 },
{ .rfmax = 766000, .val = 0x78 },
{ .rfmax = 767000, .val = 0x79 },
{ .rfmax = 768000, .val = 0x7a },
{ .rfmax = 773000, .val = 0x7b },
{ .rfmax = 774000, .val = 0x7c },
{ .rfmax = 776000, .val = 0x7d },
{ .rfmax = 777000, .val = 0x7e },
{ .rfmax = 778000, .val = 0x7f },
{ .rfmax = 779000, .val = 0x80 },
{ .rfmax = 781000, .val = 0x81 },
{ .rfmax = 783000, .val = 0x82 },
{ .rfmax = 784000, .val = 0x83 },
{ .rfmax = 785000, .val = 0x84 },
{ .rfmax = 786000, .val = 0x85 },
{ .rfmax = 793000, .val = 0x86 },
{ .rfmax = 794000, .val = 0x87 },
{ .rfmax = 795000, .val = 0x88 },
{ .rfmax = 797000, .val = 0x89 },
{ .rfmax = 799000, .val = 0x8a },
{ .rfmax = 801000, .val = 0x8b },
{ .rfmax = 802000, .val = 0x8c },
{ .rfmax = 803000, .val = 0x8d },
{ .rfmax = 804000, .val = 0x8e },
{ .rfmax = 810000, .val = 0x90 },
{ .rfmax = 811000, .val = 0x91 },
{ .rfmax = 812000, .val = 0x92 },
{ .rfmax = 814000, .val = 0x93 },
{ .rfmax = 816000, .val = 0x94 },
{ .rfmax = 817000, .val = 0x96 },
{ .rfmax = 818000, .val = 0x97 },
{ .rfmax = 820000, .val = 0x98 },
{ .rfmax = 821000, .val = 0x99 },
{ .rfmax = 822000, .val = 0x9a },
{ .rfmax = 828000, .val = 0x9b },
{ .rfmax = 829000, .val = 0x9d },
{ .rfmax = 830000, .val = 0x9f },
{ .rfmax = 831000, .val = 0xa0 },
{ .rfmax = 833000, .val = 0xa1 },
{ .rfmax = 835000, .val = 0xa2 },
{ .rfmax = 836000, .val = 0xa3 },
{ .rfmax = 837000, .val = 0xa4 },
{ .rfmax = 838000, .val = 0xa6 },
{ .rfmax = 840000, .val = 0xa8 },
{ .rfmax = 842000, .val = 0xa9 },
{ .rfmax = 845000, .val = 0xaa },
{ .rfmax = 846000, .val = 0xab },
{ .rfmax = 847000, .val = 0xad },
{ .rfmax = 848000, .val = 0xae },
{ .rfmax = 852000, .val = 0xaf },
{ .rfmax = 853000, .val = 0xb0 },
{ .rfmax = 858000, .val = 0xb1 },
{ .rfmax = 860000, .val = 0xb2 },
{ .rfmax = 861000, .val = 0xb3 },
{ .rfmax = 862000, .val = 0xb4 },
{ .rfmax = 863000, .val = 0xb6 },
{ .rfmax = 864000, .val = 0xb8 },
{ .rfmax = 865000, .val = 0xb9 },
{ .rfmax = 0, .val = 0x00 }, /* end */
};
static struct tda18271_map tda18271_ir_measure[] = {
{ .rfmax = 30000, .val = 4 },
{ .rfmax = 200000, .val = 5 },
{ .rfmax = 600000, .val = 6 },
{ .rfmax = 865000, .val = 7 },
{ .rfmax = 0, .val = 0 }, /* end */
};
static struct tda18271_map tda18271_rf_cal_dc_over_dt[] = {
{ .rfmax = 47900, .val = 0x00 },
{ .rfmax = 55000, .val = 0x00 },
{ .rfmax = 61100, .val = 0x0a },
{ .rfmax = 64000, .val = 0x0a },
{ .rfmax = 82000, .val = 0x14 },
{ .rfmax = 84000, .val = 0x19 },
{ .rfmax = 119000, .val = 0x1c },
{ .rfmax = 124000, .val = 0x20 },
{ .rfmax = 129000, .val = 0x2a },
{ .rfmax = 134000, .val = 0x32 },
{ .rfmax = 139000, .val = 0x39 },
{ .rfmax = 144000, .val = 0x3e },
{ .rfmax = 149000, .val = 0x3f },
{ .rfmax = 152600, .val = 0x40 },
{ .rfmax = 154000, .val = 0x40 },
{ .rfmax = 164700, .val = 0x41 },
{ .rfmax = 203500, .val = 0x32 },
{ .rfmax = 353000, .val = 0x19 },
{ .rfmax = 356000, .val = 0x1a },
{ .rfmax = 359000, .val = 0x1b },
{ .rfmax = 363000, .val = 0x1c },
{ .rfmax = 366000, .val = 0x1d },
{ .rfmax = 369000, .val = 0x1e },
{ .rfmax = 373000, .val = 0x1f },
{ .rfmax = 376000, .val = 0x20 },
{ .rfmax = 379000, .val = 0x21 },
{ .rfmax = 383000, .val = 0x22 },
{ .rfmax = 386000, .val = 0x23 },
{ .rfmax = 389000, .val = 0x24 },
{ .rfmax = 393000, .val = 0x25 },
{ .rfmax = 396000, .val = 0x26 },
{ .rfmax = 399000, .val = 0x27 },
{ .rfmax = 402000, .val = 0x28 },
{ .rfmax = 404000, .val = 0x29 },
{ .rfmax = 407000, .val = 0x2a },
{ .rfmax = 409000, .val = 0x2b },
{ .rfmax = 412000, .val = 0x2c },
{ .rfmax = 414000, .val = 0x2d },
{ .rfmax = 417000, .val = 0x2e },
{ .rfmax = 419000, .val = 0x2f },
{ .rfmax = 422000, .val = 0x30 },
{ .rfmax = 424000, .val = 0x31 },
{ .rfmax = 427000, .val = 0x32 },
{ .rfmax = 429000, .val = 0x33 },
{ .rfmax = 432000, .val = 0x34 },
{ .rfmax = 434000, .val = 0x35 },
{ .rfmax = 437000, .val = 0x36 },
{ .rfmax = 439000, .val = 0x37 },
{ .rfmax = 442000, .val = 0x38 },
{ .rfmax = 444000, .val = 0x39 },
{ .rfmax = 447000, .val = 0x3a },
{ .rfmax = 449000, .val = 0x3b },
{ .rfmax = 457800, .val = 0x3c },
{ .rfmax = 465000, .val = 0x0f },
{ .rfmax = 477000, .val = 0x12 },
{ .rfmax = 483000, .val = 0x14 },
{ .rfmax = 502000, .val = 0x19 },
{ .rfmax = 508000, .val = 0x1b },
{ .rfmax = 519000, .val = 0x1c },
{ .rfmax = 522000, .val = 0x1d },
{ .rfmax = 524000, .val = 0x1e },
{ .rfmax = 534000, .val = 0x1f },
{ .rfmax = 549000, .val = 0x20 },
{ .rfmax = 554000, .val = 0x22 },
{ .rfmax = 584000, .val = 0x24 },
{ .rfmax = 589000, .val = 0x26 },
{ .rfmax = 658000, .val = 0x27 },
{ .rfmax = 664000, .val = 0x2c },
{ .rfmax = 669000, .val = 0x2d },
{ .rfmax = 699000, .val = 0x2e },
{ .rfmax = 704000, .val = 0x30 },
{ .rfmax = 709000, .val = 0x31 },
{ .rfmax = 714000, .val = 0x32 },
{ .rfmax = 724000, .val = 0x33 },
{ .rfmax = 729000, .val = 0x36 },
{ .rfmax = 739000, .val = 0x38 },
{ .rfmax = 744000, .val = 0x39 },
{ .rfmax = 749000, .val = 0x3b },
{ .rfmax = 754000, .val = 0x3c },
{ .rfmax = 759000, .val = 0x3d },
{ .rfmax = 764000, .val = 0x3e },
{ .rfmax = 769000, .val = 0x3f },
{ .rfmax = 774000, .val = 0x40 },
{ .rfmax = 779000, .val = 0x41 },
{ .rfmax = 784000, .val = 0x43 },
{ .rfmax = 789000, .val = 0x46 },
{ .rfmax = 794000, .val = 0x48 },
{ .rfmax = 799000, .val = 0x4b },
{ .rfmax = 804000, .val = 0x4f },
{ .rfmax = 809000, .val = 0x54 },
{ .rfmax = 814000, .val = 0x59 },
{ .rfmax = 819000, .val = 0x5d },
{ .rfmax = 824000, .val = 0x61 },
{ .rfmax = 829000, .val = 0x68 },
{ .rfmax = 834000, .val = 0x6e },
{ .rfmax = 839000, .val = 0x75 },
{ .rfmax = 844000, .val = 0x7e },
{ .rfmax = 849000, .val = 0x82 },
{ .rfmax = 854000, .val = 0x84 },
{ .rfmax = 859000, .val = 0x8f },
{ .rfmax = 865000, .val = 0x9a },
{ .rfmax = 0, .val = 0x00 }, /* end */
};
/*---------------------------------------------------------------------*/
struct tda18271_thermo_map {
u8 d;
u8 r0;
u8 r1;
};
static struct tda18271_thermo_map tda18271_thermometer[] = {
{ .d = 0x00, .r0 = 60, .r1 = 92 },
{ .d = 0x01, .r0 = 62, .r1 = 94 },
{ .d = 0x02, .r0 = 66, .r1 = 98 },
{ .d = 0x03, .r0 = 64, .r1 = 96 },
{ .d = 0x04, .r0 = 74, .r1 = 106 },
{ .d = 0x05, .r0 = 72, .r1 = 104 },
{ .d = 0x06, .r0 = 68, .r1 = 100 },
{ .d = 0x07, .r0 = 70, .r1 = 102 },
{ .d = 0x08, .r0 = 90, .r1 = 122 },
{ .d = 0x09, .r0 = 88, .r1 = 120 },
{ .d = 0x0a, .r0 = 84, .r1 = 116 },
{ .d = 0x0b, .r0 = 86, .r1 = 118 },
{ .d = 0x0c, .r0 = 76, .r1 = 108 },
{ .d = 0x0d, .r0 = 78, .r1 = 110 },
{ .d = 0x0e, .r0 = 82, .r1 = 114 },
{ .d = 0x0f, .r0 = 80, .r1 = 112 },
{ .d = 0x00, .r0 = 0, .r1 = 0 }, /* end */
};
int tda18271_lookup_thermometer(struct dvb_frontend *fe)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
int val, i = 0;
while (tda18271_thermometer[i].d < (regs[R_TM] & 0x0f)) {
if (tda18271_thermometer[i + 1].d == 0)
break;
i++;
}
if ((regs[R_TM] & 0x20) == 0x20)
val = tda18271_thermometer[i].r1;
else
val = tda18271_thermometer[i].r0;
tda_map("(%d) tm = %d\n", i, val);
return val;
}
/*---------------------------------------------------------------------*/
struct tda18271_cid_target_map {
u32 rfmax;
u8 target;
u16 limit;
};
static struct tda18271_cid_target_map tda18271_cid_target[] = {
{ .rfmax = 46000, .target = 0x04, .limit = 1800 },
{ .rfmax = 52200, .target = 0x0a, .limit = 1500 },
{ .rfmax = 70100, .target = 0x01, .limit = 4000 },
{ .rfmax = 136800, .target = 0x18, .limit = 4000 },
{ .rfmax = 156700, .target = 0x18, .limit = 4000 },
{ .rfmax = 186250, .target = 0x0a, .limit = 4000 },
{ .rfmax = 230000, .target = 0x0a, .limit = 4000 },
{ .rfmax = 345000, .target = 0x18, .limit = 4000 },
{ .rfmax = 426000, .target = 0x0e, .limit = 4000 },
{ .rfmax = 489500, .target = 0x1e, .limit = 4000 },
{ .rfmax = 697500, .target = 0x32, .limit = 4000 },
{ .rfmax = 842000, .target = 0x3a, .limit = 4000 },
{ .rfmax = 0, .target = 0x00, .limit = 0 }, /* end */
};
int tda18271_lookup_cid_target(struct dvb_frontend *fe,
u32 *freq, u8 *cid_target, u16 *count_limit)
{
struct tda18271_priv *priv = fe->tuner_priv;
int i = 0;
while ((tda18271_cid_target[i].rfmax * 1000) < *freq) {
if (tda18271_cid_target[i + 1].rfmax == 0)
break;
i++;
}
*cid_target = tda18271_cid_target[i].target;
*count_limit = tda18271_cid_target[i].limit;
tda_map("(%d) cid_target = %02x, count_limit = %d\n", i,
tda18271_cid_target[i].target, tda18271_cid_target[i].limit);
return 0;
}
/*---------------------------------------------------------------------*/
static struct tda18271_rf_tracking_filter_cal tda18271_rf_band_template[] = {
{ .rfmax = 47900, .rfband = 0x00,
.rf1_def = 46000, .rf2_def = 0, .rf3_def = 0 },
{ .rfmax = 61100, .rfband = 0x01,
.rf1_def = 52200, .rf2_def = 0, .rf3_def = 0 },
{ .rfmax = 152600, .rfband = 0x02,
.rf1_def = 70100, .rf2_def = 136800, .rf3_def = 0 },
{ .rfmax = 164700, .rfband = 0x03,
.rf1_def = 156700, .rf2_def = 0, .rf3_def = 0 },
{ .rfmax = 203500, .rfband = 0x04,
.rf1_def = 186250, .rf2_def = 0, .rf3_def = 0 },
{ .rfmax = 457800, .rfband = 0x05,
.rf1_def = 230000, .rf2_def = 345000, .rf3_def = 426000 },
{ .rfmax = 865000, .rfband = 0x06,
.rf1_def = 489500, .rf2_def = 697500, .rf3_def = 842000 },
{ .rfmax = 0, .rfband = 0x00,
.rf1_def = 0, .rf2_def = 0, .rf3_def = 0 }, /* end */
};
int tda18271_lookup_rf_band(struct dvb_frontend *fe, u32 *freq, u8 *rf_band)
{
struct tda18271_priv *priv = fe->tuner_priv;
struct tda18271_rf_tracking_filter_cal *map = priv->rf_cal_state;
int i = 0;
while ((map[i].rfmax * 1000) < *freq) {
if (tda18271_debug & DBG_ADV)
tda_map("(%d) rfmax = %d < freq = %d, "
"rf1_def = %d, rf2_def = %d, rf3_def = %d, "
"rf1 = %d, rf2 = %d, rf3 = %d, "
"rf_a1 = %d, rf_a2 = %d, "
"rf_b1 = %d, rf_b2 = %d\n",
i, map[i].rfmax * 1000, *freq,
map[i].rf1_def, map[i].rf2_def, map[i].rf3_def,
map[i].rf1, map[i].rf2, map[i].rf3,
map[i].rf_a1, map[i].rf_a2,
map[i].rf_b1, map[i].rf_b2);
if (map[i].rfmax == 0)
return -EINVAL;
i++;
}
if (rf_band)
*rf_band = map[i].rfband;
tda_map("(%d) rf_band = %02x\n", i, map[i].rfband);
return i;
}
/*---------------------------------------------------------------------*/
struct tda18271_map_layout {
struct tda18271_pll_map *main_pll;
struct tda18271_pll_map *cal_pll;
struct tda18271_map *rf_cal;
struct tda18271_map *rf_cal_kmco;
struct tda18271_map *rf_cal_dc_over_dt;
struct tda18271_map *bp_filter;
struct tda18271_map *rf_band;
struct tda18271_map *gain_taper;
struct tda18271_map *ir_measure;
};
/*---------------------------------------------------------------------*/
int tda18271_lookup_pll_map(struct dvb_frontend *fe,
enum tda18271_map_type map_type,
u32 *freq, u8 *post_div, u8 *div)
{
struct tda18271_priv *priv = fe->tuner_priv;
struct tda18271_pll_map *map = NULL;
unsigned int i = 0;
char *map_name;
int ret = 0;
BUG_ON(!priv->maps);
switch (map_type) {
case MAIN_PLL:
map = priv->maps->main_pll;
map_name = "main_pll";
break;
case CAL_PLL:
map = priv->maps->cal_pll;
map_name = "cal_pll";
break;
default:
/* we should never get here */
map_name = "undefined";
break;
}
if (!map) {
tda_warn("%s map is not set!\n", map_name);
ret = -EINVAL;
goto fail;
}
while ((map[i].lomax * 1000) < *freq) {
if (map[i + 1].lomax == 0) {
tda_map("%s: frequency (%d) out of range\n",
map_name, *freq);
ret = -ERANGE;
break;
}
i++;
}
*post_div = map[i].pd;
*div = map[i].d;
tda_map("(%d) %s: post div = 0x%02x, div = 0x%02x\n",
i, map_name, *post_div, *div);
fail:
return ret;
}
int tda18271_lookup_map(struct dvb_frontend *fe,
enum tda18271_map_type map_type,
u32 *freq, u8 *val)
{
struct tda18271_priv *priv = fe->tuner_priv;
struct tda18271_map *map = NULL;
unsigned int i = 0;
char *map_name;
int ret = 0;
BUG_ON(!priv->maps);
switch (map_type) {
case BP_FILTER:
map = priv->maps->bp_filter;
map_name = "bp_filter";
break;
case RF_CAL_KMCO:
map = priv->maps->rf_cal_kmco;
map_name = "km";
break;
case RF_BAND:
map = priv->maps->rf_band;
map_name = "rf_band";
break;
case GAIN_TAPER:
map = priv->maps->gain_taper;
map_name = "gain_taper";
break;
case RF_CAL:
map = priv->maps->rf_cal;
map_name = "rf_cal";
break;
case IR_MEASURE:
map = priv->maps->ir_measure;
map_name = "ir_measure";
break;
case RF_CAL_DC_OVER_DT:
map = priv->maps->rf_cal_dc_over_dt;
map_name = "rf_cal_dc_over_dt";
break;
default:
/* we should never get here */
map_name = "undefined";
break;
}
if (!map) {
tda_warn("%s map is not set!\n", map_name);
ret = -EINVAL;
goto fail;
}
while ((map[i].rfmax * 1000) < *freq) {
if (map[i + 1].rfmax == 0) {
tda_map("%s: frequency (%d) out of range\n",
map_name, *freq);
ret = -ERANGE;
break;
}
i++;
}
*val = map[i].val;
tda_map("(%d) %s: 0x%02x\n", i, map_name, *val);
fail:
return ret;
}
/*---------------------------------------------------------------------*/
static struct tda18271_std_map tda18271c1_std_map = {
.fm_radio = { .if_freq = 1250, .fm_rfn = 1, .agc_mode = 3, .std = 0,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x18 */
.atv_b = { .if_freq = 6750, .fm_rfn = 0, .agc_mode = 1, .std = 6,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0e */
.atv_dk = { .if_freq = 7750, .fm_rfn = 0, .agc_mode = 1, .std = 7,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0f */
.atv_gh = { .if_freq = 7750, .fm_rfn = 0, .agc_mode = 1, .std = 7,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0f */
.atv_i = { .if_freq = 7750, .fm_rfn = 0, .agc_mode = 1, .std = 7,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0f */
.atv_l = { .if_freq = 7750, .fm_rfn = 0, .agc_mode = 1, .std = 7,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0f */
.atv_lc = { .if_freq = 1250, .fm_rfn = 0, .agc_mode = 1, .std = 7,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0f */
.atv_mn = { .if_freq = 5750, .fm_rfn = 0, .agc_mode = 1, .std = 5,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0d */
.atsc_6 = { .if_freq = 3250, .fm_rfn = 0, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1c */
.dvbt_6 = { .if_freq = 3300, .fm_rfn = 0, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1c */
.dvbt_7 = { .if_freq = 3800, .fm_rfn = 0, .agc_mode = 3, .std = 5,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1d */
.dvbt_8 = { .if_freq = 4300, .fm_rfn = 0, .agc_mode = 3, .std = 6,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1e */
.qam_6 = { .if_freq = 4000, .fm_rfn = 0, .agc_mode = 3, .std = 5,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1d */
.qam_7 = { .if_freq = 4500, .fm_rfn = 0, .agc_mode = 3, .std = 6,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1e */
.qam_8 = { .if_freq = 5000, .fm_rfn = 0, .agc_mode = 3, .std = 7,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1f */
};
static struct tda18271_std_map tda18271c2_std_map = {
.fm_radio = { .if_freq = 1250, .fm_rfn = 1, .agc_mode = 3, .std = 0,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x18 */
.atv_b = { .if_freq = 6000, .fm_rfn = 0, .agc_mode = 1, .std = 5,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0d */
.atv_dk = { .if_freq = 6900, .fm_rfn = 0, .agc_mode = 1, .std = 6,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0e */
.atv_gh = { .if_freq = 7100, .fm_rfn = 0, .agc_mode = 1, .std = 6,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0e */
.atv_i = { .if_freq = 7250, .fm_rfn = 0, .agc_mode = 1, .std = 6,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0e */
.atv_l = { .if_freq = 6900, .fm_rfn = 0, .agc_mode = 1, .std = 6,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0e */
.atv_lc = { .if_freq = 1250, .fm_rfn = 0, .agc_mode = 1, .std = 6,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0e */
.atv_mn = { .if_freq = 5400, .fm_rfn = 0, .agc_mode = 1, .std = 4,
.if_lvl = 0, .rfagc_top = 0x2c, }, /* EP3[4:0] 0x0c */
.atsc_6 = { .if_freq = 3250, .fm_rfn = 0, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1c */
.dvbt_6 = { .if_freq = 3300, .fm_rfn = 0, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1c */
.dvbt_7 = { .if_freq = 3500, .fm_rfn = 0, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1c */
.dvbt_8 = { .if_freq = 4000, .fm_rfn = 0, .agc_mode = 3, .std = 5,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1d */
.qam_6 = { .if_freq = 4000, .fm_rfn = 0, .agc_mode = 3, .std = 5,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1d */
.qam_7 = { .if_freq = 4500, .fm_rfn = 0, .agc_mode = 3, .std = 6,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1e */
.qam_8 = { .if_freq = 5000, .fm_rfn = 0, .agc_mode = 3, .std = 7,
.if_lvl = 1, .rfagc_top = 0x37, }, /* EP3[4:0] 0x1f */
};
/*---------------------------------------------------------------------*/
static struct tda18271_map_layout tda18271c1_map_layout = {
.main_pll = tda18271c1_main_pll,
.cal_pll = tda18271c1_cal_pll,
.rf_cal = tda18271c1_rf_cal,
.rf_cal_kmco = tda18271c1_km,
.bp_filter = tda18271_bp_filter,
.rf_band = tda18271_rf_band,
.gain_taper = tda18271_gain_taper,
.ir_measure = tda18271_ir_measure,
};
static struct tda18271_map_layout tda18271c2_map_layout = {
.main_pll = tda18271c2_main_pll,
.cal_pll = tda18271c2_cal_pll,
.rf_cal = tda18271c2_rf_cal,
.rf_cal_kmco = tda18271c2_km,
.rf_cal_dc_over_dt = tda18271_rf_cal_dc_over_dt,
.bp_filter = tda18271_bp_filter,
.rf_band = tda18271_rf_band,
.gain_taper = tda18271_gain_taper,
.ir_measure = tda18271_ir_measure,
};
int tda18271_assign_map_layout(struct dvb_frontend *fe)
{
struct tda18271_priv *priv = fe->tuner_priv;
int ret = 0;
switch (priv->id) {
case TDA18271HDC1:
priv->maps = &tda18271c1_map_layout;
memcpy(&priv->std, &tda18271c1_std_map,
sizeof(struct tda18271_std_map));
break;
case TDA18271HDC2:
priv->maps = &tda18271c2_map_layout;
memcpy(&priv->std, &tda18271c2_std_map,
sizeof(struct tda18271_std_map));
break;
default:
ret = -EINVAL;
break;
}
memcpy(priv->rf_cal_state, &tda18271_rf_band_template,
sizeof(tda18271_rf_band_template));
return ret;
}
/*
* Overrides for Emacs so that we follow Linus's tabbing style.
* ---------------------------------------------------------------------------
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
Andorreta/android_kernel_google_msm | drivers/mtd/devices/phram.c | 7388 | 6172 | /**
* Copyright (c) ???? Jochen Schäuble <psionic@psionic.de>
* Copyright (c) 2003-2004 Joern Engel <joern@wh.fh-wedel.de>
*
* Usage:
*
* one commend line parameter per device, each in the form:
* phram=<name>,<start>,<len>
* <name> may be up to 63 characters.
* <start> and <len> can be octal, decimal or hexadecimal. If followed
* by "ki", "Mi" or "Gi", the numbers will be interpreted as kilo, mega or
* gigabytes.
*
* Example:
* phram=swap,64Mi,128Mi phram=test,900Mi,1Mi
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <asm/io.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
struct phram_mtd_list {
struct mtd_info mtd;
struct list_head list;
};
static LIST_HEAD(phram_list);
static int phram_erase(struct mtd_info *mtd, struct erase_info *instr)
{
u_char *start = mtd->priv;
memset(start + instr->addr, 0xff, instr->len);
/*
* This'll catch a few races. Free the thing before returning :)
* I don't feel at all ashamed. This kind of thing is possible anyway
* with flash, but unlikely.
*/
instr->state = MTD_ERASE_DONE;
mtd_erase_callback(instr);
return 0;
}
static int phram_point(struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, void **virt, resource_size_t *phys)
{
*virt = mtd->priv + from;
*retlen = len;
return 0;
}
static int phram_unpoint(struct mtd_info *mtd, loff_t from, size_t len)
{
return 0;
}
static int phram_read(struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, u_char *buf)
{
u_char *start = mtd->priv;
memcpy(buf, start + from, len);
*retlen = len;
return 0;
}
static int phram_write(struct mtd_info *mtd, loff_t to, size_t len,
size_t *retlen, const u_char *buf)
{
u_char *start = mtd->priv;
memcpy(start + to, buf, len);
*retlen = len;
return 0;
}
static void unregister_devices(void)
{
struct phram_mtd_list *this, *safe;
list_for_each_entry_safe(this, safe, &phram_list, list) {
mtd_device_unregister(&this->mtd);
iounmap(this->mtd.priv);
kfree(this->mtd.name);
kfree(this);
}
}
static int register_device(char *name, unsigned long start, unsigned long len)
{
struct phram_mtd_list *new;
int ret = -ENOMEM;
new = kzalloc(sizeof(*new), GFP_KERNEL);
if (!new)
goto out0;
ret = -EIO;
new->mtd.priv = ioremap(start, len);
if (!new->mtd.priv) {
pr_err("ioremap failed\n");
goto out1;
}
new->mtd.name = name;
new->mtd.size = len;
new->mtd.flags = MTD_CAP_RAM;
new->mtd._erase = phram_erase;
new->mtd._point = phram_point;
new->mtd._unpoint = phram_unpoint;
new->mtd._read = phram_read;
new->mtd._write = phram_write;
new->mtd.owner = THIS_MODULE;
new->mtd.type = MTD_RAM;
new->mtd.erasesize = PAGE_SIZE;
new->mtd.writesize = 1;
ret = -EAGAIN;
if (mtd_device_register(&new->mtd, NULL, 0)) {
pr_err("Failed to register new device\n");
goto out2;
}
list_add_tail(&new->list, &phram_list);
return 0;
out2:
iounmap(new->mtd.priv);
out1:
kfree(new);
out0:
return ret;
}
static int ustrtoul(const char *cp, char **endp, unsigned int base)
{
unsigned long result = simple_strtoul(cp, endp, base);
switch (**endp) {
case 'G':
result *= 1024;
case 'M':
result *= 1024;
case 'k':
result *= 1024;
/* By dwmw2 editorial decree, "ki", "Mi" or "Gi" are to be used. */
if ((*endp)[1] == 'i')
(*endp) += 2;
}
return result;
}
static int parse_num32(uint32_t *num32, const char *token)
{
char *endp;
unsigned long n;
n = ustrtoul(token, &endp, 0);
if (*endp)
return -EINVAL;
*num32 = n;
return 0;
}
static int parse_name(char **pname, const char *token)
{
size_t len;
char *name;
len = strlen(token) + 1;
if (len > 64)
return -ENOSPC;
name = kmalloc(len, GFP_KERNEL);
if (!name)
return -ENOMEM;
strcpy(name, token);
*pname = name;
return 0;
}
static inline void kill_final_newline(char *str)
{
char *newline = strrchr(str, '\n');
if (newline && !newline[1])
*newline = 0;
}
#define parse_err(fmt, args...) do { \
pr_err(fmt , ## args); \
return 1; \
} while (0)
/*
* This shall contain the module parameter if any. It is of the form:
* - phram=<device>,<address>,<size> for module case
* - phram.phram=<device>,<address>,<size> for built-in case
* We leave 64 bytes for the device name, 12 for the address and 12 for the
* size.
* Example: phram.phram=rootfs,0xa0000000,512Mi
*/
static __initdata char phram_paramline[64+12+12];
static int __init phram_setup(const char *val)
{
char buf[64+12+12], *str = buf;
char *token[3];
char *name;
uint32_t start;
uint32_t len;
int i, ret;
if (strnlen(val, sizeof(buf)) >= sizeof(buf))
parse_err("parameter too long\n");
strcpy(str, val);
kill_final_newline(str);
for (i=0; i<3; i++)
token[i] = strsep(&str, ",");
if (str)
parse_err("too many arguments\n");
if (!token[2])
parse_err("not enough arguments\n");
ret = parse_name(&name, token[0]);
if (ret)
return ret;
ret = parse_num32(&start, token[1]);
if (ret) {
kfree(name);
parse_err("illegal start address\n");
}
ret = parse_num32(&len, token[2]);
if (ret) {
kfree(name);
parse_err("illegal device length\n");
}
ret = register_device(name, start, len);
if (!ret)
pr_info("%s device: %#x at %#x\n", name, len, start);
else
kfree(name);
return ret;
}
static int __init phram_param_call(const char *val, struct kernel_param *kp)
{
/*
* This function is always called before 'init_phram()', whether
* built-in or module.
*/
if (strlen(val) >= sizeof(phram_paramline))
return -ENOSPC;
strcpy(phram_paramline, val);
return 0;
}
module_param_call(phram, phram_param_call, NULL, NULL, 000);
MODULE_PARM_DESC(phram, "Memory region to map. \"phram=<name>,<start>,<length>\"");
static int __init init_phram(void)
{
if (phram_paramline[0])
return phram_setup(phram_paramline);
return 0;
}
static void __exit cleanup_phram(void)
{
unregister_devices();
}
module_init(init_phram);
module_exit(cleanup_phram);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Joern Engel <joern@wh.fh-wedel.de>");
MODULE_DESCRIPTION("MTD driver for physical RAM");
| gpl-2.0 |
Trinityhaxxor/Xperia_S_T-Core_Kernel | drivers/scsi/ch.c | 7900 | 24897 | /*
* SCSI Media Changer device driver for Linux 2.6
*
* (c) 1996-2003 Gerd Knorr <kraxel@bytesex.org>
*
*/
#define VERSION "0.25"
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/blkdev.h>
#include <linux/completion.h>
#include <linux/compat.h>
#include <linux/chio.h> /* here are all the ioctls */
#include <linux/mutex.h>
#include <linux/idr.h>
#include <linux/slab.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_driver.h>
#include <scsi/scsi_ioctl.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_dbg.h>
#define CH_DT_MAX 16
#define CH_TYPES 8
#define CH_MAX_DEVS 128
MODULE_DESCRIPTION("device driver for scsi media changer devices");
MODULE_AUTHOR("Gerd Knorr <kraxel@bytesex.org>");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_CHANGER_MAJOR);
MODULE_ALIAS_SCSI_DEVICE(TYPE_MEDIUM_CHANGER);
static DEFINE_MUTEX(ch_mutex);
static int init = 1;
module_param(init, int, 0444);
MODULE_PARM_DESC(init, \
"initialize element status on driver load (default: on)");
static int timeout_move = 300;
module_param(timeout_move, int, 0644);
MODULE_PARM_DESC(timeout_move,"timeout for move commands "
"(default: 300 seconds)");
static int timeout_init = 3600;
module_param(timeout_init, int, 0644);
MODULE_PARM_DESC(timeout_init,"timeout for INITIALIZE ELEMENT STATUS "
"(default: 3600 seconds)");
static int verbose = 1;
module_param(verbose, int, 0644);
MODULE_PARM_DESC(verbose,"be verbose (default: on)");
static int debug = 0;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug,"enable/disable debug messages, also prints more "
"detailed sense codes on scsi errors (default: off)");
static int dt_id[CH_DT_MAX] = { [ 0 ... (CH_DT_MAX-1) ] = -1 };
static int dt_lun[CH_DT_MAX];
module_param_array(dt_id, int, NULL, 0444);
module_param_array(dt_lun, int, NULL, 0444);
/* tell the driver about vendor-specific slots */
static int vendor_firsts[CH_TYPES-4];
static int vendor_counts[CH_TYPES-4];
module_param_array(vendor_firsts, int, NULL, 0444);
module_param_array(vendor_counts, int, NULL, 0444);
static const char * vendor_labels[CH_TYPES-4] = {
"v0", "v1", "v2", "v3"
};
// module_param_string_array(vendor_labels, NULL, 0444);
#define DPRINTK(fmt, arg...) \
do { \
if (debug) \
printk(KERN_DEBUG "%s: " fmt, ch->name, ##arg); \
} while (0)
#define VPRINTK(level, fmt, arg...) \
do { \
if (verbose) \
printk(level "%s: " fmt, ch->name, ##arg); \
} while (0)
/* ------------------------------------------------------------------- */
#define MAX_RETRIES 1
static struct class * ch_sysfs_class;
typedef struct {
struct list_head list;
int minor;
char name[8];
struct scsi_device *device;
struct scsi_device **dt; /* ptrs to data transfer elements */
u_int firsts[CH_TYPES];
u_int counts[CH_TYPES];
u_int unit_attention;
u_int voltags;
struct mutex lock;
} scsi_changer;
static DEFINE_IDR(ch_index_idr);
static DEFINE_SPINLOCK(ch_index_lock);
static const struct {
unsigned char sense;
unsigned char asc;
unsigned char ascq;
int errno;
} ch_err[] = {
/* Just filled in what looks right. Hav'nt checked any standard paper for
these errno assignments, so they may be wrong... */
{
.sense = ILLEGAL_REQUEST,
.asc = 0x21,
.ascq = 0x01,
.errno = EBADSLT, /* Invalid element address */
},{
.sense = ILLEGAL_REQUEST,
.asc = 0x28,
.ascq = 0x01,
.errno = EBADE, /* Import or export element accessed */
},{
.sense = ILLEGAL_REQUEST,
.asc = 0x3B,
.ascq = 0x0D,
.errno = EXFULL, /* Medium destination element full */
},{
.sense = ILLEGAL_REQUEST,
.asc = 0x3B,
.ascq = 0x0E,
.errno = EBADE, /* Medium source element empty */
},{
.sense = ILLEGAL_REQUEST,
.asc = 0x20,
.ascq = 0x00,
.errno = EBADRQC, /* Invalid command operation code */
},{
/* end of list */
}
};
/* ------------------------------------------------------------------- */
static int ch_find_errno(struct scsi_sense_hdr *sshdr)
{
int i,errno = 0;
/* Check to see if additional sense information is available */
if (scsi_sense_valid(sshdr) &&
sshdr->asc != 0) {
for (i = 0; ch_err[i].errno != 0; i++) {
if (ch_err[i].sense == sshdr->sense_key &&
ch_err[i].asc == sshdr->asc &&
ch_err[i].ascq == sshdr->ascq) {
errno = -ch_err[i].errno;
break;
}
}
}
if (errno == 0)
errno = -EIO;
return errno;
}
static int
ch_do_scsi(scsi_changer *ch, unsigned char *cmd,
void *buffer, unsigned buflength,
enum dma_data_direction direction)
{
int errno, retries = 0, timeout, result;
struct scsi_sense_hdr sshdr;
timeout = (cmd[0] == INITIALIZE_ELEMENT_STATUS)
? timeout_init : timeout_move;
retry:
errno = 0;
if (debug) {
DPRINTK("command: ");
__scsi_print_command(cmd);
}
result = scsi_execute_req(ch->device, cmd, direction, buffer,
buflength, &sshdr, timeout * HZ,
MAX_RETRIES, NULL);
DPRINTK("result: 0x%x\n",result);
if (driver_byte(result) & DRIVER_SENSE) {
if (debug)
scsi_print_sense_hdr(ch->name, &sshdr);
errno = ch_find_errno(&sshdr);
switch(sshdr.sense_key) {
case UNIT_ATTENTION:
ch->unit_attention = 1;
if (retries++ < 3)
goto retry;
break;
}
}
return errno;
}
/* ------------------------------------------------------------------------ */
static int
ch_elem_to_typecode(scsi_changer *ch, u_int elem)
{
int i;
for (i = 0; i < CH_TYPES; i++) {
if (elem >= ch->firsts[i] &&
elem < ch->firsts[i] +
ch->counts[i])
return i+1;
}
return 0;
}
static int
ch_read_element_status(scsi_changer *ch, u_int elem, char *data)
{
u_char cmd[12];
u_char *buffer;
int result;
buffer = kmalloc(512, GFP_KERNEL | GFP_DMA);
if(!buffer)
return -ENOMEM;
retry:
memset(cmd,0,sizeof(cmd));
cmd[0] = READ_ELEMENT_STATUS;
cmd[1] = (ch->device->lun << 5) |
(ch->voltags ? 0x10 : 0) |
ch_elem_to_typecode(ch,elem);
cmd[2] = (elem >> 8) & 0xff;
cmd[3] = elem & 0xff;
cmd[5] = 1;
cmd[9] = 255;
if (0 == (result = ch_do_scsi(ch, cmd, buffer, 256, DMA_FROM_DEVICE))) {
if (((buffer[16] << 8) | buffer[17]) != elem) {
DPRINTK("asked for element 0x%02x, got 0x%02x\n",
elem,(buffer[16] << 8) | buffer[17]);
kfree(buffer);
return -EIO;
}
memcpy(data,buffer+16,16);
} else {
if (ch->voltags) {
ch->voltags = 0;
VPRINTK(KERN_INFO, "device has no volume tag support\n");
goto retry;
}
DPRINTK("READ ELEMENT STATUS for element 0x%x failed\n",elem);
}
kfree(buffer);
return result;
}
static int
ch_init_elem(scsi_changer *ch)
{
int err;
u_char cmd[6];
VPRINTK(KERN_INFO, "INITIALIZE ELEMENT STATUS, may take some time ...\n");
memset(cmd,0,sizeof(cmd));
cmd[0] = INITIALIZE_ELEMENT_STATUS;
cmd[1] = ch->device->lun << 5;
err = ch_do_scsi(ch, cmd, NULL, 0, DMA_NONE);
VPRINTK(KERN_INFO, "... finished\n");
return err;
}
static int
ch_readconfig(scsi_changer *ch)
{
u_char cmd[10], data[16];
u_char *buffer;
int result,id,lun,i;
u_int elem;
buffer = kzalloc(512, GFP_KERNEL | GFP_DMA);
if (!buffer)
return -ENOMEM;
memset(cmd,0,sizeof(cmd));
cmd[0] = MODE_SENSE;
cmd[1] = ch->device->lun << 5;
cmd[2] = 0x1d;
cmd[4] = 255;
result = ch_do_scsi(ch, cmd, buffer, 255, DMA_FROM_DEVICE);
if (0 != result) {
cmd[1] |= (1<<3);
result = ch_do_scsi(ch, cmd, buffer, 255, DMA_FROM_DEVICE);
}
if (0 == result) {
ch->firsts[CHET_MT] =
(buffer[buffer[3]+ 6] << 8) | buffer[buffer[3]+ 7];
ch->counts[CHET_MT] =
(buffer[buffer[3]+ 8] << 8) | buffer[buffer[3]+ 9];
ch->firsts[CHET_ST] =
(buffer[buffer[3]+10] << 8) | buffer[buffer[3]+11];
ch->counts[CHET_ST] =
(buffer[buffer[3]+12] << 8) | buffer[buffer[3]+13];
ch->firsts[CHET_IE] =
(buffer[buffer[3]+14] << 8) | buffer[buffer[3]+15];
ch->counts[CHET_IE] =
(buffer[buffer[3]+16] << 8) | buffer[buffer[3]+17];
ch->firsts[CHET_DT] =
(buffer[buffer[3]+18] << 8) | buffer[buffer[3]+19];
ch->counts[CHET_DT] =
(buffer[buffer[3]+20] << 8) | buffer[buffer[3]+21];
VPRINTK(KERN_INFO, "type #1 (mt): 0x%x+%d [medium transport]\n",
ch->firsts[CHET_MT],
ch->counts[CHET_MT]);
VPRINTK(KERN_INFO, "type #2 (st): 0x%x+%d [storage]\n",
ch->firsts[CHET_ST],
ch->counts[CHET_ST]);
VPRINTK(KERN_INFO, "type #3 (ie): 0x%x+%d [import/export]\n",
ch->firsts[CHET_IE],
ch->counts[CHET_IE]);
VPRINTK(KERN_INFO, "type #4 (dt): 0x%x+%d [data transfer]\n",
ch->firsts[CHET_DT],
ch->counts[CHET_DT]);
} else {
VPRINTK(KERN_INFO, "reading element address assigment page failed!\n");
}
/* vendor specific element types */
for (i = 0; i < 4; i++) {
if (0 == vendor_counts[i])
continue;
if (NULL == vendor_labels[i])
continue;
ch->firsts[CHET_V1+i] = vendor_firsts[i];
ch->counts[CHET_V1+i] = vendor_counts[i];
VPRINTK(KERN_INFO, "type #%d (v%d): 0x%x+%d [%s, vendor specific]\n",
i+5,i+1,vendor_firsts[i],vendor_counts[i],
vendor_labels[i]);
}
/* look up the devices of the data transfer elements */
ch->dt = kcalloc(ch->counts[CHET_DT], sizeof(*ch->dt),
GFP_KERNEL);
if (!ch->dt) {
kfree(buffer);
return -ENOMEM;
}
for (elem = 0; elem < ch->counts[CHET_DT]; elem++) {
id = -1;
lun = 0;
if (elem < CH_DT_MAX && -1 != dt_id[elem]) {
id = dt_id[elem];
lun = dt_lun[elem];
VPRINTK(KERN_INFO, "dt 0x%x: [insmod option] ",
elem+ch->firsts[CHET_DT]);
} else if (0 != ch_read_element_status
(ch,elem+ch->firsts[CHET_DT],data)) {
VPRINTK(KERN_INFO, "dt 0x%x: READ ELEMENT STATUS failed\n",
elem+ch->firsts[CHET_DT]);
} else {
VPRINTK(KERN_INFO, "dt 0x%x: ",elem+ch->firsts[CHET_DT]);
if (data[6] & 0x80) {
VPRINTK(KERN_CONT, "not this SCSI bus\n");
ch->dt[elem] = NULL;
} else if (0 == (data[6] & 0x30)) {
VPRINTK(KERN_CONT, "ID/LUN unknown\n");
ch->dt[elem] = NULL;
} else {
id = ch->device->id;
lun = 0;
if (data[6] & 0x20) id = data[7];
if (data[6] & 0x10) lun = data[6] & 7;
}
}
if (-1 != id) {
VPRINTK(KERN_CONT, "ID %i, LUN %i, ",id,lun);
ch->dt[elem] =
scsi_device_lookup(ch->device->host,
ch->device->channel,
id,lun);
if (!ch->dt[elem]) {
/* should not happen */
VPRINTK(KERN_CONT, "Huh? device not found!\n");
} else {
VPRINTK(KERN_CONT, "name: %8.8s %16.16s %4.4s\n",
ch->dt[elem]->vendor,
ch->dt[elem]->model,
ch->dt[elem]->rev);
}
}
}
ch->voltags = 1;
kfree(buffer);
return 0;
}
/* ------------------------------------------------------------------------ */
static int
ch_position(scsi_changer *ch, u_int trans, u_int elem, int rotate)
{
u_char cmd[10];
DPRINTK("position: 0x%x\n",elem);
if (0 == trans)
trans = ch->firsts[CHET_MT];
memset(cmd,0,sizeof(cmd));
cmd[0] = POSITION_TO_ELEMENT;
cmd[1] = ch->device->lun << 5;
cmd[2] = (trans >> 8) & 0xff;
cmd[3] = trans & 0xff;
cmd[4] = (elem >> 8) & 0xff;
cmd[5] = elem & 0xff;
cmd[8] = rotate ? 1 : 0;
return ch_do_scsi(ch, cmd, NULL, 0, DMA_NONE);
}
static int
ch_move(scsi_changer *ch, u_int trans, u_int src, u_int dest, int rotate)
{
u_char cmd[12];
DPRINTK("move: 0x%x => 0x%x\n",src,dest);
if (0 == trans)
trans = ch->firsts[CHET_MT];
memset(cmd,0,sizeof(cmd));
cmd[0] = MOVE_MEDIUM;
cmd[1] = ch->device->lun << 5;
cmd[2] = (trans >> 8) & 0xff;
cmd[3] = trans & 0xff;
cmd[4] = (src >> 8) & 0xff;
cmd[5] = src & 0xff;
cmd[6] = (dest >> 8) & 0xff;
cmd[7] = dest & 0xff;
cmd[10] = rotate ? 1 : 0;
return ch_do_scsi(ch, cmd, NULL,0, DMA_NONE);
}
static int
ch_exchange(scsi_changer *ch, u_int trans, u_int src,
u_int dest1, u_int dest2, int rotate1, int rotate2)
{
u_char cmd[12];
DPRINTK("exchange: 0x%x => 0x%x => 0x%x\n",
src,dest1,dest2);
if (0 == trans)
trans = ch->firsts[CHET_MT];
memset(cmd,0,sizeof(cmd));
cmd[0] = EXCHANGE_MEDIUM;
cmd[1] = ch->device->lun << 5;
cmd[2] = (trans >> 8) & 0xff;
cmd[3] = trans & 0xff;
cmd[4] = (src >> 8) & 0xff;
cmd[5] = src & 0xff;
cmd[6] = (dest1 >> 8) & 0xff;
cmd[7] = dest1 & 0xff;
cmd[8] = (dest2 >> 8) & 0xff;
cmd[9] = dest2 & 0xff;
cmd[10] = (rotate1 ? 1 : 0) | (rotate2 ? 2 : 0);
return ch_do_scsi(ch, cmd, NULL,0, DMA_NONE);
}
static void
ch_check_voltag(char *tag)
{
int i;
for (i = 0; i < 32; i++) {
/* restrict to ascii */
if (tag[i] >= 0x7f || tag[i] < 0x20)
tag[i] = ' ';
/* don't allow search wildcards */
if (tag[i] == '?' ||
tag[i] == '*')
tag[i] = ' ';
}
}
static int
ch_set_voltag(scsi_changer *ch, u_int elem,
int alternate, int clear, u_char *tag)
{
u_char cmd[12];
u_char *buffer;
int result;
buffer = kzalloc(512, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
DPRINTK("%s %s voltag: 0x%x => \"%s\"\n",
clear ? "clear" : "set",
alternate ? "alternate" : "primary",
elem, tag);
memset(cmd,0,sizeof(cmd));
cmd[0] = SEND_VOLUME_TAG;
cmd[1] = (ch->device->lun << 5) |
ch_elem_to_typecode(ch,elem);
cmd[2] = (elem >> 8) & 0xff;
cmd[3] = elem & 0xff;
cmd[5] = clear
? (alternate ? 0x0d : 0x0c)
: (alternate ? 0x0b : 0x0a);
cmd[9] = 255;
memcpy(buffer,tag,32);
ch_check_voltag(buffer);
result = ch_do_scsi(ch, cmd, buffer, 256, DMA_TO_DEVICE);
kfree(buffer);
return result;
}
static int ch_gstatus(scsi_changer *ch, int type, unsigned char __user *dest)
{
int retval = 0;
u_char data[16];
unsigned int i;
mutex_lock(&ch->lock);
for (i = 0; i < ch->counts[type]; i++) {
if (0 != ch_read_element_status
(ch, ch->firsts[type]+i,data)) {
retval = -EIO;
break;
}
put_user(data[2], dest+i);
if (data[2] & CESTATUS_EXCEPT)
VPRINTK(KERN_INFO, "element 0x%x: asc=0x%x, ascq=0x%x\n",
ch->firsts[type]+i,
(int)data[4],(int)data[5]);
retval = ch_read_element_status
(ch, ch->firsts[type]+i,data);
if (0 != retval)
break;
}
mutex_unlock(&ch->lock);
return retval;
}
/* ------------------------------------------------------------------------ */
static int
ch_release(struct inode *inode, struct file *file)
{
scsi_changer *ch = file->private_data;
scsi_device_put(ch->device);
file->private_data = NULL;
return 0;
}
static int
ch_open(struct inode *inode, struct file *file)
{
scsi_changer *ch;
int minor = iminor(inode);
mutex_lock(&ch_mutex);
spin_lock(&ch_index_lock);
ch = idr_find(&ch_index_idr, minor);
if (NULL == ch || scsi_device_get(ch->device)) {
spin_unlock(&ch_index_lock);
mutex_unlock(&ch_mutex);
return -ENXIO;
}
spin_unlock(&ch_index_lock);
file->private_data = ch;
mutex_unlock(&ch_mutex);
return 0;
}
static int
ch_checkrange(scsi_changer *ch, unsigned int type, unsigned int unit)
{
if (type >= CH_TYPES || unit >= ch->counts[type])
return -1;
return 0;
}
static long ch_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
scsi_changer *ch = file->private_data;
int retval;
void __user *argp = (void __user *)arg;
switch (cmd) {
case CHIOGPARAMS:
{
struct changer_params params;
params.cp_curpicker = 0;
params.cp_npickers = ch->counts[CHET_MT];
params.cp_nslots = ch->counts[CHET_ST];
params.cp_nportals = ch->counts[CHET_IE];
params.cp_ndrives = ch->counts[CHET_DT];
if (copy_to_user(argp, ¶ms, sizeof(params)))
return -EFAULT;
return 0;
}
case CHIOGVPARAMS:
{
struct changer_vendor_params vparams;
memset(&vparams,0,sizeof(vparams));
if (ch->counts[CHET_V1]) {
vparams.cvp_n1 = ch->counts[CHET_V1];
strncpy(vparams.cvp_label1,vendor_labels[0],16);
}
if (ch->counts[CHET_V2]) {
vparams.cvp_n2 = ch->counts[CHET_V2];
strncpy(vparams.cvp_label2,vendor_labels[1],16);
}
if (ch->counts[CHET_V3]) {
vparams.cvp_n3 = ch->counts[CHET_V3];
strncpy(vparams.cvp_label3,vendor_labels[2],16);
}
if (ch->counts[CHET_V4]) {
vparams.cvp_n4 = ch->counts[CHET_V4];
strncpy(vparams.cvp_label4,vendor_labels[3],16);
}
if (copy_to_user(argp, &vparams, sizeof(vparams)))
return -EFAULT;
return 0;
}
case CHIOPOSITION:
{
struct changer_position pos;
if (copy_from_user(&pos, argp, sizeof (pos)))
return -EFAULT;
if (0 != ch_checkrange(ch, pos.cp_type, pos.cp_unit)) {
DPRINTK("CHIOPOSITION: invalid parameter\n");
return -EBADSLT;
}
mutex_lock(&ch->lock);
retval = ch_position(ch,0,
ch->firsts[pos.cp_type] + pos.cp_unit,
pos.cp_flags & CP_INVERT);
mutex_unlock(&ch->lock);
return retval;
}
case CHIOMOVE:
{
struct changer_move mv;
if (copy_from_user(&mv, argp, sizeof (mv)))
return -EFAULT;
if (0 != ch_checkrange(ch, mv.cm_fromtype, mv.cm_fromunit) ||
0 != ch_checkrange(ch, mv.cm_totype, mv.cm_tounit )) {
DPRINTK("CHIOMOVE: invalid parameter\n");
return -EBADSLT;
}
mutex_lock(&ch->lock);
retval = ch_move(ch,0,
ch->firsts[mv.cm_fromtype] + mv.cm_fromunit,
ch->firsts[mv.cm_totype] + mv.cm_tounit,
mv.cm_flags & CM_INVERT);
mutex_unlock(&ch->lock);
return retval;
}
case CHIOEXCHANGE:
{
struct changer_exchange mv;
if (copy_from_user(&mv, argp, sizeof (mv)))
return -EFAULT;
if (0 != ch_checkrange(ch, mv.ce_srctype, mv.ce_srcunit ) ||
0 != ch_checkrange(ch, mv.ce_fdsttype, mv.ce_fdstunit) ||
0 != ch_checkrange(ch, mv.ce_sdsttype, mv.ce_sdstunit)) {
DPRINTK("CHIOEXCHANGE: invalid parameter\n");
return -EBADSLT;
}
mutex_lock(&ch->lock);
retval = ch_exchange
(ch,0,
ch->firsts[mv.ce_srctype] + mv.ce_srcunit,
ch->firsts[mv.ce_fdsttype] + mv.ce_fdstunit,
ch->firsts[mv.ce_sdsttype] + mv.ce_sdstunit,
mv.ce_flags & CE_INVERT1, mv.ce_flags & CE_INVERT2);
mutex_unlock(&ch->lock);
return retval;
}
case CHIOGSTATUS:
{
struct changer_element_status ces;
if (copy_from_user(&ces, argp, sizeof (ces)))
return -EFAULT;
if (ces.ces_type < 0 || ces.ces_type >= CH_TYPES)
return -EINVAL;
return ch_gstatus(ch, ces.ces_type, ces.ces_data);
}
case CHIOGELEM:
{
struct changer_get_element cge;
u_char ch_cmd[12];
u_char *buffer;
unsigned int elem;
int result,i;
if (copy_from_user(&cge, argp, sizeof (cge)))
return -EFAULT;
if (0 != ch_checkrange(ch, cge.cge_type, cge.cge_unit))
return -EINVAL;
elem = ch->firsts[cge.cge_type] + cge.cge_unit;
buffer = kmalloc(512, GFP_KERNEL | GFP_DMA);
if (!buffer)
return -ENOMEM;
mutex_lock(&ch->lock);
voltag_retry:
memset(ch_cmd, 0, sizeof(ch_cmd));
ch_cmd[0] = READ_ELEMENT_STATUS;
ch_cmd[1] = (ch->device->lun << 5) |
(ch->voltags ? 0x10 : 0) |
ch_elem_to_typecode(ch,elem);
ch_cmd[2] = (elem >> 8) & 0xff;
ch_cmd[3] = elem & 0xff;
ch_cmd[5] = 1;
ch_cmd[9] = 255;
result = ch_do_scsi(ch, ch_cmd, buffer, 256, DMA_FROM_DEVICE);
if (!result) {
cge.cge_status = buffer[18];
cge.cge_flags = 0;
if (buffer[18] & CESTATUS_EXCEPT) {
cge.cge_errno = EIO;
}
if (buffer[25] & 0x80) {
cge.cge_flags |= CGE_SRC;
if (buffer[25] & 0x40)
cge.cge_flags |= CGE_INVERT;
elem = (buffer[26]<<8) | buffer[27];
for (i = 0; i < 4; i++) {
if (elem >= ch->firsts[i] &&
elem < ch->firsts[i] + ch->counts[i]) {
cge.cge_srctype = i;
cge.cge_srcunit = elem-ch->firsts[i];
}
}
}
if ((buffer[22] & 0x30) == 0x30) {
cge.cge_flags |= CGE_IDLUN;
cge.cge_id = buffer[23];
cge.cge_lun = buffer[22] & 7;
}
if (buffer[9] & 0x80) {
cge.cge_flags |= CGE_PVOLTAG;
memcpy(cge.cge_pvoltag,buffer+28,36);
}
if (buffer[9] & 0x40) {
cge.cge_flags |= CGE_AVOLTAG;
memcpy(cge.cge_avoltag,buffer+64,36);
}
} else if (ch->voltags) {
ch->voltags = 0;
VPRINTK(KERN_INFO, "device has no volume tag support\n");
goto voltag_retry;
}
kfree(buffer);
mutex_unlock(&ch->lock);
if (copy_to_user(argp, &cge, sizeof (cge)))
return -EFAULT;
return result;
}
case CHIOINITELEM:
{
mutex_lock(&ch->lock);
retval = ch_init_elem(ch);
mutex_unlock(&ch->lock);
return retval;
}
case CHIOSVOLTAG:
{
struct changer_set_voltag csv;
int elem;
if (copy_from_user(&csv, argp, sizeof(csv)))
return -EFAULT;
if (0 != ch_checkrange(ch, csv.csv_type, csv.csv_unit)) {
DPRINTK("CHIOSVOLTAG: invalid parameter\n");
return -EBADSLT;
}
elem = ch->firsts[csv.csv_type] + csv.csv_unit;
mutex_lock(&ch->lock);
retval = ch_set_voltag(ch, elem,
csv.csv_flags & CSV_AVOLTAG,
csv.csv_flags & CSV_CLEARTAG,
csv.csv_voltag);
mutex_unlock(&ch->lock);
return retval;
}
default:
return scsi_ioctl(ch->device, cmd, argp);
}
}
#ifdef CONFIG_COMPAT
struct changer_element_status32 {
int ces_type;
compat_uptr_t ces_data;
};
#define CHIOGSTATUS32 _IOW('c', 8,struct changer_element_status32)
static long ch_ioctl_compat(struct file * file,
unsigned int cmd, unsigned long arg)
{
scsi_changer *ch = file->private_data;
switch (cmd) {
case CHIOGPARAMS:
case CHIOGVPARAMS:
case CHIOPOSITION:
case CHIOMOVE:
case CHIOEXCHANGE:
case CHIOGELEM:
case CHIOINITELEM:
case CHIOSVOLTAG:
/* compatible */
return ch_ioctl(file, cmd, arg);
case CHIOGSTATUS32:
{
struct changer_element_status32 ces32;
unsigned char __user *data;
if (copy_from_user(&ces32, (void __user *)arg, sizeof (ces32)))
return -EFAULT;
if (ces32.ces_type < 0 || ces32.ces_type >= CH_TYPES)
return -EINVAL;
data = compat_ptr(ces32.ces_data);
return ch_gstatus(ch, ces32.ces_type, data);
}
default:
// return scsi_ioctl_compat(ch->device, cmd, (void*)arg);
return -ENOIOCTLCMD;
}
}
#endif
/* ------------------------------------------------------------------------ */
static int ch_probe(struct device *dev)
{
struct scsi_device *sd = to_scsi_device(dev);
struct device *class_dev;
int minor, ret = -ENOMEM;
scsi_changer *ch;
if (sd->type != TYPE_MEDIUM_CHANGER)
return -ENODEV;
ch = kzalloc(sizeof(*ch), GFP_KERNEL);
if (NULL == ch)
return -ENOMEM;
if (!idr_pre_get(&ch_index_idr, GFP_KERNEL))
goto free_ch;
spin_lock(&ch_index_lock);
ret = idr_get_new(&ch_index_idr, ch, &minor);
spin_unlock(&ch_index_lock);
if (ret)
goto free_ch;
if (minor > CH_MAX_DEVS) {
ret = -ENODEV;
goto remove_idr;
}
ch->minor = minor;
sprintf(ch->name,"ch%d",ch->minor);
class_dev = device_create(ch_sysfs_class, dev,
MKDEV(SCSI_CHANGER_MAJOR, ch->minor), ch,
"s%s", ch->name);
if (IS_ERR(class_dev)) {
printk(KERN_WARNING "ch%d: device_create failed\n",
ch->minor);
ret = PTR_ERR(class_dev);
goto remove_idr;
}
mutex_init(&ch->lock);
ch->device = sd;
ch_readconfig(ch);
if (init)
ch_init_elem(ch);
dev_set_drvdata(dev, ch);
sdev_printk(KERN_INFO, sd, "Attached scsi changer %s\n", ch->name);
return 0;
remove_idr:
idr_remove(&ch_index_idr, minor);
free_ch:
kfree(ch);
return ret;
}
static int ch_remove(struct device *dev)
{
scsi_changer *ch = dev_get_drvdata(dev);
spin_lock(&ch_index_lock);
idr_remove(&ch_index_idr, ch->minor);
spin_unlock(&ch_index_lock);
device_destroy(ch_sysfs_class, MKDEV(SCSI_CHANGER_MAJOR,ch->minor));
kfree(ch->dt);
kfree(ch);
return 0;
}
static struct scsi_driver ch_template = {
.owner = THIS_MODULE,
.gendrv = {
.name = "ch",
.probe = ch_probe,
.remove = ch_remove,
},
};
static const struct file_operations changer_fops = {
.owner = THIS_MODULE,
.open = ch_open,
.release = ch_release,
.unlocked_ioctl = ch_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ch_ioctl_compat,
#endif
.llseek = noop_llseek,
};
static int __init init_ch_module(void)
{
int rc;
printk(KERN_INFO "SCSI Media Changer driver v" VERSION " \n");
ch_sysfs_class = class_create(THIS_MODULE, "scsi_changer");
if (IS_ERR(ch_sysfs_class)) {
rc = PTR_ERR(ch_sysfs_class);
return rc;
}
rc = register_chrdev(SCSI_CHANGER_MAJOR,"ch",&changer_fops);
if (rc < 0) {
printk("Unable to get major %d for SCSI-Changer\n",
SCSI_CHANGER_MAJOR);
goto fail1;
}
rc = scsi_register_driver(&ch_template.gendrv);
if (rc < 0)
goto fail2;
return 0;
fail2:
unregister_chrdev(SCSI_CHANGER_MAJOR, "ch");
fail1:
class_destroy(ch_sysfs_class);
return rc;
}
static void __exit exit_ch_module(void)
{
scsi_unregister_driver(&ch_template.gendrv);
unregister_chrdev(SCSI_CHANGER_MAJOR, "ch");
class_destroy(ch_sysfs_class);
idr_destroy(&ch_index_idr);
}
module_init(init_ch_module);
module_exit(exit_ch_module);
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
talnoah/Lemur_kernel | drivers/video/nvidia/nv_of.c | 12764 | 1869 | /*
* linux/drivers/video/nvidia/nv_of.c
*
* Copyright 2004 Antonino A. Daplas <adaplas @pol.net>
*
* Based on rivafb-i2c.c
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/gfp.h>
#include <linux/pci.h>
#include <linux/fb.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#include "nv_type.h"
#include "nv_local.h"
#include "nv_proto.h"
#include "../edid.h"
int nvidia_probe_of_connector(struct fb_info *info, int conn, u8 **out_edid)
{
struct nvidia_par *par = info->par;
struct device_node *parent, *dp;
const unsigned char *pedid = NULL;
static char *propnames[] = {
"DFP,EDID", "LCD,EDID", "EDID", "EDID1",
"EDID,B", "EDID,A", NULL };
int i;
parent = pci_device_to_OF_node(par->pci_dev);
if (parent == NULL)
return -1;
if (par->twoHeads) {
const char *pname;
int len;
for (dp = NULL;
(dp = of_get_next_child(parent, dp)) != NULL;) {
pname = of_get_property(dp, "name", NULL);
if (!pname)
continue;
len = strlen(pname);
if ((pname[len-1] == 'A' && conn == 1) ||
(pname[len-1] == 'B' && conn == 2)) {
for (i = 0; propnames[i] != NULL; ++i) {
pedid = of_get_property(dp,
propnames[i], NULL);
if (pedid != NULL)
break;
}
of_node_put(dp);
break;
}
}
}
if (pedid == NULL) {
for (i = 0; propnames[i] != NULL; ++i) {
pedid = of_get_property(parent, propnames[i], NULL);
if (pedid != NULL)
break;
}
}
if (pedid) {
*out_edid = kmemdup(pedid, EDID_LENGTH, GFP_KERNEL);
if (*out_edid == NULL)
return -1;
printk(KERN_DEBUG "nvidiafb: Found OF EDID for head %d\n", conn);
return 0;
}
return -1;
}
| gpl-2.0 |
talnoah/m8 | drivers/misc/altera-stapl/altera-lpt.c | 13020 | 1747 | /*
* altera-lpt.c
*
* altera FPGA driver
*
* Copyright (C) Altera Corporation 1998-2001
* Copyright (C) 2010 NetUP Inc.
* Copyright (C) 2010 Abylay Ospan <aospan@netup.ru>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/io.h>
#include <linux/kernel.h>
#include "altera-exprt.h"
static int lpt_hardware_initialized;
static void byteblaster_write(int port, int data)
{
outb((u8)data, (u16)(port + 0x378));
};
static int byteblaster_read(int port)
{
int data = 0;
data = inb((u16)(port + 0x378));
return data & 0xff;
};
int netup_jtag_io_lpt(void *device, int tms, int tdi, int read_tdo)
{
int data = 0;
int tdo = 0;
int initial_lpt_ctrl = 0;
if (!lpt_hardware_initialized) {
initial_lpt_ctrl = byteblaster_read(2);
byteblaster_write(2, (initial_lpt_ctrl | 0x02) & 0xdf);
lpt_hardware_initialized = 1;
}
data = ((tdi ? 0x40 : 0) | (tms ? 0x02 : 0));
byteblaster_write(0, data);
if (read_tdo) {
tdo = byteblaster_read(1);
tdo = ((tdo & 0x80) ? 0 : 1);
}
byteblaster_write(0, data | 0x01);
byteblaster_write(0, data);
return tdo;
}
| gpl-2.0 |
kvalo/ath10k | drivers/misc/altera-stapl/altera-lpt.c | 13020 | 1747 | /*
* altera-lpt.c
*
* altera FPGA driver
*
* Copyright (C) Altera Corporation 1998-2001
* Copyright (C) 2010 NetUP Inc.
* Copyright (C) 2010 Abylay Ospan <aospan@netup.ru>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/io.h>
#include <linux/kernel.h>
#include "altera-exprt.h"
static int lpt_hardware_initialized;
static void byteblaster_write(int port, int data)
{
outb((u8)data, (u16)(port + 0x378));
};
static int byteblaster_read(int port)
{
int data = 0;
data = inb((u16)(port + 0x378));
return data & 0xff;
};
int netup_jtag_io_lpt(void *device, int tms, int tdi, int read_tdo)
{
int data = 0;
int tdo = 0;
int initial_lpt_ctrl = 0;
if (!lpt_hardware_initialized) {
initial_lpt_ctrl = byteblaster_read(2);
byteblaster_write(2, (initial_lpt_ctrl | 0x02) & 0xdf);
lpt_hardware_initialized = 1;
}
data = ((tdi ? 0x40 : 0) | (tms ? 0x02 : 0));
byteblaster_write(0, data);
if (read_tdo) {
tdo = byteblaster_read(1);
tdo = ((tdo & 0x80) ? 0 : 1);
}
byteblaster_write(0, data | 0x01);
byteblaster_write(0, data);
return tdo;
}
| gpl-2.0 |
issi5862/linux-3.17.3-nvdimm-journal | drivers/scsi/esas2r/esas2r_main.c | 221 | 50089 | /*
* linux/drivers/scsi/esas2r/esas2r_main.c
* For use with ATTO ExpressSAS R6xx SAS/SATA RAID controllers
*
* Copyright (c) 2001-2013 ATTO Technology, Inc.
* (mailto:linuxdrivers@attotech.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.
*
* NO WARRANTY
* THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
* LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
* solely responsible for determining the appropriateness of using and
* distributing the Program and assumes all risks associated with its
* exercise of rights under this Agreement, including but not limited to
* the risks and costs of program errors, damage to or loss of data,
* programs or equipment, and unavailability or interruption of operations.
*
* DISCLAIMER OF LIABILITY
* NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
* HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
*
* 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 "esas2r.h"
MODULE_DESCRIPTION(ESAS2R_DRVR_NAME ": " ESAS2R_LONGNAME " driver");
MODULE_AUTHOR("ATTO Technology, Inc.");
MODULE_LICENSE("GPL");
MODULE_VERSION(ESAS2R_VERSION_STR);
/* global definitions */
static int found_adapters;
struct esas2r_adapter *esas2r_adapters[MAX_ADAPTERS];
#define ESAS2R_VDA_EVENT_PORT1 54414
#define ESAS2R_VDA_EVENT_PORT2 54415
#define ESAS2R_VDA_EVENT_SOCK_COUNT 2
static struct esas2r_adapter *esas2r_adapter_from_kobj(struct kobject *kobj)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct Scsi_Host *host = class_to_shost(dev);
return (struct esas2r_adapter *)host->hostdata;
}
static ssize_t read_fw(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_read_fw(a, buf, off, count);
}
static ssize_t write_fw(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_write_fw(a, buf, off, count);
}
static ssize_t read_fs(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_read_fs(a, buf, off, count);
}
static ssize_t write_fs(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
int length = min(sizeof(struct esas2r_ioctl_fs), count);
int result = 0;
result = esas2r_write_fs(a, buf, off, count);
if (result < 0)
result = 0;
return length;
}
static ssize_t read_vda(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_read_vda(a, buf, off, count);
}
static ssize_t write_vda(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
return esas2r_write_vda(a, buf, off, count);
}
static ssize_t read_live_nvram(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
int length = min_t(size_t, sizeof(struct esas2r_sas_nvram), PAGE_SIZE);
memcpy(buf, a->nvram, length);
return length;
}
static ssize_t write_live_nvram(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
struct esas2r_request *rq;
int result = -EFAULT;
rq = esas2r_alloc_request(a);
if (rq == NULL)
return -ENOMEM;
if (esas2r_write_params(a, rq, (struct esas2r_sas_nvram *)buf))
result = count;
esas2r_free_request(a, rq);
return result;
}
static ssize_t read_default_nvram(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
esas2r_nvram_get_defaults(a, (struct esas2r_sas_nvram *)buf);
return sizeof(struct esas2r_sas_nvram);
}
static ssize_t read_hw(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
int length = min_t(size_t, sizeof(struct atto_ioctl), PAGE_SIZE);
if (!a->local_atto_ioctl)
return -ENOMEM;
if (handle_hba_ioctl(a, a->local_atto_ioctl) != IOCTL_SUCCESS)
return -ENOMEM;
memcpy(buf, a->local_atto_ioctl, length);
return length;
}
static ssize_t write_hw(struct file *file, struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t off, size_t count)
{
struct esas2r_adapter *a = esas2r_adapter_from_kobj(kobj);
int length = min(sizeof(struct atto_ioctl), count);
if (!a->local_atto_ioctl) {
a->local_atto_ioctl = kzalloc(sizeof(struct atto_ioctl),
GFP_KERNEL);
if (a->local_atto_ioctl == NULL) {
esas2r_log(ESAS2R_LOG_WARN,
"write_hw kzalloc failed for %d bytes",
sizeof(struct atto_ioctl));
return -ENOMEM;
}
}
memset(a->local_atto_ioctl, 0, sizeof(struct atto_ioctl));
memcpy(a->local_atto_ioctl, buf, length);
return length;
}
#define ESAS2R_RW_BIN_ATTR(_name) \
struct bin_attribute bin_attr_ ## _name = { \
.attr = \
{ .name = __stringify(_name), .mode = S_IRUSR | S_IWUSR }, \
.size = 0, \
.read = read_ ## _name, \
.write = write_ ## _name }
ESAS2R_RW_BIN_ATTR(fw);
ESAS2R_RW_BIN_ATTR(fs);
ESAS2R_RW_BIN_ATTR(vda);
ESAS2R_RW_BIN_ATTR(hw);
ESAS2R_RW_BIN_ATTR(live_nvram);
struct bin_attribute bin_attr_default_nvram = {
.attr = { .name = "default_nvram", .mode = S_IRUGO },
.size = 0,
.read = read_default_nvram,
.write = NULL
};
static struct scsi_host_template driver_template = {
.module = THIS_MODULE,
.show_info = esas2r_show_info,
.name = ESAS2R_LONGNAME,
.release = esas2r_release,
.info = esas2r_info,
.ioctl = esas2r_ioctl,
.queuecommand = esas2r_queuecommand,
.eh_abort_handler = esas2r_eh_abort,
.eh_device_reset_handler = esas2r_device_reset,
.eh_bus_reset_handler = esas2r_bus_reset,
.eh_host_reset_handler = esas2r_host_reset,
.eh_target_reset_handler = esas2r_target_reset,
.can_queue = 128,
.this_id = -1,
.sg_tablesize = SCSI_MAX_SG_SEGMENTS,
.cmd_per_lun =
ESAS2R_DEFAULT_CMD_PER_LUN,
.present = 0,
.unchecked_isa_dma = 0,
.use_clustering = ENABLE_CLUSTERING,
.emulated = 0,
.proc_name = ESAS2R_DRVR_NAME,
.slave_configure = esas2r_slave_configure,
.slave_alloc = esas2r_slave_alloc,
.slave_destroy = esas2r_slave_destroy,
.change_queue_depth = esas2r_change_queue_depth,
.change_queue_type = esas2r_change_queue_type,
.max_sectors = 0xFFFF,
};
int sgl_page_size = 512;
module_param(sgl_page_size, int, 0);
MODULE_PARM_DESC(sgl_page_size,
"Scatter/gather list (SGL) page size in number of S/G "
"entries. If your application is doing a lot of very large "
"transfers, you may want to increase the SGL page size. "
"Default 512.");
int num_sg_lists = 1024;
module_param(num_sg_lists, int, 0);
MODULE_PARM_DESC(num_sg_lists,
"Number of scatter/gather lists. Default 1024.");
int sg_tablesize = SCSI_MAX_SG_SEGMENTS;
module_param(sg_tablesize, int, 0);
MODULE_PARM_DESC(sg_tablesize,
"Maximum number of entries in a scatter/gather table.");
int num_requests = 256;
module_param(num_requests, int, 0);
MODULE_PARM_DESC(num_requests,
"Number of requests. Default 256.");
int num_ae_requests = 4;
module_param(num_ae_requests, int, 0);
MODULE_PARM_DESC(num_ae_requests,
"Number of VDA asynchromous event requests. Default 4.");
int cmd_per_lun = ESAS2R_DEFAULT_CMD_PER_LUN;
module_param(cmd_per_lun, int, 0);
MODULE_PARM_DESC(cmd_per_lun,
"Maximum number of commands per LUN. Default "
DEFINED_NUM_TO_STR(ESAS2R_DEFAULT_CMD_PER_LUN) ".");
int can_queue = 128;
module_param(can_queue, int, 0);
MODULE_PARM_DESC(can_queue,
"Maximum number of commands per adapter. Default 128.");
int esas2r_max_sectors = 0xFFFF;
module_param(esas2r_max_sectors, int, 0);
MODULE_PARM_DESC(esas2r_max_sectors,
"Maximum number of disk sectors in a single data transfer. "
"Default 65535 (largest possible setting).");
int interrupt_mode = 1;
module_param(interrupt_mode, int, 0);
MODULE_PARM_DESC(interrupt_mode,
"Defines the interrupt mode to use. 0 for legacy"
", 1 for MSI. Default is MSI (1).");
static struct pci_device_id
esas2r_pci_table[] = {
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x0049,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004A,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004B,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004C,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004D,
0,
0, 0 },
{ ATTO_VENDOR_ID, 0x0049, ATTO_VENDOR_ID, 0x004E,
0,
0, 0 },
{ 0, 0, 0, 0,
0,
0, 0 }
};
MODULE_DEVICE_TABLE(pci, esas2r_pci_table);
static int
esas2r_probe(struct pci_dev *pcid, const struct pci_device_id *id);
static void
esas2r_remove(struct pci_dev *pcid);
static struct pci_driver
esas2r_pci_driver = {
.name = ESAS2R_DRVR_NAME,
.id_table = esas2r_pci_table,
.probe = esas2r_probe,
.remove = esas2r_remove,
.suspend = esas2r_suspend,
.resume = esas2r_resume,
};
static int esas2r_probe(struct pci_dev *pcid,
const struct pci_device_id *id)
{
struct Scsi_Host *host = NULL;
struct esas2r_adapter *a;
int err;
size_t host_alloc_size = sizeof(struct esas2r_adapter)
+ ((num_requests) +
1) * sizeof(struct esas2r_request);
esas2r_log_dev(ESAS2R_LOG_DEBG, &(pcid->dev),
"esas2r_probe() 0x%02x 0x%02x 0x%02x 0x%02x",
pcid->vendor,
pcid->device,
pcid->subsystem_vendor,
pcid->subsystem_device);
esas2r_log_dev(ESAS2R_LOG_INFO, &(pcid->dev),
"before pci_enable_device() "
"enable_cnt: %d",
pcid->enable_cnt.counter);
err = pci_enable_device(pcid);
if (err != 0) {
esas2r_log_dev(ESAS2R_LOG_CRIT, &(pcid->dev),
"pci_enable_device() FAIL (%d)",
err);
return -ENODEV;
}
esas2r_log_dev(ESAS2R_LOG_INFO, &(pcid->dev),
"pci_enable_device() OK");
esas2r_log_dev(ESAS2R_LOG_INFO, &(pcid->dev),
"after pci_enable_device() enable_cnt: %d",
pcid->enable_cnt.counter);
host = scsi_host_alloc(&driver_template, host_alloc_size);
if (host == NULL) {
esas2r_log(ESAS2R_LOG_CRIT, "scsi_host_alloc() FAIL");
return -ENODEV;
}
memset(host->hostdata, 0, host_alloc_size);
a = (struct esas2r_adapter *)host->hostdata;
esas2r_log(ESAS2R_LOG_INFO, "scsi_host_alloc() OK host: %p", host);
/* override max LUN and max target id */
host->max_id = ESAS2R_MAX_ID + 1;
host->max_lun = 255;
/* we can handle 16-byte CDbs */
host->max_cmd_len = 16;
host->can_queue = can_queue;
host->cmd_per_lun = cmd_per_lun;
host->this_id = host->max_id + 1;
host->max_channel = 0;
host->unique_id = found_adapters;
host->sg_tablesize = sg_tablesize;
host->max_sectors = esas2r_max_sectors;
/* set to bus master for BIOses that don't do it for us */
esas2r_log(ESAS2R_LOG_INFO, "pci_set_master() called");
pci_set_master(pcid);
if (!esas2r_init_adapter(host, pcid, found_adapters)) {
esas2r_log(ESAS2R_LOG_CRIT,
"unable to initialize device at PCI bus %x:%x",
pcid->bus->number,
pcid->devfn);
esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
"scsi_host_put() called");
scsi_host_put(host);
return 0;
}
esas2r_log(ESAS2R_LOG_INFO, "pci_set_drvdata(%p, %p) called", pcid,
host->hostdata);
pci_set_drvdata(pcid, host);
esas2r_log(ESAS2R_LOG_INFO, "scsi_add_host() called");
err = scsi_add_host(host, &pcid->dev);
if (err) {
esas2r_log(ESAS2R_LOG_CRIT, "scsi_add_host returned %d", err);
esas2r_log_dev(ESAS2R_LOG_CRIT, &(host->shost_gendev),
"scsi_add_host() FAIL");
esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
"scsi_host_put() called");
scsi_host_put(host);
esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
"pci_set_drvdata(%p, NULL) called",
pcid);
pci_set_drvdata(pcid, NULL);
return -ENODEV;
}
esas2r_fw_event_on(a);
esas2r_log_dev(ESAS2R_LOG_INFO, &(host->shost_gendev),
"scsi_scan_host() called");
scsi_scan_host(host);
/* Add sysfs binary files */
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_fw))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: fw");
else
a->sysfs_fw_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_fs))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: fs");
else
a->sysfs_fs_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_vda))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: vda");
else
a->sysfs_vda_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_hw))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: hw");
else
a->sysfs_hw_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj, &bin_attr_live_nvram))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: live_nvram");
else
a->sysfs_live_nvram_created = 1;
if (sysfs_create_bin_file(&host->shost_dev.kobj,
&bin_attr_default_nvram))
esas2r_log_dev(ESAS2R_LOG_WARN, &(host->shost_gendev),
"Failed to create sysfs binary file: default_nvram");
else
a->sysfs_default_nvram_created = 1;
found_adapters++;
return 0;
}
static void esas2r_remove(struct pci_dev *pdev)
{
struct Scsi_Host *host;
int index;
if (pdev == NULL) {
esas2r_log(ESAS2R_LOG_WARN, "esas2r_remove pdev==NULL");
return;
}
host = pci_get_drvdata(pdev);
if (host == NULL) {
/*
* this can happen if pci_set_drvdata was already called
* to clear the host pointer. if this is the case, we
* are okay; this channel has already been cleaned up.
*/
return;
}
esas2r_log_dev(ESAS2R_LOG_INFO, &(pdev->dev),
"esas2r_remove(%p) called; "
"host:%p", pdev,
host);
index = esas2r_cleanup(host);
if (index < 0)
esas2r_log_dev(ESAS2R_LOG_WARN, &(pdev->dev),
"unknown host in %s",
__func__);
found_adapters--;
/* if this was the last adapter, clean up the rest of the driver */
if (found_adapters == 0)
esas2r_cleanup(NULL);
}
static int __init esas2r_init(void)
{
int i;
esas2r_log(ESAS2R_LOG_INFO, "%s called", __func__);
/* verify valid parameters */
if (can_queue < 1) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: can_queue must be at least 1, value "
"forced.");
can_queue = 1;
} else if (can_queue > 2048) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: can_queue must be no larger than 2048, "
"value forced.");
can_queue = 2048;
}
if (cmd_per_lun < 1) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: cmd_per_lun must be at least 1, value "
"forced.");
cmd_per_lun = 1;
} else if (cmd_per_lun > 2048) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: cmd_per_lun must be no larger than "
"2048, value forced.");
cmd_per_lun = 2048;
}
if (sg_tablesize < 32) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: sg_tablesize must be at least 32, "
"value forced.");
sg_tablesize = 32;
}
if (esas2r_max_sectors < 1) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: esas2r_max_sectors must be at least "
"1, value forced.");
esas2r_max_sectors = 1;
} else if (esas2r_max_sectors > 0xffff) {
esas2r_log(ESAS2R_LOG_WARN,
"warning: esas2r_max_sectors must be no larger "
"than 0xffff, value forced.");
esas2r_max_sectors = 0xffff;
}
sgl_page_size &= ~(ESAS2R_SGL_ALIGN - 1);
if (sgl_page_size < SGL_PG_SZ_MIN)
sgl_page_size = SGL_PG_SZ_MIN;
else if (sgl_page_size > SGL_PG_SZ_MAX)
sgl_page_size = SGL_PG_SZ_MAX;
if (num_sg_lists < NUM_SGL_MIN)
num_sg_lists = NUM_SGL_MIN;
else if (num_sg_lists > NUM_SGL_MAX)
num_sg_lists = NUM_SGL_MAX;
if (num_requests < NUM_REQ_MIN)
num_requests = NUM_REQ_MIN;
else if (num_requests > NUM_REQ_MAX)
num_requests = NUM_REQ_MAX;
if (num_ae_requests < NUM_AE_MIN)
num_ae_requests = NUM_AE_MIN;
else if (num_ae_requests > NUM_AE_MAX)
num_ae_requests = NUM_AE_MAX;
/* set up other globals */
for (i = 0; i < MAX_ADAPTERS; i++)
esas2r_adapters[i] = NULL;
/* initialize */
driver_template.module = THIS_MODULE;
if (pci_register_driver(&esas2r_pci_driver) != 0)
esas2r_log(ESAS2R_LOG_CRIT, "pci_register_driver FAILED");
else
esas2r_log(ESAS2R_LOG_INFO, "pci_register_driver() OK");
if (!found_adapters) {
pci_unregister_driver(&esas2r_pci_driver);
esas2r_cleanup(NULL);
esas2r_log(ESAS2R_LOG_CRIT,
"driver will not be loaded because no ATTO "
"%s devices were found",
ESAS2R_DRVR_NAME);
return -1;
} else {
esas2r_log(ESAS2R_LOG_INFO, "found %d adapters",
found_adapters);
}
return 0;
}
/* Handle ioctl calls to "/proc/scsi/esas2r/ATTOnode" */
static const struct file_operations esas2r_proc_fops = {
.compat_ioctl = esas2r_proc_ioctl,
.unlocked_ioctl = esas2r_proc_ioctl,
};
static struct Scsi_Host *esas2r_proc_host;
static int esas2r_proc_major;
long esas2r_proc_ioctl(struct file *fp, unsigned int cmd, unsigned long arg)
{
return esas2r_ioctl_handler(esas2r_proc_host->hostdata,
(int)cmd, (void __user *)arg);
}
static void __exit esas2r_exit(void)
{
esas2r_log(ESAS2R_LOG_INFO, "%s called", __func__);
if (esas2r_proc_major > 0) {
esas2r_log(ESAS2R_LOG_INFO, "unregister proc");
remove_proc_entry(ATTONODE_NAME,
esas2r_proc_host->hostt->proc_dir);
unregister_chrdev(esas2r_proc_major, ESAS2R_DRVR_NAME);
esas2r_proc_major = 0;
}
esas2r_log(ESAS2R_LOG_INFO, "pci_unregister_driver() called");
pci_unregister_driver(&esas2r_pci_driver);
}
int esas2r_show_info(struct seq_file *m, struct Scsi_Host *sh)
{
struct esas2r_adapter *a = (struct esas2r_adapter *)sh->hostdata;
struct esas2r_target *t;
int dev_count = 0;
esas2r_log(ESAS2R_LOG_DEBG, "esas2r_show_info (%p,%d)", m, sh->host_no);
seq_printf(m, ESAS2R_LONGNAME "\n"
"Driver version: "ESAS2R_VERSION_STR "\n"
"Flash version: %s\n"
"Firmware version: %s\n"
"Copyright "ESAS2R_COPYRIGHT_YEARS "\n"
"http://www.attotech.com\n"
"\n",
a->flash_rev,
a->fw_rev[0] ? a->fw_rev : "(none)");
seq_printf(m, "Adapter information:\n"
"--------------------\n"
"Model: %s\n"
"SAS address: %02X%02X%02X%02X:%02X%02X%02X%02X\n",
esas2r_get_model_name(a),
a->nvram->sas_addr[0],
a->nvram->sas_addr[1],
a->nvram->sas_addr[2],
a->nvram->sas_addr[3],
a->nvram->sas_addr[4],
a->nvram->sas_addr[5],
a->nvram->sas_addr[6],
a->nvram->sas_addr[7]);
seq_puts(m, "\n"
"Discovered devices:\n"
"\n"
" # Target ID\n"
"---------------\n");
for (t = a->targetdb; t < a->targetdb_end; t++)
if (t->buffered_target_state == TS_PRESENT) {
seq_printf(m, " %3d %3d\n",
++dev_count,
(u16)(uintptr_t)(t - a->targetdb));
}
if (dev_count == 0)
seq_puts(m, "none\n");
seq_puts(m, "\n");
return 0;
}
int esas2r_release(struct Scsi_Host *sh)
{
esas2r_log_dev(ESAS2R_LOG_INFO, &(sh->shost_gendev),
"esas2r_release() called");
esas2r_cleanup(sh);
if (sh->irq)
free_irq(sh->irq, NULL);
scsi_unregister(sh);
return 0;
}
const char *esas2r_info(struct Scsi_Host *sh)
{
struct esas2r_adapter *a = (struct esas2r_adapter *)sh->hostdata;
static char esas2r_info_str[512];
esas2r_log_dev(ESAS2R_LOG_INFO, &(sh->shost_gendev),
"esas2r_info() called");
/*
* if we haven't done so already, register as a char driver
* and stick a node under "/proc/scsi/esas2r/ATTOnode"
*/
if (esas2r_proc_major <= 0) {
esas2r_proc_host = sh;
esas2r_proc_major = register_chrdev(0, ESAS2R_DRVR_NAME,
&esas2r_proc_fops);
esas2r_log_dev(ESAS2R_LOG_DEBG, &(sh->shost_gendev),
"register_chrdev (major %d)",
esas2r_proc_major);
if (esas2r_proc_major > 0) {
struct proc_dir_entry *pde;
pde = proc_create(ATTONODE_NAME, 0,
sh->hostt->proc_dir,
&esas2r_proc_fops);
if (!pde) {
esas2r_log_dev(ESAS2R_LOG_WARN,
&(sh->shost_gendev),
"failed to create_proc_entry");
esas2r_proc_major = -1;
}
}
}
sprintf(esas2r_info_str,
ESAS2R_LONGNAME " (bus 0x%02X, device 0x%02X, IRQ 0x%02X)"
" driver version: "ESAS2R_VERSION_STR " firmware version: "
"%s\n",
a->pcid->bus->number, a->pcid->devfn, a->pcid->irq,
a->fw_rev[0] ? a->fw_rev : "(none)");
return esas2r_info_str;
}
/* Callback for building a request scatter/gather list */
static u32 get_physaddr_from_sgc(struct esas2r_sg_context *sgc, u64 *addr)
{
u32 len;
if (likely(sgc->cur_offset == sgc->exp_offset)) {
/*
* the normal case: caller used all bytes from previous call, so
* expected offset is the same as the current offset.
*/
if (sgc->sgel_count < sgc->num_sgel) {
/* retrieve next segment, except for first time */
if (sgc->exp_offset > (u8 *)0) {
/* advance current segment */
sgc->cur_sgel = sg_next(sgc->cur_sgel);
++(sgc->sgel_count);
}
len = sg_dma_len(sgc->cur_sgel);
(*addr) = sg_dma_address(sgc->cur_sgel);
/* save the total # bytes returned to caller so far */
sgc->exp_offset += len;
} else {
len = 0;
}
} else if (sgc->cur_offset < sgc->exp_offset) {
/*
* caller did not use all bytes from previous call. need to
* compute the address based on current segment.
*/
len = sg_dma_len(sgc->cur_sgel);
(*addr) = sg_dma_address(sgc->cur_sgel);
sgc->exp_offset -= len;
/* calculate PA based on prev segment address and offsets */
*addr = *addr +
(sgc->cur_offset - sgc->exp_offset);
sgc->exp_offset += len;
/* re-calculate length based on offset */
len = lower_32_bits(
sgc->exp_offset - sgc->cur_offset);
} else { /* if ( sgc->cur_offset > sgc->exp_offset ) */
/*
* we don't expect the caller to skip ahead.
* cur_offset will never exceed the len we return
*/
len = 0;
}
return len;
}
int esas2r_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *cmd)
{
struct esas2r_adapter *a =
(struct esas2r_adapter *)cmd->device->host->hostdata;
struct esas2r_request *rq;
struct esas2r_sg_context sgc;
unsigned bufflen;
/* Assume success, if it fails we will fix the result later. */
cmd->result = DID_OK << 16;
if (unlikely(test_bit(AF_DEGRADED_MODE, &a->flags))) {
cmd->result = DID_NO_CONNECT << 16;
cmd->scsi_done(cmd);
return 0;
}
rq = esas2r_alloc_request(a);
if (unlikely(rq == NULL)) {
esas2r_debug("esas2r_alloc_request failed");
return SCSI_MLQUEUE_HOST_BUSY;
}
rq->cmd = cmd;
bufflen = scsi_bufflen(cmd);
if (likely(bufflen != 0)) {
if (cmd->sc_data_direction == DMA_TO_DEVICE)
rq->vrq->scsi.flags |= cpu_to_le32(FCP_CMND_WRD);
else if (cmd->sc_data_direction == DMA_FROM_DEVICE)
rq->vrq->scsi.flags |= cpu_to_le32(FCP_CMND_RDD);
}
memcpy(rq->vrq->scsi.cdb, cmd->cmnd, cmd->cmd_len);
rq->vrq->scsi.length = cpu_to_le32(bufflen);
rq->target_id = cmd->device->id;
rq->vrq->scsi.flags |= cpu_to_le32(cmd->device->lun);
rq->sense_buf = cmd->sense_buffer;
rq->sense_len = SCSI_SENSE_BUFFERSIZE;
esas2r_sgc_init(&sgc, a, rq, NULL);
sgc.length = bufflen;
sgc.cur_offset = NULL;
sgc.cur_sgel = scsi_sglist(cmd);
sgc.exp_offset = NULL;
sgc.num_sgel = scsi_dma_map(cmd);
sgc.sgel_count = 0;
if (unlikely(sgc.num_sgel < 0)) {
esas2r_free_request(a, rq);
return SCSI_MLQUEUE_HOST_BUSY;
}
sgc.get_phys_addr = (PGETPHYSADDR)get_physaddr_from_sgc;
if (unlikely(!esas2r_build_sg_list(a, rq, &sgc))) {
scsi_dma_unmap(cmd);
esas2r_free_request(a, rq);
return SCSI_MLQUEUE_HOST_BUSY;
}
esas2r_debug("start request %p to %d:%d\n", rq, (int)cmd->device->id,
(int)cmd->device->lun);
esas2r_start_request(a, rq);
return 0;
}
static void complete_task_management_request(struct esas2r_adapter *a,
struct esas2r_request *rq)
{
(*rq->task_management_status_ptr) = rq->req_stat;
esas2r_free_request(a, rq);
}
/**
* Searches the specified queue for the specified queue for the command
* to abort.
*
* @param [in] a
* @param [in] abort_request
* @param [in] cmd
* t
* @return 0 on failure, 1 if command was not found, 2 if command was found
*/
static int esas2r_check_active_queue(struct esas2r_adapter *a,
struct esas2r_request **abort_request,
struct scsi_cmnd *cmd,
struct list_head *queue)
{
bool found = false;
struct esas2r_request *ar = *abort_request;
struct esas2r_request *rq;
struct list_head *element, *next;
list_for_each_safe(element, next, queue) {
rq = list_entry(element, struct esas2r_request, req_list);
if (rq->cmd == cmd) {
/* Found the request. See what to do with it. */
if (queue == &a->active_list) {
/*
* We are searching the active queue, which
* means that we need to send an abort request
* to the firmware.
*/
ar = esas2r_alloc_request(a);
if (ar == NULL) {
esas2r_log_dev(ESAS2R_LOG_WARN,
&(a->host->shost_gendev),
"unable to allocate an abort request for cmd %p",
cmd);
return 0; /* Failure */
}
/*
* Task management request must be formatted
* with a lock held.
*/
ar->sense_len = 0;
ar->vrq->scsi.length = 0;
ar->target_id = rq->target_id;
ar->vrq->scsi.flags |= cpu_to_le32(
(u8)le32_to_cpu(rq->vrq->scsi.flags));
memset(ar->vrq->scsi.cdb, 0,
sizeof(ar->vrq->scsi.cdb));
ar->vrq->scsi.flags |= cpu_to_le32(
FCP_CMND_TRM);
ar->vrq->scsi.u.abort_handle =
rq->vrq->scsi.handle;
} else {
/*
* The request is pending but not active on
* the firmware. Just free it now and we'll
* report the successful abort below.
*/
list_del_init(&rq->req_list);
esas2r_free_request(a, rq);
}
found = true;
break;
}
}
if (!found)
return 1; /* Not found */
return 2; /* found */
}
int esas2r_eh_abort(struct scsi_cmnd *cmd)
{
struct esas2r_adapter *a =
(struct esas2r_adapter *)cmd->device->host->hostdata;
struct esas2r_request *abort_request = NULL;
unsigned long flags;
struct list_head *queue;
int result;
esas2r_log(ESAS2R_LOG_INFO, "eh_abort (%p)", cmd);
if (test_bit(AF_DEGRADED_MODE, &a->flags)) {
cmd->result = DID_ABORT << 16;
scsi_set_resid(cmd, 0);
cmd->scsi_done(cmd);
return 0;
}
spin_lock_irqsave(&a->queue_lock, flags);
/*
* Run through the defer and active queues looking for the request
* to abort.
*/
queue = &a->defer_list;
check_active_queue:
result = esas2r_check_active_queue(a, &abort_request, cmd, queue);
if (!result) {
spin_unlock_irqrestore(&a->queue_lock, flags);
return FAILED;
} else if (result == 2 && (queue == &a->defer_list)) {
queue = &a->active_list;
goto check_active_queue;
}
spin_unlock_irqrestore(&a->queue_lock, flags);
if (abort_request) {
u8 task_management_status = RS_PENDING;
/*
* the request is already active, so we need to tell
* the firmware to abort it and wait for the response.
*/
abort_request->comp_cb = complete_task_management_request;
abort_request->task_management_status_ptr =
&task_management_status;
esas2r_start_request(a, abort_request);
if (atomic_read(&a->disable_cnt) == 0)
esas2r_do_deferred_processes(a);
while (task_management_status == RS_PENDING)
msleep(10);
/*
* Once we get here, the original request will have been
* completed by the firmware and the abort request will have
* been cleaned up. we're done!
*/
return SUCCESS;
}
/*
* If we get here, either we found the inactive request and
* freed it, or we didn't find it at all. Either way, success!
*/
cmd->result = DID_ABORT << 16;
scsi_set_resid(cmd, 0);
cmd->scsi_done(cmd);
return SUCCESS;
}
static int esas2r_host_bus_reset(struct scsi_cmnd *cmd, bool host_reset)
{
struct esas2r_adapter *a =
(struct esas2r_adapter *)cmd->device->host->hostdata;
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
if (host_reset)
esas2r_reset_adapter(a);
else
esas2r_reset_bus(a);
/* above call sets the AF_OS_RESET flag. wait for it to clear. */
while (test_bit(AF_OS_RESET, &a->flags)) {
msleep(10);
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
}
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
return SUCCESS;
}
int esas2r_host_reset(struct scsi_cmnd *cmd)
{
esas2r_log(ESAS2R_LOG_INFO, "host_reset (%p)", cmd);
return esas2r_host_bus_reset(cmd, true);
}
int esas2r_bus_reset(struct scsi_cmnd *cmd)
{
esas2r_log(ESAS2R_LOG_INFO, "bus_reset (%p)", cmd);
return esas2r_host_bus_reset(cmd, false);
}
static int esas2r_dev_targ_reset(struct scsi_cmnd *cmd, bool target_reset)
{
struct esas2r_adapter *a =
(struct esas2r_adapter *)cmd->device->host->hostdata;
struct esas2r_request *rq;
u8 task_management_status = RS_PENDING;
bool completed;
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
retry:
rq = esas2r_alloc_request(a);
if (rq == NULL) {
if (target_reset) {
esas2r_log(ESAS2R_LOG_CRIT,
"unable to allocate a request for a "
"target reset (%d)!",
cmd->device->id);
} else {
esas2r_log(ESAS2R_LOG_CRIT,
"unable to allocate a request for a "
"device reset (%d:%d)!",
cmd->device->id,
cmd->device->lun);
}
return FAILED;
}
rq->target_id = cmd->device->id;
rq->vrq->scsi.flags |= cpu_to_le32(cmd->device->lun);
rq->req_stat = RS_PENDING;
rq->comp_cb = complete_task_management_request;
rq->task_management_status_ptr = &task_management_status;
if (target_reset) {
esas2r_debug("issuing target reset (%p) to id %d", rq,
cmd->device->id);
completed = esas2r_send_task_mgmt(a, rq, 0x20);
} else {
esas2r_debug("issuing device reset (%p) to id %d lun %d", rq,
cmd->device->id, cmd->device->lun);
completed = esas2r_send_task_mgmt(a, rq, 0x10);
}
if (completed) {
/* Task management cmd completed right away, need to free it. */
esas2r_free_request(a, rq);
} else {
/*
* Wait for firmware to complete the request. Completion
* callback will free it.
*/
while (task_management_status == RS_PENDING)
msleep(10);
}
if (test_bit(AF_DEGRADED_MODE, &a->flags))
return FAILED;
if (task_management_status == RS_BUSY) {
/*
* Busy, probably because we are flashing. Wait a bit and
* try again.
*/
msleep(100);
goto retry;
}
return SUCCESS;
}
int esas2r_device_reset(struct scsi_cmnd *cmd)
{
esas2r_log(ESAS2R_LOG_INFO, "device_reset (%p)", cmd);
return esas2r_dev_targ_reset(cmd, false);
}
int esas2r_target_reset(struct scsi_cmnd *cmd)
{
esas2r_log(ESAS2R_LOG_INFO, "target_reset (%p)", cmd);
return esas2r_dev_targ_reset(cmd, true);
}
int esas2r_change_queue_depth(struct scsi_device *dev, int depth, int reason)
{
esas2r_log(ESAS2R_LOG_INFO, "change_queue_depth %p, %d", dev, depth);
scsi_adjust_queue_depth(dev, scsi_get_tag_type(dev), depth);
return dev->queue_depth;
}
int esas2r_change_queue_type(struct scsi_device *dev, int type)
{
esas2r_log(ESAS2R_LOG_INFO, "change_queue_type %p, %d", dev, type);
if (dev->tagged_supported) {
scsi_set_tag_type(dev, type);
if (type)
scsi_activate_tcq(dev, dev->queue_depth);
else
scsi_deactivate_tcq(dev, dev->queue_depth);
} else {
type = 0;
}
return type;
}
int esas2r_slave_alloc(struct scsi_device *dev)
{
return 0;
}
int esas2r_slave_configure(struct scsi_device *dev)
{
esas2r_log_dev(ESAS2R_LOG_INFO, &(dev->sdev_gendev),
"esas2r_slave_configure()");
if (dev->tagged_supported) {
scsi_set_tag_type(dev, MSG_SIMPLE_TAG);
scsi_activate_tcq(dev, cmd_per_lun);
} else {
scsi_set_tag_type(dev, 0);
scsi_deactivate_tcq(dev, cmd_per_lun);
}
return 0;
}
void esas2r_slave_destroy(struct scsi_device *dev)
{
esas2r_log_dev(ESAS2R_LOG_INFO, &(dev->sdev_gendev),
"esas2r_slave_destroy()");
}
void esas2r_log_request_failure(struct esas2r_adapter *a,
struct esas2r_request *rq)
{
u8 reqstatus = rq->req_stat;
if (reqstatus == RS_SUCCESS)
return;
if (rq->vrq->scsi.function == VDA_FUNC_SCSI) {
if (reqstatus == RS_SCSI_ERROR) {
if (rq->func_rsp.scsi_rsp.sense_len >= 13) {
esas2r_log(ESAS2R_LOG_WARN,
"request failure - SCSI error %x ASC:%x ASCQ:%x CDB:%x",
rq->sense_buf[2], rq->sense_buf[12],
rq->sense_buf[13],
rq->vrq->scsi.cdb[0]);
} else {
esas2r_log(ESAS2R_LOG_WARN,
"request failure - SCSI error CDB:%x\n",
rq->vrq->scsi.cdb[0]);
}
} else if ((rq->vrq->scsi.cdb[0] != INQUIRY
&& rq->vrq->scsi.cdb[0] != REPORT_LUNS)
|| (reqstatus != RS_SEL
&& reqstatus != RS_SEL2)) {
if ((reqstatus == RS_UNDERRUN) &&
(rq->vrq->scsi.cdb[0] == INQUIRY)) {
/* Don't log inquiry underruns */
} else {
esas2r_log(ESAS2R_LOG_WARN,
"request failure - cdb:%x reqstatus:%d target:%d",
rq->vrq->scsi.cdb[0], reqstatus,
rq->target_id);
}
}
}
}
void esas2r_wait_request(struct esas2r_adapter *a, struct esas2r_request *rq)
{
u32 starttime;
u32 timeout;
starttime = jiffies_to_msecs(jiffies);
timeout = rq->timeout ? rq->timeout : 5000;
while (true) {
esas2r_polled_interrupt(a);
if (rq->req_stat != RS_STARTED)
break;
schedule_timeout_interruptible(msecs_to_jiffies(100));
if ((jiffies_to_msecs(jiffies) - starttime) > timeout) {
esas2r_hdebug("request TMO");
esas2r_bugon();
rq->req_stat = RS_TIMEOUT;
esas2r_local_reset_adapter(a);
return;
}
}
}
u32 esas2r_map_data_window(struct esas2r_adapter *a, u32 addr_lo)
{
u32 offset = addr_lo & (MW_DATA_WINDOW_SIZE - 1);
u32 base = addr_lo & -(signed int)MW_DATA_WINDOW_SIZE;
if (a->window_base != base) {
esas2r_write_register_dword(a, MVR_PCI_WIN1_REMAP,
base | MVRPW1R_ENABLE);
esas2r_flush_register_dword(a, MVR_PCI_WIN1_REMAP);
a->window_base = base;
}
return offset;
}
/* Read a block of data from chip memory */
bool esas2r_read_mem_block(struct esas2r_adapter *a,
void *to,
u32 from,
u32 size)
{
u8 *end = (u8 *)to;
while (size) {
u32 len;
u32 offset;
u32 iatvr;
iatvr = (from & -(signed int)MW_DATA_WINDOW_SIZE);
esas2r_map_data_window(a, iatvr);
offset = from & (MW_DATA_WINDOW_SIZE - 1);
len = size;
if (len > MW_DATA_WINDOW_SIZE - offset)
len = MW_DATA_WINDOW_SIZE - offset;
from += len;
size -= len;
while (len--) {
*end++ = esas2r_read_data_byte(a, offset);
offset++;
}
}
return true;
}
void esas2r_nuxi_mgt_data(u8 function, void *data)
{
struct atto_vda_grp_info *g;
struct atto_vda_devinfo *d;
struct atto_vdapart_info *p;
struct atto_vda_dh_info *h;
struct atto_vda_metrics_info *m;
struct atto_vda_schedule_info *s;
struct atto_vda_buzzer_info *b;
u8 i;
switch (function) {
case VDAMGT_BUZZER_INFO:
case VDAMGT_BUZZER_SET:
b = (struct atto_vda_buzzer_info *)data;
b->duration = le32_to_cpu(b->duration);
break;
case VDAMGT_SCHEDULE_INFO:
case VDAMGT_SCHEDULE_EVENT:
s = (struct atto_vda_schedule_info *)data;
s->id = le32_to_cpu(s->id);
break;
case VDAMGT_DEV_INFO:
case VDAMGT_DEV_CLEAN:
case VDAMGT_DEV_PT_INFO:
case VDAMGT_DEV_FEATURES:
case VDAMGT_DEV_PT_FEATURES:
case VDAMGT_DEV_OPERATION:
d = (struct atto_vda_devinfo *)data;
d->capacity = le64_to_cpu(d->capacity);
d->block_size = le32_to_cpu(d->block_size);
d->ses_dev_index = le16_to_cpu(d->ses_dev_index);
d->target_id = le16_to_cpu(d->target_id);
d->lun = le16_to_cpu(d->lun);
d->features = le16_to_cpu(d->features);
break;
case VDAMGT_GRP_INFO:
case VDAMGT_GRP_CREATE:
case VDAMGT_GRP_DELETE:
case VDAMGT_ADD_STORAGE:
case VDAMGT_MEMBER_ADD:
case VDAMGT_GRP_COMMIT:
case VDAMGT_GRP_REBUILD:
case VDAMGT_GRP_COMMIT_INIT:
case VDAMGT_QUICK_RAID:
case VDAMGT_GRP_FEATURES:
case VDAMGT_GRP_COMMIT_INIT_AUTOMAP:
case VDAMGT_QUICK_RAID_INIT_AUTOMAP:
case VDAMGT_SPARE_LIST:
case VDAMGT_SPARE_ADD:
case VDAMGT_SPARE_REMOVE:
case VDAMGT_LOCAL_SPARE_ADD:
case VDAMGT_GRP_OPERATION:
g = (struct atto_vda_grp_info *)data;
g->capacity = le64_to_cpu(g->capacity);
g->block_size = le32_to_cpu(g->block_size);
g->interleave = le32_to_cpu(g->interleave);
g->features = le16_to_cpu(g->features);
for (i = 0; i < 32; i++)
g->members[i] = le16_to_cpu(g->members[i]);
break;
case VDAMGT_PART_INFO:
case VDAMGT_PART_MAP:
case VDAMGT_PART_UNMAP:
case VDAMGT_PART_AUTOMAP:
case VDAMGT_PART_SPLIT:
case VDAMGT_PART_MERGE:
p = (struct atto_vdapart_info *)data;
p->part_size = le64_to_cpu(p->part_size);
p->start_lba = le32_to_cpu(p->start_lba);
p->block_size = le32_to_cpu(p->block_size);
p->target_id = le16_to_cpu(p->target_id);
break;
case VDAMGT_DEV_HEALTH_REQ:
h = (struct atto_vda_dh_info *)data;
h->med_defect_cnt = le32_to_cpu(h->med_defect_cnt);
h->info_exc_cnt = le32_to_cpu(h->info_exc_cnt);
break;
case VDAMGT_DEV_METRICS:
m = (struct atto_vda_metrics_info *)data;
for (i = 0; i < 32; i++)
m->dev_indexes[i] = le16_to_cpu(m->dev_indexes[i]);
break;
default:
break;
}
}
void esas2r_nuxi_cfg_data(u8 function, void *data)
{
struct atto_vda_cfg_init *ci;
switch (function) {
case VDA_CFG_INIT:
case VDA_CFG_GET_INIT:
case VDA_CFG_GET_INIT2:
ci = (struct atto_vda_cfg_init *)data;
ci->date_time.year = le16_to_cpu(ci->date_time.year);
ci->sgl_page_size = le32_to_cpu(ci->sgl_page_size);
ci->vda_version = le32_to_cpu(ci->vda_version);
ci->epoch_time = le32_to_cpu(ci->epoch_time);
ci->ioctl_tunnel = le32_to_cpu(ci->ioctl_tunnel);
ci->num_targets_backend = le32_to_cpu(ci->num_targets_backend);
break;
default:
break;
}
}
void esas2r_nuxi_ae_data(union atto_vda_ae *ae)
{
struct atto_vda_ae_raid *r = &ae->raid;
struct atto_vda_ae_lu *l = &ae->lu;
switch (ae->hdr.bytype) {
case VDAAE_HDR_TYPE_RAID:
r->dwflags = le32_to_cpu(r->dwflags);
break;
case VDAAE_HDR_TYPE_LU:
l->dwevent = le32_to_cpu(l->dwevent);
l->wphys_target_id = le16_to_cpu(l->wphys_target_id);
l->id.tgtlun.wtarget_id = le16_to_cpu(l->id.tgtlun.wtarget_id);
if (l->hdr.bylength >= offsetof(struct atto_vda_ae_lu, id)
+ sizeof(struct atto_vda_ae_lu_tgt_lun_raid)) {
l->id.tgtlun_raid.dwinterleave
= le32_to_cpu(l->id.tgtlun_raid.dwinterleave);
l->id.tgtlun_raid.dwblock_size
= le32_to_cpu(l->id.tgtlun_raid.dwblock_size);
}
break;
case VDAAE_HDR_TYPE_DISK:
default:
break;
}
}
void esas2r_free_request(struct esas2r_adapter *a, struct esas2r_request *rq)
{
unsigned long flags;
esas2r_rq_destroy_request(rq, a);
spin_lock_irqsave(&a->request_lock, flags);
list_add(&rq->comp_list, &a->avail_request);
spin_unlock_irqrestore(&a->request_lock, flags);
}
struct esas2r_request *esas2r_alloc_request(struct esas2r_adapter *a)
{
struct esas2r_request *rq;
unsigned long flags;
spin_lock_irqsave(&a->request_lock, flags);
if (unlikely(list_empty(&a->avail_request))) {
spin_unlock_irqrestore(&a->request_lock, flags);
return NULL;
}
rq = list_first_entry(&a->avail_request, struct esas2r_request,
comp_list);
list_del(&rq->comp_list);
spin_unlock_irqrestore(&a->request_lock, flags);
esas2r_rq_init_request(rq, a);
return rq;
}
void esas2r_complete_request_cb(struct esas2r_adapter *a,
struct esas2r_request *rq)
{
esas2r_debug("completing request %p\n", rq);
scsi_dma_unmap(rq->cmd);
if (unlikely(rq->req_stat != RS_SUCCESS)) {
esas2r_debug("[%x STATUS %x:%x (%x)]", rq->target_id,
rq->req_stat,
rq->func_rsp.scsi_rsp.scsi_stat,
rq->cmd);
rq->cmd->result =
((esas2r_req_status_to_error(rq->req_stat) << 16)
| (rq->func_rsp.scsi_rsp.scsi_stat & STATUS_MASK));
if (rq->req_stat == RS_UNDERRUN)
scsi_set_resid(rq->cmd,
le32_to_cpu(rq->func_rsp.scsi_rsp.
residual_length));
else
scsi_set_resid(rq->cmd, 0);
}
rq->cmd->scsi_done(rq->cmd);
esas2r_free_request(a, rq);
}
/* Run tasklet to handle stuff outside of interrupt context. */
void esas2r_adapter_tasklet(unsigned long context)
{
struct esas2r_adapter *a = (struct esas2r_adapter *)context;
if (unlikely(test_bit(AF2_TIMER_TICK, &a->flags2))) {
clear_bit(AF2_TIMER_TICK, &a->flags2);
esas2r_timer_tick(a);
}
if (likely(test_bit(AF2_INT_PENDING, &a->flags2))) {
clear_bit(AF2_INT_PENDING, &a->flags2);
esas2r_adapter_interrupt(a);
}
if (esas2r_is_tasklet_pending(a))
esas2r_do_tasklet_tasks(a);
if (esas2r_is_tasklet_pending(a)
|| (test_bit(AF2_INT_PENDING, &a->flags2))
|| (test_bit(AF2_TIMER_TICK, &a->flags2))) {
clear_bit(AF_TASKLET_SCHEDULED, &a->flags);
esas2r_schedule_tasklet(a);
} else {
clear_bit(AF_TASKLET_SCHEDULED, &a->flags);
}
}
static void esas2r_timer_callback(unsigned long context);
void esas2r_kickoff_timer(struct esas2r_adapter *a)
{
init_timer(&a->timer);
a->timer.function = esas2r_timer_callback;
a->timer.data = (unsigned long)a;
a->timer.expires = jiffies +
msecs_to_jiffies(100);
add_timer(&a->timer);
}
static void esas2r_timer_callback(unsigned long context)
{
struct esas2r_adapter *a = (struct esas2r_adapter *)context;
set_bit(AF2_TIMER_TICK, &a->flags2);
esas2r_schedule_tasklet(a);
esas2r_kickoff_timer(a);
}
/*
* Firmware events need to be handled outside of interrupt context
* so we schedule a delayed_work to handle them.
*/
static void
esas2r_free_fw_event(struct esas2r_fw_event_work *fw_event)
{
unsigned long flags;
struct esas2r_adapter *a = fw_event->a;
spin_lock_irqsave(&a->fw_event_lock, flags);
list_del(&fw_event->list);
kfree(fw_event);
spin_unlock_irqrestore(&a->fw_event_lock, flags);
}
void
esas2r_fw_event_off(struct esas2r_adapter *a)
{
unsigned long flags;
spin_lock_irqsave(&a->fw_event_lock, flags);
a->fw_events_off = 1;
spin_unlock_irqrestore(&a->fw_event_lock, flags);
}
void
esas2r_fw_event_on(struct esas2r_adapter *a)
{
unsigned long flags;
spin_lock_irqsave(&a->fw_event_lock, flags);
a->fw_events_off = 0;
spin_unlock_irqrestore(&a->fw_event_lock, flags);
}
static void esas2r_add_device(struct esas2r_adapter *a, u16 target_id)
{
int ret;
struct scsi_device *scsi_dev;
scsi_dev = scsi_device_lookup(a->host, 0, target_id, 0);
if (scsi_dev) {
esas2r_log_dev(
ESAS2R_LOG_WARN,
&(scsi_dev->
sdev_gendev),
"scsi device already exists at id %d", target_id);
scsi_device_put(scsi_dev);
} else {
esas2r_log_dev(
ESAS2R_LOG_INFO,
&(a->host->
shost_gendev),
"scsi_add_device() called for 0:%d:0",
target_id);
ret = scsi_add_device(a->host, 0, target_id, 0);
if (ret) {
esas2r_log_dev(
ESAS2R_LOG_CRIT,
&(a->host->
shost_gendev),
"scsi_add_device failed with %d for id %d",
ret, target_id);
}
}
}
static void esas2r_remove_device(struct esas2r_adapter *a, u16 target_id)
{
struct scsi_device *scsi_dev;
scsi_dev = scsi_device_lookup(a->host, 0, target_id, 0);
if (scsi_dev) {
scsi_device_set_state(scsi_dev, SDEV_OFFLINE);
esas2r_log_dev(
ESAS2R_LOG_INFO,
&(scsi_dev->
sdev_gendev),
"scsi_remove_device() called for 0:%d:0",
target_id);
scsi_remove_device(scsi_dev);
esas2r_log_dev(
ESAS2R_LOG_INFO,
&(scsi_dev->
sdev_gendev),
"scsi_device_put() called");
scsi_device_put(scsi_dev);
} else {
esas2r_log_dev(
ESAS2R_LOG_WARN,
&(a->host->shost_gendev),
"no target found at id %d",
target_id);
}
}
/*
* Sends a firmware asynchronous event to anyone who happens to be
* listening on the defined ATTO VDA event ports.
*/
static void esas2r_send_ae_event(struct esas2r_fw_event_work *fw_event)
{
struct esas2r_vda_ae *ae = (struct esas2r_vda_ae *)fw_event->data;
char *type;
switch (ae->vda_ae.hdr.bytype) {
case VDAAE_HDR_TYPE_RAID:
type = "RAID group state change";
break;
case VDAAE_HDR_TYPE_LU:
type = "Mapped destination LU change";
break;
case VDAAE_HDR_TYPE_DISK:
type = "Physical disk inventory change";
break;
case VDAAE_HDR_TYPE_RESET:
type = "Firmware reset";
break;
case VDAAE_HDR_TYPE_LOG_INFO:
type = "Event Log message (INFO level)";
break;
case VDAAE_HDR_TYPE_LOG_WARN:
type = "Event Log message (WARN level)";
break;
case VDAAE_HDR_TYPE_LOG_CRIT:
type = "Event Log message (CRIT level)";
break;
case VDAAE_HDR_TYPE_LOG_FAIL:
type = "Event Log message (FAIL level)";
break;
case VDAAE_HDR_TYPE_NVC:
type = "NVCache change";
break;
case VDAAE_HDR_TYPE_TLG_INFO:
type = "Time stamped log message (INFO level)";
break;
case VDAAE_HDR_TYPE_TLG_WARN:
type = "Time stamped log message (WARN level)";
break;
case VDAAE_HDR_TYPE_TLG_CRIT:
type = "Time stamped log message (CRIT level)";
break;
case VDAAE_HDR_TYPE_PWRMGT:
type = "Power management";
break;
case VDAAE_HDR_TYPE_MUTE:
type = "Mute button pressed";
break;
case VDAAE_HDR_TYPE_DEV:
type = "Device attribute change";
break;
default:
type = "Unknown";
break;
}
esas2r_log(ESAS2R_LOG_WARN,
"An async event of type \"%s\" was received from the firmware. The event contents are:",
type);
esas2r_log_hexdump(ESAS2R_LOG_WARN, &ae->vda_ae,
ae->vda_ae.hdr.bylength);
}
static void
esas2r_firmware_event_work(struct work_struct *work)
{
struct esas2r_fw_event_work *fw_event =
container_of(work, struct esas2r_fw_event_work, work.work);
struct esas2r_adapter *a = fw_event->a;
u16 target_id = *(u16 *)&fw_event->data[0];
if (a->fw_events_off)
goto done;
switch (fw_event->type) {
case fw_event_null:
break; /* do nothing */
case fw_event_lun_change:
esas2r_remove_device(a, target_id);
esas2r_add_device(a, target_id);
break;
case fw_event_present:
esas2r_add_device(a, target_id);
break;
case fw_event_not_present:
esas2r_remove_device(a, target_id);
break;
case fw_event_vda_ae:
esas2r_send_ae_event(fw_event);
break;
}
done:
esas2r_free_fw_event(fw_event);
}
void esas2r_queue_fw_event(struct esas2r_adapter *a,
enum fw_event_type type,
void *data,
int data_sz)
{
struct esas2r_fw_event_work *fw_event;
unsigned long flags;
fw_event = kzalloc(sizeof(struct esas2r_fw_event_work), GFP_ATOMIC);
if (!fw_event) {
esas2r_log(ESAS2R_LOG_WARN,
"esas2r_queue_fw_event failed to alloc");
return;
}
if (type == fw_event_vda_ae) {
struct esas2r_vda_ae *ae =
(struct esas2r_vda_ae *)fw_event->data;
ae->signature = ESAS2R_VDA_EVENT_SIG;
ae->bus_number = a->pcid->bus->number;
ae->devfn = a->pcid->devfn;
memcpy(&ae->vda_ae, data, sizeof(ae->vda_ae));
} else {
memcpy(fw_event->data, data, data_sz);
}
fw_event->type = type;
fw_event->a = a;
spin_lock_irqsave(&a->fw_event_lock, flags);
list_add_tail(&fw_event->list, &a->fw_event_list);
INIT_DELAYED_WORK(&fw_event->work, esas2r_firmware_event_work);
queue_delayed_work_on(
smp_processor_id(), a->fw_event_q, &fw_event->work,
msecs_to_jiffies(1));
spin_unlock_irqrestore(&a->fw_event_lock, flags);
}
void esas2r_target_state_changed(struct esas2r_adapter *a, u16 targ_id,
u8 state)
{
if (state == TS_LUN_CHANGE)
esas2r_queue_fw_event(a, fw_event_lun_change, &targ_id,
sizeof(targ_id));
else if (state == TS_PRESENT)
esas2r_queue_fw_event(a, fw_event_present, &targ_id,
sizeof(targ_id));
else if (state == TS_NOT_PRESENT)
esas2r_queue_fw_event(a, fw_event_not_present, &targ_id,
sizeof(targ_id));
}
/* Translate status to a Linux SCSI mid-layer error code */
int esas2r_req_status_to_error(u8 req_stat)
{
switch (req_stat) {
case RS_OVERRUN:
case RS_UNDERRUN:
case RS_SUCCESS:
/*
* NOTE: SCSI mid-layer wants a good status for a SCSI error, because
* it will check the scsi_stat value in the completion anyway.
*/
case RS_SCSI_ERROR:
return DID_OK;
case RS_SEL:
case RS_SEL2:
return DID_NO_CONNECT;
case RS_RESET:
return DID_RESET;
case RS_ABORTED:
return DID_ABORT;
case RS_BUSY:
return DID_BUS_BUSY;
}
/* everything else is just an error. */
return DID_ERROR;
}
module_init(esas2r_init);
module_exit(esas2r_exit);
| gpl-2.0 |
CyanogenMod/lge-kernel-iproj | arch/arm/mach-msm/qdsp5v2/snddev_ecodec.c | 477 | 12212 | /* Copyright (c) 2009,2011 Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <asm/uaccess.h>
#include <mach/qdsp5v2/snddev_ecodec.h>
#include <mach/qdsp5v2/audio_dev_ctl.h>
#include <mach/qdsp5v2/audio_interct.h>
#include <mach/qdsp5v2/aux_pcm.h>
#include <mach/qdsp5v2/afe.h>
#include <mach/debug_mm.h>
#include <linux/slab.h>
/* Context for each external codec device */
struct snddev_ecodec_state {
struct snddev_ecodec_data *data;
u32 sample_rate;
bool enabled;
};
/* Global state for the driver */
struct snddev_ecodec_drv_state {
struct mutex dev_lock;
u32 rx_active; /* ensure one rx device at a time */
u32 tx_active; /* ensure one tx device at a time */
struct clk *lpa_core_clk;
struct clk *ecodec_clk;
};
#define ADSP_CTL 1
static struct snddev_ecodec_drv_state snddev_ecodec_drv;
static int snddev_ecodec_open_rx(struct snddev_ecodec_state *ecodec)
{
int rc = 0;
struct snddev_ecodec_drv_state *drv = &snddev_ecodec_drv;
struct msm_afe_config afe_config;
int ret = 0;
MM_DBG("snddev_ecodec_open_rx\n");
if (!drv->tx_active) {
/* request GPIO */
rc = aux_pcm_gpios_request();
if (rc) {
MM_ERR("GPIO enable failed\n");
goto done;
}
/* config clocks */
clk_enable(drv->lpa_core_clk);
/*if long sync is selected in aux PCM interface
ecodec clock is updated to work with 128KHz,
if short sync is selected ecodec clock is updated to
work with 2.048MHz frequency, actual clock output is
different than the SW configuration by factor of two*/
if (!(ecodec->data->conf_aux_codec_intf &
AUX_CODEC_CTL__AUX_CODEC_MODE__I2S_V)) {
if (ecodec->data->conf_aux_codec_intf &
AUX_CODEC_CTL__AUX_PCM_MODE__AUX_MASTER_V) {
MM_DBG("Update ecodec clock to 128 KHz, long "
"sync in master mode is selected\n");
ret = clk_set_rate(drv->ecodec_clk, 256000);
if (ret < 0)
MM_ERR("Error updating ecodec clock"
" to 128KHz\n");
} else if (ecodec->data->conf_aux_codec_intf &
AUX_CODEC_CTL__AUX_PCM_MODE__PRIM_SLAVE_V) {
MM_DBG("Update ecodec clock to 2 MHz, short"
" sync in slave mode is selected\n");
ret = clk_set_rate(drv->ecodec_clk, 4096000);
if (ret < 0)
MM_ERR("Error updating ecodec clock"
" to 2.048MHz\n");
} else {
MM_DBG("Update ecodec clock to 2 MHz, short"
" sync in master mode is selected\n");
ret = clk_set_rate(drv->ecodec_clk, 4096000);
if (ret < 0)
MM_ERR("Error updating ecodec clock"
" to 2.048MHz\n");
}
}
/* enable ecodec clk */
clk_enable(drv->ecodec_clk);
/* let ADSP confiure AUX PCM regs */
aux_codec_adsp_codec_ctl_en(ADSP_CTL);
/* let adsp configure pcm path */
aux_codec_pcm_path_ctl_en(ADSP_CTL);
/* choose ADSP_A */
audio_interct_aux_regsel(AUDIO_ADSP_A);
audio_interct_tpcm_source(AUDIO_ADSP_A);
audio_interct_rpcm_source(AUDIO_ADSP_A);
clk_disable(drv->lpa_core_clk);
/* send AUX_CODEC_CONFIG to AFE */
rc = afe_config_aux_codec(ecodec->data->conf_pcm_ctl_val,
ecodec->data->conf_aux_codec_intf,
ecodec->data->conf_data_format_padding_val);
if (IS_ERR_VALUE(rc))
goto error;
}
/* send CODEC CONFIG to AFE */
afe_config.sample_rate = ecodec->sample_rate / 1000;
afe_config.channel_mode = ecodec->data->channel_mode;
afe_config.volume = AFE_VOLUME_UNITY;
rc = afe_enable(AFE_HW_PATH_AUXPCM_RX, &afe_config);
if (IS_ERR_VALUE(rc)) {
if (!drv->tx_active) {
aux_pcm_gpios_free();
clk_disable(drv->ecodec_clk);
}
goto done;
}
ecodec->enabled = 1;
return 0;
error:
aux_pcm_gpios_free();
clk_disable(drv->ecodec_clk);
done:
return rc;
}
static int snddev_ecodec_close_rx(struct snddev_ecodec_state *ecodec)
{
struct snddev_ecodec_drv_state *drv = &snddev_ecodec_drv;
/* free GPIO */
if (!drv->tx_active) {
aux_pcm_gpios_free();
clk_disable(drv->ecodec_clk);
}
/* disable AFE */
afe_disable(AFE_HW_PATH_AUXPCM_RX);
ecodec->enabled = 0;
return 0;
}
static int snddev_ecodec_open_tx(struct snddev_ecodec_state *ecodec)
{
int rc = 0;
struct snddev_ecodec_drv_state *drv = &snddev_ecodec_drv;
struct msm_afe_config afe_config;
int ret = 0;
MM_DBG("snddev_ecodec_open_tx\n");
/* request GPIO */
if (!drv->rx_active) {
rc = aux_pcm_gpios_request();
if (rc) {
MM_ERR("GPIO enable failed\n");
goto done;
}
/* config clocks */
clk_enable(drv->lpa_core_clk);
/*if long sync is selected in aux PCM interface
ecodec clock is updated to work with 128KHz,
if short sync is selected ecodec clock is updated to
work with 2.048MHz frequency, actual clock output is
different than the SW configuration by factor of two*/
if (!(ecodec->data->conf_aux_codec_intf &
AUX_CODEC_CTL__AUX_CODEC_MODE__I2S_V)) {
if (ecodec->data->conf_aux_codec_intf &
AUX_CODEC_CTL__AUX_PCM_MODE__AUX_MASTER_V) {
MM_DBG("Update ecodec clock to 128 KHz, long "
"sync in master mode is selected\n");
ret = clk_set_rate(drv->ecodec_clk, 256000);
if (ret < 0)
MM_ERR("Error updating ecodec clock"
" to 128KHz\n");
} else if (ecodec->data->conf_aux_codec_intf &
AUX_CODEC_CTL__AUX_PCM_MODE__PRIM_SLAVE_V) {
MM_DBG("Update ecodec clock to 2 MHz, short"
" sync in slave mode is selected\n");
ret = clk_set_rate(drv->ecodec_clk, 4096000);
if (ret < 0)
MM_ERR("Error updating ecodec clock"
" to 2.048MHz\n");
} else {
MM_DBG("Update ecodec clock to 2 MHz, short"
" sync in master mode is selected\n");
ret = clk_set_rate(drv->ecodec_clk, 4096000);
if (ret < 0)
MM_ERR("Error updating ecodec clock"
" to 2.048MHz\n");
}
}
/* enable ecodec clk */
clk_enable(drv->ecodec_clk);
/* let ADSP confiure AUX PCM regs */
aux_codec_adsp_codec_ctl_en(ADSP_CTL);
/* let adsp configure pcm path */
aux_codec_pcm_path_ctl_en(ADSP_CTL);
/* choose ADSP_A */
audio_interct_aux_regsel(AUDIO_ADSP_A);
audio_interct_tpcm_source(AUDIO_ADSP_A);
audio_interct_rpcm_source(AUDIO_ADSP_A);
clk_disable(drv->lpa_core_clk);
/* send AUX_CODEC_CONFIG to AFE */
rc = afe_config_aux_codec(ecodec->data->conf_pcm_ctl_val,
ecodec->data->conf_aux_codec_intf,
ecodec->data->conf_data_format_padding_val);
if (IS_ERR_VALUE(rc))
goto error;
}
/* send CODEC CONFIG to AFE */
afe_config.sample_rate = ecodec->sample_rate / 1000;
afe_config.channel_mode = ecodec->data->channel_mode;
afe_config.volume = AFE_VOLUME_UNITY;
rc = afe_enable(AFE_HW_PATH_AUXPCM_TX, &afe_config);
if (IS_ERR_VALUE(rc)) {
if (!drv->rx_active) {
aux_pcm_gpios_free();
clk_disable(drv->ecodec_clk);
}
goto done;
}
ecodec->enabled = 1;
return 0;
error:
clk_disable(drv->ecodec_clk);
aux_pcm_gpios_free();
done:
return rc;
}
static int snddev_ecodec_close_tx(struct snddev_ecodec_state *ecodec)
{
struct snddev_ecodec_drv_state *drv = &snddev_ecodec_drv;
/* free GPIO */
if (!drv->rx_active) {
aux_pcm_gpios_free();
clk_disable(drv->ecodec_clk);
}
/* disable AFE */
afe_disable(AFE_HW_PATH_AUXPCM_TX);
ecodec->enabled = 0;
return 0;
}
static int snddev_ecodec_open(struct msm_snddev_info *dev_info)
{
int rc = 0;
struct snddev_ecodec_state *ecodec;
struct snddev_ecodec_drv_state *drv = &snddev_ecodec_drv;
if (!dev_info) {
rc = -EINVAL;
goto error;
}
ecodec = dev_info->private_data;
if (ecodec->data->capability & SNDDEV_CAP_RX) {
mutex_lock(&drv->dev_lock);
if (drv->rx_active) {
mutex_unlock(&drv->dev_lock);
rc = -EBUSY;
goto error;
}
rc = snddev_ecodec_open_rx(ecodec);
if (!IS_ERR_VALUE(rc))
drv->rx_active = 1;
mutex_unlock(&drv->dev_lock);
} else {
mutex_lock(&drv->dev_lock);
if (drv->tx_active) {
mutex_unlock(&drv->dev_lock);
rc = -EBUSY;
goto error;
}
rc = snddev_ecodec_open_tx(ecodec);
if (!IS_ERR_VALUE(rc))
drv->tx_active = 1;
mutex_unlock(&drv->dev_lock);
}
error:
return rc;
}
static int snddev_ecodec_close(struct msm_snddev_info *dev_info)
{
int rc = 0;
struct snddev_ecodec_state *ecodec;
struct snddev_ecodec_drv_state *drv = &snddev_ecodec_drv;
if (!dev_info) {
rc = -EINVAL;
goto error;
}
ecodec = dev_info->private_data;
if (ecodec->data->capability & SNDDEV_CAP_RX) {
mutex_lock(&drv->dev_lock);
if (!drv->rx_active) {
mutex_unlock(&drv->dev_lock);
rc = -EPERM;
goto error;
}
rc = snddev_ecodec_close_rx(ecodec);
if (!IS_ERR_VALUE(rc))
drv->rx_active = 0;
mutex_unlock(&drv->dev_lock);
} else {
mutex_lock(&drv->dev_lock);
if (!drv->tx_active) {
mutex_unlock(&drv->dev_lock);
rc = -EPERM;
goto error;
}
rc = snddev_ecodec_close_tx(ecodec);
if (!IS_ERR_VALUE(rc))
drv->tx_active = 0;
mutex_unlock(&drv->dev_lock);
}
error:
return rc;
}
static int snddev_ecodec_set_freq(struct msm_snddev_info *dev_info, u32 rate)
{
int rc = 0;
if (!dev_info) {
rc = -EINVAL;
goto error;
}
return 8000;
error:
return rc;
}
static int snddev_ecodec_probe(struct platform_device *pdev)
{
int rc = 0, i;
struct snddev_ecodec_data *pdata;
struct msm_snddev_info *dev_info;
struct snddev_ecodec_state *ecodec;
if (!pdev || !pdev->dev.platform_data) {
printk(KERN_ALERT "Invalid caller \n");
rc = -1;
goto error;
}
pdata = pdev->dev.platform_data;
ecodec = kzalloc(sizeof(struct snddev_ecodec_state), GFP_KERNEL);
if (!ecodec) {
rc = -ENOMEM;
goto error;
}
dev_info = kzalloc(sizeof(struct msm_snddev_info), GFP_KERNEL);
if (!dev_info) {
kfree(ecodec);
rc = -ENOMEM;
goto error;
}
dev_info->name = pdata->name;
dev_info->copp_id = pdata->copp_id;
dev_info->acdb_id = pdata->acdb_id;
dev_info->private_data = (void *) ecodec;
dev_info->dev_ops.open = snddev_ecodec_open;
dev_info->dev_ops.close = snddev_ecodec_close;
dev_info->dev_ops.set_freq = snddev_ecodec_set_freq;
dev_info->dev_ops.enable_sidetone = NULL;
dev_info->capability = pdata->capability;
dev_info->opened = 0;
msm_snddev_register(dev_info);
ecodec->data = pdata;
ecodec->sample_rate = 8000; /* Default to 8KHz */
if (pdata->capability & SNDDEV_CAP_RX) {
for (i = 0; i < VOC_RX_VOL_ARRAY_NUM; i++) {
dev_info->max_voc_rx_vol[i] =
pdata->max_voice_rx_vol[i];
dev_info->min_voc_rx_vol[i] =
pdata->min_voice_rx_vol[i];
}
}
error:
return rc;
}
static int snddev_ecodec_remove(struct platform_device *pdev)
{
return 0;
}
static struct platform_driver snddev_ecodec_driver = {
.probe = snddev_ecodec_probe,
.remove = snddev_ecodec_remove,
.driver = { .name = "msm_snddev_ecodec" }
};
static int __init snddev_ecodec_init(void)
{
int rc = 0;
struct snddev_ecodec_drv_state *ecodec_drv = &snddev_ecodec_drv;
MM_INFO("snddev_ecodec_init\n");
rc = platform_driver_register(&snddev_ecodec_driver);
if (IS_ERR_VALUE(rc))
goto error_platform_driver;
ecodec_drv->ecodec_clk = clk_get(NULL, "ecodec_clk");
if (IS_ERR(ecodec_drv->ecodec_clk))
goto error_ecodec_clk;
ecodec_drv->lpa_core_clk = clk_get(NULL, "lpa_core_clk");
if (IS_ERR(ecodec_drv->lpa_core_clk))
goto error_lpa_core_clk;
mutex_init(&ecodec_drv->dev_lock);
ecodec_drv->rx_active = 0;
ecodec_drv->tx_active = 0;
return 0;
error_lpa_core_clk:
clk_put(ecodec_drv->ecodec_clk);
error_ecodec_clk:
platform_driver_unregister(&snddev_ecodec_driver);
error_platform_driver:
MM_ERR("encounter error\n");
return -ENODEV;
}
static void __exit snddev_ecodec_exit(void)
{
struct snddev_ecodec_drv_state *ecodec_drv = &snddev_ecodec_drv;
platform_driver_unregister(&snddev_ecodec_driver);
clk_put(ecodec_drv->ecodec_clk);
return;
}
module_init(snddev_ecodec_init);
module_exit(snddev_ecodec_exit);
MODULE_DESCRIPTION("ECodec Sound Device driver");
MODULE_VERSION("1.0");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
karandpr/Doppler3ICS | fs/hfs/dir.c | 1501 | 8410 | /*
* linux/fs/hfs/dir.c
*
* Copyright (C) 1995-1997 Paul H. Hargrove
* (C) 2003 Ardis Technologies <roman@ardistech.com>
* This file may be distributed under the terms of the GNU General Public License.
*
* This file contains directory-related functions independent of which
* scheme is being used to represent forks.
*
* Based on the minix file system code, (C) 1991, 1992 by Linus Torvalds
*/
#include "hfs_fs.h"
#include "btree.h"
/*
* hfs_lookup()
*/
static struct dentry *hfs_lookup(struct inode *dir, struct dentry *dentry,
struct nameidata *nd)
{
hfs_cat_rec rec;
struct hfs_find_data fd;
struct inode *inode = NULL;
int res;
dentry->d_op = &hfs_dentry_operations;
hfs_find_init(HFS_SB(dir->i_sb)->cat_tree, &fd);
hfs_cat_build_key(dir->i_sb, fd.search_key, dir->i_ino, &dentry->d_name);
res = hfs_brec_read(&fd, &rec, sizeof(rec));
if (res) {
hfs_find_exit(&fd);
if (res == -ENOENT) {
/* No such entry */
inode = NULL;
goto done;
}
return ERR_PTR(res);
}
inode = hfs_iget(dir->i_sb, &fd.search_key->cat, &rec);
hfs_find_exit(&fd);
if (!inode)
return ERR_PTR(-EACCES);
done:
d_add(dentry, inode);
return NULL;
}
/*
* hfs_readdir
*/
static int hfs_readdir(struct file *filp, void *dirent, filldir_t filldir)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct super_block *sb = inode->i_sb;
int len, err;
char strbuf[HFS_MAX_NAMELEN];
union hfs_cat_rec entry;
struct hfs_find_data fd;
struct hfs_readdir_data *rd;
u16 type;
if (filp->f_pos >= inode->i_size)
return 0;
hfs_find_init(HFS_SB(sb)->cat_tree, &fd);
hfs_cat_build_key(sb, fd.search_key, inode->i_ino, NULL);
err = hfs_brec_find(&fd);
if (err)
goto out;
switch ((u32)filp->f_pos) {
case 0:
/* This is completely artificial... */
if (filldir(dirent, ".", 1, 0, inode->i_ino, DT_DIR))
goto out;
filp->f_pos++;
/* fall through */
case 1:
if (fd.entrylength > sizeof(entry) || fd.entrylength < 0) {
err = -EIO;
goto out;
}
hfs_bnode_read(fd.bnode, &entry, fd.entryoffset, fd.entrylength);
if (entry.type != HFS_CDR_THD) {
printk(KERN_ERR "hfs: bad catalog folder thread\n");
err = -EIO;
goto out;
}
//if (fd.entrylength < HFS_MIN_THREAD_SZ) {
// printk(KERN_ERR "hfs: truncated catalog thread\n");
// err = -EIO;
// goto out;
//}
if (filldir(dirent, "..", 2, 1,
be32_to_cpu(entry.thread.ParID), DT_DIR))
goto out;
filp->f_pos++;
/* fall through */
default:
if (filp->f_pos >= inode->i_size)
goto out;
err = hfs_brec_goto(&fd, filp->f_pos - 1);
if (err)
goto out;
}
for (;;) {
if (be32_to_cpu(fd.key->cat.ParID) != inode->i_ino) {
printk(KERN_ERR "hfs: walked past end of dir\n");
err = -EIO;
goto out;
}
if (fd.entrylength > sizeof(entry) || fd.entrylength < 0) {
err = -EIO;
goto out;
}
hfs_bnode_read(fd.bnode, &entry, fd.entryoffset, fd.entrylength);
type = entry.type;
len = hfs_mac2asc(sb, strbuf, &fd.key->cat.CName);
if (type == HFS_CDR_DIR) {
if (fd.entrylength < sizeof(struct hfs_cat_dir)) {
printk(KERN_ERR "hfs: small dir entry\n");
err = -EIO;
goto out;
}
if (filldir(dirent, strbuf, len, filp->f_pos,
be32_to_cpu(entry.dir.DirID), DT_DIR))
break;
} else if (type == HFS_CDR_FIL) {
if (fd.entrylength < sizeof(struct hfs_cat_file)) {
printk(KERN_ERR "hfs: small file entry\n");
err = -EIO;
goto out;
}
if (filldir(dirent, strbuf, len, filp->f_pos,
be32_to_cpu(entry.file.FlNum), DT_REG))
break;
} else {
printk(KERN_ERR "hfs: bad catalog entry type %d\n", type);
err = -EIO;
goto out;
}
filp->f_pos++;
if (filp->f_pos >= inode->i_size)
goto out;
err = hfs_brec_goto(&fd, 1);
if (err)
goto out;
}
rd = filp->private_data;
if (!rd) {
rd = kmalloc(sizeof(struct hfs_readdir_data), GFP_KERNEL);
if (!rd) {
err = -ENOMEM;
goto out;
}
filp->private_data = rd;
rd->file = filp;
list_add(&rd->list, &HFS_I(inode)->open_dir_list);
}
memcpy(&rd->key, &fd.key, sizeof(struct hfs_cat_key));
out:
hfs_find_exit(&fd);
return err;
}
static int hfs_dir_release(struct inode *inode, struct file *file)
{
struct hfs_readdir_data *rd = file->private_data;
if (rd) {
list_del(&rd->list);
kfree(rd);
}
return 0;
}
/*
* hfs_create()
*
* This is the create() entry in the inode_operations structure for
* regular HFS directories. The purpose is to create a new file in
* a directory and return a corresponding inode, given the inode for
* the directory and the name (and its length) of the new file.
*/
static int hfs_create(struct inode *dir, struct dentry *dentry, int mode,
struct nameidata *nd)
{
struct inode *inode;
int res;
inode = hfs_new_inode(dir, &dentry->d_name, mode);
if (!inode)
return -ENOSPC;
res = hfs_cat_create(inode->i_ino, dir, &dentry->d_name, inode);
if (res) {
inode->i_nlink = 0;
hfs_delete_inode(inode);
iput(inode);
return res;
}
d_instantiate(dentry, inode);
mark_inode_dirty(inode);
return 0;
}
/*
* hfs_mkdir()
*
* This is the mkdir() entry in the inode_operations structure for
* regular HFS directories. The purpose is to create a new directory
* in a directory, given the inode for the parent directory and the
* name (and its length) of the new directory.
*/
static int hfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
{
struct inode *inode;
int res;
inode = hfs_new_inode(dir, &dentry->d_name, S_IFDIR | mode);
if (!inode)
return -ENOSPC;
res = hfs_cat_create(inode->i_ino, dir, &dentry->d_name, inode);
if (res) {
inode->i_nlink = 0;
hfs_delete_inode(inode);
iput(inode);
return res;
}
d_instantiate(dentry, inode);
mark_inode_dirty(inode);
return 0;
}
/*
* hfs_unlink()
*
* This is the unlink() entry in the inode_operations structure for
* regular HFS directories. The purpose is to delete an existing
* file, given the inode for the parent directory and the name
* (and its length) of the existing file.
*/
static int hfs_unlink(struct inode *dir, struct dentry *dentry)
{
struct inode *inode;
int res;
inode = dentry->d_inode;
res = hfs_cat_delete(inode->i_ino, dir, &dentry->d_name);
if (res)
return res;
drop_nlink(inode);
hfs_delete_inode(inode);
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
return res;
}
/*
* hfs_rmdir()
*
* This is the rmdir() entry in the inode_operations structure for
* regular HFS directories. The purpose is to delete an existing
* directory, given the inode for the parent directory and the name
* (and its length) of the existing directory.
*/
static int hfs_rmdir(struct inode *dir, struct dentry *dentry)
{
struct inode *inode;
int res;
inode = dentry->d_inode;
if (inode->i_size != 2)
return -ENOTEMPTY;
res = hfs_cat_delete(inode->i_ino, dir, &dentry->d_name);
if (res)
return res;
clear_nlink(inode);
inode->i_ctime = CURRENT_TIME_SEC;
hfs_delete_inode(inode);
mark_inode_dirty(inode);
return 0;
}
/*
* hfs_rename()
*
* This is the rename() entry in the inode_operations structure for
* regular HFS directories. The purpose is to rename an existing
* file or directory, given the inode for the current directory and
* the name (and its length) of the existing file/directory and the
* inode for the new directory and the name (and its length) of the
* new file/directory.
* XXX: how do you handle must_be dir?
*/
static int hfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int res;
/* Unlink destination if it already exists */
if (new_dentry->d_inode) {
res = hfs_unlink(new_dir, new_dentry);
if (res)
return res;
}
res = hfs_cat_move(old_dentry->d_inode->i_ino,
old_dir, &old_dentry->d_name,
new_dir, &new_dentry->d_name);
if (!res)
hfs_cat_build_key(old_dir->i_sb,
(btree_key *)&HFS_I(old_dentry->d_inode)->cat_key,
new_dir->i_ino, &new_dentry->d_name);
return res;
}
const struct file_operations hfs_dir_operations = {
.read = generic_read_dir,
.readdir = hfs_readdir,
.llseek = generic_file_llseek,
.release = hfs_dir_release,
};
const struct inode_operations hfs_dir_inode_operations = {
.create = hfs_create,
.lookup = hfs_lookup,
.unlink = hfs_unlink,
.mkdir = hfs_mkdir,
.rmdir = hfs_rmdir,
.rename = hfs_rename,
.setattr = hfs_inode_setattr,
};
| gpl-2.0 |
TEAM-Gummy/android_kernel_sony_msm8x27 | drivers/media/video/msm/vx6953_reg_v4l2.c | 1757 | 3647 | /* Copyright (c) 2011, 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 "vx6953_v4l2.h"
const struct reg_struct_init vx6953_reg_init[1] = {
{
10, /*REG = 0x0112 , 10 bit */
10, /*REG = 0x0113*/
9, /*REG = 0x0301 vt_pix_clk_div*/
4, /*REG = 0x0305 pre_pll_clk_div*/
133, /*REG = 0x0307 pll_multiplier*/
10, /*REG = 0x0309 op_pix_clk_div*/
0x08, /*REG = 0x3030*/
0x02, /*REG = 0x0111*/
0x01, /*REG = 0x0b00 ,lens shading off */
0x30, /*REG = 0x3001*/
0x33, /*REG = 0x3004*/
0x09, /*REG = 0x3007*/
0x1F, /*REG = 0x3016*/
0x03, /*REG = 0x301d*/
0x11, /*REG = 0x317E*/
0x09, /*REG = 0x317F*/
0x38, /*REG = 0x3400*/
0x00, /*REG_0x0b06*/
0x80, /*REG_0x0b07*/
0x01, /*REG_0x0b08*/
0x4F, /*REG_0x0b09*/
0x18, /*REG_0x0136*/
0x00, /*/REG_0x0137*/
0x20, /*REG = 0x0b83*/
0x90, /*REG = 0x0b84*/
0x20, /*REG = 0x0b85*/
0x80, /*REG = 0x0b88*/
0x00, /*REG = 0x0b89*/
0x00, /*REG = 0x0b8a*/
}
};
const struct reg_struct vx6953_reg_pat[2] = {
{/* Preview */
0x03, /*REG = 0x0202 coarse integration_time_hi*/
0xd0, /*REG = 0x0203 coarse_integration_time_lo*/
0xc0, /*REG = 0x0205 analogue_gain_code_global*/
0x03, /*REG = 0x0340 frame_length_lines_hi*/
0xf0, /*REG = 0x0341 frame_length_lines_lo*/
0x0b, /*REG = 0x0342 line_length_pck_hi*/
0xa5, /*REG = 0x0343 line_length_pck_lo*/
0x03, /*REG = 0x3005*/
0x00, /*REG = 0x3010*/
0x01, /*REG = 0x3011*/
0x6a, /*REG = 0x301a*/
0x03, /*REG = 0x3035*/
0x2c, /*REG = 0x3036*/
0x00, /*REG = 0x3041*/
0x24, /*REG = 0x3042*/
0x81, /*REG = 0x3045*/
0x02, /*REG = 0x0b80 edof estimate*/
0x01, /*REG = 0x0900*/
0x22, /*REG = 0x0901*/
0x04, /*REG = 0x0902*/
0x03, /*REG = 0x0383*/
0x03, /*REG = 0x0387*/
0x05, /*REG = 0x034c*/
0x18, /*REG = 0x034d*/
0x03, /*REG = 0x034e*/
0xd4, /*REG = 0x034f*/
0x02, /*0x1716*/
0x04, /*0x1717*/
0x08, /*0x1718*/
0x80, /*0x1719*/
0x01, /*0x3210*/
0x02, /*0x111*/
0x01, /*0x3410*/
0x01, /*0x3098*/
0x05, /*0x309D*/
0x02,
0x04,
},
{ /* Snapshot */
0x07,/*REG = 0x0202 coarse_integration_time_hi*/
0x00,/*REG = 0x0203 coarse_integration_time_lo*/
0xc0,/*REG = 0x0205 analogue_gain_code_global*/
0x07,/*REG = 0x0340 frame_length_lines_hi*/
0xd0,/*REG = 0x0341 frame_length_lines_lo*/
0x0b,/*REG = 0x0342 line_length_pck_hi*/
0x8c,/*REG = 0x0343 line_length_pck_lo*/
0x01,/*REG = 0x3005*/
0x00,/*REG = 0x3010*/
0x00,/*REG = 0x3011*/
0x55,/*REG = 0x301a*/
0x01,/*REG = 0x3035*/
0x23,/*REG = 0x3036*/
0x00,/*REG = 0x3041*/
0x24,/*REG = 0x3042*/
0xb7,/*REG = 0x3045*/
0x01,/*REG = 0x0b80 edof application*/
0x00,/*REG = 0x0900*/
0x00,/*REG = 0x0901*/
0x00,/*REG = 0x0902*/
0x01,/*REG = 0x0383*/
0x01,/*REG = 0x0387*/
0x0A,/*REG = 0x034c*/
0x30,/*REG = 0x034d*/
0x07,/*REG = 0x034e*/
0xA8,/*REG = 0x034f*/
0x02,/*0x1716*/
0x0d,/*0x1717*/
0x07,/*0x1718*/
0x7d,/*0x1719*/
0x01,/*0x3210*/
0x02,/*0x111*/
0x01,/*0x3410*/
0x01,/*0x3098*/
0x05, /*0x309D*/
0x02,
0x00,
}
};
struct vx6953_reg vx6953_regs = {
.reg_pat_init = &vx6953_reg_init[0],
.reg_pat = &vx6953_reg_pat[0],
};
| gpl-2.0 |
davidmueller13/ZenKernel_Flounder | drivers/ata/sata_dwc_460ex.c | 1757 | 52393 | /*
* drivers/ata/sata_dwc_460ex.c
*
* Synopsys DesignWare Cores (DWC) SATA host driver
*
* Author: Mark Miesfeld <mmiesfeld@amcc.com>
*
* Ported from 2.6.19.2 to 2.6.25/26 by Stefan Roese <sr@denx.de>
* Copyright 2008 DENX Software Engineering
*
* Based on versions provided by AMCC and Synopsys which are:
* Copyright 2006 Applied Micro Circuits Corporation
* COPYRIGHT (C) 2005 SYNOPSYS, 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.
*/
#ifdef CONFIG_SATA_DWC_DEBUG
#define DEBUG
#endif
#ifdef CONFIG_SATA_DWC_VDEBUG
#define VERBOSE_DEBUG
#define DEBUG_NCQ
#endif
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/of_platform.h>
#include <linux/platform_device.h>
#include <linux/libata.h>
#include <linux/slab.h>
#include "libata.h"
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
/* These two are defined in "libata.h" */
#undef DRV_NAME
#undef DRV_VERSION
#define DRV_NAME "sata-dwc"
#define DRV_VERSION "1.3"
/* SATA DMA driver Globals */
#define DMA_NUM_CHANS 1
#define DMA_NUM_CHAN_REGS 8
/* SATA DMA Register definitions */
#define AHB_DMA_BRST_DFLT 64 /* 16 data items burst length*/
struct dmareg {
u32 low; /* Low bits 0-31 */
u32 high; /* High bits 32-63 */
};
/* DMA Per Channel registers */
struct dma_chan_regs {
struct dmareg sar; /* Source Address */
struct dmareg dar; /* Destination address */
struct dmareg llp; /* Linked List Pointer */
struct dmareg ctl; /* Control */
struct dmareg sstat; /* Source Status not implemented in core */
struct dmareg dstat; /* Destination Status not implemented in core*/
struct dmareg sstatar; /* Source Status Address not impl in core */
struct dmareg dstatar; /* Destination Status Address not implemente */
struct dmareg cfg; /* Config */
struct dmareg sgr; /* Source Gather */
struct dmareg dsr; /* Destination Scatter */
};
/* Generic Interrupt Registers */
struct dma_interrupt_regs {
struct dmareg tfr; /* Transfer Interrupt */
struct dmareg block; /* Block Interrupt */
struct dmareg srctran; /* Source Transfer Interrupt */
struct dmareg dsttran; /* Dest Transfer Interrupt */
struct dmareg error; /* Error */
};
struct ahb_dma_regs {
struct dma_chan_regs chan_regs[DMA_NUM_CHAN_REGS];
struct dma_interrupt_regs interrupt_raw; /* Raw Interrupt */
struct dma_interrupt_regs interrupt_status; /* Interrupt Status */
struct dma_interrupt_regs interrupt_mask; /* Interrupt Mask */
struct dma_interrupt_regs interrupt_clear; /* Interrupt Clear */
struct dmareg statusInt; /* Interrupt combined*/
struct dmareg rq_srcreg; /* Src Trans Req */
struct dmareg rq_dstreg; /* Dst Trans Req */
struct dmareg rq_sgl_srcreg; /* Sngl Src Trans Req*/
struct dmareg rq_sgl_dstreg; /* Sngl Dst Trans Req*/
struct dmareg rq_lst_srcreg; /* Last Src Trans Req*/
struct dmareg rq_lst_dstreg; /* Last Dst Trans Req*/
struct dmareg dma_cfg; /* DMA Config */
struct dmareg dma_chan_en; /* DMA Channel Enable*/
struct dmareg dma_id; /* DMA ID */
struct dmareg dma_test; /* DMA Test */
struct dmareg res1; /* reserved */
struct dmareg res2; /* reserved */
/*
* DMA Comp Params
* Param 6 = dma_param[0], Param 5 = dma_param[1],
* Param 4 = dma_param[2] ...
*/
struct dmareg dma_params[6];
};
/* Data structure for linked list item */
struct lli {
u32 sar; /* Source Address */
u32 dar; /* Destination address */
u32 llp; /* Linked List Pointer */
struct dmareg ctl; /* Control */
struct dmareg dstat; /* Destination Status */
};
enum {
SATA_DWC_DMAC_LLI_SZ = (sizeof(struct lli)),
SATA_DWC_DMAC_LLI_NUM = 256,
SATA_DWC_DMAC_LLI_TBL_SZ = (SATA_DWC_DMAC_LLI_SZ * \
SATA_DWC_DMAC_LLI_NUM),
SATA_DWC_DMAC_TWIDTH_BYTES = 4,
SATA_DWC_DMAC_CTRL_TSIZE_MAX = (0x00000800 * \
SATA_DWC_DMAC_TWIDTH_BYTES),
};
/* DMA Register Operation Bits */
enum {
DMA_EN = 0x00000001, /* Enable AHB DMA */
DMA_CTL_LLP_SRCEN = 0x10000000, /* Blk chain enable Src */
DMA_CTL_LLP_DSTEN = 0x08000000, /* Blk chain enable Dst */
};
#define DMA_CTL_BLK_TS(size) ((size) & 0x000000FFF) /* Blk Transfer size */
#define DMA_CHANNEL(ch) (0x00000001 << (ch)) /* Select channel */
/* Enable channel */
#define DMA_ENABLE_CHAN(ch) ((0x00000001 << (ch)) | \
((0x000000001 << (ch)) << 8))
/* Disable channel */
#define DMA_DISABLE_CHAN(ch) (0x00000000 | ((0x000000001 << (ch)) << 8))
/* Transfer Type & Flow Controller */
#define DMA_CTL_TTFC(type) (((type) & 0x7) << 20)
#define DMA_CTL_SMS(num) (((num) & 0x3) << 25) /* Src Master Select */
#define DMA_CTL_DMS(num) (((num) & 0x3) << 23)/* Dst Master Select */
/* Src Burst Transaction Length */
#define DMA_CTL_SRC_MSIZE(size) (((size) & 0x7) << 14)
/* Dst Burst Transaction Length */
#define DMA_CTL_DST_MSIZE(size) (((size) & 0x7) << 11)
/* Source Transfer Width */
#define DMA_CTL_SRC_TRWID(size) (((size) & 0x7) << 4)
/* Destination Transfer Width */
#define DMA_CTL_DST_TRWID(size) (((size) & 0x7) << 1)
/* Assign HW handshaking interface (x) to destination / source peripheral */
#define DMA_CFG_HW_HS_DEST(int_num) (((int_num) & 0xF) << 11)
#define DMA_CFG_HW_HS_SRC(int_num) (((int_num) & 0xF) << 7)
#define DMA_CFG_HW_CH_PRIOR(int_num) (((int_num) & 0xF) << 5)
#define DMA_LLP_LMS(addr, master) (((addr) & 0xfffffffc) | (master))
/*
* This define is used to set block chaining disabled in the control low
* register. It is already in little endian format so it can be &'d dirctly.
* It is essentially: cpu_to_le32(~(DMA_CTL_LLP_SRCEN | DMA_CTL_LLP_DSTEN))
*/
enum {
DMA_CTL_LLP_DISABLE_LE32 = 0xffffffe7,
DMA_CTL_TTFC_P2M_DMAC = 0x00000002, /* Per to mem, DMAC cntr */
DMA_CTL_TTFC_M2P_PER = 0x00000003, /* Mem to per, peripheral cntr */
DMA_CTL_SINC_INC = 0x00000000, /* Source Address Increment */
DMA_CTL_SINC_DEC = 0x00000200,
DMA_CTL_SINC_NOCHANGE = 0x00000400,
DMA_CTL_DINC_INC = 0x00000000, /* Destination Address Increment */
DMA_CTL_DINC_DEC = 0x00000080,
DMA_CTL_DINC_NOCHANGE = 0x00000100,
DMA_CTL_INT_EN = 0x00000001, /* Interrupt Enable */
/* Channel Configuration Register high bits */
DMA_CFG_FCMOD_REQ = 0x00000001, /* Flow Control - request based */
DMA_CFG_PROTCTL = (0x00000003 << 2),/* Protection Control */
/* Channel Configuration Register low bits */
DMA_CFG_RELD_DST = 0x80000000, /* Reload Dest / Src Addr */
DMA_CFG_RELD_SRC = 0x40000000,
DMA_CFG_HS_SELSRC = 0x00000800, /* Software handshake Src/ Dest */
DMA_CFG_HS_SELDST = 0x00000400,
DMA_CFG_FIFOEMPTY = (0x00000001 << 9), /* FIFO Empty bit */
/* Channel Linked List Pointer Register */
DMA_LLP_AHBMASTER1 = 0, /* List Master Select */
DMA_LLP_AHBMASTER2 = 1,
SATA_DWC_MAX_PORTS = 1,
SATA_DWC_SCR_OFFSET = 0x24,
SATA_DWC_REG_OFFSET = 0x64,
};
/* DWC SATA Registers */
struct sata_dwc_regs {
u32 fptagr; /* 1st party DMA tag */
u32 fpbor; /* 1st party DMA buffer offset */
u32 fptcr; /* 1st party DMA Xfr count */
u32 dmacr; /* DMA Control */
u32 dbtsr; /* DMA Burst Transac size */
u32 intpr; /* Interrupt Pending */
u32 intmr; /* Interrupt Mask */
u32 errmr; /* Error Mask */
u32 llcr; /* Link Layer Control */
u32 phycr; /* PHY Control */
u32 physr; /* PHY Status */
u32 rxbistpd; /* Recvd BIST pattern def register */
u32 rxbistpd1; /* Recvd BIST data dword1 */
u32 rxbistpd2; /* Recvd BIST pattern data dword2 */
u32 txbistpd; /* Trans BIST pattern def register */
u32 txbistpd1; /* Trans BIST data dword1 */
u32 txbistpd2; /* Trans BIST data dword2 */
u32 bistcr; /* BIST Control Register */
u32 bistfctr; /* BIST FIS Count Register */
u32 bistsr; /* BIST Status Register */
u32 bistdecr; /* BIST Dword Error count register */
u32 res[15]; /* Reserved locations */
u32 testr; /* Test Register */
u32 versionr; /* Version Register */
u32 idr; /* ID Register */
u32 unimpl[192]; /* Unimplemented */
u32 dmadr[256]; /* FIFO Locations in DMA Mode */
};
enum {
SCR_SCONTROL_DET_ENABLE = 0x00000001,
SCR_SSTATUS_DET_PRESENT = 0x00000001,
SCR_SERROR_DIAG_X = 0x04000000,
/* DWC SATA Register Operations */
SATA_DWC_TXFIFO_DEPTH = 0x01FF,
SATA_DWC_RXFIFO_DEPTH = 0x01FF,
SATA_DWC_DMACR_TMOD_TXCHEN = 0x00000004,
SATA_DWC_DMACR_TXCHEN = (0x00000001 | SATA_DWC_DMACR_TMOD_TXCHEN),
SATA_DWC_DMACR_RXCHEN = (0x00000002 | SATA_DWC_DMACR_TMOD_TXCHEN),
SATA_DWC_DMACR_TXRXCH_CLEAR = SATA_DWC_DMACR_TMOD_TXCHEN,
SATA_DWC_INTPR_DMAT = 0x00000001,
SATA_DWC_INTPR_NEWFP = 0x00000002,
SATA_DWC_INTPR_PMABRT = 0x00000004,
SATA_DWC_INTPR_ERR = 0x00000008,
SATA_DWC_INTPR_NEWBIST = 0x00000010,
SATA_DWC_INTPR_IPF = 0x10000000,
SATA_DWC_INTMR_DMATM = 0x00000001,
SATA_DWC_INTMR_NEWFPM = 0x00000002,
SATA_DWC_INTMR_PMABRTM = 0x00000004,
SATA_DWC_INTMR_ERRM = 0x00000008,
SATA_DWC_INTMR_NEWBISTM = 0x00000010,
SATA_DWC_LLCR_SCRAMEN = 0x00000001,
SATA_DWC_LLCR_DESCRAMEN = 0x00000002,
SATA_DWC_LLCR_RPDEN = 0x00000004,
/* This is all error bits, zero's are reserved fields. */
SATA_DWC_SERROR_ERR_BITS = 0x0FFF0F03
};
#define SATA_DWC_SCR0_SPD_GET(v) (((v) >> 4) & 0x0000000F)
#define SATA_DWC_DMACR_TX_CLEAR(v) (((v) & ~SATA_DWC_DMACR_TXCHEN) |\
SATA_DWC_DMACR_TMOD_TXCHEN)
#define SATA_DWC_DMACR_RX_CLEAR(v) (((v) & ~SATA_DWC_DMACR_RXCHEN) |\
SATA_DWC_DMACR_TMOD_TXCHEN)
#define SATA_DWC_DBTSR_MWR(size) (((size)/4) & SATA_DWC_TXFIFO_DEPTH)
#define SATA_DWC_DBTSR_MRD(size) ((((size)/4) & SATA_DWC_RXFIFO_DEPTH)\
<< 16)
struct sata_dwc_device {
struct device *dev; /* generic device struct */
struct ata_probe_ent *pe; /* ptr to probe-ent */
struct ata_host *host;
u8 *reg_base;
struct sata_dwc_regs *sata_dwc_regs; /* DW Synopsys SATA specific */
int irq_dma;
};
#define SATA_DWC_QCMD_MAX 32
struct sata_dwc_device_port {
struct sata_dwc_device *hsdev;
int cmd_issued[SATA_DWC_QCMD_MAX];
struct lli *llit[SATA_DWC_QCMD_MAX]; /* DMA LLI table */
dma_addr_t llit_dma[SATA_DWC_QCMD_MAX];
u32 dma_chan[SATA_DWC_QCMD_MAX];
int dma_pending[SATA_DWC_QCMD_MAX];
};
/*
* Commonly used DWC SATA driver Macros
*/
#define HSDEV_FROM_HOST(host) ((struct sata_dwc_device *)\
(host)->private_data)
#define HSDEV_FROM_AP(ap) ((struct sata_dwc_device *)\
(ap)->host->private_data)
#define HSDEVP_FROM_AP(ap) ((struct sata_dwc_device_port *)\
(ap)->private_data)
#define HSDEV_FROM_QC(qc) ((struct sata_dwc_device *)\
(qc)->ap->host->private_data)
#define HSDEV_FROM_HSDEVP(p) ((struct sata_dwc_device *)\
(hsdevp)->hsdev)
enum {
SATA_DWC_CMD_ISSUED_NOT = 0,
SATA_DWC_CMD_ISSUED_PEND = 1,
SATA_DWC_CMD_ISSUED_EXEC = 2,
SATA_DWC_CMD_ISSUED_NODATA = 3,
SATA_DWC_DMA_PENDING_NONE = 0,
SATA_DWC_DMA_PENDING_TX = 1,
SATA_DWC_DMA_PENDING_RX = 2,
};
struct sata_dwc_host_priv {
void __iomem *scr_addr_sstatus;
u32 sata_dwc_sactive_issued ;
u32 sata_dwc_sactive_queued ;
u32 dma_interrupt_count;
struct ahb_dma_regs *sata_dma_regs;
struct device *dwc_dev;
int dma_channel;
};
struct sata_dwc_host_priv host_pvt;
/*
* Prototypes
*/
static void sata_dwc_bmdma_start_by_tag(struct ata_queued_cmd *qc, u8 tag);
static int sata_dwc_qc_complete(struct ata_port *ap, struct ata_queued_cmd *qc,
u32 check_status);
static void sata_dwc_dma_xfer_complete(struct ata_port *ap, u32 check_status);
static void sata_dwc_port_stop(struct ata_port *ap);
static void sata_dwc_clear_dmacr(struct sata_dwc_device_port *hsdevp, u8 tag);
static int dma_dwc_init(struct sata_dwc_device *hsdev, int irq);
static void dma_dwc_exit(struct sata_dwc_device *hsdev);
static int dma_dwc_xfer_setup(struct scatterlist *sg, int num_elems,
struct lli *lli, dma_addr_t dma_lli,
void __iomem *addr, int dir);
static void dma_dwc_xfer_start(int dma_ch);
static const char *get_prot_descript(u8 protocol)
{
switch ((enum ata_tf_protocols)protocol) {
case ATA_PROT_NODATA:
return "ATA no data";
case ATA_PROT_PIO:
return "ATA PIO";
case ATA_PROT_DMA:
return "ATA DMA";
case ATA_PROT_NCQ:
return "ATA NCQ";
case ATAPI_PROT_NODATA:
return "ATAPI no data";
case ATAPI_PROT_PIO:
return "ATAPI PIO";
case ATAPI_PROT_DMA:
return "ATAPI DMA";
default:
return "unknown";
}
}
static const char *get_dma_dir_descript(int dma_dir)
{
switch ((enum dma_data_direction)dma_dir) {
case DMA_BIDIRECTIONAL:
return "bidirectional";
case DMA_TO_DEVICE:
return "to device";
case DMA_FROM_DEVICE:
return "from device";
default:
return "none";
}
}
static void sata_dwc_tf_dump(struct ata_taskfile *tf)
{
dev_vdbg(host_pvt.dwc_dev, "taskfile cmd: 0x%02x protocol: %s flags:"
"0x%lx device: %x\n", tf->command,
get_prot_descript(tf->protocol), tf->flags, tf->device);
dev_vdbg(host_pvt.dwc_dev, "feature: 0x%02x nsect: 0x%x lbal: 0x%x "
"lbam: 0x%x lbah: 0x%x\n", tf->feature, tf->nsect, tf->lbal,
tf->lbam, tf->lbah);
dev_vdbg(host_pvt.dwc_dev, "hob_feature: 0x%02x hob_nsect: 0x%x "
"hob_lbal: 0x%x hob_lbam: 0x%x hob_lbah: 0x%x\n",
tf->hob_feature, tf->hob_nsect, tf->hob_lbal, tf->hob_lbam,
tf->hob_lbah);
}
/*
* Function: get_burst_length_encode
* arguments: datalength: length in bytes of data
* returns value to be programmed in register corresponding to data length
* This value is effectively the log(base 2) of the length
*/
static int get_burst_length_encode(int datalength)
{
int items = datalength >> 2; /* div by 4 to get lword count */
if (items >= 64)
return 5;
if (items >= 32)
return 4;
if (items >= 16)
return 3;
if (items >= 8)
return 2;
if (items >= 4)
return 1;
return 0;
}
static void clear_chan_interrupts(int c)
{
out_le32(&(host_pvt.sata_dma_regs->interrupt_clear.tfr.low),
DMA_CHANNEL(c));
out_le32(&(host_pvt.sata_dma_regs->interrupt_clear.block.low),
DMA_CHANNEL(c));
out_le32(&(host_pvt.sata_dma_regs->interrupt_clear.srctran.low),
DMA_CHANNEL(c));
out_le32(&(host_pvt.sata_dma_regs->interrupt_clear.dsttran.low),
DMA_CHANNEL(c));
out_le32(&(host_pvt.sata_dma_regs->interrupt_clear.error.low),
DMA_CHANNEL(c));
}
/*
* Function: dma_request_channel
* arguments: None
* returns channel number if available else -1
* This function assigns the next available DMA channel from the list to the
* requester
*/
static int dma_request_channel(void)
{
/* Check if the channel is not currently in use */
if (!(in_le32(&(host_pvt.sata_dma_regs->dma_chan_en.low)) &
DMA_CHANNEL(host_pvt.dma_channel)))
return host_pvt.dma_channel;
dev_err(host_pvt.dwc_dev, "%s Channel %d is currently in use\n",
__func__, host_pvt.dma_channel);
return -1;
}
/*
* Function: dma_dwc_interrupt
* arguments: irq, dev_id, pt_regs
* returns channel number if available else -1
* Interrupt Handler for DW AHB SATA DMA
*/
static irqreturn_t dma_dwc_interrupt(int irq, void *hsdev_instance)
{
int chan;
u32 tfr_reg, err_reg;
unsigned long flags;
struct sata_dwc_device *hsdev =
(struct sata_dwc_device *)hsdev_instance;
struct ata_host *host = (struct ata_host *)hsdev->host;
struct ata_port *ap;
struct sata_dwc_device_port *hsdevp;
u8 tag = 0;
unsigned int port = 0;
spin_lock_irqsave(&host->lock, flags);
ap = host->ports[port];
hsdevp = HSDEVP_FROM_AP(ap);
tag = ap->link.active_tag;
tfr_reg = in_le32(&(host_pvt.sata_dma_regs->interrupt_status.tfr\
.low));
err_reg = in_le32(&(host_pvt.sata_dma_regs->interrupt_status.error\
.low));
dev_dbg(ap->dev, "eot=0x%08x err=0x%08x pending=%d active port=%d\n",
tfr_reg, err_reg, hsdevp->dma_pending[tag], port);
chan = host_pvt.dma_channel;
if (chan >= 0) {
/* Check for end-of-transfer interrupt. */
if (tfr_reg & DMA_CHANNEL(chan)) {
/*
* Each DMA command produces 2 interrupts. Only
* complete the command after both interrupts have been
* seen. (See sata_dwc_isr())
*/
host_pvt.dma_interrupt_count++;
sata_dwc_clear_dmacr(hsdevp, tag);
if (hsdevp->dma_pending[tag] ==
SATA_DWC_DMA_PENDING_NONE) {
dev_err(ap->dev, "DMA not pending eot=0x%08x "
"err=0x%08x tag=0x%02x pending=%d\n",
tfr_reg, err_reg, tag,
hsdevp->dma_pending[tag]);
}
if ((host_pvt.dma_interrupt_count % 2) == 0)
sata_dwc_dma_xfer_complete(ap, 1);
/* Clear the interrupt */
out_le32(&(host_pvt.sata_dma_regs->interrupt_clear\
.tfr.low),
DMA_CHANNEL(chan));
}
/* Check for error interrupt. */
if (err_reg & DMA_CHANNEL(chan)) {
/* TODO Need error handler ! */
dev_err(ap->dev, "error interrupt err_reg=0x%08x\n",
err_reg);
/* Clear the interrupt. */
out_le32(&(host_pvt.sata_dma_regs->interrupt_clear\
.error.low),
DMA_CHANNEL(chan));
}
}
spin_unlock_irqrestore(&host->lock, flags);
return IRQ_HANDLED;
}
/*
* Function: dma_request_interrupts
* arguments: hsdev
* returns status
* This function registers ISR for a particular DMA channel interrupt
*/
static int dma_request_interrupts(struct sata_dwc_device *hsdev, int irq)
{
int retval = 0;
int chan = host_pvt.dma_channel;
if (chan >= 0) {
/* Unmask error interrupt */
out_le32(&(host_pvt.sata_dma_regs)->interrupt_mask.error.low,
DMA_ENABLE_CHAN(chan));
/* Unmask end-of-transfer interrupt */
out_le32(&(host_pvt.sata_dma_regs)->interrupt_mask.tfr.low,
DMA_ENABLE_CHAN(chan));
}
retval = request_irq(irq, dma_dwc_interrupt, 0, "SATA DMA", hsdev);
if (retval) {
dev_err(host_pvt.dwc_dev, "%s: could not get IRQ %d\n",
__func__, irq);
return -ENODEV;
}
/* Mark this interrupt as requested */
hsdev->irq_dma = irq;
return 0;
}
/*
* Function: map_sg_to_lli
* The Synopsis driver has a comment proposing that better performance
* is possible by only enabling interrupts on the last item in the linked list.
* However, it seems that could be a problem if an error happened on one of the
* first items. The transfer would halt, but no error interrupt would occur.
* Currently this function sets interrupts enabled for each linked list item:
* DMA_CTL_INT_EN.
*/
static int map_sg_to_lli(struct scatterlist *sg, int num_elems,
struct lli *lli, dma_addr_t dma_lli,
void __iomem *dmadr_addr, int dir)
{
int i, idx = 0;
int fis_len = 0;
dma_addr_t next_llp;
int bl;
int sms_val, dms_val;
sms_val = 0;
dms_val = 1 + host_pvt.dma_channel;
dev_dbg(host_pvt.dwc_dev, "%s: sg=%p nelem=%d lli=%p dma_lli=0x%08x"
" dmadr=0x%08x\n", __func__, sg, num_elems, lli, (u32)dma_lli,
(u32)dmadr_addr);
bl = get_burst_length_encode(AHB_DMA_BRST_DFLT);
for (i = 0; i < num_elems; i++, sg++) {
u32 addr, offset;
u32 sg_len, len;
addr = (u32) sg_dma_address(sg);
sg_len = sg_dma_len(sg);
dev_dbg(host_pvt.dwc_dev, "%s: elem=%d sg_addr=0x%x sg_len"
"=%d\n", __func__, i, addr, sg_len);
while (sg_len) {
if (idx >= SATA_DWC_DMAC_LLI_NUM) {
/* The LLI table is not large enough. */
dev_err(host_pvt.dwc_dev, "LLI table overrun "
"(idx=%d)\n", idx);
break;
}
len = (sg_len > SATA_DWC_DMAC_CTRL_TSIZE_MAX) ?
SATA_DWC_DMAC_CTRL_TSIZE_MAX : sg_len;
offset = addr & 0xffff;
if ((offset + sg_len) > 0x10000)
len = 0x10000 - offset;
/*
* Make sure a LLI block is not created that will span
* 8K max FIS boundary. If the block spans such a FIS
* boundary, there is a chance that a DMA burst will
* cross that boundary -- this results in an error in
* the host controller.
*/
if (fis_len + len > 8192) {
dev_dbg(host_pvt.dwc_dev, "SPLITTING: fis_len="
"%d(0x%x) len=%d(0x%x)\n", fis_len,
fis_len, len, len);
len = 8192 - fis_len;
fis_len = 0;
} else {
fis_len += len;
}
if (fis_len == 8192)
fis_len = 0;
/*
* Set DMA addresses and lower half of control register
* based on direction.
*/
if (dir == DMA_FROM_DEVICE) {
lli[idx].dar = cpu_to_le32(addr);
lli[idx].sar = cpu_to_le32((u32)dmadr_addr);
lli[idx].ctl.low = cpu_to_le32(
DMA_CTL_TTFC(DMA_CTL_TTFC_P2M_DMAC) |
DMA_CTL_SMS(sms_val) |
DMA_CTL_DMS(dms_val) |
DMA_CTL_SRC_MSIZE(bl) |
DMA_CTL_DST_MSIZE(bl) |
DMA_CTL_SINC_NOCHANGE |
DMA_CTL_SRC_TRWID(2) |
DMA_CTL_DST_TRWID(2) |
DMA_CTL_INT_EN |
DMA_CTL_LLP_SRCEN |
DMA_CTL_LLP_DSTEN);
} else { /* DMA_TO_DEVICE */
lli[idx].sar = cpu_to_le32(addr);
lli[idx].dar = cpu_to_le32((u32)dmadr_addr);
lli[idx].ctl.low = cpu_to_le32(
DMA_CTL_TTFC(DMA_CTL_TTFC_M2P_PER) |
DMA_CTL_SMS(dms_val) |
DMA_CTL_DMS(sms_val) |
DMA_CTL_SRC_MSIZE(bl) |
DMA_CTL_DST_MSIZE(bl) |
DMA_CTL_DINC_NOCHANGE |
DMA_CTL_SRC_TRWID(2) |
DMA_CTL_DST_TRWID(2) |
DMA_CTL_INT_EN |
DMA_CTL_LLP_SRCEN |
DMA_CTL_LLP_DSTEN);
}
dev_dbg(host_pvt.dwc_dev, "%s setting ctl.high len: "
"0x%08x val: 0x%08x\n", __func__,
len, DMA_CTL_BLK_TS(len / 4));
/* Program the LLI CTL high register */
lli[idx].ctl.high = cpu_to_le32(DMA_CTL_BLK_TS\
(len / 4));
/* Program the next pointer. The next pointer must be
* the physical address, not the virtual address.
*/
next_llp = (dma_lli + ((idx + 1) * sizeof(struct \
lli)));
/* The last 2 bits encode the list master select. */
next_llp = DMA_LLP_LMS(next_llp, DMA_LLP_AHBMASTER2);
lli[idx].llp = cpu_to_le32(next_llp);
idx++;
sg_len -= len;
addr += len;
}
}
/*
* The last next ptr has to be zero and the last control low register
* has to have LLP_SRC_EN and LLP_DST_EN (linked list pointer source
* and destination enable) set back to 0 (disabled.) This is what tells
* the core that this is the last item in the linked list.
*/
if (idx) {
lli[idx-1].llp = 0x00000000;
lli[idx-1].ctl.low &= DMA_CTL_LLP_DISABLE_LE32;
/* Flush cache to memory */
dma_cache_sync(NULL, lli, (sizeof(struct lli) * idx),
DMA_BIDIRECTIONAL);
}
return idx;
}
/*
* Function: dma_dwc_xfer_start
* arguments: Channel number
* Return : None
* Enables the DMA channel
*/
static void dma_dwc_xfer_start(int dma_ch)
{
/* Enable the DMA channel */
out_le32(&(host_pvt.sata_dma_regs->dma_chan_en.low),
in_le32(&(host_pvt.sata_dma_regs->dma_chan_en.low)) |
DMA_ENABLE_CHAN(dma_ch));
}
static int dma_dwc_xfer_setup(struct scatterlist *sg, int num_elems,
struct lli *lli, dma_addr_t dma_lli,
void __iomem *addr, int dir)
{
int dma_ch;
int num_lli;
/* Acquire DMA channel */
dma_ch = dma_request_channel();
if (dma_ch == -1) {
dev_err(host_pvt.dwc_dev, "%s: dma channel unavailable\n",
__func__);
return -EAGAIN;
}
/* Convert SG list to linked list of items (LLIs) for AHB DMA */
num_lli = map_sg_to_lli(sg, num_elems, lli, dma_lli, addr, dir);
dev_dbg(host_pvt.dwc_dev, "%s sg: 0x%p, count: %d lli: %p dma_lli:"
" 0x%0xlx addr: %p lli count: %d\n", __func__, sg, num_elems,
lli, (u32)dma_lli, addr, num_lli);
clear_chan_interrupts(dma_ch);
/* Program the CFG register. */
out_le32(&(host_pvt.sata_dma_regs->chan_regs[dma_ch].cfg.high),
DMA_CFG_HW_HS_SRC(dma_ch) | DMA_CFG_HW_HS_DEST(dma_ch) |
DMA_CFG_PROTCTL | DMA_CFG_FCMOD_REQ);
out_le32(&(host_pvt.sata_dma_regs->chan_regs[dma_ch].cfg.low),
DMA_CFG_HW_CH_PRIOR(dma_ch));
/* Program the address of the linked list */
out_le32(&(host_pvt.sata_dma_regs->chan_regs[dma_ch].llp.low),
DMA_LLP_LMS(dma_lli, DMA_LLP_AHBMASTER2));
/* Program the CTL register with src enable / dst enable */
out_le32(&(host_pvt.sata_dma_regs->chan_regs[dma_ch].ctl.low),
DMA_CTL_LLP_SRCEN | DMA_CTL_LLP_DSTEN);
return dma_ch;
}
/*
* Function: dma_dwc_exit
* arguments: None
* returns status
* This function exits the SATA DMA driver
*/
static void dma_dwc_exit(struct sata_dwc_device *hsdev)
{
dev_dbg(host_pvt.dwc_dev, "%s:\n", __func__);
if (host_pvt.sata_dma_regs) {
iounmap(host_pvt.sata_dma_regs);
host_pvt.sata_dma_regs = NULL;
}
if (hsdev->irq_dma) {
free_irq(hsdev->irq_dma, hsdev);
hsdev->irq_dma = 0;
}
}
/*
* Function: dma_dwc_init
* arguments: hsdev
* returns status
* This function initializes the SATA DMA driver
*/
static int dma_dwc_init(struct sata_dwc_device *hsdev, int irq)
{
int err;
err = dma_request_interrupts(hsdev, irq);
if (err) {
dev_err(host_pvt.dwc_dev, "%s: dma_request_interrupts returns"
" %d\n", __func__, err);
goto error_out;
}
/* Enabe DMA */
out_le32(&(host_pvt.sata_dma_regs->dma_cfg.low), DMA_EN);
dev_notice(host_pvt.dwc_dev, "DMA initialized\n");
dev_dbg(host_pvt.dwc_dev, "SATA DMA registers=0x%p\n", host_pvt.\
sata_dma_regs);
return 0;
error_out:
dma_dwc_exit(hsdev);
return err;
}
static int sata_dwc_scr_read(struct ata_link *link, unsigned int scr, u32 *val)
{
if (scr > SCR_NOTIFICATION) {
dev_err(link->ap->dev, "%s: Incorrect SCR offset 0x%02x\n",
__func__, scr);
return -EINVAL;
}
*val = in_le32((void *)link->ap->ioaddr.scr_addr + (scr * 4));
dev_dbg(link->ap->dev, "%s: id=%d reg=%d val=val=0x%08x\n",
__func__, link->ap->print_id, scr, *val);
return 0;
}
static int sata_dwc_scr_write(struct ata_link *link, unsigned int scr, u32 val)
{
dev_dbg(link->ap->dev, "%s: id=%d reg=%d val=val=0x%08x\n",
__func__, link->ap->print_id, scr, val);
if (scr > SCR_NOTIFICATION) {
dev_err(link->ap->dev, "%s: Incorrect SCR offset 0x%02x\n",
__func__, scr);
return -EINVAL;
}
out_le32((void *)link->ap->ioaddr.scr_addr + (scr * 4), val);
return 0;
}
static u32 core_scr_read(unsigned int scr)
{
return in_le32((void __iomem *)(host_pvt.scr_addr_sstatus) +\
(scr * 4));
}
static void core_scr_write(unsigned int scr, u32 val)
{
out_le32((void __iomem *)(host_pvt.scr_addr_sstatus) + (scr * 4),
val);
}
static void clear_serror(void)
{
u32 val;
val = core_scr_read(SCR_ERROR);
core_scr_write(SCR_ERROR, val);
}
static void clear_interrupt_bit(struct sata_dwc_device *hsdev, u32 bit)
{
out_le32(&hsdev->sata_dwc_regs->intpr,
in_le32(&hsdev->sata_dwc_regs->intpr));
}
static u32 qcmd_tag_to_mask(u8 tag)
{
return 0x00000001 << (tag & 0x1f);
}
/* See ahci.c */
static void sata_dwc_error_intr(struct ata_port *ap,
struct sata_dwc_device *hsdev, uint intpr)
{
struct sata_dwc_device_port *hsdevp = HSDEVP_FROM_AP(ap);
struct ata_eh_info *ehi = &ap->link.eh_info;
unsigned int err_mask = 0, action = 0;
struct ata_queued_cmd *qc;
u32 serror;
u8 status, tag;
u32 err_reg;
ata_ehi_clear_desc(ehi);
serror = core_scr_read(SCR_ERROR);
status = ap->ops->sff_check_status(ap);
err_reg = in_le32(&(host_pvt.sata_dma_regs->interrupt_status.error.\
low));
tag = ap->link.active_tag;
dev_err(ap->dev, "%s SCR_ERROR=0x%08x intpr=0x%08x status=0x%08x "
"dma_intp=%d pending=%d issued=%d dma_err_status=0x%08x\n",
__func__, serror, intpr, status, host_pvt.dma_interrupt_count,
hsdevp->dma_pending[tag], hsdevp->cmd_issued[tag], err_reg);
/* Clear error register and interrupt bit */
clear_serror();
clear_interrupt_bit(hsdev, SATA_DWC_INTPR_ERR);
/* This is the only error happening now. TODO check for exact error */
err_mask |= AC_ERR_HOST_BUS;
action |= ATA_EH_RESET;
/* Pass this on to EH */
ehi->serror |= serror;
ehi->action |= action;
qc = ata_qc_from_tag(ap, tag);
if (qc)
qc->err_mask |= err_mask;
else
ehi->err_mask |= err_mask;
ata_port_abort(ap);
}
/*
* Function : sata_dwc_isr
* arguments : irq, void *dev_instance, struct pt_regs *regs
* Return value : irqreturn_t - status of IRQ
* This Interrupt handler called via port ops registered function.
* .irq_handler = sata_dwc_isr
*/
static irqreturn_t sata_dwc_isr(int irq, void *dev_instance)
{
struct ata_host *host = (struct ata_host *)dev_instance;
struct sata_dwc_device *hsdev = HSDEV_FROM_HOST(host);
struct ata_port *ap;
struct ata_queued_cmd *qc;
unsigned long flags;
u8 status, tag;
int handled, num_processed, port = 0;
uint intpr, sactive, sactive2, tag_mask;
struct sata_dwc_device_port *hsdevp;
host_pvt.sata_dwc_sactive_issued = 0;
spin_lock_irqsave(&host->lock, flags);
/* Read the interrupt register */
intpr = in_le32(&hsdev->sata_dwc_regs->intpr);
ap = host->ports[port];
hsdevp = HSDEVP_FROM_AP(ap);
dev_dbg(ap->dev, "%s intpr=0x%08x active_tag=%d\n", __func__, intpr,
ap->link.active_tag);
/* Check for error interrupt */
if (intpr & SATA_DWC_INTPR_ERR) {
sata_dwc_error_intr(ap, hsdev, intpr);
handled = 1;
goto DONE;
}
/* Check for DMA SETUP FIS (FP DMA) interrupt */
if (intpr & SATA_DWC_INTPR_NEWFP) {
clear_interrupt_bit(hsdev, SATA_DWC_INTPR_NEWFP);
tag = (u8)(in_le32(&hsdev->sata_dwc_regs->fptagr));
dev_dbg(ap->dev, "%s: NEWFP tag=%d\n", __func__, tag);
if (hsdevp->cmd_issued[tag] != SATA_DWC_CMD_ISSUED_PEND)
dev_warn(ap->dev, "CMD tag=%d not pending?\n", tag);
host_pvt.sata_dwc_sactive_issued |= qcmd_tag_to_mask(tag);
qc = ata_qc_from_tag(ap, tag);
/*
* Start FP DMA for NCQ command. At this point the tag is the
* active tag. It is the tag that matches the command about to
* be completed.
*/
qc->ap->link.active_tag = tag;
sata_dwc_bmdma_start_by_tag(qc, tag);
handled = 1;
goto DONE;
}
sactive = core_scr_read(SCR_ACTIVE);
tag_mask = (host_pvt.sata_dwc_sactive_issued | sactive) ^ sactive;
/* If no sactive issued and tag_mask is zero then this is not NCQ */
if (host_pvt.sata_dwc_sactive_issued == 0 && tag_mask == 0) {
if (ap->link.active_tag == ATA_TAG_POISON)
tag = 0;
else
tag = ap->link.active_tag;
qc = ata_qc_from_tag(ap, tag);
/* DEV interrupt w/ no active qc? */
if (unlikely(!qc || (qc->tf.flags & ATA_TFLAG_POLLING))) {
dev_err(ap->dev, "%s interrupt with no active qc "
"qc=%p\n", __func__, qc);
ap->ops->sff_check_status(ap);
handled = 1;
goto DONE;
}
status = ap->ops->sff_check_status(ap);
qc->ap->link.active_tag = tag;
hsdevp->cmd_issued[tag] = SATA_DWC_CMD_ISSUED_NOT;
if (status & ATA_ERR) {
dev_dbg(ap->dev, "interrupt ATA_ERR (0x%x)\n", status);
sata_dwc_qc_complete(ap, qc, 1);
handled = 1;
goto DONE;
}
dev_dbg(ap->dev, "%s non-NCQ cmd interrupt, protocol: %s\n",
__func__, get_prot_descript(qc->tf.protocol));
DRVSTILLBUSY:
if (ata_is_dma(qc->tf.protocol)) {
/*
* Each DMA transaction produces 2 interrupts. The DMAC
* transfer complete interrupt and the SATA controller
* operation done interrupt. The command should be
* completed only after both interrupts are seen.
*/
host_pvt.dma_interrupt_count++;
if (hsdevp->dma_pending[tag] == \
SATA_DWC_DMA_PENDING_NONE) {
dev_err(ap->dev, "%s: DMA not pending "
"intpr=0x%08x status=0x%08x pending"
"=%d\n", __func__, intpr, status,
hsdevp->dma_pending[tag]);
}
if ((host_pvt.dma_interrupt_count % 2) == 0)
sata_dwc_dma_xfer_complete(ap, 1);
} else if (ata_is_pio(qc->tf.protocol)) {
ata_sff_hsm_move(ap, qc, status, 0);
handled = 1;
goto DONE;
} else {
if (unlikely(sata_dwc_qc_complete(ap, qc, 1)))
goto DRVSTILLBUSY;
}
handled = 1;
goto DONE;
}
/*
* This is a NCQ command. At this point we need to figure out for which
* tags we have gotten a completion interrupt. One interrupt may serve
* as completion for more than one operation when commands are queued
* (NCQ). We need to process each completed command.
*/
/* process completed commands */
sactive = core_scr_read(SCR_ACTIVE);
tag_mask = (host_pvt.sata_dwc_sactive_issued | sactive) ^ sactive;
if (sactive != 0 || (host_pvt.sata_dwc_sactive_issued) > 1 || \
tag_mask > 1) {
dev_dbg(ap->dev, "%s NCQ:sactive=0x%08x sactive_issued=0x%08x"
"tag_mask=0x%08x\n", __func__, sactive,
host_pvt.sata_dwc_sactive_issued, tag_mask);
}
if ((tag_mask | (host_pvt.sata_dwc_sactive_issued)) != \
(host_pvt.sata_dwc_sactive_issued)) {
dev_warn(ap->dev, "Bad tag mask? sactive=0x%08x "
"(host_pvt.sata_dwc_sactive_issued)=0x%08x tag_mask"
"=0x%08x\n", sactive, host_pvt.sata_dwc_sactive_issued,
tag_mask);
}
/* read just to clear ... not bad if currently still busy */
status = ap->ops->sff_check_status(ap);
dev_dbg(ap->dev, "%s ATA status register=0x%x\n", __func__, status);
tag = 0;
num_processed = 0;
while (tag_mask) {
num_processed++;
while (!(tag_mask & 0x00000001)) {
tag++;
tag_mask <<= 1;
}
tag_mask &= (~0x00000001);
qc = ata_qc_from_tag(ap, tag);
/* To be picked up by completion functions */
qc->ap->link.active_tag = tag;
hsdevp->cmd_issued[tag] = SATA_DWC_CMD_ISSUED_NOT;
/* Let libata/scsi layers handle error */
if (status & ATA_ERR) {
dev_dbg(ap->dev, "%s ATA_ERR (0x%x)\n", __func__,
status);
sata_dwc_qc_complete(ap, qc, 1);
handled = 1;
goto DONE;
}
/* Process completed command */
dev_dbg(ap->dev, "%s NCQ command, protocol: %s\n", __func__,
get_prot_descript(qc->tf.protocol));
if (ata_is_dma(qc->tf.protocol)) {
host_pvt.dma_interrupt_count++;
if (hsdevp->dma_pending[tag] == \
SATA_DWC_DMA_PENDING_NONE)
dev_warn(ap->dev, "%s: DMA not pending?\n",
__func__);
if ((host_pvt.dma_interrupt_count % 2) == 0)
sata_dwc_dma_xfer_complete(ap, 1);
} else {
if (unlikely(sata_dwc_qc_complete(ap, qc, 1)))
goto STILLBUSY;
}
continue;
STILLBUSY:
ap->stats.idle_irq++;
dev_warn(ap->dev, "STILL BUSY IRQ ata%d: irq trap\n",
ap->print_id);
} /* while tag_mask */
/*
* Check to see if any commands completed while we were processing our
* initial set of completed commands (read status clears interrupts,
* so we might miss a completed command interrupt if one came in while
* we were processing --we read status as part of processing a completed
* command).
*/
sactive2 = core_scr_read(SCR_ACTIVE);
if (sactive2 != sactive) {
dev_dbg(ap->dev, "More completed - sactive=0x%x sactive2"
"=0x%x\n", sactive, sactive2);
}
handled = 1;
DONE:
spin_unlock_irqrestore(&host->lock, flags);
return IRQ_RETVAL(handled);
}
static void sata_dwc_clear_dmacr(struct sata_dwc_device_port *hsdevp, u8 tag)
{
struct sata_dwc_device *hsdev = HSDEV_FROM_HSDEVP(hsdevp);
if (hsdevp->dma_pending[tag] == SATA_DWC_DMA_PENDING_RX) {
out_le32(&(hsdev->sata_dwc_regs->dmacr),
SATA_DWC_DMACR_RX_CLEAR(
in_le32(&(hsdev->sata_dwc_regs->dmacr))));
} else if (hsdevp->dma_pending[tag] == SATA_DWC_DMA_PENDING_TX) {
out_le32(&(hsdev->sata_dwc_regs->dmacr),
SATA_DWC_DMACR_TX_CLEAR(
in_le32(&(hsdev->sata_dwc_regs->dmacr))));
} else {
/*
* This should not happen, it indicates the driver is out of
* sync. If it does happen, clear dmacr anyway.
*/
dev_err(host_pvt.dwc_dev, "%s DMA protocol RX and"
"TX DMA not pending tag=0x%02x pending=%d"
" dmacr: 0x%08x\n", __func__, tag,
hsdevp->dma_pending[tag],
in_le32(&(hsdev->sata_dwc_regs->dmacr)));
out_le32(&(hsdev->sata_dwc_regs->dmacr),
SATA_DWC_DMACR_TXRXCH_CLEAR);
}
}
static void sata_dwc_dma_xfer_complete(struct ata_port *ap, u32 check_status)
{
struct ata_queued_cmd *qc;
struct sata_dwc_device_port *hsdevp = HSDEVP_FROM_AP(ap);
struct sata_dwc_device *hsdev = HSDEV_FROM_AP(ap);
u8 tag = 0;
tag = ap->link.active_tag;
qc = ata_qc_from_tag(ap, tag);
if (!qc) {
dev_err(ap->dev, "failed to get qc");
return;
}
#ifdef DEBUG_NCQ
if (tag > 0) {
dev_info(ap->dev, "%s tag=%u cmd=0x%02x dma dir=%s proto=%s "
"dmacr=0x%08x\n", __func__, qc->tag, qc->tf.command,
get_dma_dir_descript(qc->dma_dir),
get_prot_descript(qc->tf.protocol),
in_le32(&(hsdev->sata_dwc_regs->dmacr)));
}
#endif
if (ata_is_dma(qc->tf.protocol)) {
if (hsdevp->dma_pending[tag] == SATA_DWC_DMA_PENDING_NONE) {
dev_err(ap->dev, "%s DMA protocol RX and TX DMA not "
"pending dmacr: 0x%08x\n", __func__,
in_le32(&(hsdev->sata_dwc_regs->dmacr)));
}
hsdevp->dma_pending[tag] = SATA_DWC_DMA_PENDING_NONE;
sata_dwc_qc_complete(ap, qc, check_status);
ap->link.active_tag = ATA_TAG_POISON;
} else {
sata_dwc_qc_complete(ap, qc, check_status);
}
}
static int sata_dwc_qc_complete(struct ata_port *ap, struct ata_queued_cmd *qc,
u32 check_status)
{
u8 status = 0;
u32 mask = 0x0;
u8 tag = qc->tag;
struct sata_dwc_device_port *hsdevp = HSDEVP_FROM_AP(ap);
host_pvt.sata_dwc_sactive_queued = 0;
dev_dbg(ap->dev, "%s checkstatus? %x\n", __func__, check_status);
if (hsdevp->dma_pending[tag] == SATA_DWC_DMA_PENDING_TX)
dev_err(ap->dev, "TX DMA PENDING\n");
else if (hsdevp->dma_pending[tag] == SATA_DWC_DMA_PENDING_RX)
dev_err(ap->dev, "RX DMA PENDING\n");
dev_dbg(ap->dev, "QC complete cmd=0x%02x status=0x%02x ata%u:"
" protocol=%d\n", qc->tf.command, status, ap->print_id,
qc->tf.protocol);
/* clear active bit */
mask = (~(qcmd_tag_to_mask(tag)));
host_pvt.sata_dwc_sactive_queued = (host_pvt.sata_dwc_sactive_queued) \
& mask;
host_pvt.sata_dwc_sactive_issued = (host_pvt.sata_dwc_sactive_issued) \
& mask;
ata_qc_complete(qc);
return 0;
}
static void sata_dwc_enable_interrupts(struct sata_dwc_device *hsdev)
{
/* Enable selective interrupts by setting the interrupt maskregister*/
out_le32(&hsdev->sata_dwc_regs->intmr,
SATA_DWC_INTMR_ERRM |
SATA_DWC_INTMR_NEWFPM |
SATA_DWC_INTMR_PMABRTM |
SATA_DWC_INTMR_DMATM);
/*
* Unmask the error bits that should trigger an error interrupt by
* setting the error mask register.
*/
out_le32(&hsdev->sata_dwc_regs->errmr, SATA_DWC_SERROR_ERR_BITS);
dev_dbg(host_pvt.dwc_dev, "%s: INTMR = 0x%08x, ERRMR = 0x%08x\n",
__func__, in_le32(&hsdev->sata_dwc_regs->intmr),
in_le32(&hsdev->sata_dwc_regs->errmr));
}
static void sata_dwc_setup_port(struct ata_ioports *port, unsigned long base)
{
port->cmd_addr = (void *)base + 0x00;
port->data_addr = (void *)base + 0x00;
port->error_addr = (void *)base + 0x04;
port->feature_addr = (void *)base + 0x04;
port->nsect_addr = (void *)base + 0x08;
port->lbal_addr = (void *)base + 0x0c;
port->lbam_addr = (void *)base + 0x10;
port->lbah_addr = (void *)base + 0x14;
port->device_addr = (void *)base + 0x18;
port->command_addr = (void *)base + 0x1c;
port->status_addr = (void *)base + 0x1c;
port->altstatus_addr = (void *)base + 0x20;
port->ctl_addr = (void *)base + 0x20;
}
/*
* Function : sata_dwc_port_start
* arguments : struct ata_ioports *port
* Return value : returns 0 if success, error code otherwise
* This function allocates the scatter gather LLI table for AHB DMA
*/
static int sata_dwc_port_start(struct ata_port *ap)
{
int err = 0;
struct sata_dwc_device *hsdev;
struct sata_dwc_device_port *hsdevp = NULL;
struct device *pdev;
int i;
hsdev = HSDEV_FROM_AP(ap);
dev_dbg(ap->dev, "%s: port_no=%d\n", __func__, ap->port_no);
hsdev->host = ap->host;
pdev = ap->host->dev;
if (!pdev) {
dev_err(ap->dev, "%s: no ap->host->dev\n", __func__);
err = -ENODEV;
goto CLEANUP;
}
/* Allocate Port Struct */
hsdevp = kzalloc(sizeof(*hsdevp), GFP_KERNEL);
if (!hsdevp) {
dev_err(ap->dev, "%s: kmalloc failed for hsdevp\n", __func__);
err = -ENOMEM;
goto CLEANUP;
}
hsdevp->hsdev = hsdev;
for (i = 0; i < SATA_DWC_QCMD_MAX; i++)
hsdevp->cmd_issued[i] = SATA_DWC_CMD_ISSUED_NOT;
ap->bmdma_prd = 0; /* set these so libata doesn't use them */
ap->bmdma_prd_dma = 0;
/*
* DMA - Assign scatter gather LLI table. We can't use the libata
* version since it's PRD is IDE PCI specific.
*/
for (i = 0; i < SATA_DWC_QCMD_MAX; i++) {
hsdevp->llit[i] = dma_alloc_coherent(pdev,
SATA_DWC_DMAC_LLI_TBL_SZ,
&(hsdevp->llit_dma[i]),
GFP_ATOMIC);
if (!hsdevp->llit[i]) {
dev_err(ap->dev, "%s: dma_alloc_coherent failed\n",
__func__);
err = -ENOMEM;
goto CLEANUP_ALLOC;
}
}
if (ap->port_no == 0) {
dev_dbg(ap->dev, "%s: clearing TXCHEN, RXCHEN in DMAC\n",
__func__);
out_le32(&hsdev->sata_dwc_regs->dmacr,
SATA_DWC_DMACR_TXRXCH_CLEAR);
dev_dbg(ap->dev, "%s: setting burst size in DBTSR\n",
__func__);
out_le32(&hsdev->sata_dwc_regs->dbtsr,
(SATA_DWC_DBTSR_MWR(AHB_DMA_BRST_DFLT) |
SATA_DWC_DBTSR_MRD(AHB_DMA_BRST_DFLT)));
}
/* Clear any error bits before libata starts issuing commands */
clear_serror();
ap->private_data = hsdevp;
dev_dbg(ap->dev, "%s: done\n", __func__);
return 0;
CLEANUP_ALLOC:
kfree(hsdevp);
CLEANUP:
dev_dbg(ap->dev, "%s: fail. ap->id = %d\n", __func__, ap->print_id);
return err;
}
static void sata_dwc_port_stop(struct ata_port *ap)
{
int i;
struct sata_dwc_device *hsdev = HSDEV_FROM_AP(ap);
struct sata_dwc_device_port *hsdevp = HSDEVP_FROM_AP(ap);
dev_dbg(ap->dev, "%s: ap->id = %d\n", __func__, ap->print_id);
if (hsdevp && hsdev) {
/* deallocate LLI table */
for (i = 0; i < SATA_DWC_QCMD_MAX; i++) {
dma_free_coherent(ap->host->dev,
SATA_DWC_DMAC_LLI_TBL_SZ,
hsdevp->llit[i], hsdevp->llit_dma[i]);
}
kfree(hsdevp);
}
ap->private_data = NULL;
}
/*
* Function : sata_dwc_exec_command_by_tag
* arguments : ata_port *ap, ata_taskfile *tf, u8 tag, u32 cmd_issued
* Return value : None
* This function keeps track of individual command tag ids and calls
* ata_exec_command in libata
*/
static void sata_dwc_exec_command_by_tag(struct ata_port *ap,
struct ata_taskfile *tf,
u8 tag, u32 cmd_issued)
{
unsigned long flags;
struct sata_dwc_device_port *hsdevp = HSDEVP_FROM_AP(ap);
dev_dbg(ap->dev, "%s cmd(0x%02x): %s tag=%d\n", __func__, tf->command,
ata_get_cmd_descript(tf->command), tag);
spin_lock_irqsave(&ap->host->lock, flags);
hsdevp->cmd_issued[tag] = cmd_issued;
spin_unlock_irqrestore(&ap->host->lock, flags);
/*
* Clear SError before executing a new command.
* sata_dwc_scr_write and read can not be used here. Clearing the PM
* managed SError register for the disk needs to be done before the
* task file is loaded.
*/
clear_serror();
ata_sff_exec_command(ap, tf);
}
static void sata_dwc_bmdma_setup_by_tag(struct ata_queued_cmd *qc, u8 tag)
{
sata_dwc_exec_command_by_tag(qc->ap, &qc->tf, tag,
SATA_DWC_CMD_ISSUED_PEND);
}
static void sata_dwc_bmdma_setup(struct ata_queued_cmd *qc)
{
u8 tag = qc->tag;
if (ata_is_ncq(qc->tf.protocol)) {
dev_dbg(qc->ap->dev, "%s: ap->link.sactive=0x%08x tag=%d\n",
__func__, qc->ap->link.sactive, tag);
} else {
tag = 0;
}
sata_dwc_bmdma_setup_by_tag(qc, tag);
}
static void sata_dwc_bmdma_start_by_tag(struct ata_queued_cmd *qc, u8 tag)
{
int start_dma;
u32 reg, dma_chan;
struct sata_dwc_device *hsdev = HSDEV_FROM_QC(qc);
struct ata_port *ap = qc->ap;
struct sata_dwc_device_port *hsdevp = HSDEVP_FROM_AP(ap);
int dir = qc->dma_dir;
dma_chan = hsdevp->dma_chan[tag];
if (hsdevp->cmd_issued[tag] != SATA_DWC_CMD_ISSUED_NOT) {
start_dma = 1;
if (dir == DMA_TO_DEVICE)
hsdevp->dma_pending[tag] = SATA_DWC_DMA_PENDING_TX;
else
hsdevp->dma_pending[tag] = SATA_DWC_DMA_PENDING_RX;
} else {
dev_err(ap->dev, "%s: Command not pending cmd_issued=%d "
"(tag=%d) DMA NOT started\n", __func__,
hsdevp->cmd_issued[tag], tag);
start_dma = 0;
}
dev_dbg(ap->dev, "%s qc=%p tag: %x cmd: 0x%02x dma_dir: %s "
"start_dma? %x\n", __func__, qc, tag, qc->tf.command,
get_dma_dir_descript(qc->dma_dir), start_dma);
sata_dwc_tf_dump(&(qc->tf));
if (start_dma) {
reg = core_scr_read(SCR_ERROR);
if (reg & SATA_DWC_SERROR_ERR_BITS) {
dev_err(ap->dev, "%s: ****** SError=0x%08x ******\n",
__func__, reg);
}
if (dir == DMA_TO_DEVICE)
out_le32(&hsdev->sata_dwc_regs->dmacr,
SATA_DWC_DMACR_TXCHEN);
else
out_le32(&hsdev->sata_dwc_regs->dmacr,
SATA_DWC_DMACR_RXCHEN);
/* Enable AHB DMA transfer on the specified channel */
dma_dwc_xfer_start(dma_chan);
}
}
static void sata_dwc_bmdma_start(struct ata_queued_cmd *qc)
{
u8 tag = qc->tag;
if (ata_is_ncq(qc->tf.protocol)) {
dev_dbg(qc->ap->dev, "%s: ap->link.sactive=0x%08x tag=%d\n",
__func__, qc->ap->link.sactive, tag);
} else {
tag = 0;
}
dev_dbg(qc->ap->dev, "%s\n", __func__);
sata_dwc_bmdma_start_by_tag(qc, tag);
}
/*
* Function : sata_dwc_qc_prep_by_tag
* arguments : ata_queued_cmd *qc, u8 tag
* Return value : None
* qc_prep for a particular queued command based on tag
*/
static void sata_dwc_qc_prep_by_tag(struct ata_queued_cmd *qc, u8 tag)
{
struct scatterlist *sg = qc->sg;
struct ata_port *ap = qc->ap;
int dma_chan;
struct sata_dwc_device *hsdev = HSDEV_FROM_AP(ap);
struct sata_dwc_device_port *hsdevp = HSDEVP_FROM_AP(ap);
dev_dbg(ap->dev, "%s: port=%d dma dir=%s n_elem=%d\n",
__func__, ap->port_no, get_dma_dir_descript(qc->dma_dir),
qc->n_elem);
dma_chan = dma_dwc_xfer_setup(sg, qc->n_elem, hsdevp->llit[tag],
hsdevp->llit_dma[tag],
(void *__iomem)(&hsdev->sata_dwc_regs->\
dmadr), qc->dma_dir);
if (dma_chan < 0) {
dev_err(ap->dev, "%s: dma_dwc_xfer_setup returns err %d\n",
__func__, dma_chan);
return;
}
hsdevp->dma_chan[tag] = dma_chan;
}
static unsigned int sata_dwc_qc_issue(struct ata_queued_cmd *qc)
{
u32 sactive;
u8 tag = qc->tag;
struct ata_port *ap = qc->ap;
#ifdef DEBUG_NCQ
if (qc->tag > 0 || ap->link.sactive > 1)
dev_info(ap->dev, "%s ap id=%d cmd(0x%02x)=%s qc tag=%d "
"prot=%s ap active_tag=0x%08x ap sactive=0x%08x\n",
__func__, ap->print_id, qc->tf.command,
ata_get_cmd_descript(qc->tf.command),
qc->tag, get_prot_descript(qc->tf.protocol),
ap->link.active_tag, ap->link.sactive);
#endif
if (!ata_is_ncq(qc->tf.protocol))
tag = 0;
sata_dwc_qc_prep_by_tag(qc, tag);
if (ata_is_ncq(qc->tf.protocol)) {
sactive = core_scr_read(SCR_ACTIVE);
sactive |= (0x00000001 << tag);
core_scr_write(SCR_ACTIVE, sactive);
dev_dbg(qc->ap->dev, "%s: tag=%d ap->link.sactive = 0x%08x "
"sactive=0x%08x\n", __func__, tag, qc->ap->link.sactive,
sactive);
ap->ops->sff_tf_load(ap, &qc->tf);
sata_dwc_exec_command_by_tag(ap, &qc->tf, qc->tag,
SATA_DWC_CMD_ISSUED_PEND);
} else {
ata_sff_qc_issue(qc);
}
return 0;
}
/*
* Function : sata_dwc_qc_prep
* arguments : ata_queued_cmd *qc
* Return value : None
* qc_prep for a particular queued command
*/
static void sata_dwc_qc_prep(struct ata_queued_cmd *qc)
{
if ((qc->dma_dir == DMA_NONE) || (qc->tf.protocol == ATA_PROT_PIO))
return;
#ifdef DEBUG_NCQ
if (qc->tag > 0)
dev_info(qc->ap->dev, "%s: qc->tag=%d ap->active_tag=0x%08x\n",
__func__, qc->tag, qc->ap->link.active_tag);
return ;
#endif
}
static void sata_dwc_error_handler(struct ata_port *ap)
{
ata_sff_error_handler(ap);
}
int sata_dwc_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
struct sata_dwc_device *hsdev = HSDEV_FROM_AP(link->ap);
int ret;
ret = sata_sff_hardreset(link, class, deadline);
sata_dwc_enable_interrupts(hsdev);
/* Reconfigure the DMA control register */
out_le32(&hsdev->sata_dwc_regs->dmacr,
SATA_DWC_DMACR_TXRXCH_CLEAR);
/* Reconfigure the DMA Burst Transaction Size register */
out_le32(&hsdev->sata_dwc_regs->dbtsr,
SATA_DWC_DBTSR_MWR(AHB_DMA_BRST_DFLT) |
SATA_DWC_DBTSR_MRD(AHB_DMA_BRST_DFLT));
return ret;
}
/*
* scsi mid-layer and libata interface structures
*/
static struct scsi_host_template sata_dwc_sht = {
ATA_NCQ_SHT(DRV_NAME),
/*
* test-only: Currently this driver doesn't handle NCQ
* correctly. We enable NCQ but set the queue depth to a
* max of 1. This will get fixed in in a future release.
*/
.sg_tablesize = LIBATA_MAX_PRD,
.can_queue = ATA_DEF_QUEUE, /* ATA_MAX_QUEUE */
.dma_boundary = ATA_DMA_BOUNDARY,
};
static struct ata_port_operations sata_dwc_ops = {
.inherits = &ata_sff_port_ops,
.error_handler = sata_dwc_error_handler,
.hardreset = sata_dwc_hardreset,
.qc_prep = sata_dwc_qc_prep,
.qc_issue = sata_dwc_qc_issue,
.scr_read = sata_dwc_scr_read,
.scr_write = sata_dwc_scr_write,
.port_start = sata_dwc_port_start,
.port_stop = sata_dwc_port_stop,
.bmdma_setup = sata_dwc_bmdma_setup,
.bmdma_start = sata_dwc_bmdma_start,
};
static const struct ata_port_info sata_dwc_port_info[] = {
{
.flags = ATA_FLAG_SATA | ATA_FLAG_NCQ,
.pio_mask = ATA_PIO4,
.udma_mask = ATA_UDMA6,
.port_ops = &sata_dwc_ops,
},
};
static int sata_dwc_probe(struct platform_device *ofdev)
{
struct sata_dwc_device *hsdev;
u32 idr, versionr;
char *ver = (char *)&versionr;
u8 *base = NULL;
int err = 0;
int irq, rc;
struct ata_host *host;
struct ata_port_info pi = sata_dwc_port_info[0];
const struct ata_port_info *ppi[] = { &pi, NULL };
struct device_node *np = ofdev->dev.of_node;
u32 dma_chan;
/* Allocate DWC SATA device */
hsdev = kzalloc(sizeof(*hsdev), GFP_KERNEL);
if (hsdev == NULL) {
dev_err(&ofdev->dev, "kmalloc failed for hsdev\n");
err = -ENOMEM;
goto error;
}
if (of_property_read_u32(np, "dma-channel", &dma_chan)) {
dev_warn(&ofdev->dev, "no dma-channel property set."
" Use channel 0\n");
dma_chan = 0;
}
host_pvt.dma_channel = dma_chan;
/* Ioremap SATA registers */
base = of_iomap(ofdev->dev.of_node, 0);
if (!base) {
dev_err(&ofdev->dev, "ioremap failed for SATA register"
" address\n");
err = -ENODEV;
goto error_kmalloc;
}
hsdev->reg_base = base;
dev_dbg(&ofdev->dev, "ioremap done for SATA register address\n");
/* Synopsys DWC SATA specific Registers */
hsdev->sata_dwc_regs = (void *__iomem)(base + SATA_DWC_REG_OFFSET);
/* Allocate and fill host */
host = ata_host_alloc_pinfo(&ofdev->dev, ppi, SATA_DWC_MAX_PORTS);
if (!host) {
dev_err(&ofdev->dev, "ata_host_alloc_pinfo failed\n");
err = -ENOMEM;
goto error_iomap;
}
host->private_data = hsdev;
/* Setup port */
host->ports[0]->ioaddr.cmd_addr = base;
host->ports[0]->ioaddr.scr_addr = base + SATA_DWC_SCR_OFFSET;
host_pvt.scr_addr_sstatus = base + SATA_DWC_SCR_OFFSET;
sata_dwc_setup_port(&host->ports[0]->ioaddr, (unsigned long)base);
/* Read the ID and Version Registers */
idr = in_le32(&hsdev->sata_dwc_regs->idr);
versionr = in_le32(&hsdev->sata_dwc_regs->versionr);
dev_notice(&ofdev->dev, "id %d, controller version %c.%c%c\n",
idr, ver[0], ver[1], ver[2]);
/* Get SATA DMA interrupt number */
irq = irq_of_parse_and_map(ofdev->dev.of_node, 1);
if (irq == NO_IRQ) {
dev_err(&ofdev->dev, "no SATA DMA irq\n");
err = -ENODEV;
goto error_out;
}
/* Get physical SATA DMA register base address */
host_pvt.sata_dma_regs = of_iomap(ofdev->dev.of_node, 1);
if (!(host_pvt.sata_dma_regs)) {
dev_err(&ofdev->dev, "ioremap failed for AHBDMA register"
" address\n");
err = -ENODEV;
goto error_out;
}
/* Save dev for later use in dev_xxx() routines */
host_pvt.dwc_dev = &ofdev->dev;
/* Initialize AHB DMAC */
dma_dwc_init(hsdev, irq);
/* Enable SATA Interrupts */
sata_dwc_enable_interrupts(hsdev);
/* Get SATA interrupt number */
irq = irq_of_parse_and_map(ofdev->dev.of_node, 0);
if (irq == NO_IRQ) {
dev_err(&ofdev->dev, "no SATA DMA irq\n");
err = -ENODEV;
goto error_out;
}
/*
* Now, register with libATA core, this will also initiate the
* device discovery process, invoking our port_start() handler &
* error_handler() to execute a dummy Softreset EH session
*/
rc = ata_host_activate(host, irq, sata_dwc_isr, 0, &sata_dwc_sht);
if (rc != 0)
dev_err(&ofdev->dev, "failed to activate host");
dev_set_drvdata(&ofdev->dev, host);
return 0;
error_out:
/* Free SATA DMA resources */
dma_dwc_exit(hsdev);
error_iomap:
iounmap(base);
error_kmalloc:
kfree(hsdev);
error:
return err;
}
static int sata_dwc_remove(struct platform_device *ofdev)
{
struct device *dev = &ofdev->dev;
struct ata_host *host = dev_get_drvdata(dev);
struct sata_dwc_device *hsdev = host->private_data;
ata_host_detach(host);
dev_set_drvdata(dev, NULL);
/* Free SATA DMA resources */
dma_dwc_exit(hsdev);
iounmap(hsdev->reg_base);
kfree(hsdev);
kfree(host);
dev_dbg(&ofdev->dev, "done\n");
return 0;
}
static const struct of_device_id sata_dwc_match[] = {
{ .compatible = "amcc,sata-460ex", },
{}
};
MODULE_DEVICE_TABLE(of, sata_dwc_match);
static struct platform_driver sata_dwc_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = sata_dwc_match,
},
.probe = sata_dwc_probe,
.remove = sata_dwc_remove,
};
module_platform_driver(sata_dwc_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mark Miesfeld <mmiesfeld@amcc.com>");
MODULE_DESCRIPTION("DesignWare Cores SATA controller low lever driver");
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
malsony/linux | drivers/input/misc/keyspan_remote.c | 1757 | 15553 | /*
* keyspan_remote: USB driver for the Keyspan DMR
*
* Copyright (C) 2005 Zymeta Corporation - Michael Downey (downey@zymeta.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, version 2.
*
* This driver has been put together with the support of Innosys, Inc.
* and Keyspan, Inc the manufacturers of the Keyspan USB DMR product.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/usb/input.h>
#define DRIVER_VERSION "v0.1"
#define DRIVER_AUTHOR "Michael Downey <downey@zymeta.com>"
#define DRIVER_DESC "Driver for the USB Keyspan remote control."
#define DRIVER_LICENSE "GPL"
/* Parameters that can be passed to the driver. */
static int debug;
module_param(debug, int, 0444);
MODULE_PARM_DESC(debug, "Enable extra debug messages and information");
/* Vendor and product ids */
#define USB_KEYSPAN_VENDOR_ID 0x06CD
#define USB_KEYSPAN_PRODUCT_UIA11 0x0202
/* Defines for converting the data from the remote. */
#define ZERO 0x18
#define ZERO_MASK 0x1F /* 5 bits for a 0 */
#define ONE 0x3C
#define ONE_MASK 0x3F /* 6 bits for a 1 */
#define SYNC 0x3F80
#define SYNC_MASK 0x3FFF /* 14 bits for a SYNC sequence */
#define STOP 0x00
#define STOP_MASK 0x1F /* 5 bits for the STOP sequence */
#define GAP 0xFF
#define RECV_SIZE 8 /* The UIA-11 type have a 8 byte limit. */
/*
* Table that maps the 31 possible keycodes to input keys.
* Currently there are 15 and 17 button models so RESERVED codes
* are blank areas in the mapping.
*/
static const unsigned short keyspan_key_table[] = {
KEY_RESERVED, /* 0 is just a place holder. */
KEY_RESERVED,
KEY_STOP,
KEY_PLAYCD,
KEY_RESERVED,
KEY_PREVIOUSSONG,
KEY_REWIND,
KEY_FORWARD,
KEY_NEXTSONG,
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_PAUSE,
KEY_VOLUMEUP,
KEY_RESERVED,
KEY_RESERVED,
KEY_RESERVED,
KEY_VOLUMEDOWN,
KEY_RESERVED,
KEY_UP,
KEY_RESERVED,
KEY_MUTE,
KEY_LEFT,
KEY_ENTER,
KEY_RIGHT,
KEY_RESERVED,
KEY_RESERVED,
KEY_DOWN,
KEY_RESERVED,
KEY_KPASTERISK,
KEY_RESERVED,
KEY_MENU
};
/* table of devices that work with this driver */
static struct usb_device_id keyspan_table[] = {
{ USB_DEVICE(USB_KEYSPAN_VENDOR_ID, USB_KEYSPAN_PRODUCT_UIA11) },
{ } /* Terminating entry */
};
/* Structure to store all the real stuff that a remote sends to us. */
struct keyspan_message {
u16 system;
u8 button;
u8 toggle;
};
/* Structure used for all the bit testing magic needed to be done. */
struct bit_tester {
u32 tester;
int len;
int pos;
int bits_left;
u8 buffer[32];
};
/* Structure to hold all of our driver specific stuff */
struct usb_keyspan {
char name[128];
char phys[64];
unsigned short keymap[ARRAY_SIZE(keyspan_key_table)];
struct usb_device *udev;
struct input_dev *input;
struct usb_interface *interface;
struct usb_endpoint_descriptor *in_endpoint;
struct urb* irq_urb;
int open;
dma_addr_t in_dma;
unsigned char *in_buffer;
/* variables used to parse messages from remote. */
struct bit_tester data;
int stage;
int toggle;
};
static struct usb_driver keyspan_driver;
/*
* Debug routine that prints out what we've received from the remote.
*/
static void keyspan_print(struct usb_keyspan* dev) /*unsigned char* data)*/
{
char codes[4 * RECV_SIZE];
int i;
for (i = 0; i < RECV_SIZE; i++)
snprintf(codes + i * 3, 4, "%02x ", dev->in_buffer[i]);
dev_info(&dev->udev->dev, "%s\n", codes);
}
/*
* Routine that manages the bit_tester structure. It makes sure that there are
* at least bits_needed bits loaded into the tester.
*/
static int keyspan_load_tester(struct usb_keyspan* dev, int bits_needed)
{
if (dev->data.bits_left >= bits_needed)
return 0;
/*
* Somehow we've missed the last message. The message will be repeated
* though so it's not too big a deal
*/
if (dev->data.pos >= dev->data.len) {
dev_dbg(&dev->interface->dev,
"%s - Error ran out of data. pos: %d, len: %d\n",
__func__, dev->data.pos, dev->data.len);
return -1;
}
/* Load as much as we can into the tester. */
while ((dev->data.bits_left + 7 < (sizeof(dev->data.tester) * 8)) &&
(dev->data.pos < dev->data.len)) {
dev->data.tester += (dev->data.buffer[dev->data.pos++] << dev->data.bits_left);
dev->data.bits_left += 8;
}
return 0;
}
static void keyspan_report_button(struct usb_keyspan *remote, int button, int press)
{
struct input_dev *input = remote->input;
input_event(input, EV_MSC, MSC_SCAN, button);
input_report_key(input, remote->keymap[button], press);
input_sync(input);
}
/*
* Routine that handles all the logic needed to parse out the message from the remote.
*/
static void keyspan_check_data(struct usb_keyspan *remote)
{
int i;
int found = 0;
struct keyspan_message message;
switch(remote->stage) {
case 0:
/*
* In stage 0 we want to find the start of a message. The remote sends a 0xFF as filler.
* So the first byte that isn't a FF should be the start of a new message.
*/
for (i = 0; i < RECV_SIZE && remote->in_buffer[i] == GAP; ++i);
if (i < RECV_SIZE) {
memcpy(remote->data.buffer, remote->in_buffer, RECV_SIZE);
remote->data.len = RECV_SIZE;
remote->data.pos = 0;
remote->data.tester = 0;
remote->data.bits_left = 0;
remote->stage = 1;
}
break;
case 1:
/*
* Stage 1 we should have 16 bytes and should be able to detect a
* SYNC. The SYNC is 14 bits, 7 0's and then 7 1's.
*/
memcpy(remote->data.buffer + remote->data.len, remote->in_buffer, RECV_SIZE);
remote->data.len += RECV_SIZE;
found = 0;
while ((remote->data.bits_left >= 14 || remote->data.pos < remote->data.len) && !found) {
for (i = 0; i < 8; ++i) {
if (keyspan_load_tester(remote, 14) != 0) {
remote->stage = 0;
return;
}
if ((remote->data.tester & SYNC_MASK) == SYNC) {
remote->data.tester = remote->data.tester >> 14;
remote->data.bits_left -= 14;
found = 1;
break;
} else {
remote->data.tester = remote->data.tester >> 1;
--remote->data.bits_left;
}
}
}
if (!found) {
remote->stage = 0;
remote->data.len = 0;
} else {
remote->stage = 2;
}
break;
case 2:
/*
* Stage 2 we should have 24 bytes which will be enough for a full
* message. We need to parse out the system code, button code,
* toggle code, and stop.
*/
memcpy(remote->data.buffer + remote->data.len, remote->in_buffer, RECV_SIZE);
remote->data.len += RECV_SIZE;
message.system = 0;
for (i = 0; i < 9; i++) {
keyspan_load_tester(remote, 6);
if ((remote->data.tester & ZERO_MASK) == ZERO) {
message.system = message.system << 1;
remote->data.tester = remote->data.tester >> 5;
remote->data.bits_left -= 5;
} else if ((remote->data.tester & ONE_MASK) == ONE) {
message.system = (message.system << 1) + 1;
remote->data.tester = remote->data.tester >> 6;
remote->data.bits_left -= 6;
} else {
dev_err(&remote->interface->dev,
"%s - Unknown sequence found in system data.\n",
__func__);
remote->stage = 0;
return;
}
}
message.button = 0;
for (i = 0; i < 5; i++) {
keyspan_load_tester(remote, 6);
if ((remote->data.tester & ZERO_MASK) == ZERO) {
message.button = message.button << 1;
remote->data.tester = remote->data.tester >> 5;
remote->data.bits_left -= 5;
} else if ((remote->data.tester & ONE_MASK) == ONE) {
message.button = (message.button << 1) + 1;
remote->data.tester = remote->data.tester >> 6;
remote->data.bits_left -= 6;
} else {
dev_err(&remote->interface->dev,
"%s - Unknown sequence found in button data.\n",
__func__);
remote->stage = 0;
return;
}
}
keyspan_load_tester(remote, 6);
if ((remote->data.tester & ZERO_MASK) == ZERO) {
message.toggle = 0;
remote->data.tester = remote->data.tester >> 5;
remote->data.bits_left -= 5;
} else if ((remote->data.tester & ONE_MASK) == ONE) {
message.toggle = 1;
remote->data.tester = remote->data.tester >> 6;
remote->data.bits_left -= 6;
} else {
dev_err(&remote->interface->dev,
"%s - Error in message, invalid toggle.\n",
__func__);
remote->stage = 0;
return;
}
keyspan_load_tester(remote, 5);
if ((remote->data.tester & STOP_MASK) == STOP) {
remote->data.tester = remote->data.tester >> 5;
remote->data.bits_left -= 5;
} else {
dev_err(&remote->interface->dev,
"Bad message received, no stop bit found.\n");
}
dev_dbg(&remote->interface->dev,
"%s found valid message: system: %d, button: %d, toggle: %d\n",
__func__, message.system, message.button, message.toggle);
if (message.toggle != remote->toggle) {
keyspan_report_button(remote, message.button, 1);
keyspan_report_button(remote, message.button, 0);
remote->toggle = message.toggle;
}
remote->stage = 0;
break;
}
}
/*
* Routine for sending all the initialization messages to the remote.
*/
static int keyspan_setup(struct usb_device* dev)
{
int retval = 0;
retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
0x11, 0x40, 0x5601, 0x0, NULL, 0, 0);
if (retval) {
dev_dbg(&dev->dev, "%s - failed to set bit rate due to error: %d\n",
__func__, retval);
return(retval);
}
retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
0x44, 0x40, 0x0, 0x0, NULL, 0, 0);
if (retval) {
dev_dbg(&dev->dev, "%s - failed to set resume sensitivity due to error: %d\n",
__func__, retval);
return(retval);
}
retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
0x22, 0x40, 0x0, 0x0, NULL, 0, 0);
if (retval) {
dev_dbg(&dev->dev, "%s - failed to turn receive on due to error: %d\n",
__func__, retval);
return(retval);
}
dev_dbg(&dev->dev, "%s - Setup complete.\n", __func__);
return(retval);
}
/*
* Routine used to handle a new message that has come in.
*/
static void keyspan_irq_recv(struct urb *urb)
{
struct usb_keyspan *dev = urb->context;
int retval;
/* Check our status in case we need to bail out early. */
switch (urb->status) {
case 0:
break;
/* Device went away so don't keep trying to read from it. */
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
return;
default:
goto resubmit;
}
if (debug)
keyspan_print(dev);
keyspan_check_data(dev);
resubmit:
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
dev_err(&dev->interface->dev,
"%s - usb_submit_urb failed with result: %d\n",
__func__, retval);
}
static int keyspan_open(struct input_dev *dev)
{
struct usb_keyspan *remote = input_get_drvdata(dev);
remote->irq_urb->dev = remote->udev;
if (usb_submit_urb(remote->irq_urb, GFP_KERNEL))
return -EIO;
return 0;
}
static void keyspan_close(struct input_dev *dev)
{
struct usb_keyspan *remote = input_get_drvdata(dev);
usb_kill_urb(remote->irq_urb);
}
static struct usb_endpoint_descriptor *keyspan_get_in_endpoint(struct usb_host_interface *iface)
{
struct usb_endpoint_descriptor *endpoint;
int i;
for (i = 0; i < iface->desc.bNumEndpoints; ++i) {
endpoint = &iface->endpoint[i].desc;
if (usb_endpoint_is_int_in(endpoint)) {
/* we found our interrupt in endpoint */
return endpoint;
}
}
return NULL;
}
/*
* Routine that sets up the driver to handle a specific USB device detected on the bus.
*/
static int keyspan_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(interface);
struct usb_endpoint_descriptor *endpoint;
struct usb_keyspan *remote;
struct input_dev *input_dev;
int i, error;
endpoint = keyspan_get_in_endpoint(interface->cur_altsetting);
if (!endpoint)
return -ENODEV;
remote = kzalloc(sizeof(*remote), GFP_KERNEL);
input_dev = input_allocate_device();
if (!remote || !input_dev) {
error = -ENOMEM;
goto fail1;
}
remote->udev = udev;
remote->input = input_dev;
remote->interface = interface;
remote->in_endpoint = endpoint;
remote->toggle = -1; /* Set to -1 so we will always not match the toggle from the first remote message. */
remote->in_buffer = usb_alloc_coherent(udev, RECV_SIZE, GFP_ATOMIC, &remote->in_dma);
if (!remote->in_buffer) {
error = -ENOMEM;
goto fail1;
}
remote->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!remote->irq_urb) {
error = -ENOMEM;
goto fail2;
}
error = keyspan_setup(udev);
if (error) {
error = -ENODEV;
goto fail3;
}
if (udev->manufacturer)
strlcpy(remote->name, udev->manufacturer, sizeof(remote->name));
if (udev->product) {
if (udev->manufacturer)
strlcat(remote->name, " ", sizeof(remote->name));
strlcat(remote->name, udev->product, sizeof(remote->name));
}
if (!strlen(remote->name))
snprintf(remote->name, sizeof(remote->name),
"USB Keyspan Remote %04x:%04x",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct));
usb_make_path(udev, remote->phys, sizeof(remote->phys));
strlcat(remote->phys, "/input0", sizeof(remote->phys));
memcpy(remote->keymap, keyspan_key_table, sizeof(remote->keymap));
input_dev->name = remote->name;
input_dev->phys = remote->phys;
usb_to_input_id(udev, &input_dev->id);
input_dev->dev.parent = &interface->dev;
input_dev->keycode = remote->keymap;
input_dev->keycodesize = sizeof(unsigned short);
input_dev->keycodemax = ARRAY_SIZE(remote->keymap);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
__set_bit(EV_KEY, input_dev->evbit);
for (i = 0; i < ARRAY_SIZE(keyspan_key_table); i++)
__set_bit(keyspan_key_table[i], input_dev->keybit);
__clear_bit(KEY_RESERVED, input_dev->keybit);
input_set_drvdata(input_dev, remote);
input_dev->open = keyspan_open;
input_dev->close = keyspan_close;
/*
* Initialize the URB to access the device.
* The urb gets sent to the device in keyspan_open()
*/
usb_fill_int_urb(remote->irq_urb,
remote->udev,
usb_rcvintpipe(remote->udev, endpoint->bEndpointAddress),
remote->in_buffer, RECV_SIZE, keyspan_irq_recv, remote,
endpoint->bInterval);
remote->irq_urb->transfer_dma = remote->in_dma;
remote->irq_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* we can register the device now, as it is ready */
error = input_register_device(remote->input);
if (error)
goto fail3;
/* save our data pointer in this interface device */
usb_set_intfdata(interface, remote);
return 0;
fail3: usb_free_urb(remote->irq_urb);
fail2: usb_free_coherent(udev, RECV_SIZE, remote->in_buffer, remote->in_dma);
fail1: kfree(remote);
input_free_device(input_dev);
return error;
}
/*
* Routine called when a device is disconnected from the USB.
*/
static void keyspan_disconnect(struct usb_interface *interface)
{
struct usb_keyspan *remote;
remote = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
if (remote) { /* We have a valid driver structure so clean up everything we allocated. */
input_unregister_device(remote->input);
usb_kill_urb(remote->irq_urb);
usb_free_urb(remote->irq_urb);
usb_free_coherent(remote->udev, RECV_SIZE, remote->in_buffer, remote->in_dma);
kfree(remote);
}
}
/*
* Standard driver set up sections
*/
static struct usb_driver keyspan_driver =
{
.name = "keyspan_remote",
.probe = keyspan_probe,
.disconnect = keyspan_disconnect,
.id_table = keyspan_table
};
module_usb_driver(keyspan_driver);
MODULE_DEVICE_TABLE(usb, keyspan_table);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE(DRIVER_LICENSE);
| gpl-2.0 |
Senthil360/android_kernel_samsung_trlte | drivers/gpu/drm/nouveau/core/subdev/fb/nv35.c | 2269 | 2736 | /*
* Copyright (C) 2010 Francisco Jerez.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include <subdev/fb.h>
struct nv35_fb_priv {
struct nouveau_fb base;
};
static void
nv35_fb_tile_comp(struct nouveau_fb *pfb, int i, u32 size, u32 flags,
struct nouveau_fb_tile *tile)
{
u32 tiles = DIV_ROUND_UP(size, 0x40);
u32 tags = round_up(tiles / pfb->ram.parts, 0x40);
if (!nouveau_mm_head(&pfb->tags, 1, tags, tags, 1, &tile->tag)) {
if (flags & 2) tile->zcomp |= 0x04000000; /* Z16 */
else tile->zcomp |= 0x08000000; /* Z24S8 */
tile->zcomp |= ((tile->tag->offset ) >> 6);
tile->zcomp |= ((tile->tag->offset + tags - 1) >> 6) << 13;
#ifdef __BIG_ENDIAN
tile->zcomp |= 0x40000000;
#endif
}
}
static int
nv35_fb_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nv35_fb_priv *priv;
int ret;
ret = nouveau_fb_create(parent, engine, oclass, &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
priv->base.memtype_valid = nv04_fb_memtype_valid;
priv->base.ram.init = nv20_fb_vram_init;
priv->base.tile.regions = 8;
priv->base.tile.init = nv30_fb_tile_init;
priv->base.tile.comp = nv35_fb_tile_comp;
priv->base.tile.fini = nv20_fb_tile_fini;
priv->base.tile.prog = nv20_fb_tile_prog;
return nouveau_fb_preinit(&priv->base);
}
struct nouveau_oclass
nv35_fb_oclass = {
.handle = NV_SUBDEV(FB, 0x35),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nv35_fb_ctor,
.dtor = _nouveau_fb_dtor,
.init = nv30_fb_init,
.fini = _nouveau_fb_fini,
},
};
| gpl-2.0 |
draekko/android_kernel_samsung_kylessopen | drivers/net/wireless/hostap/hostap_cs.c | 2269 | 18239 | #define PRISM2_PCCARD
#include <linux/module.h>
#include <linux/init.h>
#include <linux/if.h>
#include <linux/slab.h>
#include <linux/wait.h>
#include <linux/timer.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/workqueue.h>
#include <linux/wireless.h>
#include <net/iw_handler.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
#include <asm/io.h>
#include "hostap_wlan.h"
static char *dev_info = "hostap_cs";
MODULE_AUTHOR("Jouni Malinen");
MODULE_DESCRIPTION("Support for Intersil Prism2-based 802.11 wireless LAN "
"cards (PC Card).");
MODULE_SUPPORTED_DEVICE("Intersil Prism2-based WLAN cards (PC Card)");
MODULE_LICENSE("GPL");
static int ignore_cis_vcc;
module_param(ignore_cis_vcc, int, 0444);
MODULE_PARM_DESC(ignore_cis_vcc, "Ignore broken CIS VCC entry");
/* struct local_info::hw_priv */
struct hostap_cs_priv {
struct pcmcia_device *link;
int sandisk_connectplus;
};
#ifdef PRISM2_IO_DEBUG
static inline void hfa384x_outb_debug(struct net_device *dev, int a, u8 v)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTB, a, v);
outb(v, dev->base_addr + a);
spin_unlock_irqrestore(&local->lock, flags);
}
static inline u8 hfa384x_inb_debug(struct net_device *dev, int a)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
u8 v;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
v = inb(dev->base_addr + a);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INB, a, v);
spin_unlock_irqrestore(&local->lock, flags);
return v;
}
static inline void hfa384x_outw_debug(struct net_device *dev, int a, u16 v)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTW, a, v);
outw(v, dev->base_addr + a);
spin_unlock_irqrestore(&local->lock, flags);
}
static inline u16 hfa384x_inw_debug(struct net_device *dev, int a)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
u16 v;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
v = inw(dev->base_addr + a);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INW, a, v);
spin_unlock_irqrestore(&local->lock, flags);
return v;
}
static inline void hfa384x_outsw_debug(struct net_device *dev, int a,
u8 *buf, int wc)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTSW, a, wc);
outsw(dev->base_addr + a, buf, wc);
spin_unlock_irqrestore(&local->lock, flags);
}
static inline void hfa384x_insw_debug(struct net_device *dev, int a,
u8 *buf, int wc)
{
struct hostap_interface *iface;
local_info_t *local;
unsigned long flags;
iface = netdev_priv(dev);
local = iface->local;
spin_lock_irqsave(&local->lock, flags);
prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INSW, a, wc);
insw(dev->base_addr + a, buf, wc);
spin_unlock_irqrestore(&local->lock, flags);
}
#define HFA384X_OUTB(v,a) hfa384x_outb_debug(dev, (a), (v))
#define HFA384X_INB(a) hfa384x_inb_debug(dev, (a))
#define HFA384X_OUTW(v,a) hfa384x_outw_debug(dev, (a), (v))
#define HFA384X_INW(a) hfa384x_inw_debug(dev, (a))
#define HFA384X_OUTSW(a, buf, wc) hfa384x_outsw_debug(dev, (a), (buf), (wc))
#define HFA384X_INSW(a, buf, wc) hfa384x_insw_debug(dev, (a), (buf), (wc))
#else /* PRISM2_IO_DEBUG */
#define HFA384X_OUTB(v,a) outb((v), dev->base_addr + (a))
#define HFA384X_INB(a) inb(dev->base_addr + (a))
#define HFA384X_OUTW(v,a) outw((v), dev->base_addr + (a))
#define HFA384X_INW(a) inw(dev->base_addr + (a))
#define HFA384X_INSW(a, buf, wc) insw(dev->base_addr + (a), buf, wc)
#define HFA384X_OUTSW(a, buf, wc) outsw(dev->base_addr + (a), buf, wc)
#endif /* PRISM2_IO_DEBUG */
static int hfa384x_from_bap(struct net_device *dev, u16 bap, void *buf,
int len)
{
u16 d_off;
u16 *pos;
d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF;
pos = (u16 *) buf;
if (len / 2)
HFA384X_INSW(d_off, buf, len / 2);
pos += len / 2;
if (len & 1)
*((char *) pos) = HFA384X_INB(d_off);
return 0;
}
static int hfa384x_to_bap(struct net_device *dev, u16 bap, void *buf, int len)
{
u16 d_off;
u16 *pos;
d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF;
pos = (u16 *) buf;
if (len / 2)
HFA384X_OUTSW(d_off, buf, len / 2);
pos += len / 2;
if (len & 1)
HFA384X_OUTB(*((char *) pos), d_off);
return 0;
}
/* FIX: This might change at some point.. */
#include "hostap_hw.c"
static void prism2_detach(struct pcmcia_device *p_dev);
static void prism2_release(u_long arg);
static int prism2_config(struct pcmcia_device *link);
static int prism2_pccard_card_present(local_info_t *local)
{
struct hostap_cs_priv *hw_priv = local->hw_priv;
if (hw_priv != NULL && hw_priv->link != NULL && pcmcia_dev_present(hw_priv->link))
return 1;
return 0;
}
/*
* SanDisk CompactFlash WLAN Flashcard - Product Manual v1.0
* Document No. 20-10-00058, January 2004
* http://www.sandisk.com/pdf/industrial/ProdManualCFWLANv1.0.pdf
*/
#define SANDISK_WLAN_ACTIVATION_OFF 0x40
#define SANDISK_HCR_OFF 0x42
static void sandisk_set_iobase(local_info_t *local)
{
int res;
struct hostap_cs_priv *hw_priv = local->hw_priv;
res = pcmcia_write_config_byte(hw_priv->link, 0x10,
hw_priv->link->resource[0]->start & 0x00ff);
if (res != 0) {
printk(KERN_DEBUG "Prism3 SanDisk - failed to set I/O base 0 -"
" res=%d\n", res);
}
udelay(10);
res = pcmcia_write_config_byte(hw_priv->link, 0x12,
(hw_priv->link->resource[0]->start >> 8) & 0x00ff);
if (res != 0) {
printk(KERN_DEBUG "Prism3 SanDisk - failed to set I/O base 1 -"
" res=%d\n", res);
}
}
static void sandisk_write_hcr(local_info_t *local, int hcr)
{
struct net_device *dev = local->dev;
int i;
HFA384X_OUTB(0x80, SANDISK_WLAN_ACTIVATION_OFF);
udelay(50);
for (i = 0; i < 10; i++) {
HFA384X_OUTB(hcr, SANDISK_HCR_OFF);
}
udelay(55);
HFA384X_OUTB(0x45, SANDISK_WLAN_ACTIVATION_OFF);
}
static int sandisk_enable_wireless(struct net_device *dev)
{
int res, ret = 0;
struct hostap_interface *iface = netdev_priv(dev);
local_info_t *local = iface->local;
struct hostap_cs_priv *hw_priv = local->hw_priv;
if (resource_size(hw_priv->link->resource[0]) < 0x42) {
/* Not enough ports to be SanDisk multi-function card */
ret = -ENODEV;
goto done;
}
if (hw_priv->link->manf_id != 0xd601 || hw_priv->link->card_id != 0x0101) {
/* No SanDisk manfid found */
ret = -ENODEV;
goto done;
}
if (hw_priv->link->socket->functions < 2) {
/* No multi-function links found */
ret = -ENODEV;
goto done;
}
printk(KERN_DEBUG "%s: Multi-function SanDisk ConnectPlus detected"
" - using vendor-specific initialization\n", dev->name);
hw_priv->sandisk_connectplus = 1;
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,
COR_SOFT_RESET);
if (res != 0) {
printk(KERN_DEBUG "%s: SanDisk - COR sreset failed (%d)\n",
dev->name, res);
goto done;
}
mdelay(5);
/*
* Do not enable interrupts here to avoid some bogus events. Interrupts
* will be enabled during the first cor_sreset call.
*/
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,
(COR_LEVEL_REQ | 0x8 | COR_ADDR_DECODE |
COR_FUNC_ENA));
if (res != 0) {
printk(KERN_DEBUG "%s: SanDisk - COR sreset failed (%d)\n",
dev->name, res);
goto done;
}
mdelay(5);
sandisk_set_iobase(local);
HFA384X_OUTB(0xc5, SANDISK_WLAN_ACTIVATION_OFF);
udelay(10);
HFA384X_OUTB(0x4b, SANDISK_WLAN_ACTIVATION_OFF);
udelay(10);
done:
return ret;
}
static void prism2_pccard_cor_sreset(local_info_t *local)
{
int res;
u8 val;
struct hostap_cs_priv *hw_priv = local->hw_priv;
if (!prism2_pccard_card_present(local))
return;
res = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &val);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 1 (%d)\n",
res);
return;
}
printk(KERN_DEBUG "prism2_pccard_cor_sreset: original COR %02x\n",
val);
val |= COR_SOFT_RESET;
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 2 (%d)\n",
res);
return;
}
mdelay(hw_priv->sandisk_connectplus ? 5 : 2);
val &= ~COR_SOFT_RESET;
if (hw_priv->sandisk_connectplus)
val |= COR_IREQ_ENA;
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 3 (%d)\n",
res);
return;
}
mdelay(hw_priv->sandisk_connectplus ? 5 : 2);
if (hw_priv->sandisk_connectplus)
sandisk_set_iobase(local);
}
static void prism2_pccard_genesis_reset(local_info_t *local, int hcr)
{
int res;
u8 old_cor;
struct hostap_cs_priv *hw_priv = local->hw_priv;
if (!prism2_pccard_card_present(local))
return;
if (hw_priv->sandisk_connectplus) {
sandisk_write_hcr(local, hcr);
return;
}
res = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &old_cor);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 1 "
"(%d)\n", res);
return;
}
printk(KERN_DEBUG "prism2_pccard_genesis_sreset: original COR %02x\n",
old_cor);
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,
old_cor | COR_SOFT_RESET);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 2 "
"(%d)\n", res);
return;
}
mdelay(10);
/* Setup Genesis mode */
res = pcmcia_write_config_byte(hw_priv->link, CISREG_CCSR, hcr);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 3 "
"(%d)\n", res);
return;
}
mdelay(10);
res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR,
old_cor & ~COR_SOFT_RESET);
if (res != 0) {
printk(KERN_DEBUG "prism2_pccard_genesis_sreset failed 4 "
"(%d)\n", res);
return;
}
mdelay(10);
}
static struct prism2_helper_functions prism2_pccard_funcs =
{
.card_present = prism2_pccard_card_present,
.cor_sreset = prism2_pccard_cor_sreset,
.genesis_reset = prism2_pccard_genesis_reset,
.hw_type = HOSTAP_HW_PCCARD,
};
/* allocate local data and register with CardServices
* initialize dev_link structure, but do not configure the card yet */
static int hostap_cs_probe(struct pcmcia_device *p_dev)
{
int ret;
PDEBUG(DEBUG_HW, "%s: setting Vcc=33 (constant)\n", dev_info);
ret = prism2_config(p_dev);
if (ret) {
PDEBUG(DEBUG_EXTRA, "prism2_config() failed\n");
}
return ret;
}
static void prism2_detach(struct pcmcia_device *link)
{
PDEBUG(DEBUG_FLOW, "prism2_detach\n");
prism2_release((u_long)link);
/* release net devices */
if (link->priv) {
struct hostap_cs_priv *hw_priv;
struct net_device *dev;
struct hostap_interface *iface;
dev = link->priv;
iface = netdev_priv(dev);
hw_priv = iface->local->hw_priv;
prism2_free_local_data(dev);
kfree(hw_priv);
}
}
static int prism2_config_check(struct pcmcia_device *p_dev, void *priv_data)
{
if (p_dev->config_index == 0)
return -EINVAL;
return pcmcia_request_io(p_dev);
}
static int prism2_config(struct pcmcia_device *link)
{
struct net_device *dev;
struct hostap_interface *iface;
local_info_t *local;
int ret = 1;
struct hostap_cs_priv *hw_priv;
unsigned long flags;
PDEBUG(DEBUG_FLOW, "prism2_config()\n");
hw_priv = kzalloc(sizeof(*hw_priv), GFP_KERNEL);
if (hw_priv == NULL) {
ret = -ENOMEM;
goto failed;
}
/* Look for an appropriate configuration table entry in the CIS */
link->config_flags |= CONF_AUTO_SET_VPP | CONF_AUTO_AUDIO |
CONF_AUTO_CHECK_VCC | CONF_AUTO_SET_IO | CONF_ENABLE_IRQ;
if (ignore_cis_vcc)
link->config_flags &= ~CONF_AUTO_CHECK_VCC;
ret = pcmcia_loop_config(link, prism2_config_check, NULL);
if (ret) {
if (!ignore_cis_vcc)
printk(KERN_ERR "GetNextTuple(): No matching "
"CIS configuration. Maybe you need the "
"ignore_cis_vcc=1 parameter.\n");
goto failed;
}
/* Need to allocate net_device before requesting IRQ handler */
dev = prism2_init_local_data(&prism2_pccard_funcs, 0,
&link->dev);
if (dev == NULL)
goto failed;
link->priv = dev;
iface = netdev_priv(dev);
local = iface->local;
local->hw_priv = hw_priv;
hw_priv->link = link;
/*
* We enable IRQ here, but IRQ handler will not proceed
* until dev->base_addr is set below. This protect us from
* receive interrupts when driver is not initialized.
*/
ret = pcmcia_request_irq(link, prism2_interrupt);
if (ret)
goto failed;
ret = pcmcia_enable_device(link);
if (ret)
goto failed;
spin_lock_irqsave(&local->irq_init_lock, flags);
dev->irq = link->irq;
dev->base_addr = link->resource[0]->start;
spin_unlock_irqrestore(&local->irq_init_lock, flags);
local->shutdown = 0;
sandisk_enable_wireless(dev);
ret = prism2_hw_config(dev, 1);
if (!ret)
ret = hostap_hw_ready(dev);
return ret;
failed:
kfree(hw_priv);
prism2_release((u_long)link);
return ret;
}
static void prism2_release(u_long arg)
{
struct pcmcia_device *link = (struct pcmcia_device *)arg;
PDEBUG(DEBUG_FLOW, "prism2_release\n");
if (link->priv) {
struct net_device *dev = link->priv;
struct hostap_interface *iface;
iface = netdev_priv(dev);
prism2_hw_shutdown(dev, 0);
iface->local->shutdown = 1;
}
pcmcia_disable_device(link);
PDEBUG(DEBUG_FLOW, "release - done\n");
}
static int hostap_cs_suspend(struct pcmcia_device *link)
{
struct net_device *dev = (struct net_device *) link->priv;
int dev_open = 0;
struct hostap_interface *iface = NULL;
if (!dev)
return -ENODEV;
iface = netdev_priv(dev);
PDEBUG(DEBUG_EXTRA, "%s: CS_EVENT_PM_SUSPEND\n", dev_info);
if (iface && iface->local)
dev_open = iface->local->num_dev_open > 0;
if (dev_open) {
netif_stop_queue(dev);
netif_device_detach(dev);
}
prism2_suspend(dev);
return 0;
}
static int hostap_cs_resume(struct pcmcia_device *link)
{
struct net_device *dev = (struct net_device *) link->priv;
int dev_open = 0;
struct hostap_interface *iface = NULL;
if (!dev)
return -ENODEV;
iface = netdev_priv(dev);
PDEBUG(DEBUG_EXTRA, "%s: CS_EVENT_PM_RESUME\n", dev_info);
if (iface && iface->local)
dev_open = iface->local->num_dev_open > 0;
prism2_hw_shutdown(dev, 1);
prism2_hw_config(dev, dev_open ? 0 : 1);
if (dev_open) {
netif_device_attach(dev);
netif_start_queue(dev);
}
return 0;
}
static const struct pcmcia_device_id hostap_cs_ids[] = {
PCMCIA_DEVICE_MANF_CARD(0x000b, 0x7100),
PCMCIA_DEVICE_MANF_CARD(0x000b, 0x7300),
PCMCIA_DEVICE_MANF_CARD(0x0101, 0x0777),
PCMCIA_DEVICE_MANF_CARD(0x0126, 0x8000),
PCMCIA_DEVICE_MANF_CARD(0x0138, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0x01bf, 0x3301),
PCMCIA_DEVICE_MANF_CARD(0x0250, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0x026f, 0x030b),
PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1612),
PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1613),
PCMCIA_DEVICE_MANF_CARD(0x028a, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0x02aa, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0x02d2, 0x0001),
PCMCIA_DEVICE_MANF_CARD(0x50c2, 0x0001),
PCMCIA_DEVICE_MANF_CARD(0x50c2, 0x7300),
/* PCMCIA_DEVICE_MANF_CARD(0xc00f, 0x0000), conflict with pcnet_cs */
PCMCIA_DEVICE_MANF_CARD(0xc250, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0002),
PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0005),
PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0010),
PCMCIA_DEVICE_MANF_CARD(0x0126, 0x0002),
PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0xd601, 0x0005, "ADLINK 345 CF",
0x2d858104),
PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, "INTERSIL",
0x74c5e40d),
PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, "Intersil",
0x4b801a17),
PCMCIA_MFC_DEVICE_PROD_ID12(0, "SanDisk", "ConnectPlus",
0x7a954bd9, 0x74be00c6),
PCMCIA_DEVICE_PROD_ID123(
"Addtron", "AWP-100 Wireless PCMCIA", "Version 01.02",
0xe6ec52ce, 0x08649af2, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID123(
"D", "Link DWL-650 11Mbps WLAN Card", "Version 01.02",
0x71b18589, 0xb6f1b0ab, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID123(
"Instant Wireless ", " Network PC CARD", "Version 01.02",
0x11d901af, 0x6e9bd926, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID123(
"SMC", "SMC2632W", "Version 01.02",
0xc4f8b18b, 0x474a1f2a, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID12("BUFFALO", "WLI-CF-S11G",
0x2decece3, 0x82067c18),
PCMCIA_DEVICE_PROD_ID12("Compaq", "WL200_11Mbps_Wireless_PCI_Card",
0x54f7c49c, 0x15a75e5b),
PCMCIA_DEVICE_PROD_ID12("INTERSIL", "HFA384x/IEEE",
0x74c5e40d, 0xdb472a18),
PCMCIA_DEVICE_PROD_ID12("Linksys", "Wireless CompactFlash Card",
0x0733cc81, 0x0c52f395),
PCMCIA_DEVICE_PROD_ID12(
"ZoomAir 11Mbps High", "Rate wireless Networking",
0x273fe3db, 0x32a1eaee),
PCMCIA_DEVICE_PROD_ID123(
"Pretec", "CompactWLAN Card 802.11b", "2.5",
0x1cadd3e5, 0xe697636c, 0x7a5bfcf1),
PCMCIA_DEVICE_PROD_ID123(
"U.S. Robotics", "IEEE 802.11b PC-CARD", "Version 01.02",
0xc7b8df9d, 0x1700d087, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID123(
"Allied Telesyn", "AT-WCL452 Wireless PCMCIA Radio",
"Ver. 1.00",
0x5cd01705, 0x4271660f, 0x9d08ee12),
PCMCIA_DEVICE_PROD_ID123(
"Wireless LAN" , "11Mbps PC Card", "Version 01.02",
0x4b8870ff, 0x70e946d1, 0x4b74baa0),
PCMCIA_DEVICE_PROD_ID3("HFA3863", 0x355cb092),
PCMCIA_DEVICE_PROD_ID3("ISL37100P", 0x630d52b2),
PCMCIA_DEVICE_PROD_ID3("ISL37101P-10", 0xdd97a26b),
PCMCIA_DEVICE_PROD_ID3("ISL37300P", 0xc9049a39),
PCMCIA_DEVICE_NULL
};
MODULE_DEVICE_TABLE(pcmcia, hostap_cs_ids);
static struct pcmcia_driver hostap_driver = {
.name = "hostap_cs",
.probe = hostap_cs_probe,
.remove = prism2_detach,
.owner = THIS_MODULE,
.id_table = hostap_cs_ids,
.suspend = hostap_cs_suspend,
.resume = hostap_cs_resume,
};
static int __init init_prism2_pccard(void)
{
return pcmcia_register_driver(&hostap_driver);
}
static void __exit exit_prism2_pccard(void)
{
pcmcia_unregister_driver(&hostap_driver);
}
module_init(init_prism2_pccard);
module_exit(exit_prism2_pccard);
| gpl-2.0 |
zanezam/boeffla-kernel-samsung-n51x0 | drivers/net/tokenring/3c359.c | 2525 | 59955 | /*
* 3c359.c (c) 2000 Mike Phillips (mikep@linuxtr.net) All Rights Reserved
*
* Linux driver for 3Com 3c359 Tokenlink Velocity XL PCI NIC
*
* Base Driver Olympic:
* Written 1999 Peter De Schrijver & Mike Phillips
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* 7/17/00 - Clean up, version number 0.9.0. Ready to release to the world.
*
* 2/16/01 - Port up to kernel 2.4.2 ready for submission into the kernel.
* 3/05/01 - Last clean up stuff before submission.
* 2/15/01 - Finally, update to new pci api.
*
* To Do:
*/
/*
* Technical Card Details
*
* All access to data is done with 16/8 bit transfers. The transfer
* method really sucks. You can only read or write one location at a time.
*
* Also, the microcode for the card must be uploaded if the card does not have
* the flashrom on board. This is a 28K bloat in the driver when compiled
* as a module.
*
* Rx is very simple, status into a ring of descriptors, dma data transfer,
* interrupts to tell us when a packet is received.
*
* Tx is a little more interesting. Similar scenario, descriptor and dma data
* transfers, but we don't have to interrupt the card to tell it another packet
* is ready for transmission, we are just doing simple memory writes, not io or mmio
* writes. The card can be set up to simply poll on the next
* descriptor pointer and when this value is non-zero will automatically download
* the next packet. The card then interrupts us when the packet is done.
*
*/
#define XL_DEBUG 0
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/in.h>
#include <linux/ioport.h>
#include <linux/string.h>
#include <linux/proc_fs.h>
#include <linux/ptrace.h>
#include <linux/skbuff.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/trdevice.h>
#include <linux/stddef.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/spinlock.h>
#include <linux/bitops.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <net/checksum.h>
#include <asm/io.h>
#include <asm/system.h>
#include "3c359.h"
static char version[] __devinitdata =
"3c359.c v1.2.0 2/17/01 - Mike Phillips (mikep@linuxtr.net)" ;
#define FW_NAME "3com/3C359.bin"
MODULE_AUTHOR("Mike Phillips <mikep@linuxtr.net>") ;
MODULE_DESCRIPTION("3Com 3C359 Velocity XL Token Ring Adapter Driver\n") ;
MODULE_FIRMWARE(FW_NAME);
/* Module parameters */
/* Ring Speed 0,4,16
* 0 = Autosense
* 4,16 = Selected speed only, no autosense
* This allows the card to be the first on the ring
* and become the active monitor.
*
* WARNING: Some hubs will allow you to insert
* at the wrong speed.
*
* The adapter will _not_ fail to open if there are no
* active monitors on the ring, it will simply open up in
* its last known ringspeed if no ringspeed is specified.
*/
static int ringspeed[XL_MAX_ADAPTERS] = {0,} ;
module_param_array(ringspeed, int, NULL, 0);
MODULE_PARM_DESC(ringspeed,"3c359: Ringspeed selection - 4,16 or 0") ;
/* Packet buffer size */
static int pkt_buf_sz[XL_MAX_ADAPTERS] = {0,} ;
module_param_array(pkt_buf_sz, int, NULL, 0) ;
MODULE_PARM_DESC(pkt_buf_sz,"3c359: Initial buffer size") ;
/* Message Level */
static int message_level[XL_MAX_ADAPTERS] = {0,} ;
module_param_array(message_level, int, NULL, 0) ;
MODULE_PARM_DESC(message_level, "3c359: Level of reported messages") ;
/*
* This is a real nasty way of doing this, but otherwise you
* will be stuck with 1555 lines of hex #'s in the code.
*/
static DEFINE_PCI_DEVICE_TABLE(xl_pci_tbl) =
{
{PCI_VENDOR_ID_3COM,PCI_DEVICE_ID_3COM_3C359, PCI_ANY_ID, PCI_ANY_ID, },
{ } /* terminate list */
};
MODULE_DEVICE_TABLE(pci,xl_pci_tbl) ;
static int xl_init(struct net_device *dev);
static int xl_open(struct net_device *dev);
static int xl_open_hw(struct net_device *dev) ;
static int xl_hw_reset(struct net_device *dev);
static netdev_tx_t xl_xmit(struct sk_buff *skb, struct net_device *dev);
static void xl_dn_comp(struct net_device *dev);
static int xl_close(struct net_device *dev);
static void xl_set_rx_mode(struct net_device *dev);
static irqreturn_t xl_interrupt(int irq, void *dev_id);
static int xl_set_mac_address(struct net_device *dev, void *addr) ;
static void xl_arb_cmd(struct net_device *dev);
static void xl_asb_cmd(struct net_device *dev) ;
static void xl_srb_cmd(struct net_device *dev, int srb_cmd) ;
static void xl_wait_misr_flags(struct net_device *dev) ;
static int xl_change_mtu(struct net_device *dev, int mtu);
static void xl_srb_bh(struct net_device *dev) ;
static void xl_asb_bh(struct net_device *dev) ;
static void xl_reset(struct net_device *dev) ;
static void xl_freemem(struct net_device *dev) ;
/* EEProm Access Functions */
static u16 xl_ee_read(struct net_device *dev, int ee_addr) ;
static void xl_ee_write(struct net_device *dev, int ee_addr, u16 ee_value) ;
/* Debugging functions */
#if XL_DEBUG
static void print_tx_state(struct net_device *dev) ;
static void print_rx_state(struct net_device *dev) ;
static void print_tx_state(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
struct xl_tx_desc *txd ;
u8 __iomem *xl_mmio = xl_priv->xl_mmio ;
int i ;
printk("tx_ring_head: %d, tx_ring_tail: %d, free_ent: %d\n",xl_priv->tx_ring_head,
xl_priv->tx_ring_tail, xl_priv->free_ring_entries) ;
printk("Ring , Address , FSH , DnNextPtr, Buffer, Buffer_Len\n");
for (i = 0; i < 16; i++) {
txd = &(xl_priv->xl_tx_ring[i]) ;
printk("%d, %08lx, %08x, %08x, %08x, %08x\n", i, virt_to_bus(txd),
txd->framestartheader, txd->dnnextptr, txd->buffer, txd->buffer_length ) ;
}
printk("DNLISTPTR = %04x\n", readl(xl_mmio + MMIO_DNLISTPTR) );
printk("DmaCtl = %04x\n", readl(xl_mmio + MMIO_DMA_CTRL) );
printk("Queue status = %0x\n",netif_running(dev) ) ;
}
static void print_rx_state(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
struct xl_rx_desc *rxd ;
u8 __iomem *xl_mmio = xl_priv->xl_mmio ;
int i ;
printk("rx_ring_tail: %d\n", xl_priv->rx_ring_tail);
printk("Ring , Address , FrameState , UPNextPtr, FragAddr, Frag_Len\n");
for (i = 0; i < 16; i++) {
/* rxd = (struct xl_rx_desc *)xl_priv->rx_ring_dma_addr + (i * sizeof(struct xl_rx_desc)) ; */
rxd = &(xl_priv->xl_rx_ring[i]) ;
printk("%d, %08lx, %08x, %08x, %08x, %08x\n", i, virt_to_bus(rxd),
rxd->framestatus, rxd->upnextptr, rxd->upfragaddr, rxd->upfraglen ) ;
}
printk("UPLISTPTR = %04x\n", readl(xl_mmio + MMIO_UPLISTPTR));
printk("DmaCtl = %04x\n", readl(xl_mmio + MMIO_DMA_CTRL));
printk("Queue status = %0x\n",netif_running(dev));
}
#endif
/*
* Read values from the on-board EEProm. This looks very strange
* but you have to wait for the EEProm to get/set the value before
* passing/getting the next value from the nic. As with all requests
* on this nic it has to be done in two stages, a) tell the nic which
* memory address you want to access and b) pass/get the value from the nic.
* With the EEProm, you have to wait before and between access a) and b).
* As this is only read at initialization time and the wait period is very
* small we shouldn't have to worry about scheduling issues.
*/
static u16 xl_ee_read(struct net_device *dev, int ee_addr)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem *xl_mmio = xl_priv->xl_mmio ;
/* Wait for EEProm to not be busy */
writel(IO_WORD_READ | EECONTROL, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
while ( readw(xl_mmio + MMIO_MACDATA) & EEBUSY ) ;
/* Tell EEProm what we want to do and where */
writel(IO_WORD_WRITE | EECONTROL, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(EEREAD + ee_addr, xl_mmio + MMIO_MACDATA) ;
/* Wait for EEProm to not be busy */
writel(IO_WORD_READ | EECONTROL, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
while ( readw(xl_mmio + MMIO_MACDATA) & EEBUSY ) ;
/* Tell EEProm what we want to do and where */
writel(IO_WORD_WRITE | EECONTROL , xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(EEREAD + ee_addr, xl_mmio + MMIO_MACDATA) ;
/* Finally read the value from the EEProm */
writel(IO_WORD_READ | EEDATA , xl_mmio + MMIO_MAC_ACCESS_CMD) ;
return readw(xl_mmio + MMIO_MACDATA) ;
}
/*
* Write values to the onboard eeprom. As with eeprom read you need to
* set which location to write, wait, value to write, wait, with the
* added twist of having to enable eeprom writes as well.
*/
static void xl_ee_write(struct net_device *dev, int ee_addr, u16 ee_value)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem *xl_mmio = xl_priv->xl_mmio ;
/* Wait for EEProm to not be busy */
writel(IO_WORD_READ | EECONTROL, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
while ( readw(xl_mmio + MMIO_MACDATA) & EEBUSY ) ;
/* Enable write/erase */
writel(IO_WORD_WRITE | EECONTROL, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(EE_ENABLE_WRITE, xl_mmio + MMIO_MACDATA) ;
/* Wait for EEProm to not be busy */
writel(IO_WORD_READ | EECONTROL, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
while ( readw(xl_mmio + MMIO_MACDATA) & EEBUSY ) ;
/* Put the value we want to write into EEDATA */
writel(IO_WORD_WRITE | EEDATA, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(ee_value, xl_mmio + MMIO_MACDATA) ;
/* Tell EEProm to write eevalue into ee_addr */
writel(IO_WORD_WRITE | EECONTROL, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(EEWRITE + ee_addr, xl_mmio + MMIO_MACDATA) ;
/* Wait for EEProm to not be busy, to ensure write gets done */
writel(IO_WORD_READ | EECONTROL, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
while ( readw(xl_mmio + MMIO_MACDATA) & EEBUSY ) ;
return ;
}
static const struct net_device_ops xl_netdev_ops = {
.ndo_open = xl_open,
.ndo_stop = xl_close,
.ndo_start_xmit = xl_xmit,
.ndo_change_mtu = xl_change_mtu,
.ndo_set_multicast_list = xl_set_rx_mode,
.ndo_set_mac_address = xl_set_mac_address,
};
static int __devinit xl_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *dev ;
struct xl_private *xl_priv ;
static int card_no = -1 ;
int i ;
card_no++ ;
if (pci_enable_device(pdev)) {
return -ENODEV ;
}
pci_set_master(pdev);
if ((i = pci_request_regions(pdev,"3c359"))) {
return i ;
} ;
/*
* Allowing init_trdev to allocate the private data will align
* xl_private on a 32 bytes boundary which we need for the rx/tx
* descriptors
*/
dev = alloc_trdev(sizeof(struct xl_private)) ;
if (!dev) {
pci_release_regions(pdev) ;
return -ENOMEM ;
}
xl_priv = netdev_priv(dev);
#if XL_DEBUG
printk("pci_device: %p, dev:%p, dev->priv: %p, ba[0]: %10x, ba[1]:%10x\n",
pdev, dev, netdev_priv(dev), (unsigned int)pdev->resource[0].start, (unsigned int)pdev->resource[1].start);
#endif
dev->irq=pdev->irq;
dev->base_addr=pci_resource_start(pdev,0) ;
xl_priv->xl_card_name = pci_name(pdev);
xl_priv->xl_mmio=ioremap(pci_resource_start(pdev,1), XL_IO_SPACE);
xl_priv->pdev = pdev ;
if ((pkt_buf_sz[card_no] < 100) || (pkt_buf_sz[card_no] > 18000) )
xl_priv->pkt_buf_sz = PKT_BUF_SZ ;
else
xl_priv->pkt_buf_sz = pkt_buf_sz[card_no] ;
dev->mtu = xl_priv->pkt_buf_sz - TR_HLEN ;
xl_priv->xl_ring_speed = ringspeed[card_no] ;
xl_priv->xl_message_level = message_level[card_no] ;
xl_priv->xl_functional_addr[0] = xl_priv->xl_functional_addr[1] = xl_priv->xl_functional_addr[2] = xl_priv->xl_functional_addr[3] = 0 ;
xl_priv->xl_copy_all_options = 0 ;
if((i = xl_init(dev))) {
iounmap(xl_priv->xl_mmio) ;
free_netdev(dev) ;
pci_release_regions(pdev) ;
return i ;
}
dev->netdev_ops = &xl_netdev_ops;
SET_NETDEV_DEV(dev, &pdev->dev);
pci_set_drvdata(pdev,dev) ;
if ((i = register_netdev(dev))) {
printk(KERN_ERR "3C359, register netdev failed\n") ;
pci_set_drvdata(pdev,NULL) ;
iounmap(xl_priv->xl_mmio) ;
free_netdev(dev) ;
pci_release_regions(pdev) ;
return i ;
}
printk(KERN_INFO "3C359: %s registered as: %s\n",xl_priv->xl_card_name,dev->name) ;
return 0;
}
static int xl_init_firmware(struct xl_private *xl_priv)
{
int err;
err = request_firmware(&xl_priv->fw, FW_NAME, &xl_priv->pdev->dev);
if (err) {
printk(KERN_ERR "Failed to load firmware \"%s\"\n", FW_NAME);
return err;
}
if (xl_priv->fw->size < 16) {
printk(KERN_ERR "Bogus length %zu in \"%s\"\n",
xl_priv->fw->size, FW_NAME);
release_firmware(xl_priv->fw);
err = -EINVAL;
}
return err;
}
static int __devinit xl_init(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
int err;
printk(KERN_INFO "%s\n", version);
printk(KERN_INFO "%s: I/O at %hx, MMIO at %p, using irq %d\n",
xl_priv->xl_card_name, (unsigned int)dev->base_addr ,xl_priv->xl_mmio, dev->irq);
spin_lock_init(&xl_priv->xl_lock) ;
err = xl_init_firmware(xl_priv);
if (err == 0)
err = xl_hw_reset(dev);
return err;
}
/*
* Hardware reset. This needs to be a separate entity as we need to reset the card
* when we change the EEProm settings.
*/
static int xl_hw_reset(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem *xl_mmio = xl_priv->xl_mmio ;
unsigned long t ;
u16 i ;
u16 result_16 ;
u8 result_8 ;
u16 start ;
int j ;
if (xl_priv->fw == NULL)
return -EINVAL;
/*
* Reset the card. If the card has got the microcode on board, we have
* missed the initialization interrupt, so we must always do this.
*/
writew( GLOBAL_RESET, xl_mmio + MMIO_COMMAND ) ;
/*
* Must wait for cmdInProgress bit (12) to clear before continuing with
* card configuration.
*/
t=jiffies;
while (readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_CMD_IN_PROGRESS) {
schedule();
if (time_after(jiffies, t + 40 * HZ)) {
printk(KERN_ERR "%s: 3COM 3C359 Velocity XL card not responding to global reset.\n", dev->name);
return -ENODEV;
}
}
/*
* Enable pmbar by setting bit in CPAttention
*/
writel( (IO_BYTE_READ | CPATTENTION), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
result_8 = readb(xl_mmio + MMIO_MACDATA) ;
result_8 = result_8 | CPA_PMBARVIS ;
writel( (IO_BYTE_WRITE | CPATTENTION), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(result_8, xl_mmio + MMIO_MACDATA) ;
/*
* Read cpHold bit in pmbar, if cleared we have got Flashrom on board.
* If not, we need to upload the microcode to the card
*/
writel( (IO_WORD_READ | PMBAR),xl_mmio + MMIO_MAC_ACCESS_CMD);
#if XL_DEBUG
printk(KERN_INFO "Read from PMBAR = %04x\n", readw(xl_mmio + MMIO_MACDATA));
#endif
if ( readw( (xl_mmio + MMIO_MACDATA)) & PMB_CPHOLD ) {
/* Set PmBar, privateMemoryBase bits (8:2) to 0 */
writel( (IO_WORD_READ | PMBAR),xl_mmio + MMIO_MAC_ACCESS_CMD);
result_16 = readw(xl_mmio + MMIO_MACDATA) ;
result_16 = result_16 & ~((0x7F) << 2) ;
writel( (IO_WORD_WRITE | PMBAR), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(result_16,xl_mmio + MMIO_MACDATA) ;
/* Set CPAttention, memWrEn bit */
writel( (IO_BYTE_READ | CPATTENTION), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
result_8 = readb(xl_mmio + MMIO_MACDATA) ;
result_8 = result_8 | CPA_MEMWREN ;
writel( (IO_BYTE_WRITE | CPATTENTION), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(result_8, xl_mmio + MMIO_MACDATA) ;
/*
* Now to write the microcode into the shared ram
* The microcode must finish at position 0xFFFF,
* so we must subtract to get the start position for the code
*
* Looks strange but ensures compiler only uses
* 16 bit unsigned int
*/
start = (0xFFFF - (xl_priv->fw->size) + 1) ;
printk(KERN_INFO "3C359: Uploading Microcode: ");
for (i = start, j = 0; j < xl_priv->fw->size; i++, j++) {
writel(MEM_BYTE_WRITE | 0XD0000 | i,
xl_mmio + MMIO_MAC_ACCESS_CMD);
writeb(xl_priv->fw->data[j], xl_mmio + MMIO_MACDATA);
if (j % 1024 == 0)
printk(".");
}
printk("\n") ;
for (i = 0; i < 16; i++) {
writel((MEM_BYTE_WRITE | 0xDFFF0) + i,
xl_mmio + MMIO_MAC_ACCESS_CMD);
writeb(xl_priv->fw->data[xl_priv->fw->size - 16 + i],
xl_mmio + MMIO_MACDATA);
}
/*
* Have to write the start address of the upload to FFF4, but
* the address must be >> 4. You do not want to know how long
* it took me to discover this.
*/
writel(MEM_WORD_WRITE | 0xDFFF4, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(start >> 4, xl_mmio + MMIO_MACDATA);
/* Clear the CPAttention, memWrEn Bit */
writel( (IO_BYTE_READ | CPATTENTION), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
result_8 = readb(xl_mmio + MMIO_MACDATA) ;
result_8 = result_8 & ~CPA_MEMWREN ;
writel( (IO_BYTE_WRITE | CPATTENTION), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(result_8, xl_mmio + MMIO_MACDATA) ;
/* Clear the cpHold bit in pmbar */
writel( (IO_WORD_READ | PMBAR),xl_mmio + MMIO_MAC_ACCESS_CMD);
result_16 = readw(xl_mmio + MMIO_MACDATA) ;
result_16 = result_16 & ~PMB_CPHOLD ;
writel( (IO_WORD_WRITE | PMBAR), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(result_16,xl_mmio + MMIO_MACDATA) ;
} /* If microcode upload required */
/*
* The card should now go though a self test procedure and get itself ready
* to be opened, we must wait for an srb response with the initialization
* information.
*/
#if XL_DEBUG
printk(KERN_INFO "%s: Microcode uploaded, must wait for the self test to complete\n", dev->name);
#endif
writew(SETINDENABLE | 0xFFF, xl_mmio + MMIO_COMMAND) ;
t=jiffies;
while ( !(readw(xl_mmio + MMIO_INTSTATUS_AUTO) & INTSTAT_SRB) ) {
schedule();
if (time_after(jiffies, t + 15 * HZ)) {
printk(KERN_ERR "3COM 3C359 Velocity XL card not responding.\n");
return -ENODEV;
}
}
/*
* Write the RxBufArea with D000, RxEarlyThresh, TxStartThresh,
* DnPriReqThresh, read the tech docs if you want to know what
* values they need to be.
*/
writel(MMIO_WORD_WRITE | RXBUFAREA, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(0xD000, xl_mmio + MMIO_MACDATA) ;
writel(MMIO_WORD_WRITE | RXEARLYTHRESH, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(0X0020, xl_mmio + MMIO_MACDATA) ;
writew( SETTXSTARTTHRESH | 0x40 , xl_mmio + MMIO_COMMAND) ;
writeb(0x04, xl_mmio + MMIO_DNBURSTTHRESH) ;
writeb(0x04, xl_mmio + DNPRIREQTHRESH) ;
/*
* Read WRBR to provide the location of the srb block, have to use byte reads not word reads.
* Tech docs have this wrong !!!!
*/
writel(MMIO_BYTE_READ | WRBR, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
xl_priv->srb = readb(xl_mmio + MMIO_MACDATA) << 8 ;
writel( (MMIO_BYTE_READ | WRBR) + 1, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
xl_priv->srb = xl_priv->srb | readb(xl_mmio + MMIO_MACDATA) ;
#if XL_DEBUG
writel(IO_WORD_READ | SWITCHSETTINGS, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
if ( readw(xl_mmio + MMIO_MACDATA) & 2) {
printk(KERN_INFO "Default ring speed 4 mbps\n");
} else {
printk(KERN_INFO "Default ring speed 16 mbps\n");
}
printk(KERN_INFO "%s: xl_priv->srb = %04x\n",xl_priv->xl_card_name, xl_priv->srb);
#endif
return 0;
}
static int xl_open(struct net_device *dev)
{
struct xl_private *xl_priv=netdev_priv(dev);
u8 __iomem *xl_mmio = xl_priv->xl_mmio ;
u8 i ;
__le16 hwaddr[3] ; /* Should be u8[6] but we get word return values */
int open_err ;
u16 switchsettings, switchsettings_eeprom ;
if (request_irq(dev->irq, xl_interrupt, IRQF_SHARED , "3c359", dev))
return -EAGAIN;
/*
* Read the information from the EEPROM that we need.
*/
hwaddr[0] = cpu_to_le16(xl_ee_read(dev,0x10));
hwaddr[1] = cpu_to_le16(xl_ee_read(dev,0x11));
hwaddr[2] = cpu_to_le16(xl_ee_read(dev,0x12));
/* Ring speed */
switchsettings_eeprom = xl_ee_read(dev,0x08) ;
switchsettings = switchsettings_eeprom ;
if (xl_priv->xl_ring_speed != 0) {
if (xl_priv->xl_ring_speed == 4)
switchsettings = switchsettings | 0x02 ;
else
switchsettings = switchsettings & ~0x02 ;
}
/* Only write EEProm if there has been a change */
if (switchsettings != switchsettings_eeprom) {
xl_ee_write(dev,0x08,switchsettings) ;
/* Hardware reset after changing EEProm */
xl_hw_reset(dev) ;
}
memcpy(dev->dev_addr,hwaddr,dev->addr_len) ;
open_err = xl_open_hw(dev) ;
/*
* This really needs to be cleaned up with better error reporting.
*/
if (open_err != 0) { /* Something went wrong with the open command */
if (open_err & 0x07) { /* Wrong speed, retry at different speed */
printk(KERN_WARNING "%s: Open Error, retrying at different ringspeed\n", dev->name);
switchsettings = switchsettings ^ 2 ;
xl_ee_write(dev,0x08,switchsettings) ;
xl_hw_reset(dev) ;
open_err = xl_open_hw(dev) ;
if (open_err != 0) {
printk(KERN_WARNING "%s: Open error returned a second time, we're bombing out now\n", dev->name);
free_irq(dev->irq,dev) ;
return -ENODEV ;
}
} else {
printk(KERN_WARNING "%s: Open Error = %04x\n", dev->name, open_err) ;
free_irq(dev->irq,dev) ;
return -ENODEV ;
}
}
/*
* Now to set up the Rx and Tx buffer structures
*/
/* These MUST be on 8 byte boundaries */
xl_priv->xl_tx_ring = kzalloc((sizeof(struct xl_tx_desc) * XL_TX_RING_SIZE) + 7, GFP_DMA | GFP_KERNEL);
if (xl_priv->xl_tx_ring == NULL) {
printk(KERN_WARNING "%s: Not enough memory to allocate tx buffers.\n",
dev->name);
free_irq(dev->irq,dev);
return -ENOMEM;
}
xl_priv->xl_rx_ring = kzalloc((sizeof(struct xl_rx_desc) * XL_RX_RING_SIZE) +7, GFP_DMA | GFP_KERNEL);
if (xl_priv->xl_rx_ring == NULL) {
printk(KERN_WARNING "%s: Not enough memory to allocate rx buffers.\n",
dev->name);
free_irq(dev->irq,dev);
kfree(xl_priv->xl_tx_ring);
return -ENOMEM;
}
/* Setup Rx Ring */
for (i=0 ; i < XL_RX_RING_SIZE ; i++) {
struct sk_buff *skb ;
skb = dev_alloc_skb(xl_priv->pkt_buf_sz) ;
if (skb==NULL)
break ;
skb->dev = dev ;
xl_priv->xl_rx_ring[i].upfragaddr = cpu_to_le32(pci_map_single(xl_priv->pdev, skb->data,xl_priv->pkt_buf_sz, PCI_DMA_FROMDEVICE));
xl_priv->xl_rx_ring[i].upfraglen = cpu_to_le32(xl_priv->pkt_buf_sz) | RXUPLASTFRAG;
xl_priv->rx_ring_skb[i] = skb ;
}
if (i==0) {
printk(KERN_WARNING "%s: Not enough memory to allocate rx buffers. Adapter disabled\n",dev->name);
free_irq(dev->irq,dev) ;
kfree(xl_priv->xl_tx_ring);
kfree(xl_priv->xl_rx_ring);
return -EIO ;
}
xl_priv->rx_ring_no = i ;
xl_priv->rx_ring_tail = 0 ;
xl_priv->rx_ring_dma_addr = pci_map_single(xl_priv->pdev,xl_priv->xl_rx_ring, sizeof(struct xl_rx_desc) * XL_RX_RING_SIZE, PCI_DMA_TODEVICE) ;
for (i=0;i<(xl_priv->rx_ring_no-1);i++) {
xl_priv->xl_rx_ring[i].upnextptr = cpu_to_le32(xl_priv->rx_ring_dma_addr + (sizeof (struct xl_rx_desc) * (i+1)));
}
xl_priv->xl_rx_ring[i].upnextptr = 0 ;
writel(xl_priv->rx_ring_dma_addr, xl_mmio + MMIO_UPLISTPTR) ;
/* Setup Tx Ring */
xl_priv->tx_ring_dma_addr = pci_map_single(xl_priv->pdev,xl_priv->xl_tx_ring, sizeof(struct xl_tx_desc) * XL_TX_RING_SIZE,PCI_DMA_TODEVICE) ;
xl_priv->tx_ring_head = 1 ;
xl_priv->tx_ring_tail = 255 ; /* Special marker for first packet */
xl_priv->free_ring_entries = XL_TX_RING_SIZE ;
/*
* Setup the first dummy DPD entry for polling to start working.
*/
xl_priv->xl_tx_ring[0].framestartheader = TXDPDEMPTY;
xl_priv->xl_tx_ring[0].buffer = 0 ;
xl_priv->xl_tx_ring[0].buffer_length = 0 ;
xl_priv->xl_tx_ring[0].dnnextptr = 0 ;
writel(xl_priv->tx_ring_dma_addr, xl_mmio + MMIO_DNLISTPTR) ;
writel(DNUNSTALL, xl_mmio + MMIO_COMMAND) ;
writel(UPUNSTALL, xl_mmio + MMIO_COMMAND) ;
writel(DNENABLE, xl_mmio + MMIO_COMMAND) ;
writeb(0x40, xl_mmio + MMIO_DNPOLL) ;
/*
* Enable interrupts on the card
*/
writel(SETINTENABLE | INT_MASK, xl_mmio + MMIO_COMMAND) ;
writel(SETINDENABLE | INT_MASK, xl_mmio + MMIO_COMMAND) ;
netif_start_queue(dev) ;
return 0;
}
static int xl_open_hw(struct net_device *dev)
{
struct xl_private *xl_priv=netdev_priv(dev);
u8 __iomem *xl_mmio = xl_priv->xl_mmio ;
u16 vsoff ;
char ver_str[33];
int open_err ;
int i ;
unsigned long t ;
/*
* Okay, let's build up the Open.NIC srb command
*
*/
writel( (MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(OPEN_NIC, xl_mmio + MMIO_MACDATA) ;
/*
* Use this as a test byte, if it comes back with the same value, the command didn't work
*/
writel( (MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb)+ 2, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(0xff,xl_mmio + MMIO_MACDATA) ;
/* Open options */
writel( (MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb) + 8, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(0x00, xl_mmio + MMIO_MACDATA) ;
writel( (MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb) + 9, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(0x00, xl_mmio + MMIO_MACDATA) ;
/*
* Node address, be careful here, the docs say you can just put zeros here and it will use
* the hardware address, it doesn't, you must include the node address in the open command.
*/
if (xl_priv->xl_laa[0]) { /* If using a LAA address */
for (i=10;i<16;i++) {
writel( (MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb) + i, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(xl_priv->xl_laa[i-10],xl_mmio + MMIO_MACDATA) ;
}
memcpy(dev->dev_addr,xl_priv->xl_laa,dev->addr_len) ;
} else { /* Regular hardware address */
for (i=10;i<16;i++) {
writel( (MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb) + i, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(dev->dev_addr[i-10], xl_mmio + MMIO_MACDATA) ;
}
}
/* Default everything else to 0 */
for (i = 16; i < 34; i++) {
writel( (MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb) + i, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(0x00,xl_mmio + MMIO_MACDATA) ;
}
/*
* Set the csrb bit in the MISR register
*/
xl_wait_misr_flags(dev) ;
writel(MEM_BYTE_WRITE | MF_CSRB, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(0xFF, xl_mmio + MMIO_MACDATA) ;
writel(MMIO_BYTE_WRITE | MISR_SET, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(MISR_CSRB , xl_mmio + MMIO_MACDATA) ;
/*
* Now wait for the command to run
*/
t=jiffies;
while (! (readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_SRB)) {
schedule();
if (time_after(jiffies, t + 40 * HZ)) {
printk(KERN_ERR "3COM 3C359 Velocity XL card not responding.\n");
break ;
}
}
/*
* Let's interpret the open response
*/
writel( (MEM_BYTE_READ | 0xD0000 | xl_priv->srb)+2, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
if (readb(xl_mmio + MMIO_MACDATA)!=0) {
open_err = readb(xl_mmio + MMIO_MACDATA) << 8 ;
writel( (MEM_BYTE_READ | 0xD0000 | xl_priv->srb) + 7, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
open_err |= readb(xl_mmio + MMIO_MACDATA) ;
return open_err ;
} else {
writel( (MEM_WORD_READ | 0xD0000 | xl_priv->srb) + 8, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
xl_priv->asb = swab16(readw(xl_mmio + MMIO_MACDATA)) ;
printk(KERN_INFO "%s: Adapter Opened Details: ",dev->name) ;
printk("ASB: %04x",xl_priv->asb ) ;
writel( (MEM_WORD_READ | 0xD0000 | xl_priv->srb) + 10, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
printk(", SRB: %04x",swab16(readw(xl_mmio + MMIO_MACDATA)) ) ;
writel( (MEM_WORD_READ | 0xD0000 | xl_priv->srb) + 12, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
xl_priv->arb = swab16(readw(xl_mmio + MMIO_MACDATA)) ;
printk(", ARB: %04x\n",xl_priv->arb );
writel( (MEM_WORD_READ | 0xD0000 | xl_priv->srb) + 14, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
vsoff = swab16(readw(xl_mmio + MMIO_MACDATA)) ;
/*
* Interesting, sending the individual characters directly to printk was causing klogd to use
* use 100% of processor time, so we build up the string and print that instead.
*/
for (i=0;i<0x20;i++) {
writel( (MEM_BYTE_READ | 0xD0000 | vsoff) + i, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
ver_str[i] = readb(xl_mmio + MMIO_MACDATA) ;
}
ver_str[i] = '\0' ;
printk(KERN_INFO "%s: Microcode version String: %s\n",dev->name,ver_str);
}
/*
* Issue the AckInterrupt
*/
writew(ACK_INTERRUPT | SRBRACK | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
return 0 ;
}
/*
* There are two ways of implementing rx on the 359 NIC, either
* interrupt driven or polling. We are going to uses interrupts,
* it is the easier way of doing things.
*
* The Rx works with a ring of Rx descriptors. At initialise time the ring
* entries point to the next entry except for the last entry in the ring
* which points to 0. The card is programmed with the location of the first
* available descriptor and keeps reading the next_ptr until next_ptr is set
* to 0. Hopefully with a ring size of 16 the card will never get to read a next_ptr
* of 0. As the Rx interrupt is received we copy the frame up to the protocol layers
* and then point the end of the ring to our current position and point our current
* position to 0, therefore making the current position the last position on the ring.
* The last position on the ring therefore loops continually loops around the rx ring.
*
* rx_ring_tail is the position on the ring to process next. (Think of a snake, the head
* expands as the card adds new packets and we go around eating the tail processing the
* packets.)
*
* Undoubtably it could be streamlined and improved upon, but at the moment it works
* and the fast path through the routine is fine.
*
* adv_rx_ring could be inlined to increase performance, but its called a *lot* of times
* in xl_rx so would increase the size of the function significantly.
*/
static void adv_rx_ring(struct net_device *dev) /* Advance rx_ring, cut down on bloat in xl_rx */
{
struct xl_private *xl_priv=netdev_priv(dev);
int n = xl_priv->rx_ring_tail;
int prev_ring_loc;
prev_ring_loc = (n + XL_RX_RING_SIZE - 1) & (XL_RX_RING_SIZE - 1);
xl_priv->xl_rx_ring[prev_ring_loc].upnextptr = cpu_to_le32(xl_priv->rx_ring_dma_addr + (sizeof (struct xl_rx_desc) * n));
xl_priv->xl_rx_ring[n].framestatus = 0;
xl_priv->xl_rx_ring[n].upnextptr = 0;
xl_priv->rx_ring_tail++;
xl_priv->rx_ring_tail &= (XL_RX_RING_SIZE-1);
}
static void xl_rx(struct net_device *dev)
{
struct xl_private *xl_priv=netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
struct sk_buff *skb, *skb2 ;
int frame_length = 0, copy_len = 0 ;
int temp_ring_loc ;
/*
* Receive the next frame, loop around the ring until all frames
* have been received.
*/
while (xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].framestatus & (RXUPDCOMPLETE | RXUPDFULL) ) { /* Descriptor to process */
if (xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].framestatus & RXUPDFULL ) { /* UpdFull, Multiple Descriptors used for the frame */
/*
* This is a pain, you need to go through all the descriptors until the last one
* for this frame to find the framelength
*/
temp_ring_loc = xl_priv->rx_ring_tail ;
while (xl_priv->xl_rx_ring[temp_ring_loc].framestatus & RXUPDFULL ) {
temp_ring_loc++ ;
temp_ring_loc &= (XL_RX_RING_SIZE-1) ;
}
frame_length = le32_to_cpu(xl_priv->xl_rx_ring[temp_ring_loc].framestatus) & 0x7FFF;
skb = dev_alloc_skb(frame_length) ;
if (skb==NULL) { /* No memory for frame, still need to roll forward the rx ring */
printk(KERN_WARNING "%s: dev_alloc_skb failed - multi buffer !\n", dev->name) ;
while (xl_priv->rx_ring_tail != temp_ring_loc)
adv_rx_ring(dev) ;
adv_rx_ring(dev) ; /* One more time just for luck :) */
dev->stats.rx_dropped++ ;
writel(ACK_INTERRUPT | UPCOMPACK | LATCH_ACK , xl_mmio + MMIO_COMMAND) ;
return ;
}
while (xl_priv->rx_ring_tail != temp_ring_loc) {
copy_len = le32_to_cpu(xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfraglen) & 0x7FFF;
frame_length -= copy_len ;
pci_dma_sync_single_for_cpu(xl_priv->pdev,le32_to_cpu(xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfragaddr),xl_priv->pkt_buf_sz,PCI_DMA_FROMDEVICE);
skb_copy_from_linear_data(xl_priv->rx_ring_skb[xl_priv->rx_ring_tail],
skb_put(skb, copy_len),
copy_len);
pci_dma_sync_single_for_device(xl_priv->pdev,le32_to_cpu(xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfragaddr),xl_priv->pkt_buf_sz,PCI_DMA_FROMDEVICE);
adv_rx_ring(dev) ;
}
/* Now we have found the last fragment */
pci_dma_sync_single_for_cpu(xl_priv->pdev,le32_to_cpu(xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfragaddr),xl_priv->pkt_buf_sz,PCI_DMA_FROMDEVICE);
skb_copy_from_linear_data(xl_priv->rx_ring_skb[xl_priv->rx_ring_tail],
skb_put(skb,copy_len), frame_length);
/* memcpy(skb_put(skb,frame_length), bus_to_virt(xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfragaddr), frame_length) ; */
pci_dma_sync_single_for_device(xl_priv->pdev,le32_to_cpu(xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfragaddr),xl_priv->pkt_buf_sz,PCI_DMA_FROMDEVICE);
adv_rx_ring(dev) ;
skb->protocol = tr_type_trans(skb,dev) ;
netif_rx(skb) ;
} else { /* Single Descriptor Used, simply swap buffers over, fast path */
frame_length = le32_to_cpu(xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].framestatus) & 0x7FFF;
skb = dev_alloc_skb(xl_priv->pkt_buf_sz) ;
if (skb==NULL) { /* Still need to fix the rx ring */
printk(KERN_WARNING "%s: dev_alloc_skb failed in rx, single buffer\n",dev->name);
adv_rx_ring(dev) ;
dev->stats.rx_dropped++ ;
writel(ACK_INTERRUPT | UPCOMPACK | LATCH_ACK , xl_mmio + MMIO_COMMAND) ;
return ;
}
skb2 = xl_priv->rx_ring_skb[xl_priv->rx_ring_tail] ;
pci_unmap_single(xl_priv->pdev, le32_to_cpu(xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfragaddr), xl_priv->pkt_buf_sz,PCI_DMA_FROMDEVICE) ;
skb_put(skb2, frame_length) ;
skb2->protocol = tr_type_trans(skb2,dev) ;
xl_priv->rx_ring_skb[xl_priv->rx_ring_tail] = skb ;
xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfragaddr = cpu_to_le32(pci_map_single(xl_priv->pdev,skb->data,xl_priv->pkt_buf_sz, PCI_DMA_FROMDEVICE));
xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfraglen = cpu_to_le32(xl_priv->pkt_buf_sz) | RXUPLASTFRAG;
adv_rx_ring(dev) ;
dev->stats.rx_packets++ ;
dev->stats.rx_bytes += frame_length ;
netif_rx(skb2) ;
} /* if multiple buffers */
} /* while packet to do */
/* Clear the updComplete interrupt */
writel(ACK_INTERRUPT | UPCOMPACK | LATCH_ACK , xl_mmio + MMIO_COMMAND) ;
return ;
}
/*
* This is ruthless, it doesn't care what state the card is in it will
* completely reset the adapter.
*/
static void xl_reset(struct net_device *dev)
{
struct xl_private *xl_priv=netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
unsigned long t;
writew( GLOBAL_RESET, xl_mmio + MMIO_COMMAND ) ;
/*
* Must wait for cmdInProgress bit (12) to clear before continuing with
* card configuration.
*/
t=jiffies;
while (readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_CMD_IN_PROGRESS) {
if (time_after(jiffies, t + 40 * HZ)) {
printk(KERN_ERR "3COM 3C359 Velocity XL card not responding.\n");
break ;
}
}
}
static void xl_freemem(struct net_device *dev)
{
struct xl_private *xl_priv=netdev_priv(dev);
int i ;
for (i=0;i<XL_RX_RING_SIZE;i++) {
dev_kfree_skb_irq(xl_priv->rx_ring_skb[xl_priv->rx_ring_tail]) ;
pci_unmap_single(xl_priv->pdev,le32_to_cpu(xl_priv->xl_rx_ring[xl_priv->rx_ring_tail].upfragaddr),xl_priv->pkt_buf_sz, PCI_DMA_FROMDEVICE);
xl_priv->rx_ring_tail++ ;
xl_priv->rx_ring_tail &= XL_RX_RING_SIZE-1;
}
/* unmap ring */
pci_unmap_single(xl_priv->pdev,xl_priv->rx_ring_dma_addr, sizeof(struct xl_rx_desc) * XL_RX_RING_SIZE, PCI_DMA_FROMDEVICE) ;
pci_unmap_single(xl_priv->pdev,xl_priv->tx_ring_dma_addr, sizeof(struct xl_tx_desc) * XL_TX_RING_SIZE, PCI_DMA_TODEVICE) ;
kfree(xl_priv->xl_rx_ring) ;
kfree(xl_priv->xl_tx_ring) ;
return ;
}
static irqreturn_t xl_interrupt(int irq, void *dev_id)
{
struct net_device *dev = (struct net_device *)dev_id;
struct xl_private *xl_priv =netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
u16 intstatus, macstatus ;
intstatus = readw(xl_mmio + MMIO_INTSTATUS) ;
if (!(intstatus & 1)) /* We didn't generate the interrupt */
return IRQ_NONE;
spin_lock(&xl_priv->xl_lock) ;
/*
* Process the interrupt
*/
/*
* Something fishy going on here, we shouldn't get 0001 ints, not fatal though.
*/
if (intstatus == 0x0001) {
writel(ACK_INTERRUPT | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
printk(KERN_INFO "%s: 00001 int received\n",dev->name);
} else {
if (intstatus & (HOSTERRINT | SRBRINT | ARBCINT | UPCOMPINT | DNCOMPINT | HARDERRINT | (1<<8) | TXUNDERRUN | ASBFINT)) {
/*
* Host Error.
* It may be possible to recover from this, but usually it means something
* is seriously fubar, so we just close the adapter.
*/
if (intstatus & HOSTERRINT) {
printk(KERN_WARNING "%s: Host Error, performing global reset, intstatus = %04x\n",dev->name,intstatus);
writew( GLOBAL_RESET, xl_mmio + MMIO_COMMAND ) ;
printk(KERN_WARNING "%s: Resetting hardware:\n", dev->name);
netif_stop_queue(dev) ;
xl_freemem(dev) ;
free_irq(dev->irq,dev);
xl_reset(dev) ;
writel(ACK_INTERRUPT | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
spin_unlock(&xl_priv->xl_lock) ;
return IRQ_HANDLED;
} /* Host Error */
if (intstatus & SRBRINT ) { /* Srbc interrupt */
writel(ACK_INTERRUPT | SRBRACK | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
if (xl_priv->srb_queued)
xl_srb_bh(dev) ;
} /* SRBR Interrupt */
if (intstatus & TXUNDERRUN) { /* Issue DnReset command */
writel(DNRESET, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
while (readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_CMD_IN_PROGRESS) { /* Wait for command to run */
/* !!! FIX-ME !!!!
Must put a timeout check here ! */
/* Empty Loop */
}
printk(KERN_WARNING "%s: TX Underrun received\n",dev->name);
writel(ACK_INTERRUPT | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
} /* TxUnderRun */
if (intstatus & ARBCINT ) { /* Arbc interrupt */
xl_arb_cmd(dev) ;
} /* Arbc */
if (intstatus & ASBFINT) {
if (xl_priv->asb_queued == 1) {
xl_asb_cmd(dev) ;
} else if (xl_priv->asb_queued == 2) {
xl_asb_bh(dev) ;
} else {
writel(ACK_INTERRUPT | LATCH_ACK | ASBFACK, xl_mmio + MMIO_COMMAND) ;
}
} /* Asbf */
if (intstatus & UPCOMPINT ) /* UpComplete */
xl_rx(dev) ;
if (intstatus & DNCOMPINT ) /* DnComplete */
xl_dn_comp(dev) ;
if (intstatus & HARDERRINT ) { /* Hardware error */
writel(MMIO_WORD_READ | MACSTATUS, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
macstatus = readw(xl_mmio + MMIO_MACDATA) ;
printk(KERN_WARNING "%s: MacStatusError, details: ", dev->name);
if (macstatus & (1<<14))
printk(KERN_WARNING "tchk error: Unrecoverable error\n");
if (macstatus & (1<<3))
printk(KERN_WARNING "eint error: Internal watchdog timer expired\n");
if (macstatus & (1<<2))
printk(KERN_WARNING "aint error: Host tried to perform invalid operation\n");
printk(KERN_WARNING "Instatus = %02x, macstatus = %02x\n",intstatus,macstatus) ;
printk(KERN_WARNING "%s: Resetting hardware:\n", dev->name);
netif_stop_queue(dev) ;
xl_freemem(dev) ;
free_irq(dev->irq,dev);
unregister_netdev(dev) ;
free_netdev(dev) ;
xl_reset(dev) ;
writel(ACK_INTERRUPT | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
spin_unlock(&xl_priv->xl_lock) ;
return IRQ_HANDLED;
}
} else {
printk(KERN_WARNING "%s: Received Unknown interrupt : %04x\n", dev->name, intstatus);
writel(ACK_INTERRUPT | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
}
}
/* Turn interrupts back on */
writel( SETINDENABLE | INT_MASK, xl_mmio + MMIO_COMMAND) ;
writel( SETINTENABLE | INT_MASK, xl_mmio + MMIO_COMMAND) ;
spin_unlock(&xl_priv->xl_lock) ;
return IRQ_HANDLED;
}
/*
* Tx - Polling configuration
*/
static netdev_tx_t xl_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct xl_private *xl_priv=netdev_priv(dev);
struct xl_tx_desc *txd ;
int tx_head, tx_tail, tx_prev ;
unsigned long flags ;
spin_lock_irqsave(&xl_priv->xl_lock,flags) ;
netif_stop_queue(dev) ;
if (xl_priv->free_ring_entries > 1 ) {
/*
* Set up the descriptor for the packet
*/
tx_head = xl_priv->tx_ring_head ;
tx_tail = xl_priv->tx_ring_tail ;
txd = &(xl_priv->xl_tx_ring[tx_head]) ;
txd->dnnextptr = 0 ;
txd->framestartheader = cpu_to_le32(skb->len) | TXDNINDICATE;
txd->buffer = cpu_to_le32(pci_map_single(xl_priv->pdev, skb->data, skb->len, PCI_DMA_TODEVICE));
txd->buffer_length = cpu_to_le32(skb->len) | TXDNFRAGLAST;
xl_priv->tx_ring_skb[tx_head] = skb ;
dev->stats.tx_packets++ ;
dev->stats.tx_bytes += skb->len ;
/*
* Set the nextptr of the previous descriptor equal to this descriptor, add XL_TX_RING_SIZE -1
* to ensure no negative numbers in unsigned locations.
*/
tx_prev = (xl_priv->tx_ring_head + XL_TX_RING_SIZE - 1) & (XL_TX_RING_SIZE - 1) ;
xl_priv->tx_ring_head++ ;
xl_priv->tx_ring_head &= (XL_TX_RING_SIZE - 1) ;
xl_priv->free_ring_entries-- ;
xl_priv->xl_tx_ring[tx_prev].dnnextptr = cpu_to_le32(xl_priv->tx_ring_dma_addr + (sizeof (struct xl_tx_desc) * tx_head));
/* Sneaky, by doing a read on DnListPtr we can force the card to poll on the DnNextPtr */
/* readl(xl_mmio + MMIO_DNLISTPTR) ; */
netif_wake_queue(dev) ;
spin_unlock_irqrestore(&xl_priv->xl_lock,flags) ;
return NETDEV_TX_OK;
} else {
spin_unlock_irqrestore(&xl_priv->xl_lock,flags) ;
return NETDEV_TX_BUSY;
}
}
/*
* The NIC has told us that a packet has been downloaded onto the card, we must
* find out which packet it has done, clear the skb and information for the packet
* then advance around the ring for all transmitted packets
*/
static void xl_dn_comp(struct net_device *dev)
{
struct xl_private *xl_priv=netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
struct xl_tx_desc *txd ;
if (xl_priv->tx_ring_tail == 255) {/* First time */
xl_priv->xl_tx_ring[0].framestartheader = 0 ;
xl_priv->xl_tx_ring[0].dnnextptr = 0 ;
xl_priv->tx_ring_tail = 1 ;
}
while (xl_priv->xl_tx_ring[xl_priv->tx_ring_tail].framestartheader & TXDNCOMPLETE ) {
txd = &(xl_priv->xl_tx_ring[xl_priv->tx_ring_tail]) ;
pci_unmap_single(xl_priv->pdev, le32_to_cpu(txd->buffer), xl_priv->tx_ring_skb[xl_priv->tx_ring_tail]->len, PCI_DMA_TODEVICE);
txd->framestartheader = 0 ;
txd->buffer = cpu_to_le32(0xdeadbeef);
txd->buffer_length = 0 ;
dev_kfree_skb_irq(xl_priv->tx_ring_skb[xl_priv->tx_ring_tail]) ;
xl_priv->tx_ring_tail++ ;
xl_priv->tx_ring_tail &= (XL_TX_RING_SIZE - 1) ;
xl_priv->free_ring_entries++ ;
}
netif_wake_queue(dev) ;
writel(ACK_INTERRUPT | DNCOMPACK | LATCH_ACK , xl_mmio + MMIO_COMMAND) ;
}
/*
* Close the adapter properly.
* This srb reply cannot be handled from interrupt context as we have
* to free the interrupt from the driver.
*/
static int xl_close(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
unsigned long t ;
netif_stop_queue(dev) ;
/*
* Close the adapter, need to stall the rx and tx queues.
*/
writew(DNSTALL, xl_mmio + MMIO_COMMAND) ;
t=jiffies;
while (readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_CMD_IN_PROGRESS) {
schedule();
if (time_after(jiffies, t + 10 * HZ)) {
printk(KERN_ERR "%s: 3COM 3C359 Velocity XL-DNSTALL not responding.\n", dev->name);
break ;
}
}
writew(DNDISABLE, xl_mmio + MMIO_COMMAND) ;
t=jiffies;
while (readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_CMD_IN_PROGRESS) {
schedule();
if (time_after(jiffies, t + 10 * HZ)) {
printk(KERN_ERR "%s: 3COM 3C359 Velocity XL-DNDISABLE not responding.\n", dev->name);
break ;
}
}
writew(UPSTALL, xl_mmio + MMIO_COMMAND) ;
t=jiffies;
while (readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_CMD_IN_PROGRESS) {
schedule();
if (time_after(jiffies, t + 10 * HZ)) {
printk(KERN_ERR "%s: 3COM 3C359 Velocity XL-UPSTALL not responding.\n", dev->name);
break ;
}
}
/* Turn off interrupts, we will still get the indication though
* so we can trap it
*/
writel(SETINTENABLE, xl_mmio + MMIO_COMMAND) ;
xl_srb_cmd(dev,CLOSE_NIC) ;
t=jiffies;
while (!(readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_SRB)) {
schedule();
if (time_after(jiffies, t + 10 * HZ)) {
printk(KERN_ERR "%s: 3COM 3C359 Velocity XL-CLOSENIC not responding.\n", dev->name);
break ;
}
}
/* Read the srb response from the adapter */
writel(MEM_BYTE_READ | 0xd0000 | xl_priv->srb, xl_mmio + MMIO_MAC_ACCESS_CMD);
if (readb(xl_mmio + MMIO_MACDATA) != CLOSE_NIC) {
printk(KERN_INFO "%s: CLOSE_NIC did not get a CLOSE_NIC response\n",dev->name);
} else {
writel((MEM_BYTE_READ | 0xd0000 | xl_priv->srb) +2, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
if (readb(xl_mmio + MMIO_MACDATA)==0) {
printk(KERN_INFO "%s: Adapter has been closed\n",dev->name);
writew(ACK_INTERRUPT | SRBRACK | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
xl_freemem(dev) ;
free_irq(dev->irq,dev) ;
} else {
printk(KERN_INFO "%s: Close nic command returned error code %02x\n",dev->name, readb(xl_mmio + MMIO_MACDATA)) ;
}
}
/* Reset the upload and download logic */
writew(UPRESET, xl_mmio + MMIO_COMMAND) ;
t=jiffies;
while (readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_CMD_IN_PROGRESS) {
schedule();
if (time_after(jiffies, t + 10 * HZ)) {
printk(KERN_ERR "%s: 3COM 3C359 Velocity XL-UPRESET not responding.\n", dev->name);
break ;
}
}
writew(DNRESET, xl_mmio + MMIO_COMMAND) ;
t=jiffies;
while (readw(xl_mmio + MMIO_INTSTATUS) & INTSTAT_CMD_IN_PROGRESS) {
schedule();
if (time_after(jiffies, t + 10 * HZ)) {
printk(KERN_ERR "%s: 3COM 3C359 Velocity XL-DNRESET not responding.\n", dev->name);
break ;
}
}
xl_hw_reset(dev) ;
return 0 ;
}
static void xl_set_rx_mode(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
struct netdev_hw_addr *ha;
unsigned char dev_mc_address[4] ;
u16 options ;
if (dev->flags & IFF_PROMISC)
options = 0x0004 ;
else
options = 0x0000 ;
if (options ^ xl_priv->xl_copy_all_options) { /* Changed, must send command */
xl_priv->xl_copy_all_options = options ;
xl_srb_cmd(dev, SET_RECEIVE_MODE) ;
return ;
}
dev_mc_address[0] = dev_mc_address[1] = dev_mc_address[2] = dev_mc_address[3] = 0 ;
netdev_for_each_mc_addr(ha, dev) {
dev_mc_address[0] |= ha->addr[2];
dev_mc_address[1] |= ha->addr[3];
dev_mc_address[2] |= ha->addr[4];
dev_mc_address[3] |= ha->addr[5];
}
if (memcmp(xl_priv->xl_functional_addr,dev_mc_address,4) != 0) { /* Options have changed, run the command */
memcpy(xl_priv->xl_functional_addr, dev_mc_address,4) ;
xl_srb_cmd(dev, SET_FUNC_ADDRESS) ;
}
return ;
}
/*
* We issued an srb command and now we must read
* the response from the completed command.
*/
static void xl_srb_bh(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
u8 srb_cmd, ret_code ;
int i ;
writel(MEM_BYTE_READ | 0xd0000 | xl_priv->srb, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
srb_cmd = readb(xl_mmio + MMIO_MACDATA) ;
writel((MEM_BYTE_READ | 0xd0000 | xl_priv->srb) +2, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
ret_code = readb(xl_mmio + MMIO_MACDATA) ;
/* Ret_code is standard across all commands */
switch (ret_code) {
case 1:
printk(KERN_INFO "%s: Command: %d - Invalid Command code\n",dev->name,srb_cmd) ;
break ;
case 4:
printk(KERN_INFO "%s: Command: %d - Adapter is closed, must be open for this command\n",dev->name,srb_cmd);
break ;
case 6:
printk(KERN_INFO "%s: Command: %d - Options Invalid for command\n",dev->name,srb_cmd);
break ;
case 0: /* Successful command execution */
switch (srb_cmd) {
case READ_LOG: /* Returns 14 bytes of data from the NIC */
if(xl_priv->xl_message_level)
printk(KERN_INFO "%s: READ.LOG 14 bytes of data ",dev->name) ;
/*
* We still have to read the log even if message_level = 0 and we don't want
* to see it
*/
for (i=0;i<14;i++) {
writel(MEM_BYTE_READ | 0xd0000 | xl_priv->srb | i, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
if(xl_priv->xl_message_level)
printk("%02x:",readb(xl_mmio + MMIO_MACDATA)) ;
}
printk("\n") ;
break ;
case SET_FUNC_ADDRESS:
if(xl_priv->xl_message_level)
printk(KERN_INFO "%s: Functional Address Set\n",dev->name);
break ;
case CLOSE_NIC:
if(xl_priv->xl_message_level)
printk(KERN_INFO "%s: Received CLOSE_NIC interrupt in interrupt handler\n",dev->name);
break ;
case SET_MULTICAST_MODE:
if(xl_priv->xl_message_level)
printk(KERN_INFO "%s: Multicast options successfully changed\n",dev->name) ;
break ;
case SET_RECEIVE_MODE:
if(xl_priv->xl_message_level) {
if (xl_priv->xl_copy_all_options == 0x0004)
printk(KERN_INFO "%s: Entering promiscuous mode\n", dev->name);
else
printk(KERN_INFO "%s: Entering normal receive mode\n",dev->name);
}
break ;
} /* switch */
break ;
} /* switch */
return ;
}
static int xl_set_mac_address (struct net_device *dev, void *addr)
{
struct sockaddr *saddr = addr ;
struct xl_private *xl_priv = netdev_priv(dev);
if (netif_running(dev)) {
printk(KERN_WARNING "%s: Cannot set mac/laa address while card is open\n", dev->name) ;
return -EIO ;
}
memcpy(xl_priv->xl_laa, saddr->sa_data,dev->addr_len) ;
if (xl_priv->xl_message_level) {
printk(KERN_INFO "%s: MAC/LAA Set to = %x.%x.%x.%x.%x.%x\n",dev->name, xl_priv->xl_laa[0],
xl_priv->xl_laa[1], xl_priv->xl_laa[2],
xl_priv->xl_laa[3], xl_priv->xl_laa[4],
xl_priv->xl_laa[5]);
}
return 0 ;
}
static void xl_arb_cmd(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
u8 arb_cmd ;
u16 lan_status, lan_status_diff ;
writel( ( MEM_BYTE_READ | 0xD0000 | xl_priv->arb), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
arb_cmd = readb(xl_mmio + MMIO_MACDATA) ;
if (arb_cmd == RING_STATUS_CHANGE) { /* Ring.Status.Change */
writel( ( (MEM_WORD_READ | 0xD0000 | xl_priv->arb) + 6), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
printk(KERN_INFO "%s: Ring Status Change: New Status = %04x\n", dev->name, swab16(readw(xl_mmio + MMIO_MACDATA) )) ;
lan_status = swab16(readw(xl_mmio + MMIO_MACDATA));
/* Acknowledge interrupt, this tells nic we are done with the arb */
writel(ACK_INTERRUPT | ARBCACK | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
lan_status_diff = xl_priv->xl_lan_status ^ lan_status ;
if (lan_status_diff & (LSC_LWF | LSC_ARW | LSC_FPE | LSC_RR) ) {
if (lan_status_diff & LSC_LWF)
printk(KERN_WARNING "%s: Short circuit detected on the lobe\n",dev->name);
if (lan_status_diff & LSC_ARW)
printk(KERN_WARNING "%s: Auto removal error\n",dev->name);
if (lan_status_diff & LSC_FPE)
printk(KERN_WARNING "%s: FDX Protocol Error\n",dev->name);
if (lan_status_diff & LSC_RR)
printk(KERN_WARNING "%s: Force remove MAC frame received\n",dev->name);
/* Adapter has been closed by the hardware */
netif_stop_queue(dev);
xl_freemem(dev) ;
free_irq(dev->irq,dev);
printk(KERN_WARNING "%s: Adapter has been closed\n", dev->name);
} /* If serious error */
if (xl_priv->xl_message_level) {
if (lan_status_diff & LSC_SIG_LOSS)
printk(KERN_WARNING "%s: No receive signal detected\n", dev->name);
if (lan_status_diff & LSC_HARD_ERR)
printk(KERN_INFO "%s: Beaconing\n",dev->name);
if (lan_status_diff & LSC_SOFT_ERR)
printk(KERN_WARNING "%s: Adapter transmitted Soft Error Report Mac Frame\n",dev->name);
if (lan_status_diff & LSC_TRAN_BCN)
printk(KERN_INFO "%s: We are transmitting the beacon, aaah\n",dev->name);
if (lan_status_diff & LSC_SS)
printk(KERN_INFO "%s: Single Station on the ring\n", dev->name);
if (lan_status_diff & LSC_RING_REC)
printk(KERN_INFO "%s: Ring recovery ongoing\n",dev->name);
if (lan_status_diff & LSC_FDX_MODE)
printk(KERN_INFO "%s: Operating in FDX mode\n",dev->name);
}
if (lan_status_diff & LSC_CO) {
if (xl_priv->xl_message_level)
printk(KERN_INFO "%s: Counter Overflow\n", dev->name);
/* Issue READ.LOG command */
xl_srb_cmd(dev, READ_LOG) ;
}
/* There is no command in the tech docs to issue the read_sr_counters */
if (lan_status_diff & LSC_SR_CO) {
if (xl_priv->xl_message_level)
printk(KERN_INFO "%s: Source routing counters overflow\n", dev->name);
}
xl_priv->xl_lan_status = lan_status ;
} /* Lan.change.status */
else if ( arb_cmd == RECEIVE_DATA) { /* Received.Data */
#if XL_DEBUG
printk(KERN_INFO "Received.Data\n");
#endif
writel( ((MEM_WORD_READ | 0xD0000 | xl_priv->arb) + 6), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
xl_priv->mac_buffer = swab16(readw(xl_mmio + MMIO_MACDATA)) ;
/* Now we are going to be really basic here and not do anything
* with the data at all. The tech docs do not give me enough
* information to calculate the buffers properly so we're
* just going to tell the nic that we've dealt with the frame
* anyway.
*/
/* Acknowledge interrupt, this tells nic we are done with the arb */
writel(ACK_INTERRUPT | ARBCACK | LATCH_ACK, xl_mmio + MMIO_COMMAND) ;
/* Is the ASB free ? */
xl_priv->asb_queued = 0 ;
writel( ((MEM_BYTE_READ | 0xD0000 | xl_priv->asb) + 2), xl_mmio + MMIO_MAC_ACCESS_CMD) ;
if (readb(xl_mmio + MMIO_MACDATA) != 0xff) {
xl_priv->asb_queued = 1 ;
xl_wait_misr_flags(dev) ;
writel(MEM_BYTE_WRITE | MF_ASBFR, xl_mmio + MMIO_MAC_ACCESS_CMD);
writeb(0xff, xl_mmio + MMIO_MACDATA) ;
writel(MMIO_BYTE_WRITE | MISR_SET, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(MISR_ASBFR, xl_mmio + MMIO_MACDATA) ;
return ;
/* Drop out and wait for the bottom half to be run */
}
xl_asb_cmd(dev) ;
} else {
printk(KERN_WARNING "%s: Received unknown arb (xl_priv) command: %02x\n",dev->name,arb_cmd);
}
/* Acknowledge the arb interrupt */
writel(ACK_INTERRUPT | ARBCACK | LATCH_ACK , xl_mmio + MMIO_COMMAND) ;
return ;
}
/*
* There is only one asb command, but we can get called from different
* places.
*/
static void xl_asb_cmd(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
if (xl_priv->asb_queued == 1)
writel(ACK_INTERRUPT | LATCH_ACK | ASBFACK, xl_mmio + MMIO_COMMAND) ;
writel(MEM_BYTE_WRITE | 0xd0000 | xl_priv->asb, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(0x81, xl_mmio + MMIO_MACDATA) ;
writel(MEM_WORD_WRITE | 0xd0000 | xl_priv->asb | 6, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(swab16(xl_priv->mac_buffer), xl_mmio + MMIO_MACDATA) ;
xl_wait_misr_flags(dev) ;
writel(MEM_BYTE_WRITE | MF_RASB, xl_mmio + MMIO_MAC_ACCESS_CMD);
writeb(0xff, xl_mmio + MMIO_MACDATA) ;
writel(MMIO_BYTE_WRITE | MISR_SET, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(MISR_RASB, xl_mmio + MMIO_MACDATA) ;
xl_priv->asb_queued = 2 ;
return ;
}
/*
* This will only get called if there was an error
* from the asb cmd.
*/
static void xl_asb_bh(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
u8 ret_code ;
writel(MMIO_BYTE_READ | 0xd0000 | xl_priv->asb | 2, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
ret_code = readb(xl_mmio + MMIO_MACDATA) ;
switch (ret_code) {
case 0x01:
printk(KERN_INFO "%s: ASB Command, unrecognized command code\n",dev->name);
break ;
case 0x26:
printk(KERN_INFO "%s: ASB Command, unexpected receive buffer\n", dev->name);
break ;
case 0x40:
printk(KERN_INFO "%s: ASB Command, Invalid Station ID\n", dev->name);
break ;
}
xl_priv->asb_queued = 0 ;
writel(ACK_INTERRUPT | LATCH_ACK | ASBFACK, xl_mmio + MMIO_COMMAND) ;
return ;
}
/*
* Issue srb commands to the nic
*/
static void xl_srb_cmd(struct net_device *dev, int srb_cmd)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
switch (srb_cmd) {
case READ_LOG:
writel(MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(READ_LOG, xl_mmio + MMIO_MACDATA) ;
break;
case CLOSE_NIC:
writel(MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(CLOSE_NIC, xl_mmio + MMIO_MACDATA) ;
break ;
case SET_RECEIVE_MODE:
writel(MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(SET_RECEIVE_MODE, xl_mmio + MMIO_MACDATA) ;
writel(MEM_WORD_WRITE | 0xD0000 | xl_priv->srb | 4, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writew(xl_priv->xl_copy_all_options, xl_mmio + MMIO_MACDATA) ;
break ;
case SET_FUNC_ADDRESS:
writel(MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(SET_FUNC_ADDRESS, xl_mmio + MMIO_MACDATA) ;
writel(MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb | 6 , xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(xl_priv->xl_functional_addr[0], xl_mmio + MMIO_MACDATA) ;
writel(MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb | 7 , xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(xl_priv->xl_functional_addr[1], xl_mmio + MMIO_MACDATA) ;
writel(MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb | 8 , xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(xl_priv->xl_functional_addr[2], xl_mmio + MMIO_MACDATA) ;
writel(MEM_BYTE_WRITE | 0xD0000 | xl_priv->srb | 9 , xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(xl_priv->xl_functional_addr[3], xl_mmio + MMIO_MACDATA) ;
break ;
} /* switch */
xl_wait_misr_flags(dev) ;
/* Write 0xff to the CSRB flag */
writel(MEM_BYTE_WRITE | MF_CSRB , xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(0xFF, xl_mmio + MMIO_MACDATA) ;
/* Set csrb bit in MISR register to process command */
writel(MMIO_BYTE_WRITE | MISR_SET, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(MISR_CSRB, xl_mmio + MMIO_MACDATA) ;
xl_priv->srb_queued = 1 ;
return ;
}
/*
* This is nasty, to use the MISR command you have to wait for 6 memory locations
* to be zero. This is the way the driver does on other OS'es so we should be ok with
* the empty loop.
*/
static void xl_wait_misr_flags(struct net_device *dev)
{
struct xl_private *xl_priv = netdev_priv(dev);
u8 __iomem * xl_mmio = xl_priv->xl_mmio ;
int i ;
writel(MMIO_BYTE_READ | MISR_RW, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
if (readb(xl_mmio + MMIO_MACDATA) != 0) { /* Misr not clear */
for (i=0; i<6; i++) {
writel(MEM_BYTE_READ | 0xDFFE0 | i, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
while (readb(xl_mmio + MMIO_MACDATA) != 0 ) {} ; /* Empty Loop */
}
}
writel(MMIO_BYTE_WRITE | MISR_AND, xl_mmio + MMIO_MAC_ACCESS_CMD) ;
writeb(0x80, xl_mmio + MMIO_MACDATA) ;
return ;
}
/*
* Change mtu size, this should work the same as olympic
*/
static int xl_change_mtu(struct net_device *dev, int mtu)
{
struct xl_private *xl_priv = netdev_priv(dev);
u16 max_mtu ;
if (xl_priv->xl_ring_speed == 4)
max_mtu = 4500 ;
else
max_mtu = 18000 ;
if (mtu > max_mtu)
return -EINVAL ;
if (mtu < 100)
return -EINVAL ;
dev->mtu = mtu ;
xl_priv->pkt_buf_sz = mtu + TR_HLEN ;
return 0 ;
}
static void __devexit xl_remove_one (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct xl_private *xl_priv=netdev_priv(dev);
release_firmware(xl_priv->fw);
unregister_netdev(dev);
iounmap(xl_priv->xl_mmio) ;
pci_release_regions(pdev) ;
pci_set_drvdata(pdev,NULL) ;
free_netdev(dev);
return ;
}
static struct pci_driver xl_3c359_driver = {
.name = "3c359",
.id_table = xl_pci_tbl,
.probe = xl_probe,
.remove = __devexit_p(xl_remove_one),
};
static int __init xl_pci_init (void)
{
return pci_register_driver(&xl_3c359_driver);
}
static void __exit xl_pci_cleanup (void)
{
pci_unregister_driver (&xl_3c359_driver);
}
module_init(xl_pci_init);
module_exit(xl_pci_cleanup);
MODULE_LICENSE("GPL") ;
| gpl-2.0 |
pikachukaki/android_kernel_huawei_honor | drivers/net/irda/donauboe.c | 2525 | 48253 | /*****************************************************************
*
* Filename: donauboe.c
* Version: 2.17
* Description: Driver for the Toshiba OBOE (or type-O or 701)
* FIR Chipset, also supports the DONAUOBOE (type-DO
* or d01) FIR chipset which as far as I know is
* register compatible.
* Documentation: http://libxg.free.fr/irda/lib-irda.html
* Status: Experimental.
* Author: James McKenzie <james@fishsoup.dhs.org>
* Created at: Sat May 8 12:35:27 1999
* Modified: Paul Bristow <paul.bristow@technologist.com>
* Modified: Mon Nov 11 19:10:05 1999
* Modified: James McKenzie <james@fishsoup.dhs.org>
* Modified: Thu Mar 16 12:49:00 2000 (Substantial rewrite)
* Modified: Sat Apr 29 00:23:03 2000 (Added DONAUOBOE support)
* Modified: Wed May 24 23:45:02 2000 (Fixed chipio_t structure)
* Modified: 2.13 Christian Gennerat <christian.gennerat@polytechnique.org>
* Modified: 2.13 dim jan 07 21:57:39 2001 (tested with kernel 2.4 & irnet/ppp)
* Modified: 2.14 Christian Gennerat <christian.gennerat@polytechnique.org>
* Modified: 2.14 lun fev 05 17:55:59 2001 (adapted to patch-2.4.1-pre8-irda1)
* Modified: 2.15 Martin Lucina <mato@kotelna.sk>
* Modified: 2.15 Fri Jun 21 20:40:59 2002 (sync with 2.4.18, substantial fixes)
* Modified: 2.16 Martin Lucina <mato@kotelna.sk>
* Modified: 2.16 Sat Jun 22 18:54:29 2002 (fix freeregion, default to verbose)
* Modified: 2.17 Christian Gennerat <christian.gennerat@polytechnique.org>
* Modified: 2.17 jeu sep 12 08:50:20 2002 (save_flags();cli(); replaced by spinlocks)
* Modified: 2.18 Christian Gennerat <christian.gennerat@polytechnique.org>
* Modified: 2.18 ven jan 10 03:14:16 2003 Change probe default options
*
* Copyright (c) 1999 James McKenzie, 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.
*
* Neither James McKenzie nor Cambridge University admit liability nor
* provide warranty for any of this software. This material is
* provided "AS-IS" and at no charge.
*
* Applicable Models : Libretto 100/110CT and many more.
* Toshiba refers to this chip as the type-O IR port,
* or the type-DO IR port.
*
********************************************************************/
/* Look at toshoboe.h (currently in include/net/irda) for details of */
/* Where to get documentation on the chip */
/* See below for a description of the logic in this driver */
/* User servicable parts */
/* USE_PROBE Create the code which probes the chip and does a few tests */
/* do_probe module parameter Enable this code */
/* Probe code is very useful for understanding how the hardware works */
/* Use it with various combinations of TT_LEN, RX_LEN */
/* Strongly recommended, disable if the probe fails on your machine */
/* and send me <james@fishsoup.dhs.org> the output of dmesg */
#define USE_PROBE 1
#undef USE_PROBE
/* Trace Transmit ring, interrupts, Receive ring or not ? */
#define PROBE_VERBOSE 1
/* Debug option, examine sent and received raw data */
/* Irdadump is better, but does not see all packets. enable it if you want. */
#undef DUMP_PACKETS
/* MIR mode has not been tested. Some behaviour is different */
/* Seems to work against an Ericsson R520 for me. -Martin */
#define USE_MIR
/* Schedule back to back hardware transmits wherever possible, otherwise */
/* we need an interrupt for every frame, unset if oboe works for a bit and */
/* then hangs */
#define OPTIMIZE_TX
/* Set the number of slots in the rings */
/* If you get rx/tx fifo overflows at high bitrates, you can try increasing */
/* these */
#define RING_SIZE (OBOE_RING_SIZE_RX8 | OBOE_RING_SIZE_TX8)
#define TX_SLOTS 8
#define RX_SLOTS 8
/* Less user servicable parts below here */
/* Test, Transmit and receive buffer sizes, adjust at your peril */
/* remarks: nfs usually needs 1k blocks */
/* remarks: in SIR mode, CRC is received, -> RX_LEN=TX_LEN+2 */
/* remarks: test accepts large blocks. Standard is 0x80 */
/* When TT_LEN > RX_LEN (SIR mode) data is stored in successive slots. */
/* When 3 or more slots are needed for each test packet, */
/* data received in the first slots is overwritten, even */
/* if OBOE_CTL_RX_HW_OWNS is not set, without any error! */
#define TT_LEN 0x80
#define TX_LEN 0xc00
#define RX_LEN 0xc04
/* Real transmitted length (SIR mode) is about 14+(2%*TX_LEN) more */
/* long than user-defined length (see async_wrap_skb) and is less then 4K */
/* Real received length is (max RX_LEN) differs from user-defined */
/* length only b the CRC (2 or 4 bytes) */
#define BUF_SAFETY 0x7a
#define RX_BUF_SZ (RX_LEN)
#define TX_BUF_SZ (TX_LEN+BUF_SAFETY)
/* Logic of the netdev part of this driver */
/* The RX ring is filled with buffers, when a packet arrives */
/* it is DMA'd into the buffer which is marked used and RxDone called */
/* RxDone forms an skb (and checks the CRC if in SIR mode) and ships */
/* the packet off upstairs */
/* The transmitter on the oboe chip can work in one of two modes */
/* for each ring->tx[] the transmitter can either */
/* a) transmit the packet, leave the trasmitter enabled and proceed to */
/* the next ring */
/* OR */
/* b) transmit the packet, switch off the transmitter and issue TxDone */
/* All packets are entered into the ring in mode b), if the ring was */
/* empty the transmitter is started. */
/* If OPTIMIZE_TX is defined then in TxDone if the ring contains */
/* more than one packet, all but the last are set to mode a) [HOWEVER */
/* the hardware may not notice this, this is why we start in mode b) ] */
/* then restart the transmitter */
/* If OPTIMIZE_TX is not defined then we just restart the transmitter */
/* if the ring isn't empty */
/* Speed changes are delayed until the TxRing is empty */
/* mtt is handled by generating packets with bad CRCs, before the data */
/* TODO: */
/* check the mtt works ok */
/* finish the watchdog */
/* No user servicable parts below here */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/rtnetlink.h>
#include <asm/system.h>
#include <asm/io.h>
#include <net/irda/wrapper.h>
#include <net/irda/irda.h>
//#include <net/irda/irmod.h>
//#include <net/irda/irlap_frame.h>
#include <net/irda/irda_device.h>
#include <net/irda/crc.h>
#include "donauboe.h"
#define INB(port) inb_p(port)
#define OUTB(val,port) outb_p(val,port)
#define OUTBP(val,port) outb_p(val,port)
#define PROMPT OUTB(OBOE_PROMPT_BIT,OBOE_PROMPT);
#if PROBE_VERBOSE
#define PROBE_DEBUG(args...) (printk (args))
#else
#define PROBE_DEBUG(args...) ;
#endif
/* Set the DMA to be byte at a time */
#define CONFIG0H_DMA_OFF OBOE_CONFIG0H_RCVANY
#define CONFIG0H_DMA_ON_NORX CONFIG0H_DMA_OFF| OBOE_CONFIG0H_ENDMAC
#define CONFIG0H_DMA_ON CONFIG0H_DMA_ON_NORX | OBOE_CONFIG0H_ENRX
static DEFINE_PCI_DEVICE_TABLE(toshoboe_pci_tbl) = {
{ PCI_VENDOR_ID_TOSHIBA, PCI_DEVICE_ID_FIR701, PCI_ANY_ID, PCI_ANY_ID, },
{ PCI_VENDOR_ID_TOSHIBA, PCI_DEVICE_ID_FIRD01, PCI_ANY_ID, PCI_ANY_ID, },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(pci, toshoboe_pci_tbl);
#define DRIVER_NAME "toshoboe"
static char *driver_name = DRIVER_NAME;
static int max_baud = 4000000;
#ifdef USE_PROBE
static int do_probe = 0;
#endif
/**********************************************************************/
static int
toshoboe_checkfcs (unsigned char *buf, int len)
{
int i;
union
{
__u16 value;
__u8 bytes[2];
}
fcs;
fcs.value = INIT_FCS;
for (i = 0; i < len; ++i)
fcs.value = irda_fcs (fcs.value, *(buf++));
return fcs.value == GOOD_FCS;
}
/***********************************************************************/
/* Generic chip handling code */
#ifdef DUMP_PACKETS
static unsigned char dump[50];
static void
_dumpbufs (unsigned char *data, int len, char tete)
{
int i,j;
char head=tete;
for (i=0;i<len;i+=16) {
for (j=0;j<16 && i+j<len;j++) { sprintf(&dump[3*j],"%02x.",data[i+j]); }
dump [3*j]=0;
IRDA_DEBUG (2, "%c%s\n",head , dump);
head='+';
}
}
#endif
#ifdef USE_PROBE
/* Dump the registers */
static void
toshoboe_dumpregs (struct toshoboe_cb *self)
{
__u32 ringbase;
IRDA_DEBUG (4, "%s()\n", __func__);
ringbase = INB (OBOE_RING_BASE0) << 10;
ringbase |= INB (OBOE_RING_BASE1) << 18;
ringbase |= INB (OBOE_RING_BASE2) << 26;
printk (KERN_ERR DRIVER_NAME ": Register dump:\n");
printk (KERN_ERR "Interrupts: Tx:%d Rx:%d TxUnder:%d RxOver:%d Sip:%d\n",
self->int_tx, self->int_rx, self->int_txunder, self->int_rxover,
self->int_sip);
printk (KERN_ERR "RX %02x TX %02x RingBase %08x\n",
INB (OBOE_RXSLOT), INB (OBOE_TXSLOT), ringbase);
printk (KERN_ERR "RING_SIZE %02x IER %02x ISR %02x\n",
INB (OBOE_RING_SIZE), INB (OBOE_IER), INB (OBOE_ISR));
printk (KERN_ERR "CONFIG1 %02x STATUS %02x\n",
INB (OBOE_CONFIG1), INB (OBOE_STATUS));
printk (KERN_ERR "CONFIG0 %02x%02x ENABLE %02x%02x\n",
INB (OBOE_CONFIG0H), INB (OBOE_CONFIG0L),
INB (OBOE_ENABLEH), INB (OBOE_ENABLEL));
printk (KERN_ERR "NEW_PCONFIG %02x%02x CURR_PCONFIG %02x%02x\n",
INB (OBOE_NEW_PCONFIGH), INB (OBOE_NEW_PCONFIGL),
INB (OBOE_CURR_PCONFIGH), INB (OBOE_CURR_PCONFIGL));
printk (KERN_ERR "MAXLEN %02x%02x RXCOUNT %02x%02x\n",
INB (OBOE_MAXLENH), INB (OBOE_MAXLENL),
INB (OBOE_RXCOUNTL), INB (OBOE_RXCOUNTH));
if (self->ring)
{
int i;
ringbase = virt_to_bus (self->ring);
printk (KERN_ERR "Ring at %08x:\n", ringbase);
printk (KERN_ERR "RX:");
for (i = 0; i < RX_SLOTS; ++i)
printk (" (%d,%02x)",self->ring->rx[i].len,self->ring->rx[i].control);
printk ("\n");
printk (KERN_ERR "TX:");
for (i = 0; i < RX_SLOTS; ++i)
printk (" (%d,%02x)",self->ring->tx[i].len,self->ring->tx[i].control);
printk ("\n");
}
}
#endif
/*Don't let the chip look at memory */
static void
toshoboe_disablebm (struct toshoboe_cb *self)
{
__u8 command;
IRDA_DEBUG (4, "%s()\n", __func__);
pci_read_config_byte (self->pdev, PCI_COMMAND, &command);
command &= ~PCI_COMMAND_MASTER;
pci_write_config_byte (self->pdev, PCI_COMMAND, command);
}
/* Shutdown the chip and point the taskfile reg somewhere else */
static void
toshoboe_stopchip (struct toshoboe_cb *self)
{
IRDA_DEBUG (4, "%s()\n", __func__);
/*Disable interrupts */
OUTB (0x0, OBOE_IER);
/*Disable DMA, Disable Rx, Disable Tx */
OUTB (CONFIG0H_DMA_OFF, OBOE_CONFIG0H);
/*Disable SIR MIR FIR, Tx and Rx */
OUTB (0x00, OBOE_ENABLEH);
/*Point the ring somewhere safe */
OUTB (0x3f, OBOE_RING_BASE2);
OUTB (0xff, OBOE_RING_BASE1);
OUTB (0xff, OBOE_RING_BASE0);
OUTB (RX_LEN >> 8, OBOE_MAXLENH);
OUTB (RX_LEN & 0xff, OBOE_MAXLENL);
/*Acknoledge any pending interrupts */
OUTB (0xff, OBOE_ISR);
/*Why */
OUTB (OBOE_ENABLEH_PHYANDCLOCK, OBOE_ENABLEH);
/*switch it off */
OUTB (OBOE_CONFIG1_OFF, OBOE_CONFIG1);
toshoboe_disablebm (self);
}
/* Transmitter initialization */
static void
toshoboe_start_DMA (struct toshoboe_cb *self, int opts)
{
OUTB (0x0, OBOE_ENABLEH);
OUTB (CONFIG0H_DMA_ON | opts, OBOE_CONFIG0H);
OUTB (OBOE_ENABLEH_PHYANDCLOCK, OBOE_ENABLEH);
PROMPT;
}
/*Set the baud rate */
static void
toshoboe_setbaud (struct toshoboe_cb *self)
{
__u16 pconfig = 0;
__u8 config0l = 0;
IRDA_DEBUG (2, "%s(%d/%d)\n", __func__, self->speed, self->io.speed);
switch (self->speed)
{
case 2400:
case 4800:
case 9600:
case 19200:
case 38400:
case 57600:
case 115200:
#ifdef USE_MIR
case 1152000:
#endif
case 4000000:
break;
default:
printk (KERN_ERR DRIVER_NAME ": switch to unsupported baudrate %d\n",
self->speed);
return;
}
switch (self->speed)
{
/* For SIR the preamble is done by adding XBOFs */
/* to the packet */
/* set to filtered SIR mode, filter looks for BOF and EOF */
case 2400:
pconfig |= 47 << OBOE_PCONFIG_BAUDSHIFT;
pconfig |= 25 << OBOE_PCONFIG_WIDTHSHIFT;
break;
case 4800:
pconfig |= 23 << OBOE_PCONFIG_BAUDSHIFT;
pconfig |= 25 << OBOE_PCONFIG_WIDTHSHIFT;
break;
case 9600:
pconfig |= 11 << OBOE_PCONFIG_BAUDSHIFT;
pconfig |= 25 << OBOE_PCONFIG_WIDTHSHIFT;
break;
case 19200:
pconfig |= 5 << OBOE_PCONFIG_BAUDSHIFT;
pconfig |= 25 << OBOE_PCONFIG_WIDTHSHIFT;
break;
case 38400:
pconfig |= 2 << OBOE_PCONFIG_BAUDSHIFT;
pconfig |= 25 << OBOE_PCONFIG_WIDTHSHIFT;
break;
case 57600:
pconfig |= 1 << OBOE_PCONFIG_BAUDSHIFT;
pconfig |= 25 << OBOE_PCONFIG_WIDTHSHIFT;
break;
case 115200:
pconfig |= 0 << OBOE_PCONFIG_BAUDSHIFT;
pconfig |= 25 << OBOE_PCONFIG_WIDTHSHIFT;
break;
default:
/*Set to packet based reception */
OUTB (RX_LEN >> 8, OBOE_MAXLENH);
OUTB (RX_LEN & 0xff, OBOE_MAXLENL);
break;
}
switch (self->speed)
{
case 2400:
case 4800:
case 9600:
case 19200:
case 38400:
case 57600:
case 115200:
config0l = OBOE_CONFIG0L_ENSIR;
if (self->async)
{
/*Set to character based reception */
/*System will lock if MAXLEN=0 */
/*so have to be careful */
OUTB (0x01, OBOE_MAXLENH);
OUTB (0x01, OBOE_MAXLENL);
OUTB (0x00, OBOE_MAXLENH);
}
else
{
/*Set to packet based reception */
config0l |= OBOE_CONFIG0L_ENSIRF;
OUTB (RX_LEN >> 8, OBOE_MAXLENH);
OUTB (RX_LEN & 0xff, OBOE_MAXLENL);
}
break;
#ifdef USE_MIR
/* MIR mode */
/* Set for 16 bit CRC and enable MIR */
/* Preamble now handled by the chip */
case 1152000:
pconfig |= 0 << OBOE_PCONFIG_BAUDSHIFT;
pconfig |= 8 << OBOE_PCONFIG_WIDTHSHIFT;
pconfig |= 1 << OBOE_PCONFIG_PREAMBLESHIFT;
config0l = OBOE_CONFIG0L_CRC16 | OBOE_CONFIG0L_ENMIR;
break;
#endif
/* FIR mode */
/* Set for 32 bit CRC and enable FIR */
/* Preamble handled by the chip */
case 4000000:
pconfig |= 0 << OBOE_PCONFIG_BAUDSHIFT;
/* Documentation says 14, but toshiba use 15 in their drivers */
pconfig |= 15 << OBOE_PCONFIG_PREAMBLESHIFT;
config0l = OBOE_CONFIG0L_ENFIR;
break;
}
/* Copy into new PHY config buffer */
OUTBP (pconfig >> 8, OBOE_NEW_PCONFIGH);
OUTB (pconfig & 0xff, OBOE_NEW_PCONFIGL);
OUTB (config0l, OBOE_CONFIG0L);
/* Now make OBOE copy from new PHY to current PHY */
OUTB (0x0, OBOE_ENABLEH);
OUTB (OBOE_ENABLEH_PHYANDCLOCK, OBOE_ENABLEH);
PROMPT;
/* speed change executed */
self->new_speed = 0;
self->io.speed = self->speed;
}
/*Let the chip look at memory */
static void
toshoboe_enablebm (struct toshoboe_cb *self)
{
IRDA_DEBUG (4, "%s()\n", __func__);
pci_set_master (self->pdev);
}
/*setup the ring */
static void
toshoboe_initring (struct toshoboe_cb *self)
{
int i;
IRDA_DEBUG (4, "%s()\n", __func__);
for (i = 0; i < TX_SLOTS; ++i)
{
self->ring->tx[i].len = 0;
self->ring->tx[i].control = 0x00;
self->ring->tx[i].address = virt_to_bus (self->tx_bufs[i]);
}
for (i = 0; i < RX_SLOTS; ++i)
{
self->ring->rx[i].len = RX_LEN;
self->ring->rx[i].len = 0;
self->ring->rx[i].address = virt_to_bus (self->rx_bufs[i]);
self->ring->rx[i].control = OBOE_CTL_RX_HW_OWNS;
}
}
static void
toshoboe_resetptrs (struct toshoboe_cb *self)
{
/* Can reset pointers by twidling DMA */
OUTB (0x0, OBOE_ENABLEH);
OUTBP (CONFIG0H_DMA_OFF, OBOE_CONFIG0H);
OUTB (OBOE_ENABLEH_PHYANDCLOCK, OBOE_ENABLEH);
self->rxs = inb_p (OBOE_RXSLOT) & OBOE_SLOT_MASK;
self->txs = inb_p (OBOE_TXSLOT) & OBOE_SLOT_MASK;
}
/* Called in locked state */
static void
toshoboe_initptrs (struct toshoboe_cb *self)
{
/* spin_lock_irqsave(self->spinlock, flags); */
/* save_flags (flags); */
/* Can reset pointers by twidling DMA */
toshoboe_resetptrs (self);
OUTB (0x0, OBOE_ENABLEH);
OUTB (CONFIG0H_DMA_ON, OBOE_CONFIG0H);
OUTB (OBOE_ENABLEH_PHYANDCLOCK, OBOE_ENABLEH);
self->txpending = 0;
/* spin_unlock_irqrestore(self->spinlock, flags); */
/* restore_flags (flags); */
}
/* Wake the chip up and get it looking at the rings */
/* Called in locked state */
static void
toshoboe_startchip (struct toshoboe_cb *self)
{
__u32 physaddr;
IRDA_DEBUG (4, "%s()\n", __func__);
toshoboe_initring (self);
toshoboe_enablebm (self);
OUTBP (OBOE_CONFIG1_RESET, OBOE_CONFIG1);
OUTBP (OBOE_CONFIG1_ON, OBOE_CONFIG1);
/* Stop the clocks */
OUTB (0, OBOE_ENABLEH);
/*Set size of rings */
OUTB (RING_SIZE, OBOE_RING_SIZE);
/*Acknoledge any pending interrupts */
OUTB (0xff, OBOE_ISR);
/*Enable ints */
OUTB (OBOE_INT_TXDONE | OBOE_INT_RXDONE |
OBOE_INT_TXUNDER | OBOE_INT_RXOVER | OBOE_INT_SIP , OBOE_IER);
/*Acknoledge any pending interrupts */
OUTB (0xff, OBOE_ISR);
/*Set the maximum packet length to 0xfff (4095) */
OUTB (RX_LEN >> 8, OBOE_MAXLENH);
OUTB (RX_LEN & 0xff, OBOE_MAXLENL);
/*Shutdown DMA */
OUTB (CONFIG0H_DMA_OFF, OBOE_CONFIG0H);
/*Find out where the rings live */
physaddr = virt_to_bus (self->ring);
IRDA_ASSERT ((physaddr & 0x3ff) == 0,
printk (KERN_ERR DRIVER_NAME "ring not correctly aligned\n");
return;);
OUTB ((physaddr >> 10) & 0xff, OBOE_RING_BASE0);
OUTB ((physaddr >> 18) & 0xff, OBOE_RING_BASE1);
OUTB ((physaddr >> 26) & 0x3f, OBOE_RING_BASE2);
/*Enable DMA controller in byte mode and RX */
OUTB (CONFIG0H_DMA_ON, OBOE_CONFIG0H);
/* Start up the clocks */
OUTB (OBOE_ENABLEH_PHYANDCLOCK, OBOE_ENABLEH);
/*set to sensible speed */
self->speed = 9600;
toshoboe_setbaud (self);
toshoboe_initptrs (self);
}
static void
toshoboe_isntstuck (struct toshoboe_cb *self)
{
}
static void
toshoboe_checkstuck (struct toshoboe_cb *self)
{
unsigned long flags;
if (0)
{
spin_lock_irqsave(&self->spinlock, flags);
/* This will reset the chip completely */
printk (KERN_ERR DRIVER_NAME ": Resetting chip\n");
toshoboe_stopchip (self);
toshoboe_startchip (self);
spin_unlock_irqrestore(&self->spinlock, flags);
}
}
/*Generate packet of about mtt us long */
static int
toshoboe_makemttpacket (struct toshoboe_cb *self, void *buf, int mtt)
{
int xbofs;
xbofs = ((int) (mtt/100)) * (int) (self->speed);
xbofs=xbofs/80000; /*Eight bits per byte, and mtt is in us*/
xbofs++;
IRDA_DEBUG (2, DRIVER_NAME
": generated mtt of %d bytes for %d us at %d baud\n"
, xbofs,mtt,self->speed);
if (xbofs > TX_LEN)
{
printk (KERN_ERR DRIVER_NAME ": wanted %d bytes MTT but TX_LEN is %d\n",
xbofs, TX_LEN);
xbofs = TX_LEN;
}
/*xbofs will do for SIR, MIR and FIR,SIR mode doesn't generate a checksum anyway */
memset (buf, XBOF, xbofs);
return xbofs;
}
#ifdef USE_PROBE
/***********************************************************************/
/* Probe code */
static void
toshoboe_dumptx (struct toshoboe_cb *self)
{
int i;
PROBE_DEBUG(KERN_WARNING "TX:");
for (i = 0; i < RX_SLOTS; ++i)
PROBE_DEBUG(" (%d,%02x)",self->ring->tx[i].len,self->ring->tx[i].control);
PROBE_DEBUG(" [%d]\n",self->speed);
}
static void
toshoboe_dumprx (struct toshoboe_cb *self, int score)
{
int i;
PROBE_DEBUG(" %d\nRX:",score);
for (i = 0; i < RX_SLOTS; ++i)
PROBE_DEBUG(" (%d,%02x)",self->ring->rx[i].len,self->ring->rx[i].control);
PROBE_DEBUG("\n");
}
static inline int
stuff_byte (__u8 byte, __u8 * buf)
{
switch (byte)
{
case BOF: /* FALLTHROUGH */
case EOF: /* FALLTHROUGH */
case CE:
/* Insert transparently coded */
buf[0] = CE; /* Send link escape */
buf[1] = byte ^ IRDA_TRANS; /* Complement bit 5 */
return 2;
/* break; */
default:
/* Non-special value, no transparency required */
buf[0] = byte;
return 1;
/* break; */
}
}
static irqreturn_t
toshoboe_probeinterrupt (int irq, void *dev_id)
{
struct toshoboe_cb *self = dev_id;
__u8 irqstat;
irqstat = INB (OBOE_ISR);
/* was it us */
if (!(irqstat & OBOE_INT_MASK))
return IRQ_NONE;
/* Ack all the interrupts */
OUTB (irqstat, OBOE_ISR);
if (irqstat & OBOE_INT_TXDONE)
{
int txp;
self->int_tx++;
PROBE_DEBUG("T");
txp = INB (OBOE_TXSLOT) & OBOE_SLOT_MASK;
if (self->ring->tx[txp].control & OBOE_CTL_TX_HW_OWNS)
{
self->int_tx+=100;
PROBE_DEBUG("S");
toshoboe_start_DMA(self, OBOE_CONFIG0H_ENTX | OBOE_CONFIG0H_LOOP);
}
}
if (irqstat & OBOE_INT_RXDONE) {
self->int_rx++;
PROBE_DEBUG("R"); }
if (irqstat & OBOE_INT_TXUNDER) {
self->int_txunder++;
PROBE_DEBUG("U"); }
if (irqstat & OBOE_INT_RXOVER) {
self->int_rxover++;
PROBE_DEBUG("O"); }
if (irqstat & OBOE_INT_SIP) {
self->int_sip++;
PROBE_DEBUG("I"); }
return IRQ_HANDLED;
}
static int
toshoboe_maketestpacket (unsigned char *buf, int badcrc, int fir)
{
int i;
int len = 0;
union
{
__u16 value;
__u8 bytes[2];
}
fcs;
if (fir)
{
memset (buf, 0, TT_LEN);
return TT_LEN;
}
fcs.value = INIT_FCS;
memset (buf, XBOF, 10);
len += 10;
buf[len++] = BOF;
for (i = 0; i < TT_LEN; ++i)
{
len += stuff_byte (i, buf + len);
fcs.value = irda_fcs (fcs.value, i);
}
len += stuff_byte (fcs.bytes[0] ^ badcrc, buf + len);
len += stuff_byte (fcs.bytes[1] ^ badcrc, buf + len);
buf[len++] = EOF;
len++;
return len;
}
static int
toshoboe_probefail (struct toshoboe_cb *self, char *msg)
{
printk (KERN_ERR DRIVER_NAME "probe(%d) failed %s\n",self-> speed, msg);
toshoboe_dumpregs (self);
toshoboe_stopchip (self);
free_irq (self->io.irq, (void *) self);
return 0;
}
static int
toshoboe_numvalidrcvs (struct toshoboe_cb *self)
{
int i, ret = 0;
for (i = 0; i < RX_SLOTS; ++i)
if ((self->ring->rx[i].control & 0xe0) == 0)
ret++;
return ret;
}
static int
toshoboe_numrcvs (struct toshoboe_cb *self)
{
int i, ret = 0;
for (i = 0; i < RX_SLOTS; ++i)
if (!(self->ring->rx[i].control & OBOE_CTL_RX_HW_OWNS))
ret++;
return ret;
}
static int
toshoboe_probe (struct toshoboe_cb *self)
{
int i, j, n;
#ifdef USE_MIR
static const int bauds[] = { 9600, 115200, 4000000, 1152000 };
#else
static const int bauds[] = { 9600, 115200, 4000000 };
#endif
unsigned long flags;
IRDA_DEBUG (4, "%s()\n", __func__);
if (request_irq (self->io.irq, toshoboe_probeinterrupt,
self->io.irqflags, "toshoboe", (void *) self))
{
printk (KERN_ERR DRIVER_NAME ": probe failed to allocate irq %d\n",
self->io.irq);
return 0;
}
/* test 1: SIR filter and back to back */
for (j = 0; j < ARRAY_SIZE(bauds); ++j)
{
int fir = (j > 1);
toshoboe_stopchip (self);
spin_lock_irqsave(&self->spinlock, flags);
/*Address is already setup */
toshoboe_startchip (self);
self->int_rx = self->int_tx = 0;
self->speed = bauds[j];
toshoboe_setbaud (self);
toshoboe_initptrs (self);
spin_unlock_irqrestore(&self->spinlock, flags);
self->ring->tx[self->txs].control =
/* (FIR only) OBOE_CTL_TX_SIP needed for switching to next slot */
/* MIR: all received data is stored in one slot */
(fir) ? OBOE_CTL_TX_HW_OWNS | OBOE_CTL_TX_RTCENTX
: OBOE_CTL_TX_HW_OWNS ;
self->ring->tx[self->txs].len =
toshoboe_maketestpacket (self->tx_bufs[self->txs], 0, fir);
self->txs++;
self->txs %= TX_SLOTS;
self->ring->tx[self->txs].control =
(fir) ? OBOE_CTL_TX_HW_OWNS | OBOE_CTL_TX_SIP
: OBOE_CTL_TX_HW_OWNS | OBOE_CTL_TX_RTCENTX ;
self->ring->tx[self->txs].len =
toshoboe_maketestpacket (self->tx_bufs[self->txs], 0, fir);
self->txs++;
self->txs %= TX_SLOTS;
self->ring->tx[self->txs].control =
(fir) ? OBOE_CTL_TX_HW_OWNS | OBOE_CTL_TX_RTCENTX
: OBOE_CTL_TX_HW_OWNS ;
self->ring->tx[self->txs].len =
toshoboe_maketestpacket (self->tx_bufs[self->txs], 0, fir);
self->txs++;
self->txs %= TX_SLOTS;
self->ring->tx[self->txs].control =
(fir) ? OBOE_CTL_TX_HW_OWNS | OBOE_CTL_TX_RTCENTX
| OBOE_CTL_TX_SIP | OBOE_CTL_TX_BAD_CRC
: OBOE_CTL_TX_HW_OWNS | OBOE_CTL_TX_RTCENTX ;
self->ring->tx[self->txs].len =
toshoboe_maketestpacket (self->tx_bufs[self->txs], 0, fir);
self->txs++;
self->txs %= TX_SLOTS;
toshoboe_dumptx (self);
/* Turn on TX and RX and loopback */
toshoboe_start_DMA(self, OBOE_CONFIG0H_ENTX | OBOE_CONFIG0H_LOOP);
i = 0;
n = fir ? 1 : 4;
while (toshoboe_numvalidrcvs (self) != n)
{
if (i > 4800)
return toshoboe_probefail (self, "filter test");
udelay ((9600*(TT_LEN+16))/self->speed);
i++;
}
n = fir ? 203 : 102;
while ((toshoboe_numrcvs(self) != self->int_rx) || (self->int_tx != n))
{
if (i > 4800)
return toshoboe_probefail (self, "interrupt test");
udelay ((9600*(TT_LEN+16))/self->speed);
i++;
}
toshoboe_dumprx (self,i);
}
/* test 2: SIR in char at a time */
toshoboe_stopchip (self);
self->int_rx = self->int_tx = 0;
spin_lock_irqsave(&self->spinlock, flags);
toshoboe_startchip (self);
spin_unlock_irqrestore(&self->spinlock, flags);
self->async = 1;
self->speed = 115200;
toshoboe_setbaud (self);
self->ring->tx[self->txs].control =
OBOE_CTL_TX_RTCENTX | OBOE_CTL_TX_HW_OWNS;
self->ring->tx[self->txs].len = 4;
((unsigned char *) self->tx_bufs[self->txs])[0] = 'f';
((unsigned char *) self->tx_bufs[self->txs])[1] = 'i';
((unsigned char *) self->tx_bufs[self->txs])[2] = 's';
((unsigned char *) self->tx_bufs[self->txs])[3] = 'h';
toshoboe_dumptx (self);
toshoboe_start_DMA(self, OBOE_CONFIG0H_ENTX | OBOE_CONFIG0H_LOOP);
i = 0;
while (toshoboe_numvalidrcvs (self) != 4)
{
if (i > 100)
return toshoboe_probefail (self, "Async test");
udelay (100);
i++;
}
while ((toshoboe_numrcvs (self) != self->int_rx) || (self->int_tx != 1))
{
if (i > 100)
return toshoboe_probefail (self, "Async interrupt test");
udelay (100);
i++;
}
toshoboe_dumprx (self,i);
self->async = 0;
self->speed = 9600;
toshoboe_setbaud (self);
toshoboe_stopchip (self);
free_irq (self->io.irq, (void *) self);
printk (KERN_WARNING DRIVER_NAME ": Self test passed ok\n");
return 1;
}
#endif
/******************************************************************/
/* Netdev style code */
/* Transmit something */
static netdev_tx_t
toshoboe_hard_xmit (struct sk_buff *skb, struct net_device *dev)
{
struct toshoboe_cb *self;
__s32 speed;
int mtt, len, ctl;
unsigned long flags;
struct irda_skb_cb *cb = (struct irda_skb_cb *) skb->cb;
self = netdev_priv(dev);
IRDA_ASSERT (self != NULL, return NETDEV_TX_OK; );
IRDA_DEBUG (1, "%s.tx:%x(%x)%x\n", __func__
,skb->len,self->txpending,INB (OBOE_ENABLEH));
if (!cb->magic) {
IRDA_DEBUG (2, "%s.Not IrLAP:%x\n", __func__, cb->magic);
#ifdef DUMP_PACKETS
_dumpbufs(skb->data,skb->len,'>');
#endif
}
/* change speed pending, wait for its execution */
if (self->new_speed)
return NETDEV_TX_BUSY;
/* device stopped (apm) wait for restart */
if (self->stopped)
return NETDEV_TX_BUSY;
toshoboe_checkstuck (self);
/* Check if we need to change the speed */
/* But not now. Wait after transmission if mtt not required */
speed=irda_get_next_speed(skb);
if ((speed != self->io.speed) && (speed != -1))
{
spin_lock_irqsave(&self->spinlock, flags);
if (self->txpending || skb->len)
{
self->new_speed = speed;
IRDA_DEBUG (1, "%s: Queued TxDone scheduled speed change %d\n" ,
__func__, speed);
/* if no data, that's all! */
if (!skb->len)
{
spin_unlock_irqrestore(&self->spinlock, flags);
dev_kfree_skb (skb);
return NETDEV_TX_OK;
}
/* True packet, go on, but */
/* do not accept anything before change speed execution */
netif_stop_queue(dev);
/* ready to process TxDone interrupt */
spin_unlock_irqrestore(&self->spinlock, flags);
}
else
{
/* idle and no data, change speed now */
self->speed = speed;
toshoboe_setbaud (self);
spin_unlock_irqrestore(&self->spinlock, flags);
dev_kfree_skb (skb);
return NETDEV_TX_OK;
}
}
if ((mtt = irda_get_mtt(skb)))
{
/* This is fair since the queue should be empty anyway */
spin_lock_irqsave(&self->spinlock, flags);
if (self->txpending)
{
spin_unlock_irqrestore(&self->spinlock, flags);
return NETDEV_TX_BUSY;
}
/* If in SIR mode we need to generate a string of XBOFs */
/* In MIR and FIR we need to generate a string of data */
/* which we will add a wrong checksum to */
mtt = toshoboe_makemttpacket (self, self->tx_bufs[self->txs], mtt);
IRDA_DEBUG (1, "%s.mtt:%x(%x)%d\n", __func__
,skb->len,mtt,self->txpending);
if (mtt)
{
self->ring->tx[self->txs].len = mtt & 0xfff;
ctl = OBOE_CTL_TX_HW_OWNS | OBOE_CTL_TX_RTCENTX;
if (INB (OBOE_ENABLEH) & OBOE_ENABLEH_FIRON)
{
ctl |= OBOE_CTL_TX_BAD_CRC | OBOE_CTL_TX_SIP ;
}
#ifdef USE_MIR
else if (INB (OBOE_ENABLEH) & OBOE_ENABLEH_MIRON)
{
ctl |= OBOE_CTL_TX_BAD_CRC;
}
#endif
self->ring->tx[self->txs].control = ctl;
OUTB (0x0, OBOE_ENABLEH);
/* It is only a timer. Do not send mtt packet outside! */
toshoboe_start_DMA(self, OBOE_CONFIG0H_ENTX | OBOE_CONFIG0H_LOOP);
self->txpending++;
self->txs++;
self->txs %= TX_SLOTS;
}
else
{
printk(KERN_ERR DRIVER_NAME ": problem with mtt packet - ignored\n");
}
spin_unlock_irqrestore(&self->spinlock, flags);
}
#ifdef DUMP_PACKETS
dumpbufs(skb->data,skb->len,'>');
#endif
spin_lock_irqsave(&self->spinlock, flags);
if (self->ring->tx[self->txs].control & OBOE_CTL_TX_HW_OWNS)
{
IRDA_DEBUG (0, "%s.ful:%x(%x)%x\n", __func__
,skb->len, self->ring->tx[self->txs].control, self->txpending);
toshoboe_start_DMA(self, OBOE_CONFIG0H_ENTX);
spin_unlock_irqrestore(&self->spinlock, flags);
return NETDEV_TX_BUSY;
}
if (INB (OBOE_ENABLEH) & OBOE_ENABLEH_SIRON)
{
len = async_wrap_skb (skb, self->tx_bufs[self->txs], TX_BUF_SZ);
}
else
{
len = skb->len;
skb_copy_from_linear_data(skb, self->tx_bufs[self->txs], len);
}
self->ring->tx[self->txs].len = len & 0x0fff;
/*Sometimes the HW doesn't see us assert RTCENTX in the interrupt code */
/*later this plays safe, we garuntee the last packet to be transmitted */
/*has RTCENTX set */
ctl = OBOE_CTL_TX_HW_OWNS | OBOE_CTL_TX_RTCENTX;
if (INB (OBOE_ENABLEH) & OBOE_ENABLEH_FIRON)
{
ctl |= OBOE_CTL_TX_SIP ;
}
self->ring->tx[self->txs].control = ctl;
/* If transmitter is idle start in one-shot mode */
if (!self->txpending)
toshoboe_start_DMA(self, OBOE_CONFIG0H_ENTX);
self->txpending++;
self->txs++;
self->txs %= TX_SLOTS;
spin_unlock_irqrestore(&self->spinlock, flags);
dev_kfree_skb (skb);
return NETDEV_TX_OK;
}
/*interrupt handler */
static irqreturn_t
toshoboe_interrupt (int irq, void *dev_id)
{
struct toshoboe_cb *self = dev_id;
__u8 irqstat;
struct sk_buff *skb = NULL;
irqstat = INB (OBOE_ISR);
/* was it us */
if (!(irqstat & OBOE_INT_MASK))
return IRQ_NONE;
/* Ack all the interrupts */
OUTB (irqstat, OBOE_ISR);
toshoboe_isntstuck (self);
/* Txdone */
if (irqstat & OBOE_INT_TXDONE)
{
int txp, txpc;
int i;
txp = self->txpending;
self->txpending = 0;
for (i = 0; i < TX_SLOTS; ++i)
{
if (self->ring->tx[i].control & OBOE_CTL_TX_HW_OWNS)
self->txpending++;
}
IRDA_DEBUG (1, "%s.txd(%x)%x/%x\n", __func__
,irqstat,txp,self->txpending);
txp = INB (OBOE_TXSLOT) & OBOE_SLOT_MASK;
/* Got anything queued ? start it together */
if (self->ring->tx[txp].control & OBOE_CTL_TX_HW_OWNS)
{
txpc = txp;
#ifdef OPTIMIZE_TX
while (self->ring->tx[txpc].control & OBOE_CTL_TX_HW_OWNS)
{
txp = txpc;
txpc++;
txpc %= TX_SLOTS;
self->netdev->stats.tx_packets++;
if (self->ring->tx[txpc].control & OBOE_CTL_TX_HW_OWNS)
self->ring->tx[txp].control &= ~OBOE_CTL_TX_RTCENTX;
}
self->netdev->stats.tx_packets--;
#else
self->netdev->stats.tx_packets++;
#endif
toshoboe_start_DMA(self, OBOE_CONFIG0H_ENTX);
}
if ((!self->txpending) && (self->new_speed))
{
self->speed = self->new_speed;
IRDA_DEBUG (1, "%s: Executed TxDone scheduled speed change %d\n",
__func__, self->speed);
toshoboe_setbaud (self);
}
/* Tell network layer that we want more frames */
if (!self->new_speed)
netif_wake_queue(self->netdev);
}
if (irqstat & OBOE_INT_RXDONE)
{
while (!(self->ring->rx[self->rxs].control & OBOE_CTL_RX_HW_OWNS))
{
int len = self->ring->rx[self->rxs].len;
skb = NULL;
IRDA_DEBUG (3, "%s.rcv:%x(%x)\n", __func__
,len,self->ring->rx[self->rxs].control);
#ifdef DUMP_PACKETS
dumpbufs(self->rx_bufs[self->rxs],len,'<');
#endif
if (self->ring->rx[self->rxs].control == 0)
{
__u8 enable = INB (OBOE_ENABLEH);
/* In SIR mode we need to check the CRC as this */
/* hasn't been done by the hardware */
if (enable & OBOE_ENABLEH_SIRON)
{
if (!toshoboe_checkfcs (self->rx_bufs[self->rxs], len))
len = 0;
/*Trim off the CRC */
if (len > 1)
len -= 2;
else
len = 0;
IRDA_DEBUG (1, "%s.SIR:%x(%x)\n", __func__, len,enable);
}
#ifdef USE_MIR
else if (enable & OBOE_ENABLEH_MIRON)
{
if (len > 1)
len -= 2;
else
len = 0;
IRDA_DEBUG (2, "%s.MIR:%x(%x)\n", __func__, len,enable);
}
#endif
else if (enable & OBOE_ENABLEH_FIRON)
{
if (len > 3)
len -= 4; /*FIXME: check this */
else
len = 0;
IRDA_DEBUG (1, "%s.FIR:%x(%x)\n", __func__, len,enable);
}
else
IRDA_DEBUG (0, "%s.?IR:%x(%x)\n", __func__, len,enable);
if (len)
{
skb = dev_alloc_skb (len + 1);
if (skb)
{
skb_reserve (skb, 1);
skb_put (skb, len);
skb_copy_to_linear_data(skb, self->rx_bufs[self->rxs],
len);
self->netdev->stats.rx_packets++;
skb->dev = self->netdev;
skb_reset_mac_header(skb);
skb->protocol = htons (ETH_P_IRDA);
}
else
{
printk (KERN_INFO
"%s(), memory squeeze, dropping frame.\n",
__func__);
}
}
}
else
{
/* TODO: =========================================== */
/* if OBOE_CTL_RX_LENGTH, our buffers are too small */
/* (MIR or FIR) data is lost. */
/* (SIR) data is splitted in several slots. */
/* we have to join all the received buffers received */
/*in a large buffer before checking CRC. */
IRDA_DEBUG (0, "%s.err:%x(%x)\n", __func__
,len,self->ring->rx[self->rxs].control);
}
self->ring->rx[self->rxs].len = 0x0;
self->ring->rx[self->rxs].control = OBOE_CTL_RX_HW_OWNS;
self->rxs++;
self->rxs %= RX_SLOTS;
if (skb)
netif_rx (skb);
}
}
if (irqstat & OBOE_INT_TXUNDER)
{
printk (KERN_WARNING DRIVER_NAME ": tx fifo underflow\n");
}
if (irqstat & OBOE_INT_RXOVER)
{
printk (KERN_WARNING DRIVER_NAME ": rx fifo overflow\n");
}
/* This must be useful for something... */
if (irqstat & OBOE_INT_SIP)
{
self->int_sip++;
IRDA_DEBUG (1, "%s.sip:%x(%x)%x\n", __func__
,self->int_sip,irqstat,self->txpending);
}
return IRQ_HANDLED;
}
static int
toshoboe_net_open (struct net_device *dev)
{
struct toshoboe_cb *self;
unsigned long flags;
int rc;
IRDA_DEBUG (4, "%s()\n", __func__);
self = netdev_priv(dev);
if (self->async)
return -EBUSY;
if (self->stopped)
return 0;
rc = request_irq (self->io.irq, toshoboe_interrupt,
IRQF_SHARED | IRQF_DISABLED, dev->name, self);
if (rc)
return rc;
spin_lock_irqsave(&self->spinlock, flags);
toshoboe_startchip (self);
spin_unlock_irqrestore(&self->spinlock, flags);
/* Ready to play! */
netif_start_queue(dev);
/*
* Open new IrLAP layer instance, now that everything should be
* initialized properly
*/
self->irlap = irlap_open (dev, &self->qos, driver_name);
self->irdad = 1;
return 0;
}
static int
toshoboe_net_close (struct net_device *dev)
{
struct toshoboe_cb *self;
IRDA_DEBUG (4, "%s()\n", __func__);
IRDA_ASSERT (dev != NULL, return -1; );
self = netdev_priv(dev);
/* Stop device */
netif_stop_queue(dev);
/* Stop and remove instance of IrLAP */
if (self->irlap)
irlap_close (self->irlap);
self->irlap = NULL;
self->irdad = 0;
free_irq (self->io.irq, (void *) self);
if (!self->stopped)
{
toshoboe_stopchip (self);
}
return 0;
}
/*
* Function toshoboe_net_ioctl (dev, rq, cmd)
*
* Process IOCTL commands for this device
*
*/
static int
toshoboe_net_ioctl (struct net_device *dev, struct ifreq *rq, int cmd)
{
struct if_irda_req *irq = (struct if_irda_req *) rq;
struct toshoboe_cb *self;
unsigned long flags;
int ret = 0;
IRDA_ASSERT (dev != NULL, return -1; );
self = netdev_priv(dev);
IRDA_ASSERT (self != NULL, return -1; );
IRDA_DEBUG (5, "%s(), %s, (cmd=0x%X)\n", __func__, dev->name, cmd);
/* Disable interrupts & save flags */
spin_lock_irqsave(&self->spinlock, flags);
switch (cmd)
{
case SIOCSBANDWIDTH: /* Set bandwidth */
/* This function will also be used by IrLAP to change the
* speed, so we still must allow for speed change within
* interrupt context.
*/
IRDA_DEBUG (1, "%s(BANDWIDTH), %s, (%X/%ld\n", __func__
,dev->name, INB (OBOE_STATUS), irq->ifr_baudrate );
if (!in_interrupt () && !capable (CAP_NET_ADMIN)) {
ret = -EPERM;
goto out;
}
/* self->speed=irq->ifr_baudrate; */
/* toshoboe_setbaud(self); */
/* Just change speed once - inserted by Paul Bristow */
self->new_speed = irq->ifr_baudrate;
break;
case SIOCSMEDIABUSY: /* Set media busy */
IRDA_DEBUG (1, "%s(MEDIABUSY), %s, (%X/%x)\n", __func__
,dev->name, INB (OBOE_STATUS), capable (CAP_NET_ADMIN) );
if (!capable (CAP_NET_ADMIN)) {
ret = -EPERM;
goto out;
}
irda_device_set_media_busy (self->netdev, TRUE);
break;
case SIOCGRECEIVING: /* Check if we are receiving right now */
irq->ifr_receiving = (INB (OBOE_STATUS) & OBOE_STATUS_RXBUSY) ? 1 : 0;
IRDA_DEBUG (3, "%s(RECEIVING), %s, (%X/%x)\n", __func__
,dev->name, INB (OBOE_STATUS), irq->ifr_receiving );
break;
default:
IRDA_DEBUG (1, "%s(?), %s, (cmd=0x%X)\n", __func__, dev->name, cmd);
ret = -EOPNOTSUPP;
}
out:
spin_unlock_irqrestore(&self->spinlock, flags);
return ret;
}
MODULE_DESCRIPTION("Toshiba OBOE IrDA Device Driver");
MODULE_AUTHOR("James McKenzie <james@fishsoup.dhs.org>");
MODULE_LICENSE("GPL");
module_param (max_baud, int, 0);
MODULE_PARM_DESC(max_baud, "Maximum baud rate");
#ifdef USE_PROBE
module_param (do_probe, bool, 0);
MODULE_PARM_DESC(do_probe, "Enable/disable chip probing and self-test");
#endif
static void
toshoboe_close (struct pci_dev *pci_dev)
{
int i;
struct toshoboe_cb *self = (struct toshoboe_cb*)pci_get_drvdata(pci_dev);
IRDA_DEBUG (4, "%s()\n", __func__);
IRDA_ASSERT (self != NULL, return; );
if (!self->stopped)
{
toshoboe_stopchip (self);
}
release_region (self->io.fir_base, self->io.fir_ext);
for (i = 0; i < TX_SLOTS; ++i)
{
kfree (self->tx_bufs[i]);
self->tx_bufs[i] = NULL;
}
for (i = 0; i < RX_SLOTS; ++i)
{
kfree (self->rx_bufs[i]);
self->rx_bufs[i] = NULL;
}
unregister_netdev(self->netdev);
kfree (self->ringbuf);
self->ringbuf = NULL;
self->ring = NULL;
free_netdev(self->netdev);
}
static const struct net_device_ops toshoboe_netdev_ops = {
.ndo_open = toshoboe_net_open,
.ndo_stop = toshoboe_net_close,
.ndo_start_xmit = toshoboe_hard_xmit,
.ndo_do_ioctl = toshoboe_net_ioctl,
};
static int
toshoboe_open (struct pci_dev *pci_dev, const struct pci_device_id *pdid)
{
struct toshoboe_cb *self;
struct net_device *dev;
int i = 0;
int ok = 0;
int err;
IRDA_DEBUG (4, "%s()\n", __func__);
if ((err=pci_enable_device(pci_dev)))
return err;
dev = alloc_irdadev(sizeof (struct toshoboe_cb));
if (dev == NULL)
{
printk (KERN_ERR DRIVER_NAME ": can't allocate memory for "
"IrDA control block\n");
return -ENOMEM;
}
self = netdev_priv(dev);
self->netdev = dev;
self->pdev = pci_dev;
self->base = pci_resource_start(pci_dev,0);
self->io.fir_base = self->base;
self->io.fir_ext = OBOE_IO_EXTENT;
self->io.irq = pci_dev->irq;
self->io.irqflags = IRQF_SHARED | IRQF_DISABLED;
self->speed = self->io.speed = 9600;
self->async = 0;
/* Lock the port that we need */
if (NULL==request_region (self->io.fir_base, self->io.fir_ext, driver_name))
{
printk (KERN_ERR DRIVER_NAME ": can't get iobase of 0x%03x\n"
,self->io.fir_base);
err = -EBUSY;
goto freeself;
}
spin_lock_init(&self->spinlock);
irda_init_max_qos_capabilies (&self->qos);
self->qos.baud_rate.bits = 0;
if (max_baud >= 2400)
self->qos.baud_rate.bits |= IR_2400;
/*if (max_baud>=4800) idev->qos.baud_rate.bits|=IR_4800; */
if (max_baud >= 9600)
self->qos.baud_rate.bits |= IR_9600;
if (max_baud >= 19200)
self->qos.baud_rate.bits |= IR_19200;
if (max_baud >= 115200)
self->qos.baud_rate.bits |= IR_115200;
#ifdef USE_MIR
if (max_baud >= 1152000)
{
self->qos.baud_rate.bits |= IR_1152000;
}
#endif
if (max_baud >= 4000000)
{
self->qos.baud_rate.bits |= (IR_4000000 << 8);
}
/*FIXME: work this out... */
self->qos.min_turn_time.bits = 0xff;
irda_qos_bits_to_value (&self->qos);
/* Allocate twice the size to guarantee alignment */
self->ringbuf = kmalloc(OBOE_RING_LEN << 1, GFP_KERNEL);
if (!self->ringbuf)
{
printk (KERN_ERR DRIVER_NAME ": can't allocate DMA buffers\n");
err = -ENOMEM;
goto freeregion;
}
#if (BITS_PER_LONG == 64)
#error broken on 64-bit: casts pointer to 32-bit, and then back to pointer.
#endif
/*We need to align the taskfile on a taskfile size boundary */
{
unsigned long addr;
addr = (__u32) self->ringbuf;
addr &= ~(OBOE_RING_LEN - 1);
addr += OBOE_RING_LEN;
self->ring = (struct OboeRing *) addr;
}
memset (self->ring, 0, OBOE_RING_LEN);
self->io.mem_base = (__u32) self->ring;
ok = 1;
for (i = 0; i < TX_SLOTS; ++i)
{
self->tx_bufs[i] = kmalloc (TX_BUF_SZ, GFP_KERNEL);
if (!self->tx_bufs[i])
ok = 0;
}
for (i = 0; i < RX_SLOTS; ++i)
{
self->rx_bufs[i] = kmalloc (RX_BUF_SZ, GFP_KERNEL);
if (!self->rx_bufs[i])
ok = 0;
}
if (!ok)
{
printk (KERN_ERR DRIVER_NAME ": can't allocate rx/tx buffers\n");
err = -ENOMEM;
goto freebufs;
}
#ifdef USE_PROBE
if (do_probe)
if (!toshoboe_probe (self))
{
err = -ENODEV;
goto freebufs;
}
#endif
SET_NETDEV_DEV(dev, &pci_dev->dev);
dev->netdev_ops = &toshoboe_netdev_ops;
err = register_netdev(dev);
if (err)
{
printk (KERN_ERR DRIVER_NAME ": register_netdev() failed\n");
err = -ENOMEM;
goto freebufs;
}
printk (KERN_INFO "IrDA: Registered device %s\n", dev->name);
pci_set_drvdata(pci_dev,self);
printk (KERN_INFO DRIVER_NAME ": Using multiple tasks\n");
return 0;
freebufs:
for (i = 0; i < TX_SLOTS; ++i)
kfree (self->tx_bufs[i]);
for (i = 0; i < RX_SLOTS; ++i)
kfree (self->rx_bufs[i]);
kfree(self->ringbuf);
freeregion:
release_region (self->io.fir_base, self->io.fir_ext);
freeself:
free_netdev(dev);
return err;
}
static int
toshoboe_gotosleep (struct pci_dev *pci_dev, pm_message_t crap)
{
struct toshoboe_cb *self = (struct toshoboe_cb*)pci_get_drvdata(pci_dev);
unsigned long flags;
int i = 10;
IRDA_DEBUG (4, "%s()\n", __func__);
if (!self || self->stopped)
return 0;
if ((!self->irdad) && (!self->async))
return 0;
/* Flush all packets */
while ((i--) && (self->txpending))
udelay (10000);
spin_lock_irqsave(&self->spinlock, flags);
toshoboe_stopchip (self);
self->stopped = 1;
self->txpending = 0;
spin_unlock_irqrestore(&self->spinlock, flags);
return 0;
}
static int
toshoboe_wakeup (struct pci_dev *pci_dev)
{
struct toshoboe_cb *self = (struct toshoboe_cb*)pci_get_drvdata(pci_dev);
unsigned long flags;
IRDA_DEBUG (4, "%s()\n", __func__);
if (!self || !self->stopped)
return 0;
if ((!self->irdad) && (!self->async))
return 0;
spin_lock_irqsave(&self->spinlock, flags);
toshoboe_startchip (self);
self->stopped = 0;
netif_wake_queue(self->netdev);
spin_unlock_irqrestore(&self->spinlock, flags);
return 0;
}
static struct pci_driver donauboe_pci_driver = {
.name = "donauboe",
.id_table = toshoboe_pci_tbl,
.probe = toshoboe_open,
.remove = toshoboe_close,
.suspend = toshoboe_gotosleep,
.resume = toshoboe_wakeup
};
static int __init
donauboe_init (void)
{
return pci_register_driver(&donauboe_pci_driver);
}
static void __exit
donauboe_cleanup (void)
{
pci_unregister_driver(&donauboe_pci_driver);
}
module_init(donauboe_init);
module_exit(donauboe_cleanup);
| gpl-2.0 |
CyanogenMod/motorola-kernel-stingray | drivers/net/tokenring/madgemc.c | 2525 | 21153 | /*
* madgemc.c: Driver for the Madge Smart 16/4 MC16 MCA token ring card.
*
* Written 2000 by Adam Fritzler
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* This driver module supports the following cards:
* - Madge Smart 16/4 Ringnode MC16
* - Madge Smart 16/4 Ringnode MC32 (??)
*
* Maintainer(s):
* AF Adam Fritzler
*
* Modification History:
* 16-Jan-00 AF Created
*
*/
static const char version[] = "madgemc.c: v0.91 23/01/2000 by Adam Fritzler\n";
#include <linux/module.h>
#include <linux/mca.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/trdevice.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/irq.h>
#include "tms380tr.h"
#include "madgemc.h" /* Madge-specific constants */
#define MADGEMC_IO_EXTENT 32
#define MADGEMC_SIF_OFFSET 0x08
struct card_info {
/*
* These are read from the BIA ROM.
*/
unsigned int manid;
unsigned int cardtype;
unsigned int cardrev;
unsigned int ramsize;
/*
* These are read from the MCA POS registers.
*/
unsigned int burstmode:2;
unsigned int fairness:1; /* 0 = Fair, 1 = Unfair */
unsigned int arblevel:4;
unsigned int ringspeed:2; /* 0 = 4mb, 1 = 16, 2 = Auto/none */
unsigned int cabletype:1; /* 0 = RJ45, 1 = DB9 */
};
static int madgemc_open(struct net_device *dev);
static int madgemc_close(struct net_device *dev);
static int madgemc_chipset_init(struct net_device *dev);
static void madgemc_read_rom(struct net_device *dev, struct card_info *card);
static unsigned short madgemc_setnselout_pins(struct net_device *dev);
static void madgemc_setcabletype(struct net_device *dev, int type);
static int madgemc_mcaproc(char *buf, int slot, void *d);
static void madgemc_setregpage(struct net_device *dev, int page);
static void madgemc_setsifsel(struct net_device *dev, int val);
static void madgemc_setint(struct net_device *dev, int val);
static irqreturn_t madgemc_interrupt(int irq, void *dev_id);
/*
* These work around paging, however they don't guarantee you're on the
* right page.
*/
#define SIFREADB(reg) (inb(dev->base_addr + ((reg<0x8)?reg:reg-0x8)))
#define SIFWRITEB(val, reg) (outb(val, dev->base_addr + ((reg<0x8)?reg:reg-0x8)))
#define SIFREADW(reg) (inw(dev->base_addr + ((reg<0x8)?reg:reg-0x8)))
#define SIFWRITEW(val, reg) (outw(val, dev->base_addr + ((reg<0x8)?reg:reg-0x8)))
/*
* Read a byte-length value from the register.
*/
static unsigned short madgemc_sifreadb(struct net_device *dev, unsigned short reg)
{
unsigned short ret;
if (reg<0x8)
ret = SIFREADB(reg);
else {
madgemc_setregpage(dev, 1);
ret = SIFREADB(reg);
madgemc_setregpage(dev, 0);
}
return ret;
}
/*
* Write a byte-length value to a register.
*/
static void madgemc_sifwriteb(struct net_device *dev, unsigned short val, unsigned short reg)
{
if (reg<0x8)
SIFWRITEB(val, reg);
else {
madgemc_setregpage(dev, 1);
SIFWRITEB(val, reg);
madgemc_setregpage(dev, 0);
}
}
/*
* Read a word-length value from a register
*/
static unsigned short madgemc_sifreadw(struct net_device *dev, unsigned short reg)
{
unsigned short ret;
if (reg<0x8)
ret = SIFREADW(reg);
else {
madgemc_setregpage(dev, 1);
ret = SIFREADW(reg);
madgemc_setregpage(dev, 0);
}
return ret;
}
/*
* Write a word-length value to a register.
*/
static void madgemc_sifwritew(struct net_device *dev, unsigned short val, unsigned short reg)
{
if (reg<0x8)
SIFWRITEW(val, reg);
else {
madgemc_setregpage(dev, 1);
SIFWRITEW(val, reg);
madgemc_setregpage(dev, 0);
}
}
static struct net_device_ops madgemc_netdev_ops __read_mostly;
static int __devinit madgemc_probe(struct device *device)
{
static int versionprinted;
struct net_device *dev;
struct net_local *tp;
struct card_info *card;
struct mca_device *mdev = to_mca_device(device);
int ret = 0;
if (versionprinted++ == 0)
printk("%s", version);
if(mca_device_claimed(mdev))
return -EBUSY;
mca_device_set_claim(mdev, 1);
dev = alloc_trdev(sizeof(struct net_local));
if (!dev) {
printk("madgemc: unable to allocate dev space\n");
mca_device_set_claim(mdev, 0);
ret = -ENOMEM;
goto getout;
}
dev->netdev_ops = &madgemc_netdev_ops;
card = kmalloc(sizeof(struct card_info), GFP_KERNEL);
if (card==NULL) {
printk("madgemc: unable to allocate card struct\n");
ret = -ENOMEM;
goto getout1;
}
/*
* Parse configuration information. This all comes
* directly from the publicly available @002d.ADF.
* Get it from Madge or your local ADF library.
*/
/*
* Base address
*/
dev->base_addr = 0x0a20 +
((mdev->pos[2] & MC16_POS2_ADDR2)?0x0400:0) +
((mdev->pos[0] & MC16_POS0_ADDR1)?0x1000:0) +
((mdev->pos[3] & MC16_POS3_ADDR3)?0x2000:0);
/*
* Interrupt line
*/
switch(mdev->pos[0] >> 6) { /* upper two bits */
case 0x1: dev->irq = 3; break;
case 0x2: dev->irq = 9; break; /* IRQ 2 = IRQ 9 */
case 0x3: dev->irq = 10; break;
default: dev->irq = 0; break;
}
if (dev->irq == 0) {
printk("%s: invalid IRQ\n", dev->name);
ret = -EBUSY;
goto getout2;
}
if (!request_region(dev->base_addr, MADGEMC_IO_EXTENT,
"madgemc")) {
printk(KERN_INFO "madgemc: unable to setup Smart MC in slot %d because of I/O base conflict at 0x%04lx\n", mdev->slot, dev->base_addr);
dev->base_addr += MADGEMC_SIF_OFFSET;
ret = -EBUSY;
goto getout2;
}
dev->base_addr += MADGEMC_SIF_OFFSET;
/*
* Arbitration Level
*/
card->arblevel = ((mdev->pos[0] >> 1) & 0x7) + 8;
/*
* Burst mode and Fairness
*/
card->burstmode = ((mdev->pos[2] >> 6) & 0x3);
card->fairness = ((mdev->pos[2] >> 4) & 0x1);
/*
* Ring Speed
*/
if ((mdev->pos[1] >> 2)&0x1)
card->ringspeed = 2; /* not selected */
else if ((mdev->pos[2] >> 5) & 0x1)
card->ringspeed = 1; /* 16Mb */
else
card->ringspeed = 0; /* 4Mb */
/*
* Cable type
*/
if ((mdev->pos[1] >> 6)&0x1)
card->cabletype = 1; /* STP/DB9 */
else
card->cabletype = 0; /* UTP/RJ-45 */
/*
* ROM Info. This requires us to actually twiddle
* bits on the card, so we must ensure above that
* the base address is free of conflict (request_region above).
*/
madgemc_read_rom(dev, card);
if (card->manid != 0x4d) { /* something went wrong */
printk(KERN_INFO "%s: Madge MC ROM read failed (unknown manufacturer ID %02x)\n", dev->name, card->manid);
goto getout3;
}
if ((card->cardtype != 0x08) && (card->cardtype != 0x0d)) {
printk(KERN_INFO "%s: Madge MC ROM read failed (unknown card ID %02x)\n", dev->name, card->cardtype);
ret = -EIO;
goto getout3;
}
/* All cards except Rev 0 and 1 MC16's have 256kb of RAM */
if ((card->cardtype == 0x08) && (card->cardrev <= 0x01))
card->ramsize = 128;
else
card->ramsize = 256;
printk("%s: %s Rev %d at 0x%04lx IRQ %d\n",
dev->name,
(card->cardtype == 0x08)?MADGEMC16_CARDNAME:
MADGEMC32_CARDNAME, card->cardrev,
dev->base_addr, dev->irq);
if (card->cardtype == 0x0d)
printk("%s: Warning: MC32 support is experimental and highly untested\n", dev->name);
if (card->ringspeed==2) { /* Unknown */
printk("%s: Warning: Ring speed not set in POS -- Please run the reference disk and set it!\n", dev->name);
card->ringspeed = 1; /* default to 16mb */
}
printk("%s: RAM Size: %dKB\n", dev->name, card->ramsize);
printk("%s: Ring Speed: %dMb/sec on %s\n", dev->name,
(card->ringspeed)?16:4,
card->cabletype?"STP/DB9":"UTP/RJ-45");
printk("%s: Arbitration Level: %d\n", dev->name,
card->arblevel);
printk("%s: Burst Mode: ", dev->name);
switch(card->burstmode) {
case 0: printk("Cycle steal"); break;
case 1: printk("Limited burst"); break;
case 2: printk("Delayed release"); break;
case 3: printk("Immediate release"); break;
}
printk(" (%s)\n", (card->fairness)?"Unfair":"Fair");
/*
* Enable SIF before we assign the interrupt handler,
* just in case we get spurious interrupts that need
* handling.
*/
outb(0, dev->base_addr + MC_CONTROL_REG0); /* sanity */
madgemc_setsifsel(dev, 1);
if (request_irq(dev->irq, madgemc_interrupt, IRQF_SHARED,
"madgemc", dev)) {
ret = -EBUSY;
goto getout3;
}
madgemc_chipset_init(dev); /* enables interrupts! */
madgemc_setcabletype(dev, card->cabletype);
/* Setup MCA structures */
mca_device_set_name(mdev, (card->cardtype == 0x08)?MADGEMC16_CARDNAME:MADGEMC32_CARDNAME);
mca_set_adapter_procfn(mdev->slot, madgemc_mcaproc, dev);
printk("%s: Ring Station Address: %pM\n",
dev->name, dev->dev_addr);
if (tmsdev_init(dev, device)) {
printk("%s: unable to get memory for dev->priv.\n",
dev->name);
ret = -ENOMEM;
goto getout4;
}
tp = netdev_priv(dev);
/*
* The MC16 is physically a 32bit card. However, Madge
* insists on calling it 16bit, so I'll assume here that
* they know what they're talking about. Cut off DMA
* at 16mb.
*/
tp->setnselout = madgemc_setnselout_pins;
tp->sifwriteb = madgemc_sifwriteb;
tp->sifreadb = madgemc_sifreadb;
tp->sifwritew = madgemc_sifwritew;
tp->sifreadw = madgemc_sifreadw;
tp->DataRate = (card->ringspeed)?SPEED_16:SPEED_4;
memcpy(tp->ProductID, "Madge MCA 16/4 ", PROD_ID_SIZE + 1);
tp->tmspriv = card;
dev_set_drvdata(device, dev);
if (register_netdev(dev) == 0)
return 0;
dev_set_drvdata(device, NULL);
ret = -ENOMEM;
getout4:
free_irq(dev->irq, dev);
getout3:
release_region(dev->base_addr-MADGEMC_SIF_OFFSET,
MADGEMC_IO_EXTENT);
getout2:
kfree(card);
getout1:
free_netdev(dev);
getout:
mca_device_set_claim(mdev, 0);
return ret;
}
/*
* Handle interrupts generated by the card
*
* The MicroChannel Madge cards need slightly more handling
* after an interrupt than other TMS380 cards do.
*
* First we must make sure it was this card that generated the
* interrupt (since interrupt sharing is allowed). Then,
* because we're using level-triggered interrupts (as is
* standard on MCA), we must toggle the interrupt line
* on the card in order to claim and acknowledge the interrupt.
* Once that is done, the interrupt should be handlable in
* the normal tms380tr_interrupt() routine.
*
* There's two ways we can check to see if the interrupt is ours,
* both with their own disadvantages...
*
* 1) Read in the SIFSTS register from the TMS controller. This
* is guaranteed to be accurate, however, there's a fairly
* large performance penalty for doing so: the Madge chips
* must request the register from the Eagle, the Eagle must
* read them from its internal bus, and then take the route
* back out again, for a 16bit read.
*
* 2) Use the MC_CONTROL_REG0_SINTR bit from the Madge ASICs.
* The major disadvantage here is that the accuracy of the
* bit is in question. However, it cuts out the extra read
* cycles it takes to read the Eagle's SIF, as its only an
* 8bit read, and theoretically the Madge bit is directly
* connected to the interrupt latch coming out of the Eagle
* hardware (that statement is not verified).
*
* I can't determine which of these methods has the best win. For now,
* we make a compromise. Use the Madge way for the first interrupt,
* which should be the fast-path, and then once we hit the first
* interrupt, keep on trying using the SIF method until we've
* exhausted all contiguous interrupts.
*
*/
static irqreturn_t madgemc_interrupt(int irq, void *dev_id)
{
int pending,reg1;
struct net_device *dev;
if (!dev_id) {
printk("madgemc_interrupt: was not passed a dev_id!\n");
return IRQ_NONE;
}
dev = (struct net_device *)dev_id;
/* Make sure its really us. -- the Madge way */
pending = inb(dev->base_addr + MC_CONTROL_REG0);
if (!(pending & MC_CONTROL_REG0_SINTR))
return IRQ_NONE; /* not our interrupt */
/*
* Since we're level-triggered, we may miss the rising edge
* of the next interrupt while we're off handling this one,
* so keep checking until the SIF verifies that it has nothing
* left for us to do.
*/
pending = STS_SYSTEM_IRQ;
do {
if (pending & STS_SYSTEM_IRQ) {
/* Toggle the interrupt to reset the latch on card */
reg1 = inb(dev->base_addr + MC_CONTROL_REG1);
outb(reg1 ^ MC_CONTROL_REG1_SINTEN,
dev->base_addr + MC_CONTROL_REG1);
outb(reg1, dev->base_addr + MC_CONTROL_REG1);
/* Continue handling as normal */
tms380tr_interrupt(irq, dev_id);
pending = SIFREADW(SIFSTS); /* restart - the SIF way */
} else
return IRQ_HANDLED;
} while (1);
return IRQ_HANDLED; /* not reachable */
}
/*
* Set the card to the preferred ring speed.
*
* Unlike newer cards, the MC16/32 have their speed selection
* circuit connected to the Madge ASICs and not to the TMS380
* NSELOUT pins. Set the ASIC bits correctly here, and return
* zero to leave the TMS NSELOUT bits unaffected.
*
*/
static unsigned short madgemc_setnselout_pins(struct net_device *dev)
{
unsigned char reg1;
struct net_local *tp = netdev_priv(dev);
reg1 = inb(dev->base_addr + MC_CONTROL_REG1);
if(tp->DataRate == SPEED_16)
reg1 |= MC_CONTROL_REG1_SPEED_SEL; /* add for 16mb */
else if (reg1 & MC_CONTROL_REG1_SPEED_SEL)
reg1 ^= MC_CONTROL_REG1_SPEED_SEL; /* remove for 4mb */
outb(reg1, dev->base_addr + MC_CONTROL_REG1);
return 0; /* no change */
}
/*
* Set the register page. This equates to the SRSX line
* on the TMS380Cx6.
*
* Register selection is normally done via three contiguous
* bits. However, some boards (such as the MC16/32) use only
* two bits, plus a separate bit in the glue chip. This
* sets the SRSX bit (the top bit). See page 4-17 in the
* Yellow Book for which registers are affected.
*
*/
static void madgemc_setregpage(struct net_device *dev, int page)
{
static int reg1;
reg1 = inb(dev->base_addr + MC_CONTROL_REG1);
if ((page == 0) && (reg1 & MC_CONTROL_REG1_SRSX)) {
outb(reg1 ^ MC_CONTROL_REG1_SRSX,
dev->base_addr + MC_CONTROL_REG1);
}
else if (page == 1) {
outb(reg1 | MC_CONTROL_REG1_SRSX,
dev->base_addr + MC_CONTROL_REG1);
}
reg1 = inb(dev->base_addr + MC_CONTROL_REG1);
}
/*
* The SIF registers are not mapped into register space by default
* Set this to 1 to map them, 0 to map the BIA ROM.
*
*/
static void madgemc_setsifsel(struct net_device *dev, int val)
{
unsigned int reg0;
reg0 = inb(dev->base_addr + MC_CONTROL_REG0);
if ((val == 0) && (reg0 & MC_CONTROL_REG0_SIFSEL)) {
outb(reg0 ^ MC_CONTROL_REG0_SIFSEL,
dev->base_addr + MC_CONTROL_REG0);
} else if (val == 1) {
outb(reg0 | MC_CONTROL_REG0_SIFSEL,
dev->base_addr + MC_CONTROL_REG0);
}
reg0 = inb(dev->base_addr + MC_CONTROL_REG0);
}
/*
* Enable SIF interrupts
*
* This does not enable interrupts in the SIF, but rather
* enables SIF interrupts to be passed onto the host.
*
*/
static void madgemc_setint(struct net_device *dev, int val)
{
unsigned int reg1;
reg1 = inb(dev->base_addr + MC_CONTROL_REG1);
if ((val == 0) && (reg1 & MC_CONTROL_REG1_SINTEN)) {
outb(reg1 ^ MC_CONTROL_REG1_SINTEN,
dev->base_addr + MC_CONTROL_REG1);
} else if (val == 1) {
outb(reg1 | MC_CONTROL_REG1_SINTEN,
dev->base_addr + MC_CONTROL_REG1);
}
}
/*
* Cable type is set via control register 7. Bit zero high
* for UTP, low for STP.
*/
static void madgemc_setcabletype(struct net_device *dev, int type)
{
outb((type==0)?MC_CONTROL_REG7_CABLEUTP:MC_CONTROL_REG7_CABLESTP,
dev->base_addr + MC_CONTROL_REG7);
}
/*
* Enable the functions of the Madge chipset needed for
* full working order.
*/
static int madgemc_chipset_init(struct net_device *dev)
{
outb(0, dev->base_addr + MC_CONTROL_REG1); /* pull SRESET low */
tms380tr_wait(100); /* wait for card to reset */
/* bring back into normal operating mode */
outb(MC_CONTROL_REG1_NSRESET, dev->base_addr + MC_CONTROL_REG1);
/* map SIF registers */
madgemc_setsifsel(dev, 1);
/* enable SIF interrupts */
madgemc_setint(dev, 1);
return 0;
}
/*
* Disable the board, and put back into power-up state.
*/
static void madgemc_chipset_close(struct net_device *dev)
{
/* disable interrupts */
madgemc_setint(dev, 0);
/* unmap SIF registers */
madgemc_setsifsel(dev, 0);
}
/*
* Read the card type (MC16 or MC32) from the card.
*
* The configuration registers are stored in two separate
* pages. Pages are flipped by clearing bit 3 of CONTROL_REG0 (PAGE)
* for page zero, or setting bit 3 for page one.
*
* Page zero contains the following data:
* Byte 0: Manufacturer ID (0x4D -- ASCII "M")
* Byte 1: Card type:
* 0x08 for MC16
* 0x0D for MC32
* Byte 2: Card revision
* Byte 3: Mirror of POS config register 0
* Byte 4: Mirror of POS 1
* Byte 5: Mirror of POS 2
*
* Page one contains the following data:
* Byte 0: Unused
* Byte 1-6: BIA, MSB to LSB.
*
* Note that to read the BIA, we must unmap the SIF registers
* by clearing bit 2 of CONTROL_REG0 (SIFSEL), as the data
* will reside in the same logical location. For this reason,
* _never_ read the BIA while the Eagle processor is running!
* The SIF will be completely inaccessible until the BIA operation
* is complete.
*
*/
static void madgemc_read_rom(struct net_device *dev, struct card_info *card)
{
unsigned long ioaddr;
unsigned char reg0, reg1, tmpreg0, i;
ioaddr = dev->base_addr;
reg0 = inb(ioaddr + MC_CONTROL_REG0);
reg1 = inb(ioaddr + MC_CONTROL_REG1);
/* Switch to page zero and unmap SIF */
tmpreg0 = reg0 & ~(MC_CONTROL_REG0_PAGE + MC_CONTROL_REG0_SIFSEL);
outb(tmpreg0, ioaddr + MC_CONTROL_REG0);
card->manid = inb(ioaddr + MC_ROM_MANUFACTURERID);
card->cardtype = inb(ioaddr + MC_ROM_ADAPTERID);
card->cardrev = inb(ioaddr + MC_ROM_REVISION);
/* Switch to rom page one */
outb(tmpreg0 | MC_CONTROL_REG0_PAGE, ioaddr + MC_CONTROL_REG0);
/* Read BIA */
dev->addr_len = 6;
for (i = 0; i < 6; i++)
dev->dev_addr[i] = inb(ioaddr + MC_ROM_BIA_START + i);
/* Restore original register values */
outb(reg0, ioaddr + MC_CONTROL_REG0);
outb(reg1, ioaddr + MC_CONTROL_REG1);
}
static int madgemc_open(struct net_device *dev)
{
/*
* Go ahead and reinitialize the chipset again, just to
* make sure we didn't get left in a bad state.
*/
madgemc_chipset_init(dev);
tms380tr_open(dev);
return 0;
}
static int madgemc_close(struct net_device *dev)
{
tms380tr_close(dev);
madgemc_chipset_close(dev);
return 0;
}
/*
* Give some details available from /proc/mca/slotX
*/
static int madgemc_mcaproc(char *buf, int slot, void *d)
{
struct net_device *dev = (struct net_device *)d;
struct net_local *tp = netdev_priv(dev);
struct card_info *curcard = tp->tmspriv;
int len = 0;
len += sprintf(buf+len, "-------\n");
if (curcard) {
len += sprintf(buf+len, "Card Revision: %d\n", curcard->cardrev);
len += sprintf(buf+len, "RAM Size: %dkb\n", curcard->ramsize);
len += sprintf(buf+len, "Cable type: %s\n", (curcard->cabletype)?"STP/DB9":"UTP/RJ-45");
len += sprintf(buf+len, "Configured ring speed: %dMb/sec\n", (curcard->ringspeed)?16:4);
len += sprintf(buf+len, "Running ring speed: %dMb/sec\n", (tp->DataRate==SPEED_16)?16:4);
len += sprintf(buf+len, "Device: %s\n", dev->name);
len += sprintf(buf+len, "IO Port: 0x%04lx\n", dev->base_addr);
len += sprintf(buf+len, "IRQ: %d\n", dev->irq);
len += sprintf(buf+len, "Arbitration Level: %d\n", curcard->arblevel);
len += sprintf(buf+len, "Burst Mode: ");
switch(curcard->burstmode) {
case 0: len += sprintf(buf+len, "Cycle steal"); break;
case 1: len += sprintf(buf+len, "Limited burst"); break;
case 2: len += sprintf(buf+len, "Delayed release"); break;
case 3: len += sprintf(buf+len, "Immediate release"); break;
}
len += sprintf(buf+len, " (%s)\n", (curcard->fairness)?"Unfair":"Fair");
len += sprintf(buf+len, "Ring Station Address: %pM\n",
dev->dev_addr);
} else
len += sprintf(buf+len, "Card not configured\n");
return len;
}
static int __devexit madgemc_remove(struct device *device)
{
struct net_device *dev = dev_get_drvdata(device);
struct net_local *tp;
struct card_info *card;
BUG_ON(!dev);
tp = netdev_priv(dev);
card = tp->tmspriv;
kfree(card);
tp->tmspriv = NULL;
unregister_netdev(dev);
release_region(dev->base_addr-MADGEMC_SIF_OFFSET, MADGEMC_IO_EXTENT);
free_irq(dev->irq, dev);
tmsdev_term(dev);
free_netdev(dev);
dev_set_drvdata(device, NULL);
return 0;
}
static short madgemc_adapter_ids[] __initdata = {
0x002d,
0x0000
};
static struct mca_driver madgemc_driver = {
.id_table = madgemc_adapter_ids,
.driver = {
.name = "madgemc",
.bus = &mca_bus_type,
.probe = madgemc_probe,
.remove = __devexit_p(madgemc_remove),
},
};
static int __init madgemc_init (void)
{
madgemc_netdev_ops = tms380tr_netdev_ops;
madgemc_netdev_ops.ndo_open = madgemc_open;
madgemc_netdev_ops.ndo_stop = madgemc_close;
return mca_register_driver (&madgemc_driver);
}
static void __exit madgemc_exit (void)
{
mca_unregister_driver (&madgemc_driver);
}
module_init(madgemc_init);
module_exit(madgemc_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
andyhui/linux-kernel-3.12.17 | arch/mips/pci/pci-xlr.c | 2525 | 9448 | /*
* Copyright 2003-2011 NetLogic Microsystems, Inc. (NetLogic). All rights
* reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the NetLogic
* license below:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY NETLOGIC ``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 NETLOGIC OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/msi.h>
#include <linux/mm.h>
#include <linux/irq.h>
#include <linux/irqdesc.h>
#include <linux/console.h>
#include <linux/pci_regs.h>
#include <asm/io.h>
#include <asm/netlogic/interrupt.h>
#include <asm/netlogic/haldefs.h>
#include <asm/netlogic/common.h>
#include <asm/netlogic/xlr/msidef.h>
#include <asm/netlogic/xlr/iomap.h>
#include <asm/netlogic/xlr/pic.h>
#include <asm/netlogic/xlr/xlr.h>
static void *pci_config_base;
#define pci_cfg_addr(bus, devfn, off) (((bus) << 16) | ((devfn) << 8) | (off))
/* PCI ops */
static inline u32 pci_cfg_read_32bit(struct pci_bus *bus, unsigned int devfn,
int where)
{
u32 data;
u32 *cfgaddr;
cfgaddr = (u32 *)(pci_config_base +
pci_cfg_addr(bus->number, devfn, where & ~3));
data = *cfgaddr;
return cpu_to_le32(data);
}
static inline void pci_cfg_write_32bit(struct pci_bus *bus, unsigned int devfn,
int where, u32 data)
{
u32 *cfgaddr;
cfgaddr = (u32 *)(pci_config_base +
pci_cfg_addr(bus->number, devfn, where & ~3));
*cfgaddr = cpu_to_le32(data);
}
static int nlm_pcibios_read(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 *val)
{
u32 data;
if ((size == 2) && (where & 1))
return PCIBIOS_BAD_REGISTER_NUMBER;
else if ((size == 4) && (where & 3))
return PCIBIOS_BAD_REGISTER_NUMBER;
data = pci_cfg_read_32bit(bus, devfn, where);
if (size == 1)
*val = (data >> ((where & 3) << 3)) & 0xff;
else if (size == 2)
*val = (data >> ((where & 3) << 3)) & 0xffff;
else
*val = data;
return PCIBIOS_SUCCESSFUL;
}
static int nlm_pcibios_write(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
u32 data;
if ((size == 2) && (where & 1))
return PCIBIOS_BAD_REGISTER_NUMBER;
else if ((size == 4) && (where & 3))
return PCIBIOS_BAD_REGISTER_NUMBER;
data = pci_cfg_read_32bit(bus, devfn, where);
if (size == 1)
data = (data & ~(0xff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
else if (size == 2)
data = (data & ~(0xffff << ((where & 3) << 3))) |
(val << ((where & 3) << 3));
else
data = val;
pci_cfg_write_32bit(bus, devfn, where, data);
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops nlm_pci_ops = {
.read = nlm_pcibios_read,
.write = nlm_pcibios_write
};
static struct resource nlm_pci_mem_resource = {
.name = "XLR PCI MEM",
.start = 0xd0000000UL, /* 256MB PCI mem @ 0xd000_0000 */
.end = 0xdfffffffUL,
.flags = IORESOURCE_MEM,
};
static struct resource nlm_pci_io_resource = {
.name = "XLR IO MEM",
.start = 0x10000000UL, /* 16MB PCI IO @ 0x1000_0000 */
.end = 0x100fffffUL,
.flags = IORESOURCE_IO,
};
struct pci_controller nlm_pci_controller = {
.index = 0,
.pci_ops = &nlm_pci_ops,
.mem_resource = &nlm_pci_mem_resource,
.mem_offset = 0x00000000UL,
.io_resource = &nlm_pci_io_resource,
.io_offset = 0x00000000UL,
};
/*
* The top level PCIe links on the XLS PCIe controller appear as
* bridges. Given a device, this function finds which link it is
* on.
*/
static struct pci_dev *xls_get_pcie_link(const struct pci_dev *dev)
{
struct pci_bus *bus, *p;
/* Find the bridge on bus 0 */
bus = dev->bus;
for (p = bus->parent; p && p->number != 0; p = p->parent)
bus = p;
return p ? bus->self : NULL;
}
static int nlm_pci_link_to_irq(int link)
{
switch (link) {
case 0:
return PIC_PCIE_LINK0_IRQ;
case 1:
return PIC_PCIE_LINK1_IRQ;
case 2:
if (nlm_chip_is_xls_b())
return PIC_PCIE_XLSB0_LINK2_IRQ;
else
return PIC_PCIE_LINK2_IRQ;
case 3:
if (nlm_chip_is_xls_b())
return PIC_PCIE_XLSB0_LINK3_IRQ;
else
return PIC_PCIE_LINK3_IRQ;
}
WARN(1, "Unexpected link %d\n", link);
return 0;
}
static int get_irq_vector(const struct pci_dev *dev)
{
struct pci_dev *lnk;
int link;
if (!nlm_chip_is_xls())
return PIC_PCIX_IRQ; /* for XLR just one IRQ */
lnk = xls_get_pcie_link(dev);
if (lnk == NULL)
return 0;
link = PCI_SLOT(lnk->devfn);
return nlm_pci_link_to_irq(link);
}
#ifdef CONFIG_PCI_MSI
void destroy_irq(unsigned int irq)
{
/* nothing to do yet */
}
void arch_teardown_msi_irq(unsigned int irq)
{
destroy_irq(irq);
}
int arch_setup_msi_irq(struct pci_dev *dev, struct msi_desc *desc)
{
struct msi_msg msg;
struct pci_dev *lnk;
int irq, ret;
u16 val;
/* MSI not supported on XLR */
if (!nlm_chip_is_xls())
return 1;
/*
* Enable MSI on the XLS PCIe controller bridge which was disabled
* at enumeration, the bridge MSI capability is at 0x50
*/
lnk = xls_get_pcie_link(dev);
if (lnk == NULL)
return 1;
pci_read_config_word(lnk, 0x50 + PCI_MSI_FLAGS, &val);
if ((val & PCI_MSI_FLAGS_ENABLE) == 0) {
val |= PCI_MSI_FLAGS_ENABLE;
pci_write_config_word(lnk, 0x50 + PCI_MSI_FLAGS, val);
}
irq = get_irq_vector(dev);
if (irq <= 0)
return 1;
msg.address_hi = MSI_ADDR_BASE_HI;
msg.address_lo = MSI_ADDR_BASE_LO |
MSI_ADDR_DEST_MODE_PHYSICAL |
MSI_ADDR_REDIRECTION_CPU;
msg.data = MSI_DATA_TRIGGER_EDGE |
MSI_DATA_LEVEL_ASSERT |
MSI_DATA_DELIVERY_FIXED;
ret = irq_set_msi_desc(irq, desc);
if (ret < 0) {
destroy_irq(irq);
return ret;
}
write_msi_msg(irq, &msg);
return 0;
}
#endif
/* Extra ACK needed for XLR on chip PCI controller */
static void xlr_pci_ack(struct irq_data *d)
{
uint64_t pcibase = nlm_mmio_base(NETLOGIC_IO_PCIX_OFFSET);
nlm_read_reg(pcibase, (0x140 >> 2));
}
/* Extra ACK needed for XLS on chip PCIe controller */
static void xls_pcie_ack(struct irq_data *d)
{
uint64_t pciebase_le = nlm_mmio_base(NETLOGIC_IO_PCIE_1_OFFSET);
switch (d->irq) {
case PIC_PCIE_LINK0_IRQ:
nlm_write_reg(pciebase_le, (0x90 >> 2), 0xffffffff);
break;
case PIC_PCIE_LINK1_IRQ:
nlm_write_reg(pciebase_le, (0x94 >> 2), 0xffffffff);
break;
case PIC_PCIE_LINK2_IRQ:
nlm_write_reg(pciebase_le, (0x190 >> 2), 0xffffffff);
break;
case PIC_PCIE_LINK3_IRQ:
nlm_write_reg(pciebase_le, (0x194 >> 2), 0xffffffff);
break;
}
}
/* For XLS B silicon, the 3,4 PCI interrupts are different */
static void xls_pcie_ack_b(struct irq_data *d)
{
uint64_t pciebase_le = nlm_mmio_base(NETLOGIC_IO_PCIE_1_OFFSET);
switch (d->irq) {
case PIC_PCIE_LINK0_IRQ:
nlm_write_reg(pciebase_le, (0x90 >> 2), 0xffffffff);
break;
case PIC_PCIE_LINK1_IRQ:
nlm_write_reg(pciebase_le, (0x94 >> 2), 0xffffffff);
break;
case PIC_PCIE_XLSB0_LINK2_IRQ:
nlm_write_reg(pciebase_le, (0x190 >> 2), 0xffffffff);
break;
case PIC_PCIE_XLSB0_LINK3_IRQ:
nlm_write_reg(pciebase_le, (0x194 >> 2), 0xffffffff);
break;
}
}
int __init pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
return get_irq_vector(dev);
}
/* Do platform specific device initialization at pci_enable_device() time */
int pcibios_plat_dev_init(struct pci_dev *dev)
{
return 0;
}
static int __init pcibios_init(void)
{
void (*extra_ack)(struct irq_data *);
int link, irq;
/* PSB assigns PCI resources */
pci_set_flags(PCI_PROBE_ONLY);
pci_config_base = ioremap(DEFAULT_PCI_CONFIG_BASE, 16 << 20);
/* Extend IO port for memory mapped io */
ioport_resource.start = 0;
ioport_resource.end = ~0;
set_io_port_base(CKSEG1);
nlm_pci_controller.io_map_base = CKSEG1;
pr_info("Registering XLR/XLS PCIX/PCIE Controller.\n");
register_pci_controller(&nlm_pci_controller);
/*
* For PCI interrupts, we need to ack the PCI controller too, overload
* irq handler data to do this
*/
if (!nlm_chip_is_xls()) {
/* XLR PCI controller ACK */
nlm_set_pic_extra_ack(0, PIC_PCIX_IRQ, xlr_pci_ack);
} else {
if (nlm_chip_is_xls_b())
extra_ack = xls_pcie_ack_b;
else
extra_ack = xls_pcie_ack;
for (link = 0; link < 4; link++) {
irq = nlm_pci_link_to_irq(link);
nlm_set_pic_extra_ack(0, irq, extra_ack);
}
}
return 0;
}
arch_initcall(pcibios_init);
| gpl-2.0 |
invisiblek/android_kernel_samsung_jaspervzw | drivers/net/enic/enic_pp.c | 2781 | 6841 | /*
* Copyright 2011 Cisco Systems, Inc. All rights reserved.
*
* This program is free software; you may redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/rtnetlink.h>
#include <net/ip.h>
#include "vnic_vic.h"
#include "enic_res.h"
#include "enic.h"
#include "enic_dev.h"
static int enic_set_port_profile(struct enic *enic)
{
struct net_device *netdev = enic->netdev;
struct vic_provinfo *vp;
const u8 oui[3] = VIC_PROVINFO_CISCO_OUI;
const u16 os_type = htons(VIC_GENERIC_PROV_OS_TYPE_LINUX);
char uuid_str[38];
char client_mac_str[18];
u8 *client_mac;
int err;
if (!(enic->pp.set & ENIC_SET_NAME) || !strlen(enic->pp.name))
return -EINVAL;
vp = vic_provinfo_alloc(GFP_KERNEL, oui,
VIC_PROVINFO_GENERIC_TYPE);
if (!vp)
return -ENOMEM;
VIC_PROVINFO_ADD_TLV(vp,
VIC_GENERIC_PROV_TLV_PORT_PROFILE_NAME_STR,
strlen(enic->pp.name) + 1, enic->pp.name);
if (!is_zero_ether_addr(enic->pp.mac_addr))
client_mac = enic->pp.mac_addr;
else
client_mac = netdev->dev_addr;
VIC_PROVINFO_ADD_TLV(vp,
VIC_GENERIC_PROV_TLV_CLIENT_MAC_ADDR,
ETH_ALEN, client_mac);
snprintf(client_mac_str, sizeof(client_mac_str), "%pM", client_mac);
VIC_PROVINFO_ADD_TLV(vp,
VIC_GENERIC_PROV_TLV_CLUSTER_PORT_UUID_STR,
sizeof(client_mac_str), client_mac_str);
if (enic->pp.set & ENIC_SET_INSTANCE) {
sprintf(uuid_str, "%pUB", enic->pp.instance_uuid);
VIC_PROVINFO_ADD_TLV(vp,
VIC_GENERIC_PROV_TLV_CLIENT_UUID_STR,
sizeof(uuid_str), uuid_str);
}
if (enic->pp.set & ENIC_SET_HOST) {
sprintf(uuid_str, "%pUB", enic->pp.host_uuid);
VIC_PROVINFO_ADD_TLV(vp,
VIC_GENERIC_PROV_TLV_HOST_UUID_STR,
sizeof(uuid_str), uuid_str);
}
VIC_PROVINFO_ADD_TLV(vp,
VIC_GENERIC_PROV_TLV_OS_TYPE,
sizeof(os_type), &os_type);
err = enic_dev_status_to_errno(enic_dev_init_prov2(enic, vp));
add_tlv_failure:
vic_provinfo_free(vp);
return err;
}
static int enic_unset_port_profile(struct enic *enic)
{
int err;
err = enic_vnic_dev_deinit(enic);
if (err)
return enic_dev_status_to_errno(err);
enic_reset_addr_lists(enic);
return 0;
}
static int enic_are_pp_different(struct enic_port_profile *pp1,
struct enic_port_profile *pp2)
{
return strcmp(pp1->name, pp2->name) | !!memcmp(pp1->instance_uuid,
pp2->instance_uuid, PORT_UUID_MAX) |
!!memcmp(pp1->host_uuid, pp2->host_uuid, PORT_UUID_MAX) |
!!memcmp(pp1->mac_addr, pp2->mac_addr, ETH_ALEN);
}
static int enic_pp_preassociate(struct enic *enic,
struct enic_port_profile *prev_pp, int *restore_pp);
static int enic_pp_disassociate(struct enic *enic,
struct enic_port_profile *prev_pp, int *restore_pp);
static int enic_pp_preassociate_rr(struct enic *enic,
struct enic_port_profile *prev_pp, int *restore_pp);
static int enic_pp_associate(struct enic *enic,
struct enic_port_profile *prev_pp, int *restore_pp);
static int (*enic_pp_handlers[])(struct enic *enic,
struct enic_port_profile *prev_state, int *restore_pp) = {
[PORT_REQUEST_PREASSOCIATE] = enic_pp_preassociate,
[PORT_REQUEST_PREASSOCIATE_RR] = enic_pp_preassociate_rr,
[PORT_REQUEST_ASSOCIATE] = enic_pp_associate,
[PORT_REQUEST_DISASSOCIATE] = enic_pp_disassociate,
};
static const int enic_pp_handlers_count =
sizeof(enic_pp_handlers)/sizeof(*enic_pp_handlers);
static int enic_pp_preassociate(struct enic *enic,
struct enic_port_profile *prev_pp, int *restore_pp)
{
return -EOPNOTSUPP;
}
static int enic_pp_disassociate(struct enic *enic,
struct enic_port_profile *prev_pp, int *restore_pp)
{
return enic_unset_port_profile(enic);
}
static int enic_pp_preassociate_rr(struct enic *enic,
struct enic_port_profile *prev_pp, int *restore_pp)
{
int err;
int active = 0;
if (enic->pp.request != PORT_REQUEST_ASSOCIATE) {
/* If pre-associate is not part of an associate.
We always disassociate first */
err = enic_pp_handlers[PORT_REQUEST_DISASSOCIATE](enic,
prev_pp, restore_pp);
if (err)
return err;
*restore_pp = 0;
}
*restore_pp = 0;
err = enic_set_port_profile(enic);
if (err)
return err;
/* If pre-associate is not part of an associate. */
if (enic->pp.request != PORT_REQUEST_ASSOCIATE)
err = enic_dev_status_to_errno(enic_dev_enable2(enic, active));
return err;
}
static int enic_pp_associate(struct enic *enic,
struct enic_port_profile *prev_pp, int *restore_pp)
{
int err;
int active = 1;
/* Check if a pre-associate was called before */
if (prev_pp->request != PORT_REQUEST_PREASSOCIATE_RR ||
(prev_pp->request == PORT_REQUEST_PREASSOCIATE_RR &&
enic_are_pp_different(prev_pp, &enic->pp))) {
err = enic_pp_handlers[PORT_REQUEST_DISASSOCIATE](
enic, prev_pp, restore_pp);
if (err)
return err;
*restore_pp = 0;
}
err = enic_pp_handlers[PORT_REQUEST_PREASSOCIATE_RR](
enic, prev_pp, restore_pp);
if (err)
return err;
*restore_pp = 0;
return enic_dev_status_to_errno(enic_dev_enable2(enic, active));
}
int enic_process_set_pp_request(struct enic *enic,
struct enic_port_profile *prev_pp, int *restore_pp)
{
if (enic->pp.request < enic_pp_handlers_count
&& enic_pp_handlers[enic->pp.request])
return enic_pp_handlers[enic->pp.request](enic,
prev_pp, restore_pp);
else
return -EOPNOTSUPP;
}
int enic_process_get_pp_request(struct enic *enic, int request,
u16 *response)
{
int err, status = ERR_SUCCESS;
switch (request) {
case PORT_REQUEST_PREASSOCIATE_RR:
case PORT_REQUEST_ASSOCIATE:
err = enic_dev_enable2_done(enic, &status);
break;
case PORT_REQUEST_DISASSOCIATE:
err = enic_dev_deinit_done(enic, &status);
break;
default:
return -EINVAL;
}
if (err)
status = err;
switch (status) {
case ERR_SUCCESS:
*response = PORT_PROFILE_RESPONSE_SUCCESS;
break;
case ERR_EINVAL:
*response = PORT_PROFILE_RESPONSE_INVALID;
break;
case ERR_EBADSTATE:
*response = PORT_PROFILE_RESPONSE_BADSTATE;
break;
case ERR_ENOMEM:
*response = PORT_PROFILE_RESPONSE_INSUFFICIENT_RESOURCES;
break;
case ERR_EINPROGRESS:
*response = PORT_PROFILE_RESPONSE_INPROGRESS;
break;
default:
*response = PORT_PROFILE_RESPONSE_ERROR;
break;
}
return 0;
}
| gpl-2.0 |
thanhphat11/kernel-stock-4.4.2-ef63slk | drivers/rtc/rtc-rv3029c2.c | 3805 | 11868 | /*
* Micro Crystal RV-3029C2 rtc class driver
*
* Author: Gregory Hermant <gregory.hermant@calao-systems.com>
*
* based on previously existing rtc class drivers
*
* 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.
*
* NOTE: Currently this driver only supports the bare minimum for read
* and write the RTC and alarms. The extra features provided by this chip
* (trickle charger, eeprom, T° compensation) are unavailable.
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/bcd.h>
#include <linux/rtc.h>
/* Register map */
/* control section */
#define RV3029C2_ONOFF_CTRL 0x00
#define RV3029C2_IRQ_CTRL 0x01
#define RV3029C2_IRQ_CTRL_AIE (1 << 0)
#define RV3029C2_IRQ_FLAGS 0x02
#define RV3029C2_IRQ_FLAGS_AF (1 << 0)
#define RV3029C2_STATUS 0x03
#define RV3029C2_STATUS_VLOW1 (1 << 2)
#define RV3029C2_STATUS_VLOW2 (1 << 3)
#define RV3029C2_STATUS_SR (1 << 4)
#define RV3029C2_STATUS_PON (1 << 5)
#define RV3029C2_STATUS_EEBUSY (1 << 7)
#define RV3029C2_RST_CTRL 0x04
#define RV3029C2_CONTROL_SECTION_LEN 0x05
/* watch section */
#define RV3029C2_W_SEC 0x08
#define RV3029C2_W_MINUTES 0x09
#define RV3029C2_W_HOURS 0x0A
#define RV3029C2_REG_HR_12_24 (1<<6) /* 24h/12h mode */
#define RV3029C2_REG_HR_PM (1<<5) /* PM/AM bit in 12h mode */
#define RV3029C2_W_DATE 0x0B
#define RV3029C2_W_DAYS 0x0C
#define RV3029C2_W_MONTHS 0x0D
#define RV3029C2_W_YEARS 0x0E
#define RV3029C2_WATCH_SECTION_LEN 0x07
/* alarm section */
#define RV3029C2_A_SC 0x10
#define RV3029C2_A_MN 0x11
#define RV3029C2_A_HR 0x12
#define RV3029C2_A_DT 0x13
#define RV3029C2_A_DW 0x14
#define RV3029C2_A_MO 0x15
#define RV3029C2_A_YR 0x16
#define RV3029C2_ALARM_SECTION_LEN 0x07
/* timer section */
#define RV3029C2_TIMER_LOW 0x18
#define RV3029C2_TIMER_HIGH 0x19
/* temperature section */
#define RV3029C2_TEMP_PAGE 0x20
/* eeprom data section */
#define RV3029C2_E2P_EEDATA1 0x28
#define RV3029C2_E2P_EEDATA2 0x29
/* eeprom control section */
#define RV3029C2_CONTROL_E2P_EECTRL 0x30
#define RV3029C2_TRICKLE_1K (1<<0) /* 1K resistance */
#define RV3029C2_TRICKLE_5K (1<<1) /* 5K resistance */
#define RV3029C2_TRICKLE_20K (1<<2) /* 20K resistance */
#define RV3029C2_TRICKLE_80K (1<<3) /* 80K resistance */
#define RV3029C2_CONTROL_E2P_XTALOFFSET 0x31
#define RV3029C2_CONTROL_E2P_QCOEF 0x32
#define RV3029C2_CONTROL_E2P_TURNOVER 0x33
/* user ram section */
#define RV3029C2_USR1_RAM_PAGE 0x38
#define RV3029C2_USR1_SECTION_LEN 0x04
#define RV3029C2_USR2_RAM_PAGE 0x3C
#define RV3029C2_USR2_SECTION_LEN 0x04
static int
rv3029c2_i2c_read_regs(struct i2c_client *client, u8 reg, u8 *buf,
unsigned len)
{
int ret;
if ((reg > RV3029C2_USR1_RAM_PAGE + 7) ||
(reg + len > RV3029C2_USR1_RAM_PAGE + 8))
return -EINVAL;
ret = i2c_smbus_read_i2c_block_data(client, reg, len, buf);
if (ret < 0)
return ret;
if (ret < len)
return -EIO;
return 0;
}
static int
rv3029c2_i2c_write_regs(struct i2c_client *client, u8 reg, u8 const buf[],
unsigned len)
{
if ((reg > RV3029C2_USR1_RAM_PAGE + 7) ||
(reg + len > RV3029C2_USR1_RAM_PAGE + 8))
return -EINVAL;
return i2c_smbus_write_i2c_block_data(client, reg, len, buf);
}
static int
rv3029c2_i2c_get_sr(struct i2c_client *client, u8 *buf)
{
int ret = rv3029c2_i2c_read_regs(client, RV3029C2_STATUS, buf, 1);
if (ret < 0)
return -EIO;
dev_dbg(&client->dev, "status = 0x%.2x (%d)\n", buf[0], buf[0]);
return 0;
}
static int
rv3029c2_i2c_set_sr(struct i2c_client *client, u8 val)
{
u8 buf[1];
int sr;
buf[0] = val;
sr = rv3029c2_i2c_write_regs(client, RV3029C2_STATUS, buf, 1);
dev_dbg(&client->dev, "status = 0x%.2x (%d)\n", buf[0], buf[0]);
if (sr < 0)
return -EIO;
return 0;
}
static int
rv3029c2_i2c_read_time(struct i2c_client *client, struct rtc_time *tm)
{
u8 buf[1];
int ret;
u8 regs[RV3029C2_WATCH_SECTION_LEN] = { 0, };
ret = rv3029c2_i2c_get_sr(client, buf);
if (ret < 0) {
dev_err(&client->dev, "%s: reading SR failed\n", __func__);
return -EIO;
}
ret = rv3029c2_i2c_read_regs(client, RV3029C2_W_SEC , regs,
RV3029C2_WATCH_SECTION_LEN);
if (ret < 0) {
dev_err(&client->dev, "%s: reading RTC section failed\n",
__func__);
return ret;
}
tm->tm_sec = bcd2bin(regs[RV3029C2_W_SEC-RV3029C2_W_SEC]);
tm->tm_min = bcd2bin(regs[RV3029C2_W_MINUTES-RV3029C2_W_SEC]);
/* HR field has a more complex interpretation */
{
const u8 _hr = regs[RV3029C2_W_HOURS-RV3029C2_W_SEC];
if (_hr & RV3029C2_REG_HR_12_24) {
/* 12h format */
tm->tm_hour = bcd2bin(_hr & 0x1f);
if (_hr & RV3029C2_REG_HR_PM) /* PM flag set */
tm->tm_hour += 12;
} else /* 24h format */
tm->tm_hour = bcd2bin(_hr & 0x3f);
}
tm->tm_mday = bcd2bin(regs[RV3029C2_W_DATE-RV3029C2_W_SEC]);
tm->tm_mon = bcd2bin(regs[RV3029C2_W_MONTHS-RV3029C2_W_SEC]) - 1;
tm->tm_year = bcd2bin(regs[RV3029C2_W_YEARS-RV3029C2_W_SEC]) + 100;
tm->tm_wday = bcd2bin(regs[RV3029C2_W_DAYS-RV3029C2_W_SEC]) - 1;
return 0;
}
static int rv3029c2_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
return rv3029c2_i2c_read_time(to_i2c_client(dev), tm);
}
static int
rv3029c2_i2c_read_alarm(struct i2c_client *client, struct rtc_wkalrm *alarm)
{
struct rtc_time *const tm = &alarm->time;
int ret;
u8 regs[8];
ret = rv3029c2_i2c_get_sr(client, regs);
if (ret < 0) {
dev_err(&client->dev, "%s: reading SR failed\n", __func__);
return -EIO;
}
ret = rv3029c2_i2c_read_regs(client, RV3029C2_A_SC, regs,
RV3029C2_ALARM_SECTION_LEN);
if (ret < 0) {
dev_err(&client->dev, "%s: reading alarm section failed\n",
__func__);
return ret;
}
tm->tm_sec = bcd2bin(regs[RV3029C2_A_SC-RV3029C2_A_SC] & 0x7f);
tm->tm_min = bcd2bin(regs[RV3029C2_A_MN-RV3029C2_A_SC] & 0x7f);
tm->tm_hour = bcd2bin(regs[RV3029C2_A_HR-RV3029C2_A_SC] & 0x3f);
tm->tm_mday = bcd2bin(regs[RV3029C2_A_DT-RV3029C2_A_SC] & 0x3f);
tm->tm_mon = bcd2bin(regs[RV3029C2_A_MO-RV3029C2_A_SC] & 0x1f) - 1;
tm->tm_year = bcd2bin(regs[RV3029C2_A_YR-RV3029C2_A_SC] & 0x7f) + 100;
tm->tm_wday = bcd2bin(regs[RV3029C2_A_DW-RV3029C2_A_SC] & 0x07) - 1;
return 0;
}
static int
rv3029c2_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alarm)
{
return rv3029c2_i2c_read_alarm(to_i2c_client(dev), alarm);
}
static int rv3029c2_rtc_i2c_alarm_set_irq(struct i2c_client *client,
int enable)
{
int ret;
u8 buf[1];
/* enable AIE irq */
ret = rv3029c2_i2c_read_regs(client, RV3029C2_IRQ_CTRL, buf, 1);
if (ret < 0) {
dev_err(&client->dev, "can't read INT reg\n");
return ret;
}
if (enable)
buf[0] |= RV3029C2_IRQ_CTRL_AIE;
else
buf[0] &= ~RV3029C2_IRQ_CTRL_AIE;
ret = rv3029c2_i2c_write_regs(client, RV3029C2_IRQ_CTRL, buf, 1);
if (ret < 0) {
dev_err(&client->dev, "can't set INT reg\n");
return ret;
}
return 0;
}
static int rv3029c2_rtc_i2c_set_alarm(struct i2c_client *client,
struct rtc_wkalrm *alarm)
{
struct rtc_time *const tm = &alarm->time;
int ret;
u8 regs[8];
/*
* The clock has an 8 bit wide bcd-coded register (they never learn)
* for the year. tm_year is an offset from 1900 and we are interested
* in the 2000-2099 range, so any value less than 100 is invalid.
*/
if (tm->tm_year < 100)
return -EINVAL;
ret = rv3029c2_i2c_get_sr(client, regs);
if (ret < 0) {
dev_err(&client->dev, "%s: reading SR failed\n", __func__);
return -EIO;
}
regs[RV3029C2_A_SC-RV3029C2_A_SC] = bin2bcd(tm->tm_sec & 0x7f);
regs[RV3029C2_A_MN-RV3029C2_A_SC] = bin2bcd(tm->tm_min & 0x7f);
regs[RV3029C2_A_HR-RV3029C2_A_SC] = bin2bcd(tm->tm_hour & 0x3f);
regs[RV3029C2_A_DT-RV3029C2_A_SC] = bin2bcd(tm->tm_mday & 0x3f);
regs[RV3029C2_A_MO-RV3029C2_A_SC] = bin2bcd((tm->tm_mon & 0x1f) - 1);
regs[RV3029C2_A_DW-RV3029C2_A_SC] = bin2bcd((tm->tm_wday & 7) - 1);
regs[RV3029C2_A_YR-RV3029C2_A_SC] = bin2bcd((tm->tm_year & 0x7f) - 100);
ret = rv3029c2_i2c_write_regs(client, RV3029C2_A_SC, regs,
RV3029C2_ALARM_SECTION_LEN);
if (ret < 0)
return ret;
if (alarm->enabled) {
u8 buf[1];
/* clear AF flag */
ret = rv3029c2_i2c_read_regs(client, RV3029C2_IRQ_FLAGS,
buf, 1);
if (ret < 0) {
dev_err(&client->dev, "can't read alarm flag\n");
return ret;
}
buf[0] &= ~RV3029C2_IRQ_FLAGS_AF;
ret = rv3029c2_i2c_write_regs(client, RV3029C2_IRQ_FLAGS,
buf, 1);
if (ret < 0) {
dev_err(&client->dev, "can't set alarm flag\n");
return ret;
}
/* enable AIE irq */
ret = rv3029c2_rtc_i2c_alarm_set_irq(client, 1);
if (ret)
return ret;
dev_dbg(&client->dev, "alarm IRQ armed\n");
} else {
/* disable AIE irq */
ret = rv3029c2_rtc_i2c_alarm_set_irq(client, 1);
if (ret)
return ret;
dev_dbg(&client->dev, "alarm IRQ disabled\n");
}
return 0;
}
static int rv3029c2_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alarm)
{
return rv3029c2_rtc_i2c_set_alarm(to_i2c_client(dev), alarm);
}
static int
rv3029c2_i2c_set_time(struct i2c_client *client, struct rtc_time const *tm)
{
u8 regs[8];
int ret;
/*
* The clock has an 8 bit wide bcd-coded register (they never learn)
* for the year. tm_year is an offset from 1900 and we are interested
* in the 2000-2099 range, so any value less than 100 is invalid.
*/
if (tm->tm_year < 100)
return -EINVAL;
regs[RV3029C2_W_SEC-RV3029C2_W_SEC] = bin2bcd(tm->tm_sec);
regs[RV3029C2_W_MINUTES-RV3029C2_W_SEC] = bin2bcd(tm->tm_min);
regs[RV3029C2_W_HOURS-RV3029C2_W_SEC] = bin2bcd(tm->tm_hour);
regs[RV3029C2_W_DATE-RV3029C2_W_SEC] = bin2bcd(tm->tm_mday);
regs[RV3029C2_W_MONTHS-RV3029C2_W_SEC] = bin2bcd(tm->tm_mon+1);
regs[RV3029C2_W_DAYS-RV3029C2_W_SEC] = bin2bcd((tm->tm_wday & 7)+1);
regs[RV3029C2_W_YEARS-RV3029C2_W_SEC] = bin2bcd(tm->tm_year - 100);
ret = rv3029c2_i2c_write_regs(client, RV3029C2_W_SEC, regs,
RV3029C2_WATCH_SECTION_LEN);
if (ret < 0)
return ret;
ret = rv3029c2_i2c_get_sr(client, regs);
if (ret < 0) {
dev_err(&client->dev, "%s: reading SR failed\n", __func__);
return ret;
}
/* clear PON bit */
ret = rv3029c2_i2c_set_sr(client, (regs[0] & ~RV3029C2_STATUS_PON));
if (ret < 0) {
dev_err(&client->dev, "%s: reading SR failed\n", __func__);
return ret;
}
return 0;
}
static int rv3029c2_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
return rv3029c2_i2c_set_time(to_i2c_client(dev), tm);
}
static const struct rtc_class_ops rv3029c2_rtc_ops = {
.read_time = rv3029c2_rtc_read_time,
.set_time = rv3029c2_rtc_set_time,
.read_alarm = rv3029c2_rtc_read_alarm,
.set_alarm = rv3029c2_rtc_set_alarm,
};
static struct i2c_device_id rv3029c2_id[] = {
{ "rv3029c2", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, rv3029c2_id);
static int __devinit
rv3029c2_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct rtc_device *rtc;
int rc = 0;
u8 buf[1];
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_EMUL))
return -ENODEV;
rtc = rtc_device_register(client->name,
&client->dev, &rv3029c2_rtc_ops,
THIS_MODULE);
if (IS_ERR(rtc))
return PTR_ERR(rtc);
i2c_set_clientdata(client, rtc);
rc = rv3029c2_i2c_get_sr(client, buf);
if (rc < 0) {
dev_err(&client->dev, "reading status failed\n");
goto exit_unregister;
}
return 0;
exit_unregister:
rtc_device_unregister(rtc);
return rc;
}
static int __devexit rv3029c2_remove(struct i2c_client *client)
{
struct rtc_device *rtc = i2c_get_clientdata(client);
rtc_device_unregister(rtc);
return 0;
}
static struct i2c_driver rv3029c2_driver = {
.driver = {
.name = "rtc-rv3029c2",
},
.probe = rv3029c2_probe,
.remove = __devexit_p(rv3029c2_remove),
.id_table = rv3029c2_id,
};
module_i2c_driver(rv3029c2_driver);
MODULE_AUTHOR("Gregory Hermant <gregory.hermant@calao-systems.com>");
MODULE_DESCRIPTION("Micro Crystal RV3029C2 RTC driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
denseye73/mynewkernel | drivers/gpu/drm/drm_bufs.c | 4829 | 43436 | /**
* \file drm_bufs.c
* Generic buffer template
*
* \author Rickard E. (Rik) Faith <faith@valinux.com>
* \author Gareth Hughes <gareth@valinux.com>
*/
/*
* Created: Thu Nov 23 03:10:50 2000 by gareth@valinux.com
*
* Copyright 1999, 2000 Precision Insight, Inc., Cedar Park, Texas.
* 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
* VA LINUX SYSTEMS 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/vmalloc.h>
#include <linux/slab.h>
#include <linux/log2.h>
#include <linux/export.h>
#include <asm/shmparam.h>
#include "drmP.h"
static struct drm_map_list *drm_find_matching_map(struct drm_device *dev,
struct drm_local_map *map)
{
struct drm_map_list *entry;
list_for_each_entry(entry, &dev->maplist, head) {
/*
* Because the kernel-userspace ABI is fixed at a 32-bit offset
* while PCI resources may live above that, we only compare the
* lower 32 bits of the map offset for maps of type
* _DRM_FRAMEBUFFER or _DRM_REGISTERS.
* It is assumed that if a driver have more than one resource
* of each type, the lower 32 bits are different.
*/
if (!entry->map ||
map->type != entry->map->type ||
entry->master != dev->primary->master)
continue;
switch (map->type) {
case _DRM_SHM:
if (map->flags != _DRM_CONTAINS_LOCK)
break;
return entry;
case _DRM_REGISTERS:
case _DRM_FRAME_BUFFER:
if ((entry->map->offset & 0xffffffff) ==
(map->offset & 0xffffffff))
return entry;
default: /* Make gcc happy */
;
}
if (entry->map->offset == map->offset)
return entry;
}
return NULL;
}
static int drm_map_handle(struct drm_device *dev, struct drm_hash_item *hash,
unsigned long user_token, int hashed_handle, int shm)
{
int use_hashed_handle, shift;
unsigned long add;
#if (BITS_PER_LONG == 64)
use_hashed_handle = ((user_token & 0xFFFFFFFF00000000UL) || hashed_handle);
#elif (BITS_PER_LONG == 32)
use_hashed_handle = hashed_handle;
#else
#error Unsupported long size. Neither 64 nor 32 bits.
#endif
if (!use_hashed_handle) {
int ret;
hash->key = user_token >> PAGE_SHIFT;
ret = drm_ht_insert_item(&dev->map_hash, hash);
if (ret != -EINVAL)
return ret;
}
shift = 0;
add = DRM_MAP_HASH_OFFSET >> PAGE_SHIFT;
if (shm && (SHMLBA > PAGE_SIZE)) {
int bits = ilog2(SHMLBA >> PAGE_SHIFT) + 1;
/* For shared memory, we have to preserve the SHMLBA
* bits of the eventual vma->vm_pgoff value during
* mmap(). Otherwise we run into cache aliasing problems
* on some platforms. On these platforms, the pgoff of
* a mmap() request is used to pick a suitable virtual
* address for the mmap() region such that it will not
* cause cache aliasing problems.
*
* Therefore, make sure the SHMLBA relevant bits of the
* hash value we use are equal to those in the original
* kernel virtual address.
*/
shift = bits;
add |= ((user_token >> PAGE_SHIFT) & ((1UL << bits) - 1UL));
}
return drm_ht_just_insert_please(&dev->map_hash, hash,
user_token, 32 - PAGE_SHIFT - 3,
shift, add);
}
/**
* Core function to create a range of memory available for mapping by a
* non-root process.
*
* Adjusts the memory offset to its absolute value according to the mapping
* type. Adds the map to the map list drm_device::maplist. Adds MTRR's where
* applicable and if supported by the kernel.
*/
static int drm_addmap_core(struct drm_device * dev, resource_size_t offset,
unsigned int size, enum drm_map_type type,
enum drm_map_flags flags,
struct drm_map_list ** maplist)
{
struct drm_local_map *map;
struct drm_map_list *list;
drm_dma_handle_t *dmah;
unsigned long user_token;
int ret;
map = kmalloc(sizeof(*map), GFP_KERNEL);
if (!map)
return -ENOMEM;
map->offset = offset;
map->size = size;
map->flags = flags;
map->type = type;
/* Only allow shared memory to be removable since we only keep enough
* book keeping information about shared memory to allow for removal
* when processes fork.
*/
if ((map->flags & _DRM_REMOVABLE) && map->type != _DRM_SHM) {
kfree(map);
return -EINVAL;
}
DRM_DEBUG("offset = 0x%08llx, size = 0x%08lx, type = %d\n",
(unsigned long long)map->offset, map->size, map->type);
/* page-align _DRM_SHM maps. They are allocated here so there is no security
* hole created by that and it works around various broken drivers that use
* a non-aligned quantity to map the SAREA. --BenH
*/
if (map->type == _DRM_SHM)
map->size = PAGE_ALIGN(map->size);
if ((map->offset & (~(resource_size_t)PAGE_MASK)) || (map->size & (~PAGE_MASK))) {
kfree(map);
return -EINVAL;
}
map->mtrr = -1;
map->handle = NULL;
switch (map->type) {
case _DRM_REGISTERS:
case _DRM_FRAME_BUFFER:
#if !defined(__sparc__) && !defined(__alpha__) && !defined(__ia64__) && !defined(__powerpc64__) && !defined(__x86_64__) && !defined(__arm__)
if (map->offset + (map->size-1) < map->offset ||
map->offset < virt_to_phys(high_memory)) {
kfree(map);
return -EINVAL;
}
#endif
/* Some drivers preinitialize some maps, without the X Server
* needing to be aware of it. Therefore, we just return success
* when the server tries to create a duplicate map.
*/
list = drm_find_matching_map(dev, map);
if (list != NULL) {
if (list->map->size != map->size) {
DRM_DEBUG("Matching maps of type %d with "
"mismatched sizes, (%ld vs %ld)\n",
map->type, map->size,
list->map->size);
list->map->size = map->size;
}
kfree(map);
*maplist = list;
return 0;
}
if (drm_core_has_MTRR(dev)) {
if (map->type == _DRM_FRAME_BUFFER ||
(map->flags & _DRM_WRITE_COMBINING)) {
map->mtrr = mtrr_add(map->offset, map->size,
MTRR_TYPE_WRCOMB, 1);
}
}
if (map->type == _DRM_REGISTERS) {
map->handle = ioremap(map->offset, map->size);
if (!map->handle) {
kfree(map);
return -ENOMEM;
}
}
break;
case _DRM_SHM:
list = drm_find_matching_map(dev, map);
if (list != NULL) {
if(list->map->size != map->size) {
DRM_DEBUG("Matching maps of type %d with "
"mismatched sizes, (%ld vs %ld)\n",
map->type, map->size, list->map->size);
list->map->size = map->size;
}
kfree(map);
*maplist = list;
return 0;
}
map->handle = vmalloc_user(map->size);
DRM_DEBUG("%lu %d %p\n",
map->size, drm_order(map->size), map->handle);
if (!map->handle) {
kfree(map);
return -ENOMEM;
}
map->offset = (unsigned long)map->handle;
if (map->flags & _DRM_CONTAINS_LOCK) {
/* Prevent a 2nd X Server from creating a 2nd lock */
if (dev->primary->master->lock.hw_lock != NULL) {
vfree(map->handle);
kfree(map);
return -EBUSY;
}
dev->sigdata.lock = dev->primary->master->lock.hw_lock = map->handle; /* Pointer to lock */
}
break;
case _DRM_AGP: {
struct drm_agp_mem *entry;
int valid = 0;
if (!drm_core_has_AGP(dev)) {
kfree(map);
return -EINVAL;
}
#ifdef __alpha__
map->offset += dev->hose->mem_space->start;
#endif
/* In some cases (i810 driver), user space may have already
* added the AGP base itself, because dev->agp->base previously
* only got set during AGP enable. So, only add the base
* address if the map's offset isn't already within the
* aperture.
*/
if (map->offset < dev->agp->base ||
map->offset > dev->agp->base +
dev->agp->agp_info.aper_size * 1024 * 1024 - 1) {
map->offset += dev->agp->base;
}
map->mtrr = dev->agp->agp_mtrr; /* for getmap */
/* This assumes the DRM is in total control of AGP space.
* It's not always the case as AGP can be in the control
* of user space (i.e. i810 driver). So this loop will get
* skipped and we double check that dev->agp->memory is
* actually set as well as being invalid before EPERM'ing
*/
list_for_each_entry(entry, &dev->agp->memory, head) {
if ((map->offset >= entry->bound) &&
(map->offset + map->size <= entry->bound + entry->pages * PAGE_SIZE)) {
valid = 1;
break;
}
}
if (!list_empty(&dev->agp->memory) && !valid) {
kfree(map);
return -EPERM;
}
DRM_DEBUG("AGP offset = 0x%08llx, size = 0x%08lx\n",
(unsigned long long)map->offset, map->size);
break;
}
case _DRM_GEM:
DRM_ERROR("tried to addmap GEM object\n");
break;
case _DRM_SCATTER_GATHER:
if (!dev->sg) {
kfree(map);
return -EINVAL;
}
map->offset += (unsigned long)dev->sg->virtual;
break;
case _DRM_CONSISTENT:
/* dma_addr_t is 64bit on i386 with CONFIG_HIGHMEM64G,
* As we're limiting the address to 2^32-1 (or less),
* casting it down to 32 bits is no problem, but we
* need to point to a 64bit variable first. */
dmah = drm_pci_alloc(dev, map->size, map->size);
if (!dmah) {
kfree(map);
return -ENOMEM;
}
map->handle = dmah->vaddr;
map->offset = (unsigned long)dmah->busaddr;
kfree(dmah);
break;
default:
kfree(map);
return -EINVAL;
}
list = kzalloc(sizeof(*list), GFP_KERNEL);
if (!list) {
if (map->type == _DRM_REGISTERS)
iounmap(map->handle);
kfree(map);
return -EINVAL;
}
list->map = map;
mutex_lock(&dev->struct_mutex);
list_add(&list->head, &dev->maplist);
/* Assign a 32-bit handle */
/* We do it here so that dev->struct_mutex protects the increment */
user_token = (map->type == _DRM_SHM) ? (unsigned long)map->handle :
map->offset;
ret = drm_map_handle(dev, &list->hash, user_token, 0,
(map->type == _DRM_SHM));
if (ret) {
if (map->type == _DRM_REGISTERS)
iounmap(map->handle);
kfree(map);
kfree(list);
mutex_unlock(&dev->struct_mutex);
return ret;
}
list->user_token = list->hash.key << PAGE_SHIFT;
mutex_unlock(&dev->struct_mutex);
if (!(map->flags & _DRM_DRIVER))
list->master = dev->primary->master;
*maplist = list;
return 0;
}
int drm_addmap(struct drm_device * dev, resource_size_t offset,
unsigned int size, enum drm_map_type type,
enum drm_map_flags flags, struct drm_local_map ** map_ptr)
{
struct drm_map_list *list;
int rc;
rc = drm_addmap_core(dev, offset, size, type, flags, &list);
if (!rc)
*map_ptr = list->map;
return rc;
}
EXPORT_SYMBOL(drm_addmap);
/**
* Ioctl to specify a range of memory that is available for mapping by a
* non-root process.
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg pointer to a drm_map structure.
* \return zero on success or a negative value on error.
*
*/
int drm_addmap_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_map *map = data;
struct drm_map_list *maplist;
int err;
if (!(capable(CAP_SYS_ADMIN) || map->type == _DRM_AGP || map->type == _DRM_SHM))
return -EPERM;
err = drm_addmap_core(dev, map->offset, map->size, map->type,
map->flags, &maplist);
if (err)
return err;
/* avoid a warning on 64-bit, this casting isn't very nice, but the API is set so too late */
map->handle = (void *)(unsigned long)maplist->user_token;
return 0;
}
/**
* Remove a map private from list and deallocate resources if the mapping
* isn't in use.
*
* Searches the map on drm_device::maplist, removes it from the list, see if
* its being used, and free any associate resource (such as MTRR's) if it's not
* being on use.
*
* \sa drm_addmap
*/
int drm_rmmap_locked(struct drm_device *dev, struct drm_local_map *map)
{
struct drm_map_list *r_list = NULL, *list_t;
drm_dma_handle_t dmah;
int found = 0;
struct drm_master *master;
/* Find the list entry for the map and remove it */
list_for_each_entry_safe(r_list, list_t, &dev->maplist, head) {
if (r_list->map == map) {
master = r_list->master;
list_del(&r_list->head);
drm_ht_remove_key(&dev->map_hash,
r_list->user_token >> PAGE_SHIFT);
kfree(r_list);
found = 1;
break;
}
}
if (!found)
return -EINVAL;
switch (map->type) {
case _DRM_REGISTERS:
iounmap(map->handle);
/* FALLTHROUGH */
case _DRM_FRAME_BUFFER:
if (drm_core_has_MTRR(dev) && map->mtrr >= 0) {
int retcode;
retcode = mtrr_del(map->mtrr, map->offset, map->size);
DRM_DEBUG("mtrr_del=%d\n", retcode);
}
break;
case _DRM_SHM:
vfree(map->handle);
if (master) {
if (dev->sigdata.lock == master->lock.hw_lock)
dev->sigdata.lock = NULL;
master->lock.hw_lock = NULL; /* SHM removed */
master->lock.file_priv = NULL;
wake_up_interruptible_all(&master->lock.lock_queue);
}
break;
case _DRM_AGP:
case _DRM_SCATTER_GATHER:
break;
case _DRM_CONSISTENT:
dmah.vaddr = map->handle;
dmah.busaddr = map->offset;
dmah.size = map->size;
__drm_pci_free(dev, &dmah);
break;
case _DRM_GEM:
DRM_ERROR("tried to rmmap GEM object\n");
break;
}
kfree(map);
return 0;
}
EXPORT_SYMBOL(drm_rmmap_locked);
int drm_rmmap(struct drm_device *dev, struct drm_local_map *map)
{
int ret;
mutex_lock(&dev->struct_mutex);
ret = drm_rmmap_locked(dev, map);
mutex_unlock(&dev->struct_mutex);
return ret;
}
EXPORT_SYMBOL(drm_rmmap);
/* The rmmap ioctl appears to be unnecessary. All mappings are torn down on
* the last close of the device, and this is necessary for cleanup when things
* exit uncleanly. Therefore, having userland manually remove mappings seems
* like a pointless exercise since they're going away anyway.
*
* One use case might be after addmap is allowed for normal users for SHM and
* gets used by drivers that the server doesn't need to care about. This seems
* unlikely.
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg pointer to a struct drm_map structure.
* \return zero on success or a negative value on error.
*/
int drm_rmmap_ioctl(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_map *request = data;
struct drm_local_map *map = NULL;
struct drm_map_list *r_list;
int ret;
mutex_lock(&dev->struct_mutex);
list_for_each_entry(r_list, &dev->maplist, head) {
if (r_list->map &&
r_list->user_token == (unsigned long)request->handle &&
r_list->map->flags & _DRM_REMOVABLE) {
map = r_list->map;
break;
}
}
/* List has wrapped around to the head pointer, or its empty we didn't
* find anything.
*/
if (list_empty(&dev->maplist) || !map) {
mutex_unlock(&dev->struct_mutex);
return -EINVAL;
}
/* Register and framebuffer maps are permanent */
if ((map->type == _DRM_REGISTERS) || (map->type == _DRM_FRAME_BUFFER)) {
mutex_unlock(&dev->struct_mutex);
return 0;
}
ret = drm_rmmap_locked(dev, map);
mutex_unlock(&dev->struct_mutex);
return ret;
}
/**
* Cleanup after an error on one of the addbufs() functions.
*
* \param dev DRM device.
* \param entry buffer entry where the error occurred.
*
* Frees any pages and buffers associated with the given entry.
*/
static void drm_cleanup_buf_error(struct drm_device * dev,
struct drm_buf_entry * entry)
{
int i;
if (entry->seg_count) {
for (i = 0; i < entry->seg_count; i++) {
if (entry->seglist[i]) {
drm_pci_free(dev, entry->seglist[i]);
}
}
kfree(entry->seglist);
entry->seg_count = 0;
}
if (entry->buf_count) {
for (i = 0; i < entry->buf_count; i++) {
kfree(entry->buflist[i].dev_private);
}
kfree(entry->buflist);
entry->buf_count = 0;
}
}
#if __OS_HAS_AGP
/**
* Add AGP buffers for DMA transfers.
*
* \param dev struct drm_device to which the buffers are to be added.
* \param request pointer to a struct drm_buf_desc describing the request.
* \return zero on success or a negative number on failure.
*
* After some sanity checks creates a drm_buf structure for each buffer and
* reallocates the buffer list of the same size order to accommodate the new
* buffers.
*/
int drm_addbufs_agp(struct drm_device * dev, struct drm_buf_desc * request)
{
struct drm_device_dma *dma = dev->dma;
struct drm_buf_entry *entry;
struct drm_agp_mem *agp_entry;
struct drm_buf *buf;
unsigned long offset;
unsigned long agp_offset;
int count;
int order;
int size;
int alignment;
int page_order;
int total;
int byte_count;
int i, valid;
struct drm_buf **temp_buflist;
if (!dma)
return -EINVAL;
count = request->count;
order = drm_order(request->size);
size = 1 << order;
alignment = (request->flags & _DRM_PAGE_ALIGN)
? PAGE_ALIGN(size) : size;
page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
total = PAGE_SIZE << page_order;
byte_count = 0;
agp_offset = dev->agp->base + request->agp_start;
DRM_DEBUG("count: %d\n", count);
DRM_DEBUG("order: %d\n", order);
DRM_DEBUG("size: %d\n", size);
DRM_DEBUG("agp_offset: %lx\n", agp_offset);
DRM_DEBUG("alignment: %d\n", alignment);
DRM_DEBUG("page_order: %d\n", page_order);
DRM_DEBUG("total: %d\n", total);
if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
return -EINVAL;
if (dev->queue_count)
return -EBUSY; /* Not while in use */
/* Make sure buffers are located in AGP memory that we own */
valid = 0;
list_for_each_entry(agp_entry, &dev->agp->memory, head) {
if ((agp_offset >= agp_entry->bound) &&
(agp_offset + total * count <= agp_entry->bound + agp_entry->pages * PAGE_SIZE)) {
valid = 1;
break;
}
}
if (!list_empty(&dev->agp->memory) && !valid) {
DRM_DEBUG("zone invalid\n");
return -EINVAL;
}
spin_lock(&dev->count_lock);
if (dev->buf_use) {
spin_unlock(&dev->count_lock);
return -EBUSY;
}
atomic_inc(&dev->buf_alloc);
spin_unlock(&dev->count_lock);
mutex_lock(&dev->struct_mutex);
entry = &dma->bufs[order];
if (entry->buf_count) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM; /* May only call once for each order */
}
if (count < 0 || count > 4096) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -EINVAL;
}
entry->buflist = kzalloc(count * sizeof(*entry->buflist), GFP_KERNEL);
if (!entry->buflist) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
entry->buf_size = size;
entry->page_order = page_order;
offset = 0;
while (entry->buf_count < count) {
buf = &entry->buflist[entry->buf_count];
buf->idx = dma->buf_count + entry->buf_count;
buf->total = alignment;
buf->order = order;
buf->used = 0;
buf->offset = (dma->byte_count + offset);
buf->bus_address = agp_offset + offset;
buf->address = (void *)(agp_offset + offset);
buf->next = NULL;
buf->waiting = 0;
buf->pending = 0;
init_waitqueue_head(&buf->dma_wait);
buf->file_priv = NULL;
buf->dev_priv_size = dev->driver->dev_priv_size;
buf->dev_private = kzalloc(buf->dev_priv_size, GFP_KERNEL);
if (!buf->dev_private) {
/* Set count correctly so we free the proper amount. */
entry->buf_count = count;
drm_cleanup_buf_error(dev, entry);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
DRM_DEBUG("buffer %d @ %p\n", entry->buf_count, buf->address);
offset += alignment;
entry->buf_count++;
byte_count += PAGE_SIZE << page_order;
}
DRM_DEBUG("byte_count: %d\n", byte_count);
temp_buflist = krealloc(dma->buflist,
(dma->buf_count + entry->buf_count) *
sizeof(*dma->buflist), GFP_KERNEL);
if (!temp_buflist) {
/* Free the entry because it isn't valid */
drm_cleanup_buf_error(dev, entry);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
dma->buflist = temp_buflist;
for (i = 0; i < entry->buf_count; i++) {
dma->buflist[i + dma->buf_count] = &entry->buflist[i];
}
dma->buf_count += entry->buf_count;
dma->seg_count += entry->seg_count;
dma->page_count += byte_count >> PAGE_SHIFT;
dma->byte_count += byte_count;
DRM_DEBUG("dma->buf_count : %d\n", dma->buf_count);
DRM_DEBUG("entry->buf_count : %d\n", entry->buf_count);
mutex_unlock(&dev->struct_mutex);
request->count = entry->buf_count;
request->size = size;
dma->flags = _DRM_DMA_USE_AGP;
atomic_dec(&dev->buf_alloc);
return 0;
}
EXPORT_SYMBOL(drm_addbufs_agp);
#endif /* __OS_HAS_AGP */
int drm_addbufs_pci(struct drm_device * dev, struct drm_buf_desc * request)
{
struct drm_device_dma *dma = dev->dma;
int count;
int order;
int size;
int total;
int page_order;
struct drm_buf_entry *entry;
drm_dma_handle_t *dmah;
struct drm_buf *buf;
int alignment;
unsigned long offset;
int i;
int byte_count;
int page_count;
unsigned long *temp_pagelist;
struct drm_buf **temp_buflist;
if (!drm_core_check_feature(dev, DRIVER_PCI_DMA))
return -EINVAL;
if (!dma)
return -EINVAL;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
count = request->count;
order = drm_order(request->size);
size = 1 << order;
DRM_DEBUG("count=%d, size=%d (%d), order=%d, queue_count=%d\n",
request->count, request->size, size, order, dev->queue_count);
if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
return -EINVAL;
if (dev->queue_count)
return -EBUSY; /* Not while in use */
alignment = (request->flags & _DRM_PAGE_ALIGN)
? PAGE_ALIGN(size) : size;
page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
total = PAGE_SIZE << page_order;
spin_lock(&dev->count_lock);
if (dev->buf_use) {
spin_unlock(&dev->count_lock);
return -EBUSY;
}
atomic_inc(&dev->buf_alloc);
spin_unlock(&dev->count_lock);
mutex_lock(&dev->struct_mutex);
entry = &dma->bufs[order];
if (entry->buf_count) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM; /* May only call once for each order */
}
if (count < 0 || count > 4096) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -EINVAL;
}
entry->buflist = kzalloc(count * sizeof(*entry->buflist), GFP_KERNEL);
if (!entry->buflist) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
entry->seglist = kzalloc(count * sizeof(*entry->seglist), GFP_KERNEL);
if (!entry->seglist) {
kfree(entry->buflist);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
/* Keep the original pagelist until we know all the allocations
* have succeeded
*/
temp_pagelist = kmalloc((dma->page_count + (count << page_order)) *
sizeof(*dma->pagelist), GFP_KERNEL);
if (!temp_pagelist) {
kfree(entry->buflist);
kfree(entry->seglist);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
memcpy(temp_pagelist,
dma->pagelist, dma->page_count * sizeof(*dma->pagelist));
DRM_DEBUG("pagelist: %d entries\n",
dma->page_count + (count << page_order));
entry->buf_size = size;
entry->page_order = page_order;
byte_count = 0;
page_count = 0;
while (entry->buf_count < count) {
dmah = drm_pci_alloc(dev, PAGE_SIZE << page_order, 0x1000);
if (!dmah) {
/* Set count correctly so we free the proper amount. */
entry->buf_count = count;
entry->seg_count = count;
drm_cleanup_buf_error(dev, entry);
kfree(temp_pagelist);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
entry->seglist[entry->seg_count++] = dmah;
for (i = 0; i < (1 << page_order); i++) {
DRM_DEBUG("page %d @ 0x%08lx\n",
dma->page_count + page_count,
(unsigned long)dmah->vaddr + PAGE_SIZE * i);
temp_pagelist[dma->page_count + page_count++]
= (unsigned long)dmah->vaddr + PAGE_SIZE * i;
}
for (offset = 0;
offset + size <= total && entry->buf_count < count;
offset += alignment, ++entry->buf_count) {
buf = &entry->buflist[entry->buf_count];
buf->idx = dma->buf_count + entry->buf_count;
buf->total = alignment;
buf->order = order;
buf->used = 0;
buf->offset = (dma->byte_count + byte_count + offset);
buf->address = (void *)(dmah->vaddr + offset);
buf->bus_address = dmah->busaddr + offset;
buf->next = NULL;
buf->waiting = 0;
buf->pending = 0;
init_waitqueue_head(&buf->dma_wait);
buf->file_priv = NULL;
buf->dev_priv_size = dev->driver->dev_priv_size;
buf->dev_private = kzalloc(buf->dev_priv_size,
GFP_KERNEL);
if (!buf->dev_private) {
/* Set count correctly so we free the proper amount. */
entry->buf_count = count;
entry->seg_count = count;
drm_cleanup_buf_error(dev, entry);
kfree(temp_pagelist);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
DRM_DEBUG("buffer %d @ %p\n",
entry->buf_count, buf->address);
}
byte_count += PAGE_SIZE << page_order;
}
temp_buflist = krealloc(dma->buflist,
(dma->buf_count + entry->buf_count) *
sizeof(*dma->buflist), GFP_KERNEL);
if (!temp_buflist) {
/* Free the entry because it isn't valid */
drm_cleanup_buf_error(dev, entry);
kfree(temp_pagelist);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
dma->buflist = temp_buflist;
for (i = 0; i < entry->buf_count; i++) {
dma->buflist[i + dma->buf_count] = &entry->buflist[i];
}
/* No allocations failed, so now we can replace the original pagelist
* with the new one.
*/
if (dma->page_count) {
kfree(dma->pagelist);
}
dma->pagelist = temp_pagelist;
dma->buf_count += entry->buf_count;
dma->seg_count += entry->seg_count;
dma->page_count += entry->seg_count << page_order;
dma->byte_count += PAGE_SIZE * (entry->seg_count << page_order);
mutex_unlock(&dev->struct_mutex);
request->count = entry->buf_count;
request->size = size;
if (request->flags & _DRM_PCI_BUFFER_RO)
dma->flags = _DRM_DMA_USE_PCI_RO;
atomic_dec(&dev->buf_alloc);
return 0;
}
EXPORT_SYMBOL(drm_addbufs_pci);
static int drm_addbufs_sg(struct drm_device * dev, struct drm_buf_desc * request)
{
struct drm_device_dma *dma = dev->dma;
struct drm_buf_entry *entry;
struct drm_buf *buf;
unsigned long offset;
unsigned long agp_offset;
int count;
int order;
int size;
int alignment;
int page_order;
int total;
int byte_count;
int i;
struct drm_buf **temp_buflist;
if (!drm_core_check_feature(dev, DRIVER_SG))
return -EINVAL;
if (!dma)
return -EINVAL;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
count = request->count;
order = drm_order(request->size);
size = 1 << order;
alignment = (request->flags & _DRM_PAGE_ALIGN)
? PAGE_ALIGN(size) : size;
page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
total = PAGE_SIZE << page_order;
byte_count = 0;
agp_offset = request->agp_start;
DRM_DEBUG("count: %d\n", count);
DRM_DEBUG("order: %d\n", order);
DRM_DEBUG("size: %d\n", size);
DRM_DEBUG("agp_offset: %lu\n", agp_offset);
DRM_DEBUG("alignment: %d\n", alignment);
DRM_DEBUG("page_order: %d\n", page_order);
DRM_DEBUG("total: %d\n", total);
if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
return -EINVAL;
if (dev->queue_count)
return -EBUSY; /* Not while in use */
spin_lock(&dev->count_lock);
if (dev->buf_use) {
spin_unlock(&dev->count_lock);
return -EBUSY;
}
atomic_inc(&dev->buf_alloc);
spin_unlock(&dev->count_lock);
mutex_lock(&dev->struct_mutex);
entry = &dma->bufs[order];
if (entry->buf_count) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM; /* May only call once for each order */
}
if (count < 0 || count > 4096) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -EINVAL;
}
entry->buflist = kzalloc(count * sizeof(*entry->buflist),
GFP_KERNEL);
if (!entry->buflist) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
entry->buf_size = size;
entry->page_order = page_order;
offset = 0;
while (entry->buf_count < count) {
buf = &entry->buflist[entry->buf_count];
buf->idx = dma->buf_count + entry->buf_count;
buf->total = alignment;
buf->order = order;
buf->used = 0;
buf->offset = (dma->byte_count + offset);
buf->bus_address = agp_offset + offset;
buf->address = (void *)(agp_offset + offset
+ (unsigned long)dev->sg->virtual);
buf->next = NULL;
buf->waiting = 0;
buf->pending = 0;
init_waitqueue_head(&buf->dma_wait);
buf->file_priv = NULL;
buf->dev_priv_size = dev->driver->dev_priv_size;
buf->dev_private = kzalloc(buf->dev_priv_size, GFP_KERNEL);
if (!buf->dev_private) {
/* Set count correctly so we free the proper amount. */
entry->buf_count = count;
drm_cleanup_buf_error(dev, entry);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
DRM_DEBUG("buffer %d @ %p\n", entry->buf_count, buf->address);
offset += alignment;
entry->buf_count++;
byte_count += PAGE_SIZE << page_order;
}
DRM_DEBUG("byte_count: %d\n", byte_count);
temp_buflist = krealloc(dma->buflist,
(dma->buf_count + entry->buf_count) *
sizeof(*dma->buflist), GFP_KERNEL);
if (!temp_buflist) {
/* Free the entry because it isn't valid */
drm_cleanup_buf_error(dev, entry);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
dma->buflist = temp_buflist;
for (i = 0; i < entry->buf_count; i++) {
dma->buflist[i + dma->buf_count] = &entry->buflist[i];
}
dma->buf_count += entry->buf_count;
dma->seg_count += entry->seg_count;
dma->page_count += byte_count >> PAGE_SHIFT;
dma->byte_count += byte_count;
DRM_DEBUG("dma->buf_count : %d\n", dma->buf_count);
DRM_DEBUG("entry->buf_count : %d\n", entry->buf_count);
mutex_unlock(&dev->struct_mutex);
request->count = entry->buf_count;
request->size = size;
dma->flags = _DRM_DMA_USE_SG;
atomic_dec(&dev->buf_alloc);
return 0;
}
static int drm_addbufs_fb(struct drm_device * dev, struct drm_buf_desc * request)
{
struct drm_device_dma *dma = dev->dma;
struct drm_buf_entry *entry;
struct drm_buf *buf;
unsigned long offset;
unsigned long agp_offset;
int count;
int order;
int size;
int alignment;
int page_order;
int total;
int byte_count;
int i;
struct drm_buf **temp_buflist;
if (!drm_core_check_feature(dev, DRIVER_FB_DMA))
return -EINVAL;
if (!dma)
return -EINVAL;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
count = request->count;
order = drm_order(request->size);
size = 1 << order;
alignment = (request->flags & _DRM_PAGE_ALIGN)
? PAGE_ALIGN(size) : size;
page_order = order - PAGE_SHIFT > 0 ? order - PAGE_SHIFT : 0;
total = PAGE_SIZE << page_order;
byte_count = 0;
agp_offset = request->agp_start;
DRM_DEBUG("count: %d\n", count);
DRM_DEBUG("order: %d\n", order);
DRM_DEBUG("size: %d\n", size);
DRM_DEBUG("agp_offset: %lu\n", agp_offset);
DRM_DEBUG("alignment: %d\n", alignment);
DRM_DEBUG("page_order: %d\n", page_order);
DRM_DEBUG("total: %d\n", total);
if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
return -EINVAL;
if (dev->queue_count)
return -EBUSY; /* Not while in use */
spin_lock(&dev->count_lock);
if (dev->buf_use) {
spin_unlock(&dev->count_lock);
return -EBUSY;
}
atomic_inc(&dev->buf_alloc);
spin_unlock(&dev->count_lock);
mutex_lock(&dev->struct_mutex);
entry = &dma->bufs[order];
if (entry->buf_count) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM; /* May only call once for each order */
}
if (count < 0 || count > 4096) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -EINVAL;
}
entry->buflist = kzalloc(count * sizeof(*entry->buflist),
GFP_KERNEL);
if (!entry->buflist) {
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
entry->buf_size = size;
entry->page_order = page_order;
offset = 0;
while (entry->buf_count < count) {
buf = &entry->buflist[entry->buf_count];
buf->idx = dma->buf_count + entry->buf_count;
buf->total = alignment;
buf->order = order;
buf->used = 0;
buf->offset = (dma->byte_count + offset);
buf->bus_address = agp_offset + offset;
buf->address = (void *)(agp_offset + offset);
buf->next = NULL;
buf->waiting = 0;
buf->pending = 0;
init_waitqueue_head(&buf->dma_wait);
buf->file_priv = NULL;
buf->dev_priv_size = dev->driver->dev_priv_size;
buf->dev_private = kzalloc(buf->dev_priv_size, GFP_KERNEL);
if (!buf->dev_private) {
/* Set count correctly so we free the proper amount. */
entry->buf_count = count;
drm_cleanup_buf_error(dev, entry);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
DRM_DEBUG("buffer %d @ %p\n", entry->buf_count, buf->address);
offset += alignment;
entry->buf_count++;
byte_count += PAGE_SIZE << page_order;
}
DRM_DEBUG("byte_count: %d\n", byte_count);
temp_buflist = krealloc(dma->buflist,
(dma->buf_count + entry->buf_count) *
sizeof(*dma->buflist), GFP_KERNEL);
if (!temp_buflist) {
/* Free the entry because it isn't valid */
drm_cleanup_buf_error(dev, entry);
mutex_unlock(&dev->struct_mutex);
atomic_dec(&dev->buf_alloc);
return -ENOMEM;
}
dma->buflist = temp_buflist;
for (i = 0; i < entry->buf_count; i++) {
dma->buflist[i + dma->buf_count] = &entry->buflist[i];
}
dma->buf_count += entry->buf_count;
dma->seg_count += entry->seg_count;
dma->page_count += byte_count >> PAGE_SHIFT;
dma->byte_count += byte_count;
DRM_DEBUG("dma->buf_count : %d\n", dma->buf_count);
DRM_DEBUG("entry->buf_count : %d\n", entry->buf_count);
mutex_unlock(&dev->struct_mutex);
request->count = entry->buf_count;
request->size = size;
dma->flags = _DRM_DMA_USE_FB;
atomic_dec(&dev->buf_alloc);
return 0;
}
/**
* Add buffers for DMA transfers (ioctl).
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg pointer to a struct drm_buf_desc request.
* \return zero on success or a negative number on failure.
*
* According with the memory type specified in drm_buf_desc::flags and the
* build options, it dispatches the call either to addbufs_agp(),
* addbufs_sg() or addbufs_pci() for AGP, scatter-gather or consistent
* PCI memory respectively.
*/
int drm_addbufs(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_buf_desc *request = data;
int ret;
if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
return -EINVAL;
#if __OS_HAS_AGP
if (request->flags & _DRM_AGP_BUFFER)
ret = drm_addbufs_agp(dev, request);
else
#endif
if (request->flags & _DRM_SG_BUFFER)
ret = drm_addbufs_sg(dev, request);
else if (request->flags & _DRM_FB_BUFFER)
ret = drm_addbufs_fb(dev, request);
else
ret = drm_addbufs_pci(dev, request);
return ret;
}
/**
* Get information about the buffer mappings.
*
* This was originally mean for debugging purposes, or by a sophisticated
* client library to determine how best to use the available buffers (e.g.,
* large buffers can be used for image transfer).
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg pointer to a drm_buf_info structure.
* \return zero on success or a negative number on failure.
*
* Increments drm_device::buf_use while holding the drm_device::count_lock
* lock, preventing of allocating more buffers after this call. Information
* about each requested buffer is then copied into user space.
*/
int drm_infobufs(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_device_dma *dma = dev->dma;
struct drm_buf_info *request = data;
int i;
int count;
if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
return -EINVAL;
if (!dma)
return -EINVAL;
spin_lock(&dev->count_lock);
if (atomic_read(&dev->buf_alloc)) {
spin_unlock(&dev->count_lock);
return -EBUSY;
}
++dev->buf_use; /* Can't allocate more after this call */
spin_unlock(&dev->count_lock);
for (i = 0, count = 0; i < DRM_MAX_ORDER + 1; i++) {
if (dma->bufs[i].buf_count)
++count;
}
DRM_DEBUG("count = %d\n", count);
if (request->count >= count) {
for (i = 0, count = 0; i < DRM_MAX_ORDER + 1; i++) {
if (dma->bufs[i].buf_count) {
struct drm_buf_desc __user *to =
&request->list[count];
struct drm_buf_entry *from = &dma->bufs[i];
struct drm_freelist *list = &dma->bufs[i].freelist;
if (copy_to_user(&to->count,
&from->buf_count,
sizeof(from->buf_count)) ||
copy_to_user(&to->size,
&from->buf_size,
sizeof(from->buf_size)) ||
copy_to_user(&to->low_mark,
&list->low_mark,
sizeof(list->low_mark)) ||
copy_to_user(&to->high_mark,
&list->high_mark,
sizeof(list->high_mark)))
return -EFAULT;
DRM_DEBUG("%d %d %d %d %d\n",
i,
dma->bufs[i].buf_count,
dma->bufs[i].buf_size,
dma->bufs[i].freelist.low_mark,
dma->bufs[i].freelist.high_mark);
++count;
}
}
}
request->count = count;
return 0;
}
/**
* Specifies a low and high water mark for buffer allocation
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg a pointer to a drm_buf_desc structure.
* \return zero on success or a negative number on failure.
*
* Verifies that the size order is bounded between the admissible orders and
* updates the respective drm_device_dma::bufs entry low and high water mark.
*
* \note This ioctl is deprecated and mostly never used.
*/
int drm_markbufs(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_device_dma *dma = dev->dma;
struct drm_buf_desc *request = data;
int order;
struct drm_buf_entry *entry;
if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
return -EINVAL;
if (!dma)
return -EINVAL;
DRM_DEBUG("%d, %d, %d\n",
request->size, request->low_mark, request->high_mark);
order = drm_order(request->size);
if (order < DRM_MIN_ORDER || order > DRM_MAX_ORDER)
return -EINVAL;
entry = &dma->bufs[order];
if (request->low_mark < 0 || request->low_mark > entry->buf_count)
return -EINVAL;
if (request->high_mark < 0 || request->high_mark > entry->buf_count)
return -EINVAL;
entry->freelist.low_mark = request->low_mark;
entry->freelist.high_mark = request->high_mark;
return 0;
}
/**
* Unreserve the buffers in list, previously reserved using drmDMA.
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg pointer to a drm_buf_free structure.
* \return zero on success or a negative number on failure.
*
* Calls free_buffer() for each used buffer.
* This function is primarily used for debugging.
*/
int drm_freebufs(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_device_dma *dma = dev->dma;
struct drm_buf_free *request = data;
int i;
int idx;
struct drm_buf *buf;
if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
return -EINVAL;
if (!dma)
return -EINVAL;
DRM_DEBUG("%d\n", request->count);
for (i = 0; i < request->count; i++) {
if (copy_from_user(&idx, &request->list[i], sizeof(idx)))
return -EFAULT;
if (idx < 0 || idx >= dma->buf_count) {
DRM_ERROR("Index %d (of %d max)\n",
idx, dma->buf_count - 1);
return -EINVAL;
}
buf = dma->buflist[idx];
if (buf->file_priv != file_priv) {
DRM_ERROR("Process %d freeing buffer not owned\n",
task_pid_nr(current));
return -EINVAL;
}
drm_free_buffer(dev, buf);
}
return 0;
}
/**
* Maps all of the DMA buffers into client-virtual space (ioctl).
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg pointer to a drm_buf_map structure.
* \return zero on success or a negative number on failure.
*
* Maps the AGP, SG or PCI buffer region with vm_mmap(), and copies information
* about each buffer into user space. For PCI buffers, it calls vm_mmap() with
* offset equal to 0, which drm_mmap() interpretes as PCI buffers and calls
* drm_mmap_dma().
*/
int drm_mapbufs(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_device_dma *dma = dev->dma;
int retcode = 0;
const int zero = 0;
unsigned long virtual;
unsigned long address;
struct drm_buf_map *request = data;
int i;
if (!drm_core_check_feature(dev, DRIVER_HAVE_DMA))
return -EINVAL;
if (!dma)
return -EINVAL;
spin_lock(&dev->count_lock);
if (atomic_read(&dev->buf_alloc)) {
spin_unlock(&dev->count_lock);
return -EBUSY;
}
dev->buf_use++; /* Can't allocate more after this call */
spin_unlock(&dev->count_lock);
if (request->count >= dma->buf_count) {
if ((drm_core_has_AGP(dev) && (dma->flags & _DRM_DMA_USE_AGP))
|| (drm_core_check_feature(dev, DRIVER_SG)
&& (dma->flags & _DRM_DMA_USE_SG))
|| (drm_core_check_feature(dev, DRIVER_FB_DMA)
&& (dma->flags & _DRM_DMA_USE_FB))) {
struct drm_local_map *map = dev->agp_buffer_map;
unsigned long token = dev->agp_buffer_token;
if (!map) {
retcode = -EINVAL;
goto done;
}
virtual = vm_mmap(file_priv->filp, 0, map->size,
PROT_READ | PROT_WRITE,
MAP_SHARED,
token);
} else {
virtual = vm_mmap(file_priv->filp, 0, dma->byte_count,
PROT_READ | PROT_WRITE,
MAP_SHARED, 0);
}
if (virtual > -1024UL) {
/* Real error */
retcode = (signed long)virtual;
goto done;
}
request->virtual = (void __user *)virtual;
for (i = 0; i < dma->buf_count; i++) {
if (copy_to_user(&request->list[i].idx,
&dma->buflist[i]->idx,
sizeof(request->list[0].idx))) {
retcode = -EFAULT;
goto done;
}
if (copy_to_user(&request->list[i].total,
&dma->buflist[i]->total,
sizeof(request->list[0].total))) {
retcode = -EFAULT;
goto done;
}
if (copy_to_user(&request->list[i].used,
&zero, sizeof(zero))) {
retcode = -EFAULT;
goto done;
}
address = virtual + dma->buflist[i]->offset; /* *** */
if (copy_to_user(&request->list[i].address,
&address, sizeof(address))) {
retcode = -EFAULT;
goto done;
}
}
}
done:
request->count = dma->buf_count;
DRM_DEBUG("%d buffers, retcode = %d\n", request->count, retcode);
return retcode;
}
/**
* Compute size order. Returns the exponent of the smaller power of two which
* is greater or equal to given number.
*
* \param size size.
* \return order.
*
* \todo Can be made faster.
*/
int drm_order(unsigned long size)
{
int order;
unsigned long tmp;
for (order = 0, tmp = size >> 1; tmp; tmp >>= 1, order++) ;
if (size & (size - 1))
++order;
return order;
}
EXPORT_SYMBOL(drm_order);
| gpl-2.0 |
Monadiac/cm_kernel_samsung_hlte | arch/powerpc/oprofile/op_model_cell.c | 6877 | 50568 | /*
* Cell Broadband Engine OProfile Support
*
* (C) Copyright IBM Corporation 2006
*
* Author: David Erb (djerb@us.ibm.com)
* Modifications:
* Carl Love <carll@us.ibm.com>
* Maynard Johnson <maynardj@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/cpufreq.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/kthread.h>
#include <linux/oprofile.h>
#include <linux/percpu.h>
#include <linux/smp.h>
#include <linux/spinlock.h>
#include <linux/timer.h>
#include <asm/cell-pmu.h>
#include <asm/cputable.h>
#include <asm/firmware.h>
#include <asm/io.h>
#include <asm/oprofile_impl.h>
#include <asm/processor.h>
#include <asm/prom.h>
#include <asm/ptrace.h>
#include <asm/reg.h>
#include <asm/rtas.h>
#include <asm/cell-regs.h>
#include "../platforms/cell/interrupt.h"
#include "cell/pr_util.h"
#define PPU_PROFILING 0
#define SPU_PROFILING_CYCLES 1
#define SPU_PROFILING_EVENTS 2
#define SPU_EVENT_NUM_START 4100
#define SPU_EVENT_NUM_STOP 4399
#define SPU_PROFILE_EVENT_ADDR 4363 /* spu, address trace, decimal */
#define SPU_PROFILE_EVENT_ADDR_MASK_A 0x146 /* sub unit set to zero */
#define SPU_PROFILE_EVENT_ADDR_MASK_B 0x186 /* sub unit set to zero */
#define NUM_SPUS_PER_NODE 8
#define SPU_CYCLES_EVENT_NUM 2 /* event number for SPU_CYCLES */
#define PPU_CYCLES_EVENT_NUM 1 /* event number for CYCLES */
#define PPU_CYCLES_GRP_NUM 1 /* special group number for identifying
* PPU_CYCLES event
*/
#define CBE_COUNT_ALL_CYCLES 0x42800000 /* PPU cycle event specifier */
#define NUM_THREADS 2 /* number of physical threads in
* physical processor
*/
#define NUM_DEBUG_BUS_WORDS 4
#define NUM_INPUT_BUS_WORDS 2
#define MAX_SPU_COUNT 0xFFFFFF /* maximum 24 bit LFSR value */
/* Minimum HW interval timer setting to send value to trace buffer is 10 cycle.
* To configure counter to send value every N cycles set counter to
* 2^32 - 1 - N.
*/
#define NUM_INTERVAL_CYC 0xFFFFFFFF - 10
/*
* spu_cycle_reset is the number of cycles between samples.
* This variable is used for SPU profiling and should ONLY be set
* at the beginning of cell_reg_setup; otherwise, it's read-only.
*/
static unsigned int spu_cycle_reset;
static unsigned int profiling_mode;
static int spu_evnt_phys_spu_indx;
struct pmc_cntrl_data {
unsigned long vcntr;
unsigned long evnts;
unsigned long masks;
unsigned long enabled;
};
/*
* ibm,cbe-perftools rtas parameters
*/
struct pm_signal {
u16 cpu; /* Processor to modify */
u16 sub_unit; /* hw subunit this applies to (if applicable)*/
short int signal_group; /* Signal Group to Enable/Disable */
u8 bus_word; /* Enable/Disable on this Trace/Trigger/Event
* Bus Word(s) (bitmask)
*/
u8 bit; /* Trigger/Event bit (if applicable) */
};
/*
* rtas call arguments
*/
enum {
SUBFUNC_RESET = 1,
SUBFUNC_ACTIVATE = 2,
SUBFUNC_DEACTIVATE = 3,
PASSTHRU_IGNORE = 0,
PASSTHRU_ENABLE = 1,
PASSTHRU_DISABLE = 2,
};
struct pm_cntrl {
u16 enable;
u16 stop_at_max;
u16 trace_mode;
u16 freeze;
u16 count_mode;
u16 spu_addr_trace;
u8 trace_buf_ovflw;
};
static struct {
u32 group_control;
u32 debug_bus_control;
struct pm_cntrl pm_cntrl;
u32 pm07_cntrl[NR_PHYS_CTRS];
} pm_regs;
#define GET_SUB_UNIT(x) ((x & 0x0000f000) >> 12)
#define GET_BUS_WORD(x) ((x & 0x000000f0) >> 4)
#define GET_BUS_TYPE(x) ((x & 0x00000300) >> 8)
#define GET_POLARITY(x) ((x & 0x00000002) >> 1)
#define GET_COUNT_CYCLES(x) (x & 0x00000001)
#define GET_INPUT_CONTROL(x) ((x & 0x00000004) >> 2)
static DEFINE_PER_CPU(unsigned long[NR_PHYS_CTRS], pmc_values);
static unsigned long spu_pm_cnt[MAX_NUMNODES * NUM_SPUS_PER_NODE];
static struct pmc_cntrl_data pmc_cntrl[NUM_THREADS][NR_PHYS_CTRS];
/*
* The CELL profiling code makes rtas calls to setup the debug bus to
* route the performance signals. Additionally, SPU profiling requires
* a second rtas call to setup the hardware to capture the SPU PCs.
* The EIO error value is returned if the token lookups or the rtas
* call fail. The EIO error number is the best choice of the existing
* error numbers. The probability of rtas related error is very low. But
* by returning EIO and printing additional information to dmsg the user
* will know that OProfile did not start and dmesg will tell them why.
* OProfile does not support returning errors on Stop. Not a huge issue
* since failure to reset the debug bus or stop the SPU PC collection is
* not a fatel issue. Chances are if the Stop failed, Start doesn't work
* either.
*/
/*
* Interpetation of hdw_thread:
* 0 - even virtual cpus 0, 2, 4,...
* 1 - odd virtual cpus 1, 3, 5, ...
*
* FIXME: this is strictly wrong, we need to clean this up in a number
* of places. It works for now. -arnd
*/
static u32 hdw_thread;
static u32 virt_cntr_inter_mask;
static struct timer_list timer_virt_cntr;
static struct timer_list timer_spu_event_swap;
/*
* pm_signal needs to be global since it is initialized in
* cell_reg_setup at the time when the necessary information
* is available.
*/
static struct pm_signal pm_signal[NR_PHYS_CTRS];
static int pm_rtas_token; /* token for debug bus setup call */
static int spu_rtas_token; /* token for SPU cycle profiling */
static u32 reset_value[NR_PHYS_CTRS];
static int num_counters;
static int oprofile_running;
static DEFINE_SPINLOCK(cntr_lock);
static u32 ctr_enabled;
static unsigned char input_bus[NUM_INPUT_BUS_WORDS];
/*
* Firmware interface functions
*/
static int
rtas_ibm_cbe_perftools(int subfunc, int passthru,
void *address, unsigned long length)
{
u64 paddr = __pa(address);
return rtas_call(pm_rtas_token, 5, 1, NULL, subfunc,
passthru, paddr >> 32, paddr & 0xffffffff, length);
}
static void pm_rtas_reset_signals(u32 node)
{
int ret;
struct pm_signal pm_signal_local;
/*
* The debug bus is being set to the passthru disable state.
* However, the FW still expects atleast one legal signal routing
* entry or it will return an error on the arguments. If we don't
* supply a valid entry, we must ignore all return values. Ignoring
* all return values means we might miss an error we should be
* concerned about.
*/
/* fw expects physical cpu #. */
pm_signal_local.cpu = node;
pm_signal_local.signal_group = 21;
pm_signal_local.bus_word = 1;
pm_signal_local.sub_unit = 0;
pm_signal_local.bit = 0;
ret = rtas_ibm_cbe_perftools(SUBFUNC_RESET, PASSTHRU_DISABLE,
&pm_signal_local,
sizeof(struct pm_signal));
if (unlikely(ret))
/*
* Not a fatal error. For Oprofile stop, the oprofile
* functions do not support returning an error for
* failure to stop OProfile.
*/
printk(KERN_WARNING "%s: rtas returned: %d\n",
__func__, ret);
}
static int pm_rtas_activate_signals(u32 node, u32 count)
{
int ret;
int i, j;
struct pm_signal pm_signal_local[NR_PHYS_CTRS];
/*
* There is no debug setup required for the cycles event.
* Note that only events in the same group can be used.
* Otherwise, there will be conflicts in correctly routing
* the signals on the debug bus. It is the responsibility
* of the OProfile user tool to check the events are in
* the same group.
*/
i = 0;
for (j = 0; j < count; j++) {
if (pm_signal[j].signal_group != PPU_CYCLES_GRP_NUM) {
/* fw expects physical cpu # */
pm_signal_local[i].cpu = node;
pm_signal_local[i].signal_group
= pm_signal[j].signal_group;
pm_signal_local[i].bus_word = pm_signal[j].bus_word;
pm_signal_local[i].sub_unit = pm_signal[j].sub_unit;
pm_signal_local[i].bit = pm_signal[j].bit;
i++;
}
}
if (i != 0) {
ret = rtas_ibm_cbe_perftools(SUBFUNC_ACTIVATE, PASSTHRU_ENABLE,
pm_signal_local,
i * sizeof(struct pm_signal));
if (unlikely(ret)) {
printk(KERN_WARNING "%s: rtas returned: %d\n",
__func__, ret);
return -EIO;
}
}
return 0;
}
/*
* PM Signal functions
*/
static void set_pm_event(u32 ctr, int event, u32 unit_mask)
{
struct pm_signal *p;
u32 signal_bit;
u32 bus_word, bus_type, count_cycles, polarity, input_control;
int j, i;
if (event == PPU_CYCLES_EVENT_NUM) {
/* Special Event: Count all cpu cycles */
pm_regs.pm07_cntrl[ctr] = CBE_COUNT_ALL_CYCLES;
p = &(pm_signal[ctr]);
p->signal_group = PPU_CYCLES_GRP_NUM;
p->bus_word = 1;
p->sub_unit = 0;
p->bit = 0;
goto out;
} else {
pm_regs.pm07_cntrl[ctr] = 0;
}
bus_word = GET_BUS_WORD(unit_mask);
bus_type = GET_BUS_TYPE(unit_mask);
count_cycles = GET_COUNT_CYCLES(unit_mask);
polarity = GET_POLARITY(unit_mask);
input_control = GET_INPUT_CONTROL(unit_mask);
signal_bit = (event % 100);
p = &(pm_signal[ctr]);
p->signal_group = event / 100;
p->bus_word = bus_word;
p->sub_unit = GET_SUB_UNIT(unit_mask);
pm_regs.pm07_cntrl[ctr] = 0;
pm_regs.pm07_cntrl[ctr] |= PM07_CTR_COUNT_CYCLES(count_cycles);
pm_regs.pm07_cntrl[ctr] |= PM07_CTR_POLARITY(polarity);
pm_regs.pm07_cntrl[ctr] |= PM07_CTR_INPUT_CONTROL(input_control);
/*
* Some of the islands signal selection is based on 64 bit words.
* The debug bus words are 32 bits, the input words to the performance
* counters are defined as 32 bits. Need to convert the 64 bit island
* specification to the appropriate 32 input bit and bus word for the
* performance counter event selection. See the CELL Performance
* monitoring signals manual and the Perf cntr hardware descriptions
* for the details.
*/
if (input_control == 0) {
if (signal_bit > 31) {
signal_bit -= 32;
if (bus_word == 0x3)
bus_word = 0x2;
else if (bus_word == 0xc)
bus_word = 0x8;
}
if ((bus_type == 0) && p->signal_group >= 60)
bus_type = 2;
if ((bus_type == 1) && p->signal_group >= 50)
bus_type = 0;
pm_regs.pm07_cntrl[ctr] |= PM07_CTR_INPUT_MUX(signal_bit);
} else {
pm_regs.pm07_cntrl[ctr] = 0;
p->bit = signal_bit;
}
for (i = 0; i < NUM_DEBUG_BUS_WORDS; i++) {
if (bus_word & (1 << i)) {
pm_regs.debug_bus_control |=
(bus_type << (30 - (2 * i)));
for (j = 0; j < NUM_INPUT_BUS_WORDS; j++) {
if (input_bus[j] == 0xff) {
input_bus[j] = i;
pm_regs.group_control |=
(i << (30 - (2 * j)));
break;
}
}
}
}
out:
;
}
static void write_pm_cntrl(int cpu)
{
/*
* Oprofile will use 32 bit counters, set bits 7:10 to 0
* pmregs.pm_cntrl is a global
*/
u32 val = 0;
if (pm_regs.pm_cntrl.enable == 1)
val |= CBE_PM_ENABLE_PERF_MON;
if (pm_regs.pm_cntrl.stop_at_max == 1)
val |= CBE_PM_STOP_AT_MAX;
if (pm_regs.pm_cntrl.trace_mode != 0)
val |= CBE_PM_TRACE_MODE_SET(pm_regs.pm_cntrl.trace_mode);
if (pm_regs.pm_cntrl.trace_buf_ovflw == 1)
val |= CBE_PM_TRACE_BUF_OVFLW(pm_regs.pm_cntrl.trace_buf_ovflw);
if (pm_regs.pm_cntrl.freeze == 1)
val |= CBE_PM_FREEZE_ALL_CTRS;
val |= CBE_PM_SPU_ADDR_TRACE_SET(pm_regs.pm_cntrl.spu_addr_trace);
/*
* Routine set_count_mode must be called previously to set
* the count mode based on the user selection of user and kernel.
*/
val |= CBE_PM_COUNT_MODE_SET(pm_regs.pm_cntrl.count_mode);
cbe_write_pm(cpu, pm_control, val);
}
static inline void
set_count_mode(u32 kernel, u32 user)
{
/*
* The user must specify user and kernel if they want them. If
* neither is specified, OProfile will count in hypervisor mode.
* pm_regs.pm_cntrl is a global
*/
if (kernel) {
if (user)
pm_regs.pm_cntrl.count_mode = CBE_COUNT_ALL_MODES;
else
pm_regs.pm_cntrl.count_mode =
CBE_COUNT_SUPERVISOR_MODE;
} else {
if (user)
pm_regs.pm_cntrl.count_mode = CBE_COUNT_PROBLEM_MODE;
else
pm_regs.pm_cntrl.count_mode =
CBE_COUNT_HYPERVISOR_MODE;
}
}
static inline void enable_ctr(u32 cpu, u32 ctr, u32 *pm07_cntrl)
{
pm07_cntrl[ctr] |= CBE_PM_CTR_ENABLE;
cbe_write_pm07_control(cpu, ctr, pm07_cntrl[ctr]);
}
/*
* Oprofile is expected to collect data on all CPUs simultaneously.
* However, there is one set of performance counters per node. There are
* two hardware threads or virtual CPUs on each node. Hence, OProfile must
* multiplex in time the performance counter collection on the two virtual
* CPUs. The multiplexing of the performance counters is done by this
* virtual counter routine.
*
* The pmc_values used below is defined as 'per-cpu' but its use is
* more akin to 'per-node'. We need to store two sets of counter
* values per node -- one for the previous run and one for the next.
* The per-cpu[NR_PHYS_CTRS] gives us the storage we need. Each odd/even
* pair of per-cpu arrays is used for storing the previous and next
* pmc values for a given node.
* NOTE: We use the per-cpu variable to improve cache performance.
*
* This routine will alternate loading the virtual counters for
* virtual CPUs
*/
static void cell_virtual_cntr(unsigned long data)
{
int i, prev_hdw_thread, next_hdw_thread;
u32 cpu;
unsigned long flags;
/*
* Make sure that the interrupt_hander and the virt counter are
* not both playing with the counters on the same node.
*/
spin_lock_irqsave(&cntr_lock, flags);
prev_hdw_thread = hdw_thread;
/* switch the cpu handling the interrupts */
hdw_thread = 1 ^ hdw_thread;
next_hdw_thread = hdw_thread;
pm_regs.group_control = 0;
pm_regs.debug_bus_control = 0;
for (i = 0; i < NUM_INPUT_BUS_WORDS; i++)
input_bus[i] = 0xff;
/*
* There are some per thread events. Must do the
* set event, for the thread that is being started
*/
for (i = 0; i < num_counters; i++)
set_pm_event(i,
pmc_cntrl[next_hdw_thread][i].evnts,
pmc_cntrl[next_hdw_thread][i].masks);
/*
* The following is done only once per each node, but
* we need cpu #, not node #, to pass to the cbe_xxx functions.
*/
for_each_online_cpu(cpu) {
if (cbe_get_hw_thread_id(cpu))
continue;
/*
* stop counters, save counter values, restore counts
* for previous thread
*/
cbe_disable_pm(cpu);
cbe_disable_pm_interrupts(cpu);
for (i = 0; i < num_counters; i++) {
per_cpu(pmc_values, cpu + prev_hdw_thread)[i]
= cbe_read_ctr(cpu, i);
if (per_cpu(pmc_values, cpu + next_hdw_thread)[i]
== 0xFFFFFFFF)
/* If the cntr value is 0xffffffff, we must
* reset that to 0xfffffff0 when the current
* thread is restarted. This will generate a
* new interrupt and make sure that we never
* restore the counters to the max value. If
* the counters were restored to the max value,
* they do not increment and no interrupts are
* generated. Hence no more samples will be
* collected on that cpu.
*/
cbe_write_ctr(cpu, i, 0xFFFFFFF0);
else
cbe_write_ctr(cpu, i,
per_cpu(pmc_values,
cpu +
next_hdw_thread)[i]);
}
/*
* Switch to the other thread. Change the interrupt
* and control regs to be scheduled on the CPU
* corresponding to the thread to execute.
*/
for (i = 0; i < num_counters; i++) {
if (pmc_cntrl[next_hdw_thread][i].enabled) {
/*
* There are some per thread events.
* Must do the set event, enable_cntr
* for each cpu.
*/
enable_ctr(cpu, i,
pm_regs.pm07_cntrl);
} else {
cbe_write_pm07_control(cpu, i, 0);
}
}
/* Enable interrupts on the CPU thread that is starting */
cbe_enable_pm_interrupts(cpu, next_hdw_thread,
virt_cntr_inter_mask);
cbe_enable_pm(cpu);
}
spin_unlock_irqrestore(&cntr_lock, flags);
mod_timer(&timer_virt_cntr, jiffies + HZ / 10);
}
static void start_virt_cntrs(void)
{
init_timer(&timer_virt_cntr);
timer_virt_cntr.function = cell_virtual_cntr;
timer_virt_cntr.data = 0UL;
timer_virt_cntr.expires = jiffies + HZ / 10;
add_timer(&timer_virt_cntr);
}
static int cell_reg_setup_spu_cycles(struct op_counter_config *ctr,
struct op_system_config *sys, int num_ctrs)
{
spu_cycle_reset = ctr[0].count;
/*
* Each node will need to make the rtas call to start
* and stop SPU profiling. Get the token once and store it.
*/
spu_rtas_token = rtas_token("ibm,cbe-spu-perftools");
if (unlikely(spu_rtas_token == RTAS_UNKNOWN_SERVICE)) {
printk(KERN_ERR
"%s: rtas token ibm,cbe-spu-perftools unknown\n",
__func__);
return -EIO;
}
return 0;
}
/* Unfortunately, the hardware will only support event profiling
* on one SPU per node at a time. Therefore, we must time slice
* the profiling across all SPUs in the node. Note, we do this
* in parallel for each node. The following routine is called
* periodically based on kernel timer to switch which SPU is
* being monitored in a round robbin fashion.
*/
static void spu_evnt_swap(unsigned long data)
{
int node;
int cur_phys_spu, nxt_phys_spu, cur_spu_evnt_phys_spu_indx;
unsigned long flags;
int cpu;
int ret;
u32 interrupt_mask;
/* enable interrupts on cntr 0 */
interrupt_mask = CBE_PM_CTR_OVERFLOW_INTR(0);
hdw_thread = 0;
/* Make sure spu event interrupt handler and spu event swap
* don't access the counters simultaneously.
*/
spin_lock_irqsave(&cntr_lock, flags);
cur_spu_evnt_phys_spu_indx = spu_evnt_phys_spu_indx;
if (++(spu_evnt_phys_spu_indx) == NUM_SPUS_PER_NODE)
spu_evnt_phys_spu_indx = 0;
pm_signal[0].sub_unit = spu_evnt_phys_spu_indx;
pm_signal[1].sub_unit = spu_evnt_phys_spu_indx;
pm_signal[2].sub_unit = spu_evnt_phys_spu_indx;
/* switch the SPU being profiled on each node */
for_each_online_cpu(cpu) {
if (cbe_get_hw_thread_id(cpu))
continue;
node = cbe_cpu_to_node(cpu);
cur_phys_spu = (node * NUM_SPUS_PER_NODE)
+ cur_spu_evnt_phys_spu_indx;
nxt_phys_spu = (node * NUM_SPUS_PER_NODE)
+ spu_evnt_phys_spu_indx;
/*
* stop counters, save counter values, restore counts
* for previous physical SPU
*/
cbe_disable_pm(cpu);
cbe_disable_pm_interrupts(cpu);
spu_pm_cnt[cur_phys_spu]
= cbe_read_ctr(cpu, 0);
/* restore previous count for the next spu to sample */
/* NOTE, hardware issue, counter will not start if the
* counter value is at max (0xFFFFFFFF).
*/
if (spu_pm_cnt[nxt_phys_spu] >= 0xFFFFFFFF)
cbe_write_ctr(cpu, 0, 0xFFFFFFF0);
else
cbe_write_ctr(cpu, 0, spu_pm_cnt[nxt_phys_spu]);
pm_rtas_reset_signals(cbe_cpu_to_node(cpu));
/* setup the debug bus measure the one event and
* the two events to route the next SPU's PC on
* the debug bus
*/
ret = pm_rtas_activate_signals(cbe_cpu_to_node(cpu), 3);
if (ret)
printk(KERN_ERR "%s: pm_rtas_activate_signals failed, "
"SPU event swap\n", __func__);
/* clear the trace buffer, don't want to take PC for
* previous SPU*/
cbe_write_pm(cpu, trace_address, 0);
enable_ctr(cpu, 0, pm_regs.pm07_cntrl);
/* Enable interrupts on the CPU thread that is starting */
cbe_enable_pm_interrupts(cpu, hdw_thread,
interrupt_mask);
cbe_enable_pm(cpu);
}
spin_unlock_irqrestore(&cntr_lock, flags);
/* swap approximately every 0.1 seconds */
mod_timer(&timer_spu_event_swap, jiffies + HZ / 25);
}
static void start_spu_event_swap(void)
{
init_timer(&timer_spu_event_swap);
timer_spu_event_swap.function = spu_evnt_swap;
timer_spu_event_swap.data = 0UL;
timer_spu_event_swap.expires = jiffies + HZ / 25;
add_timer(&timer_spu_event_swap);
}
static int cell_reg_setup_spu_events(struct op_counter_config *ctr,
struct op_system_config *sys, int num_ctrs)
{
int i;
/* routine is called once for all nodes */
spu_evnt_phys_spu_indx = 0;
/*
* For all events except PPU CYCLEs, each node will need to make
* the rtas cbe-perftools call to setup and reset the debug bus.
* Make the token lookup call once and store it in the global
* variable pm_rtas_token.
*/
pm_rtas_token = rtas_token("ibm,cbe-perftools");
if (unlikely(pm_rtas_token == RTAS_UNKNOWN_SERVICE)) {
printk(KERN_ERR
"%s: rtas token ibm,cbe-perftools unknown\n",
__func__);
return -EIO;
}
/* setup the pm_control register settings,
* settings will be written per node by the
* cell_cpu_setup() function.
*/
pm_regs.pm_cntrl.trace_buf_ovflw = 1;
/* Use the occurrence trace mode to have SPU PC saved
* to the trace buffer. Occurrence data in trace buffer
* is not used. Bit 2 must be set to store SPU addresses.
*/
pm_regs.pm_cntrl.trace_mode = 2;
pm_regs.pm_cntrl.spu_addr_trace = 0x1; /* using debug bus
event 2 & 3 */
/* setup the debug bus event array with the SPU PC routing events.
* Note, pm_signal[0] will be filled in by set_pm_event() call below.
*/
pm_signal[1].signal_group = SPU_PROFILE_EVENT_ADDR / 100;
pm_signal[1].bus_word = GET_BUS_WORD(SPU_PROFILE_EVENT_ADDR_MASK_A);
pm_signal[1].bit = SPU_PROFILE_EVENT_ADDR % 100;
pm_signal[1].sub_unit = spu_evnt_phys_spu_indx;
pm_signal[2].signal_group = SPU_PROFILE_EVENT_ADDR / 100;
pm_signal[2].bus_word = GET_BUS_WORD(SPU_PROFILE_EVENT_ADDR_MASK_B);
pm_signal[2].bit = SPU_PROFILE_EVENT_ADDR % 100;
pm_signal[2].sub_unit = spu_evnt_phys_spu_indx;
/* Set the user selected spu event to profile on,
* note, only one SPU profiling event is supported
*/
num_counters = 1; /* Only support one SPU event at a time */
set_pm_event(0, ctr[0].event, ctr[0].unit_mask);
reset_value[0] = 0xFFFFFFFF - ctr[0].count;
/* global, used by cell_cpu_setup */
ctr_enabled |= 1;
/* Initialize the count for each SPU to the reset value */
for (i=0; i < MAX_NUMNODES * NUM_SPUS_PER_NODE; i++)
spu_pm_cnt[i] = reset_value[0];
return 0;
}
static int cell_reg_setup_ppu(struct op_counter_config *ctr,
struct op_system_config *sys, int num_ctrs)
{
/* routine is called once for all nodes */
int i, j, cpu;
num_counters = num_ctrs;
if (unlikely(num_ctrs > NR_PHYS_CTRS)) {
printk(KERN_ERR
"%s: Oprofile, number of specified events " \
"exceeds number of physical counters\n",
__func__);
return -EIO;
}
set_count_mode(sys->enable_kernel, sys->enable_user);
/* Setup the thread 0 events */
for (i = 0; i < num_ctrs; ++i) {
pmc_cntrl[0][i].evnts = ctr[i].event;
pmc_cntrl[0][i].masks = ctr[i].unit_mask;
pmc_cntrl[0][i].enabled = ctr[i].enabled;
pmc_cntrl[0][i].vcntr = i;
for_each_possible_cpu(j)
per_cpu(pmc_values, j)[i] = 0;
}
/*
* Setup the thread 1 events, map the thread 0 event to the
* equivalent thread 1 event.
*/
for (i = 0; i < num_ctrs; ++i) {
if ((ctr[i].event >= 2100) && (ctr[i].event <= 2111))
pmc_cntrl[1][i].evnts = ctr[i].event + 19;
else if (ctr[i].event == 2203)
pmc_cntrl[1][i].evnts = ctr[i].event;
else if ((ctr[i].event >= 2200) && (ctr[i].event <= 2215))
pmc_cntrl[1][i].evnts = ctr[i].event + 16;
else
pmc_cntrl[1][i].evnts = ctr[i].event;
pmc_cntrl[1][i].masks = ctr[i].unit_mask;
pmc_cntrl[1][i].enabled = ctr[i].enabled;
pmc_cntrl[1][i].vcntr = i;
}
for (i = 0; i < NUM_INPUT_BUS_WORDS; i++)
input_bus[i] = 0xff;
/*
* Our counters count up, and "count" refers to
* how much before the next interrupt, and we interrupt
* on overflow. So we calculate the starting value
* which will give us "count" until overflow.
* Then we set the events on the enabled counters.
*/
for (i = 0; i < num_counters; ++i) {
/* start with virtual counter set 0 */
if (pmc_cntrl[0][i].enabled) {
/* Using 32bit counters, reset max - count */
reset_value[i] = 0xFFFFFFFF - ctr[i].count;
set_pm_event(i,
pmc_cntrl[0][i].evnts,
pmc_cntrl[0][i].masks);
/* global, used by cell_cpu_setup */
ctr_enabled |= (1 << i);
}
}
/* initialize the previous counts for the virtual cntrs */
for_each_online_cpu(cpu)
for (i = 0; i < num_counters; ++i) {
per_cpu(pmc_values, cpu)[i] = reset_value[i];
}
return 0;
}
/* This function is called once for all cpus combined */
static int cell_reg_setup(struct op_counter_config *ctr,
struct op_system_config *sys, int num_ctrs)
{
int ret=0;
spu_cycle_reset = 0;
/* initialize the spu_arr_trace value, will be reset if
* doing spu event profiling.
*/
pm_regs.group_control = 0;
pm_regs.debug_bus_control = 0;
pm_regs.pm_cntrl.stop_at_max = 1;
pm_regs.pm_cntrl.trace_mode = 0;
pm_regs.pm_cntrl.freeze = 1;
pm_regs.pm_cntrl.trace_buf_ovflw = 0;
pm_regs.pm_cntrl.spu_addr_trace = 0;
/*
* For all events except PPU CYCLEs, each node will need to make
* the rtas cbe-perftools call to setup and reset the debug bus.
* Make the token lookup call once and store it in the global
* variable pm_rtas_token.
*/
pm_rtas_token = rtas_token("ibm,cbe-perftools");
if (unlikely(pm_rtas_token == RTAS_UNKNOWN_SERVICE)) {
printk(KERN_ERR
"%s: rtas token ibm,cbe-perftools unknown\n",
__func__);
return -EIO;
}
if (ctr[0].event == SPU_CYCLES_EVENT_NUM) {
profiling_mode = SPU_PROFILING_CYCLES;
ret = cell_reg_setup_spu_cycles(ctr, sys, num_ctrs);
} else if ((ctr[0].event >= SPU_EVENT_NUM_START) &&
(ctr[0].event <= SPU_EVENT_NUM_STOP)) {
profiling_mode = SPU_PROFILING_EVENTS;
spu_cycle_reset = ctr[0].count;
/* for SPU event profiling, need to setup the
* pm_signal array with the events to route the
* SPU PC before making the FW call. Note, only
* one SPU event for profiling can be specified
* at a time.
*/
cell_reg_setup_spu_events(ctr, sys, num_ctrs);
} else {
profiling_mode = PPU_PROFILING;
ret = cell_reg_setup_ppu(ctr, sys, num_ctrs);
}
return ret;
}
/* This function is called once for each cpu */
static int cell_cpu_setup(struct op_counter_config *cntr)
{
u32 cpu = smp_processor_id();
u32 num_enabled = 0;
int i;
int ret;
/* Cycle based SPU profiling does not use the performance
* counters. The trace array is configured to collect
* the data.
*/
if (profiling_mode == SPU_PROFILING_CYCLES)
return 0;
/* There is one performance monitor per processor chip (i.e. node),
* so we only need to perform this function once per node.
*/
if (cbe_get_hw_thread_id(cpu))
return 0;
/* Stop all counters */
cbe_disable_pm(cpu);
cbe_disable_pm_interrupts(cpu);
cbe_write_pm(cpu, pm_start_stop, 0);
cbe_write_pm(cpu, group_control, pm_regs.group_control);
cbe_write_pm(cpu, debug_bus_control, pm_regs.debug_bus_control);
write_pm_cntrl(cpu);
for (i = 0; i < num_counters; ++i) {
if (ctr_enabled & (1 << i)) {
pm_signal[num_enabled].cpu = cbe_cpu_to_node(cpu);
num_enabled++;
}
}
/*
* The pm_rtas_activate_signals will return -EIO if the FW
* call failed.
*/
if (profiling_mode == SPU_PROFILING_EVENTS) {
/* For SPU event profiling also need to setup the
* pm interval timer
*/
ret = pm_rtas_activate_signals(cbe_cpu_to_node(cpu),
num_enabled+2);
/* store PC from debug bus to Trace buffer as often
* as possible (every 10 cycles)
*/
cbe_write_pm(cpu, pm_interval, NUM_INTERVAL_CYC);
return ret;
} else
return pm_rtas_activate_signals(cbe_cpu_to_node(cpu),
num_enabled);
}
#define ENTRIES 303
#define MAXLFSR 0xFFFFFF
/* precomputed table of 24 bit LFSR values */
static int initial_lfsr[] = {
8221349, 12579195, 5379618, 10097839, 7512963, 7519310, 3955098, 10753424,
15507573, 7458917, 285419, 2641121, 9780088, 3915503, 6668768, 1548716,
4885000, 8774424, 9650099, 2044357, 2304411, 9326253, 10332526, 4421547,
3440748, 10179459, 13332843, 10375561, 1313462, 8375100, 5198480, 6071392,
9341783, 1526887, 3985002, 1439429, 13923762, 7010104, 11969769, 4547026,
2040072, 4025602, 3437678, 7939992, 11444177, 4496094, 9803157, 10745556,
3671780, 4257846, 5662259, 13196905, 3237343, 12077182, 16222879, 7587769,
14706824, 2184640, 12591135, 10420257, 7406075, 3648978, 11042541, 15906893,
11914928, 4732944, 10695697, 12928164, 11980531, 4430912, 11939291, 2917017,
6119256, 4172004, 9373765, 8410071, 14788383, 5047459, 5474428, 1737756,
15967514, 13351758, 6691285, 8034329, 2856544, 14394753, 11310160, 12149558,
7487528, 7542781, 15668898, 12525138, 12790975, 3707933, 9106617, 1965401,
16219109, 12801644, 2443203, 4909502, 8762329, 3120803, 6360315, 9309720,
15164599, 10844842, 4456529, 6667610, 14924259, 884312, 6234963, 3326042,
15973422, 13919464, 5272099, 6414643, 3909029, 2764324, 5237926, 4774955,
10445906, 4955302, 5203726, 10798229, 11443419, 2303395, 333836, 9646934,
3464726, 4159182, 568492, 995747, 10318756, 13299332, 4836017, 8237783,
3878992, 2581665, 11394667, 5672745, 14412947, 3159169, 9094251, 16467278,
8671392, 15230076, 4843545, 7009238, 15504095, 1494895, 9627886, 14485051,
8304291, 252817, 12421642, 16085736, 4774072, 2456177, 4160695, 15409741,
4902868, 5793091, 13162925, 16039714, 782255, 11347835, 14884586, 366972,
16308990, 11913488, 13390465, 2958444, 10340278, 1177858, 1319431, 10426302,
2868597, 126119, 5784857, 5245324, 10903900, 16436004, 3389013, 1742384,
14674502, 10279218, 8536112, 10364279, 6877778, 14051163, 1025130, 6072469,
1988305, 8354440, 8216060, 16342977, 13112639, 3976679, 5913576, 8816697,
6879995, 14043764, 3339515, 9364420, 15808858, 12261651, 2141560, 5636398,
10345425, 10414756, 781725, 6155650, 4746914, 5078683, 7469001, 6799140,
10156444, 9667150, 10116470, 4133858, 2121972, 1124204, 1003577, 1611214,
14304602, 16221850, 13878465, 13577744, 3629235, 8772583, 10881308, 2410386,
7300044, 5378855, 9301235, 12755149, 4977682, 8083074, 10327581, 6395087,
9155434, 15501696, 7514362, 14520507, 15808945, 3244584, 4741962, 9658130,
14336147, 8654727, 7969093, 15759799, 14029445, 5038459, 9894848, 8659300,
13699287, 8834306, 10712885, 14753895, 10410465, 3373251, 309501, 9561475,
5526688, 14647426, 14209836, 5339224, 207299, 14069911, 8722990, 2290950,
3258216, 12505185, 6007317, 9218111, 14661019, 10537428, 11731949, 9027003,
6641507, 9490160, 200241, 9720425, 16277895, 10816638, 1554761, 10431375,
7467528, 6790302, 3429078, 14633753, 14428997, 11463204, 3576212, 2003426,
6123687, 820520, 9992513, 15784513, 5778891, 6428165, 8388607
};
/*
* The hardware uses an LFSR counting sequence to determine when to capture
* the SPU PCs. An LFSR sequence is like a puesdo random number sequence
* where each number occurs once in the sequence but the sequence is not in
* numerical order. The SPU PC capture is done when the LFSR sequence reaches
* the last value in the sequence. Hence the user specified value N
* corresponds to the LFSR number that is N from the end of the sequence.
*
* To avoid the time to compute the LFSR, a lookup table is used. The 24 bit
* LFSR sequence is broken into four ranges. The spacing of the precomputed
* values is adjusted in each range so the error between the user specifed
* number (N) of events between samples and the actual number of events based
* on the precomputed value will be les then about 6.2%. Note, if the user
* specifies N < 2^16, the LFSR value that is 2^16 from the end will be used.
* This is to prevent the loss of samples because the trace buffer is full.
*
* User specified N Step between Index in
* precomputed values precomputed
* table
* 0 to 2^16-1 ---- 0
* 2^16 to 2^16+2^19-1 2^12 1 to 128
* 2^16+2^19 to 2^16+2^19+2^22-1 2^15 129 to 256
* 2^16+2^19+2^22 to 2^24-1 2^18 257 to 302
*
*
* For example, the LFSR values in the second range are computed for 2^16,
* 2^16+2^12, ... , 2^19-2^16, 2^19 and stored in the table at indicies
* 1, 2,..., 127, 128.
*
* The 24 bit LFSR value for the nth number in the sequence can be
* calculated using the following code:
*
* #define size 24
* int calculate_lfsr(int n)
* {
* int i;
* unsigned int newlfsr0;
* unsigned int lfsr = 0xFFFFFF;
* unsigned int howmany = n;
*
* for (i = 2; i < howmany + 2; i++) {
* newlfsr0 = (((lfsr >> (size - 1 - 0)) & 1) ^
* ((lfsr >> (size - 1 - 1)) & 1) ^
* (((lfsr >> (size - 1 - 6)) & 1) ^
* ((lfsr >> (size - 1 - 23)) & 1)));
*
* lfsr >>= 1;
* lfsr = lfsr | (newlfsr0 << (size - 1));
* }
* return lfsr;
* }
*/
#define V2_16 (0x1 << 16)
#define V2_19 (0x1 << 19)
#define V2_22 (0x1 << 22)
static int calculate_lfsr(int n)
{
/*
* The ranges and steps are in powers of 2 so the calculations
* can be done using shifts rather then divide.
*/
int index;
if ((n >> 16) == 0)
index = 0;
else if (((n - V2_16) >> 19) == 0)
index = ((n - V2_16) >> 12) + 1;
else if (((n - V2_16 - V2_19) >> 22) == 0)
index = ((n - V2_16 - V2_19) >> 15 ) + 1 + 128;
else if (((n - V2_16 - V2_19 - V2_22) >> 24) == 0)
index = ((n - V2_16 - V2_19 - V2_22) >> 18 ) + 1 + 256;
else
index = ENTRIES-1;
/* make sure index is valid */
if ((index >= ENTRIES) || (index < 0))
index = ENTRIES-1;
return initial_lfsr[index];
}
static int pm_rtas_activate_spu_profiling(u32 node)
{
int ret, i;
struct pm_signal pm_signal_local[NUM_SPUS_PER_NODE];
/*
* Set up the rtas call to configure the debug bus to
* route the SPU PCs. Setup the pm_signal for each SPU
*/
for (i = 0; i < ARRAY_SIZE(pm_signal_local); i++) {
pm_signal_local[i].cpu = node;
pm_signal_local[i].signal_group = 41;
/* spu i on word (i/2) */
pm_signal_local[i].bus_word = 1 << i / 2;
/* spu i */
pm_signal_local[i].sub_unit = i;
pm_signal_local[i].bit = 63;
}
ret = rtas_ibm_cbe_perftools(SUBFUNC_ACTIVATE,
PASSTHRU_ENABLE, pm_signal_local,
(ARRAY_SIZE(pm_signal_local)
* sizeof(struct pm_signal)));
if (unlikely(ret)) {
printk(KERN_WARNING "%s: rtas returned: %d\n",
__func__, ret);
return -EIO;
}
return 0;
}
#ifdef CONFIG_CPU_FREQ
static int
oprof_cpufreq_notify(struct notifier_block *nb, unsigned long val, void *data)
{
int ret = 0;
struct cpufreq_freqs *frq = data;
if ((val == CPUFREQ_PRECHANGE && frq->old < frq->new) ||
(val == CPUFREQ_POSTCHANGE && frq->old > frq->new) ||
(val == CPUFREQ_RESUMECHANGE || val == CPUFREQ_SUSPENDCHANGE))
set_spu_profiling_frequency(frq->new, spu_cycle_reset);
return ret;
}
static struct notifier_block cpu_freq_notifier_block = {
.notifier_call = oprof_cpufreq_notify
};
#endif
/*
* Note the generic OProfile stop calls do not support returning
* an error on stop. Hence, will not return an error if the FW
* calls fail on stop. Failure to reset the debug bus is not an issue.
* Failure to disable the SPU profiling is not an issue. The FW calls
* to enable the performance counters and debug bus will work even if
* the hardware was not cleanly reset.
*/
static void cell_global_stop_spu_cycles(void)
{
int subfunc, rtn_value;
unsigned int lfsr_value;
int cpu;
oprofile_running = 0;
smp_wmb();
#ifdef CONFIG_CPU_FREQ
cpufreq_unregister_notifier(&cpu_freq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
#endif
for_each_online_cpu(cpu) {
if (cbe_get_hw_thread_id(cpu))
continue;
subfunc = 3; /*
* 2 - activate SPU tracing,
* 3 - deactivate
*/
lfsr_value = 0x8f100000;
rtn_value = rtas_call(spu_rtas_token, 3, 1, NULL,
subfunc, cbe_cpu_to_node(cpu),
lfsr_value);
if (unlikely(rtn_value != 0)) {
printk(KERN_ERR
"%s: rtas call ibm,cbe-spu-perftools " \
"failed, return = %d\n",
__func__, rtn_value);
}
/* Deactivate the signals */
pm_rtas_reset_signals(cbe_cpu_to_node(cpu));
}
stop_spu_profiling_cycles();
}
static void cell_global_stop_spu_events(void)
{
int cpu;
oprofile_running = 0;
stop_spu_profiling_events();
smp_wmb();
for_each_online_cpu(cpu) {
if (cbe_get_hw_thread_id(cpu))
continue;
cbe_sync_irq(cbe_cpu_to_node(cpu));
/* Stop the counters */
cbe_disable_pm(cpu);
cbe_write_pm07_control(cpu, 0, 0);
/* Deactivate the signals */
pm_rtas_reset_signals(cbe_cpu_to_node(cpu));
/* Deactivate interrupts */
cbe_disable_pm_interrupts(cpu);
}
del_timer_sync(&timer_spu_event_swap);
}
static void cell_global_stop_ppu(void)
{
int cpu;
/*
* This routine will be called once for the system.
* There is one performance monitor per node, so we
* only need to perform this function once per node.
*/
del_timer_sync(&timer_virt_cntr);
oprofile_running = 0;
smp_wmb();
for_each_online_cpu(cpu) {
if (cbe_get_hw_thread_id(cpu))
continue;
cbe_sync_irq(cbe_cpu_to_node(cpu));
/* Stop the counters */
cbe_disable_pm(cpu);
/* Deactivate the signals */
pm_rtas_reset_signals(cbe_cpu_to_node(cpu));
/* Deactivate interrupts */
cbe_disable_pm_interrupts(cpu);
}
}
static void cell_global_stop(void)
{
if (profiling_mode == PPU_PROFILING)
cell_global_stop_ppu();
else if (profiling_mode == SPU_PROFILING_EVENTS)
cell_global_stop_spu_events();
else
cell_global_stop_spu_cycles();
}
static int cell_global_start_spu_cycles(struct op_counter_config *ctr)
{
int subfunc;
unsigned int lfsr_value;
int cpu;
int ret;
int rtas_error;
unsigned int cpu_khzfreq = 0;
/* The SPU profiling uses time-based profiling based on
* cpu frequency, so if configured with the CPU_FREQ
* option, we should detect frequency changes and react
* accordingly.
*/
#ifdef CONFIG_CPU_FREQ
ret = cpufreq_register_notifier(&cpu_freq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
if (ret < 0)
/* this is not a fatal error */
printk(KERN_ERR "CPU freq change registration failed: %d\n",
ret);
else
cpu_khzfreq = cpufreq_quick_get(smp_processor_id());
#endif
set_spu_profiling_frequency(cpu_khzfreq, spu_cycle_reset);
for_each_online_cpu(cpu) {
if (cbe_get_hw_thread_id(cpu))
continue;
/*
* Setup SPU cycle-based profiling.
* Set perf_mon_control bit 0 to a zero before
* enabling spu collection hardware.
*/
cbe_write_pm(cpu, pm_control, 0);
if (spu_cycle_reset > MAX_SPU_COUNT)
/* use largest possible value */
lfsr_value = calculate_lfsr(MAX_SPU_COUNT-1);
else
lfsr_value = calculate_lfsr(spu_cycle_reset);
/* must use a non zero value. Zero disables data collection. */
if (lfsr_value == 0)
lfsr_value = calculate_lfsr(1);
lfsr_value = lfsr_value << 8; /* shift lfsr to correct
* register location
*/
/* debug bus setup */
ret = pm_rtas_activate_spu_profiling(cbe_cpu_to_node(cpu));
if (unlikely(ret)) {
rtas_error = ret;
goto out;
}
subfunc = 2; /* 2 - activate SPU tracing, 3 - deactivate */
/* start profiling */
ret = rtas_call(spu_rtas_token, 3, 1, NULL, subfunc,
cbe_cpu_to_node(cpu), lfsr_value);
if (unlikely(ret != 0)) {
printk(KERN_ERR
"%s: rtas call ibm,cbe-spu-perftools failed, " \
"return = %d\n", __func__, ret);
rtas_error = -EIO;
goto out;
}
}
rtas_error = start_spu_profiling_cycles(spu_cycle_reset);
if (rtas_error)
goto out_stop;
oprofile_running = 1;
return 0;
out_stop:
cell_global_stop_spu_cycles(); /* clean up the PMU/debug bus */
out:
return rtas_error;
}
static int cell_global_start_spu_events(struct op_counter_config *ctr)
{
int cpu;
u32 interrupt_mask = 0;
int rtn = 0;
hdw_thread = 0;
/* spu event profiling, uses the performance counters to generate
* an interrupt. The hardware is setup to store the SPU program
* counter into the trace array. The occurrence mode is used to
* enable storing data to the trace buffer. The bits are set
* to send/store the SPU address in the trace buffer. The debug
* bus must be setup to route the SPU program counter onto the
* debug bus. The occurrence data in the trace buffer is not used.
*/
/* This routine gets called once for the system.
* There is one performance monitor per node, so we
* only need to perform this function once per node.
*/
for_each_online_cpu(cpu) {
if (cbe_get_hw_thread_id(cpu))
continue;
/*
* Setup SPU event-based profiling.
* Set perf_mon_control bit 0 to a zero before
* enabling spu collection hardware.
*
* Only support one SPU event on one SPU per node.
*/
if (ctr_enabled & 1) {
cbe_write_ctr(cpu, 0, reset_value[0]);
enable_ctr(cpu, 0, pm_regs.pm07_cntrl);
interrupt_mask |=
CBE_PM_CTR_OVERFLOW_INTR(0);
} else {
/* Disable counter */
cbe_write_pm07_control(cpu, 0, 0);
}
cbe_get_and_clear_pm_interrupts(cpu);
cbe_enable_pm_interrupts(cpu, hdw_thread, interrupt_mask);
cbe_enable_pm(cpu);
/* clear the trace buffer */
cbe_write_pm(cpu, trace_address, 0);
}
/* Start the timer to time slice collecting the event profile
* on each of the SPUs. Note, can collect profile on one SPU
* per node at a time.
*/
start_spu_event_swap();
start_spu_profiling_events();
oprofile_running = 1;
smp_wmb();
return rtn;
}
static int cell_global_start_ppu(struct op_counter_config *ctr)
{
u32 cpu, i;
u32 interrupt_mask = 0;
/* This routine gets called once for the system.
* There is one performance monitor per node, so we
* only need to perform this function once per node.
*/
for_each_online_cpu(cpu) {
if (cbe_get_hw_thread_id(cpu))
continue;
interrupt_mask = 0;
for (i = 0; i < num_counters; ++i) {
if (ctr_enabled & (1 << i)) {
cbe_write_ctr(cpu, i, reset_value[i]);
enable_ctr(cpu, i, pm_regs.pm07_cntrl);
interrupt_mask |= CBE_PM_CTR_OVERFLOW_INTR(i);
} else {
/* Disable counter */
cbe_write_pm07_control(cpu, i, 0);
}
}
cbe_get_and_clear_pm_interrupts(cpu);
cbe_enable_pm_interrupts(cpu, hdw_thread, interrupt_mask);
cbe_enable_pm(cpu);
}
virt_cntr_inter_mask = interrupt_mask;
oprofile_running = 1;
smp_wmb();
/*
* NOTE: start_virt_cntrs will result in cell_virtual_cntr() being
* executed which manipulates the PMU. We start the "virtual counter"
* here so that we do not need to synchronize access to the PMU in
* the above for-loop.
*/
start_virt_cntrs();
return 0;
}
static int cell_global_start(struct op_counter_config *ctr)
{
if (profiling_mode == SPU_PROFILING_CYCLES)
return cell_global_start_spu_cycles(ctr);
else if (profiling_mode == SPU_PROFILING_EVENTS)
return cell_global_start_spu_events(ctr);
else
return cell_global_start_ppu(ctr);
}
/* The SPU interrupt handler
*
* SPU event profiling works as follows:
* The pm_signal[0] holds the one SPU event to be measured. It is routed on
* the debug bus using word 0 or 1. The value of pm_signal[1] and
* pm_signal[2] contain the necessary events to route the SPU program
* counter for the selected SPU onto the debug bus using words 2 and 3.
* The pm_interval register is setup to write the SPU PC value into the
* trace buffer at the maximum rate possible. The trace buffer is configured
* to store the PCs, wrapping when it is full. The performance counter is
* initialized to the max hardware count minus the number of events, N, between
* samples. Once the N events have occurred, a HW counter overflow occurs
* causing the generation of a HW counter interrupt which also stops the
* writing of the SPU PC values to the trace buffer. Hence the last PC
* written to the trace buffer is the SPU PC that we want. Unfortunately,
* we have to read from the beginning of the trace buffer to get to the
* last value written. We just hope the PPU has nothing better to do then
* service this interrupt. The PC for the specific SPU being profiled is
* extracted from the trace buffer processed and stored. The trace buffer
* is cleared, interrupts are cleared, the counter is reset to max - N.
* A kernel timer is used to periodically call the routine spu_evnt_swap()
* to switch to the next physical SPU in the node to profile in round robbin
* order. This way data is collected for all SPUs on the node. It does mean
* that we need to use a relatively small value of N to ensure enough samples
* on each SPU are collected each SPU is being profiled 1/8 of the time.
* It may also be necessary to use a longer sample collection period.
*/
static void cell_handle_interrupt_spu(struct pt_regs *regs,
struct op_counter_config *ctr)
{
u32 cpu, cpu_tmp;
u64 trace_entry;
u32 interrupt_mask;
u64 trace_buffer[2];
u64 last_trace_buffer;
u32 sample;
u32 trace_addr;
unsigned long sample_array_lock_flags;
int spu_num;
unsigned long flags;
/* Make sure spu event interrupt handler and spu event swap
* don't access the counters simultaneously.
*/
cpu = smp_processor_id();
spin_lock_irqsave(&cntr_lock, flags);
cpu_tmp = cpu;
cbe_disable_pm(cpu);
interrupt_mask = cbe_get_and_clear_pm_interrupts(cpu);
sample = 0xABCDEF;
trace_entry = 0xfedcba;
last_trace_buffer = 0xdeadbeaf;
if ((oprofile_running == 1) && (interrupt_mask != 0)) {
/* disable writes to trace buff */
cbe_write_pm(cpu, pm_interval, 0);
/* only have one perf cntr being used, cntr 0 */
if ((interrupt_mask & CBE_PM_CTR_OVERFLOW_INTR(0))
&& ctr[0].enabled)
/* The SPU PC values will be read
* from the trace buffer, reset counter
*/
cbe_write_ctr(cpu, 0, reset_value[0]);
trace_addr = cbe_read_pm(cpu, trace_address);
while (!(trace_addr & CBE_PM_TRACE_BUF_EMPTY)) {
/* There is data in the trace buffer to process
* Read the buffer until you get to the last
* entry. This is the value we want.
*/
cbe_read_trace_buffer(cpu, trace_buffer);
trace_addr = cbe_read_pm(cpu, trace_address);
}
/* SPU Address 16 bit count format for 128 bit
* HW trace buffer is used for the SPU PC storage
* HDR bits 0:15
* SPU Addr 0 bits 16:31
* SPU Addr 1 bits 32:47
* unused bits 48:127
*
* HDR: bit4 = 1 SPU Address 0 valid
* HDR: bit5 = 1 SPU Address 1 valid
* - unfortunately, the valid bits don't seem to work
*
* Note trace_buffer[0] holds bits 0:63 of the HW
* trace buffer, trace_buffer[1] holds bits 64:127
*/
trace_entry = trace_buffer[0]
& 0x00000000FFFF0000;
/* only top 16 of the 18 bit SPU PC address
* is stored in trace buffer, hence shift right
* by 16 -2 bits */
sample = trace_entry >> 14;
last_trace_buffer = trace_buffer[0];
spu_num = spu_evnt_phys_spu_indx
+ (cbe_cpu_to_node(cpu) * NUM_SPUS_PER_NODE);
/* make sure only one process at a time is calling
* spu_sync_buffer()
*/
spin_lock_irqsave(&oprof_spu_smpl_arry_lck,
sample_array_lock_flags);
spu_sync_buffer(spu_num, &sample, 1);
spin_unlock_irqrestore(&oprof_spu_smpl_arry_lck,
sample_array_lock_flags);
smp_wmb(); /* insure spu event buffer updates are written
* don't want events intermingled... */
/* The counters were frozen by the interrupt.
* Reenable the interrupt and restart the counters.
*/
cbe_write_pm(cpu, pm_interval, NUM_INTERVAL_CYC);
cbe_enable_pm_interrupts(cpu, hdw_thread,
virt_cntr_inter_mask);
/* clear the trace buffer, re-enable writes to trace buff */
cbe_write_pm(cpu, trace_address, 0);
cbe_write_pm(cpu, pm_interval, NUM_INTERVAL_CYC);
/* The writes to the various performance counters only writes
* to a latch. The new values (interrupt setting bits, reset
* counter value etc.) are not copied to the actual registers
* until the performance monitor is enabled. In order to get
* this to work as desired, the performance monitor needs to
* be disabled while writing to the latches. This is a
* HW design issue.
*/
write_pm_cntrl(cpu);
cbe_enable_pm(cpu);
}
spin_unlock_irqrestore(&cntr_lock, flags);
}
static void cell_handle_interrupt_ppu(struct pt_regs *regs,
struct op_counter_config *ctr)
{
u32 cpu;
u64 pc;
int is_kernel;
unsigned long flags = 0;
u32 interrupt_mask;
int i;
cpu = smp_processor_id();
/*
* Need to make sure the interrupt handler and the virt counter
* routine are not running at the same time. See the
* cell_virtual_cntr() routine for additional comments.
*/
spin_lock_irqsave(&cntr_lock, flags);
/*
* Need to disable and reenable the performance counters
* to get the desired behavior from the hardware. This
* is hardware specific.
*/
cbe_disable_pm(cpu);
interrupt_mask = cbe_get_and_clear_pm_interrupts(cpu);
/*
* If the interrupt mask has been cleared, then the virt cntr
* has cleared the interrupt. When the thread that generated
* the interrupt is restored, the data count will be restored to
* 0xffffff0 to cause the interrupt to be regenerated.
*/
if ((oprofile_running == 1) && (interrupt_mask != 0)) {
pc = regs->nip;
is_kernel = is_kernel_addr(pc);
for (i = 0; i < num_counters; ++i) {
if ((interrupt_mask & CBE_PM_CTR_OVERFLOW_INTR(i))
&& ctr[i].enabled) {
oprofile_add_ext_sample(pc, regs, i, is_kernel);
cbe_write_ctr(cpu, i, reset_value[i]);
}
}
/*
* The counters were frozen by the interrupt.
* Reenable the interrupt and restart the counters.
* If there was a race between the interrupt handler and
* the virtual counter routine. The virtual counter
* routine may have cleared the interrupts. Hence must
* use the virt_cntr_inter_mask to re-enable the interrupts.
*/
cbe_enable_pm_interrupts(cpu, hdw_thread,
virt_cntr_inter_mask);
/*
* The writes to the various performance counters only writes
* to a latch. The new values (interrupt setting bits, reset
* counter value etc.) are not copied to the actual registers
* until the performance monitor is enabled. In order to get
* this to work as desired, the performance monitor needs to
* be disabled while writing to the latches. This is a
* HW design issue.
*/
cbe_enable_pm(cpu);
}
spin_unlock_irqrestore(&cntr_lock, flags);
}
static void cell_handle_interrupt(struct pt_regs *regs,
struct op_counter_config *ctr)
{
if (profiling_mode == PPU_PROFILING)
cell_handle_interrupt_ppu(regs, ctr);
else
cell_handle_interrupt_spu(regs, ctr);
}
/*
* This function is called from the generic OProfile
* driver. When profiling PPUs, we need to do the
* generic sync start; otherwise, do spu_sync_start.
*/
static int cell_sync_start(void)
{
if ((profiling_mode == SPU_PROFILING_CYCLES) ||
(profiling_mode == SPU_PROFILING_EVENTS))
return spu_sync_start();
else
return DO_GENERIC_SYNC;
}
static int cell_sync_stop(void)
{
if ((profiling_mode == SPU_PROFILING_CYCLES) ||
(profiling_mode == SPU_PROFILING_EVENTS))
return spu_sync_stop();
else
return 1;
}
struct op_powerpc_model op_model_cell = {
.reg_setup = cell_reg_setup,
.cpu_setup = cell_cpu_setup,
.global_start = cell_global_start,
.global_stop = cell_global_stop,
.sync_start = cell_sync_start,
.sync_stop = cell_sync_stop,
.handle_interrupt = cell_handle_interrupt,
};
| gpl-2.0 |
nsingh94/caf-7x30 | Documentation/vDSO/vdso_test.c | 8413 | 2488 | /*
* vdso_test.c: Sample code to test parse_vdso.c on x86_64
* Copyright (c) 2011 Andy Lutomirski
* Subject to the GNU General Public License, version 2
*
* You can amuse yourself by compiling with:
* gcc -std=gnu99 -nostdlib
* -Os -fno-asynchronous-unwind-tables -flto
* vdso_test.c parse_vdso.c -o vdso_test
* to generate a small binary with no dependencies at all.
*/
#include <sys/syscall.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdint.h>
extern void *vdso_sym(const char *version, const char *name);
extern void vdso_init_from_sysinfo_ehdr(uintptr_t base);
extern void vdso_init_from_auxv(void *auxv);
/* We need a libc functions... */
int strcmp(const char *a, const char *b)
{
/* This implementation is buggy: it never returns -1. */
while (*a || *b) {
if (*a != *b)
return 1;
if (*a == 0 || *b == 0)
return 1;
a++;
b++;
}
return 0;
}
/* ...and two syscalls. This is x86_64-specific. */
static inline long linux_write(int fd, const void *data, size_t len)
{
long ret;
asm volatile ("syscall" : "=a" (ret) : "a" (__NR_write),
"D" (fd), "S" (data), "d" (len) :
"cc", "memory", "rcx",
"r8", "r9", "r10", "r11" );
return ret;
}
static inline void linux_exit(int code)
{
asm volatile ("syscall" : : "a" (__NR_exit), "D" (code));
}
void to_base10(char *lastdig, uint64_t n)
{
while (n) {
*lastdig = (n % 10) + '0';
n /= 10;
lastdig--;
}
}
__attribute__((externally_visible)) void c_main(void **stack)
{
/* Parse the stack */
long argc = (long)*stack;
stack += argc + 2;
/* Now we're pointing at the environment. Skip it. */
while(*stack)
stack++;
stack++;
/* Now we're pointing at auxv. Initialize the vDSO parser. */
vdso_init_from_auxv((void *)stack);
/* Find gettimeofday. */
typedef long (*gtod_t)(struct timeval *tv, struct timezone *tz);
gtod_t gtod = (gtod_t)vdso_sym("LINUX_2.6", "__vdso_gettimeofday");
if (!gtod)
linux_exit(1);
struct timeval tv;
long ret = gtod(&tv, 0);
if (ret == 0) {
char buf[] = "The time is .000000\n";
to_base10(buf + 31, tv.tv_sec);
to_base10(buf + 38, tv.tv_usec);
linux_write(1, buf, sizeof(buf) - 1);
} else {
linux_exit(ret);
}
linux_exit(0);
}
/*
* This is the real entry point. It passes the initial stack into
* the C entry point.
*/
asm (
".text\n"
".global _start\n"
".type _start,@function\n"
"_start:\n\t"
"mov %rsp,%rdi\n\t"
"jmp c_main"
);
| gpl-2.0 |
regiesoriano/rs_kernel_msm | drivers/gpu/drm/i915/i915_ioc32.c | 9181 | 7179 | /**
* \file i915_ioc32.c
*
* 32-bit ioctl compatibility routines for the i915 DRM.
*
* \author Alan Hourihane <alanh@fairlite.demon.co.uk>
*
*
* Copyright (C) Paul Mackerras 2005
* Copyright (C) Alan Hourihane 2005
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHOR 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/compat.h>
#include "drmP.h"
#include "drm.h"
#include "i915_drm.h"
typedef struct _drm_i915_batchbuffer32 {
int start; /* agp offset */
int used; /* nr bytes in use */
int DR1; /* hw flags for GFX_OP_DRAWRECT_INFO */
int DR4; /* window origin for GFX_OP_DRAWRECT_INFO */
int num_cliprects; /* mulitpass with multiple cliprects? */
u32 cliprects; /* pointer to userspace cliprects */
} drm_i915_batchbuffer32_t;
static int compat_i915_batchbuffer(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_i915_batchbuffer32_t batchbuffer32;
drm_i915_batchbuffer_t __user *batchbuffer;
if (copy_from_user
(&batchbuffer32, (void __user *)arg, sizeof(batchbuffer32)))
return -EFAULT;
batchbuffer = compat_alloc_user_space(sizeof(*batchbuffer));
if (!access_ok(VERIFY_WRITE, batchbuffer, sizeof(*batchbuffer))
|| __put_user(batchbuffer32.start, &batchbuffer->start)
|| __put_user(batchbuffer32.used, &batchbuffer->used)
|| __put_user(batchbuffer32.DR1, &batchbuffer->DR1)
|| __put_user(batchbuffer32.DR4, &batchbuffer->DR4)
|| __put_user(batchbuffer32.num_cliprects,
&batchbuffer->num_cliprects)
|| __put_user((int __user *)(unsigned long)batchbuffer32.cliprects,
&batchbuffer->cliprects))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_I915_BATCHBUFFER,
(unsigned long)batchbuffer);
}
typedef struct _drm_i915_cmdbuffer32 {
u32 buf; /* pointer to userspace command buffer */
int sz; /* nr bytes in buf */
int DR1; /* hw flags for GFX_OP_DRAWRECT_INFO */
int DR4; /* window origin for GFX_OP_DRAWRECT_INFO */
int num_cliprects; /* mulitpass with multiple cliprects? */
u32 cliprects; /* pointer to userspace cliprects */
} drm_i915_cmdbuffer32_t;
static int compat_i915_cmdbuffer(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_i915_cmdbuffer32_t cmdbuffer32;
drm_i915_cmdbuffer_t __user *cmdbuffer;
if (copy_from_user
(&cmdbuffer32, (void __user *)arg, sizeof(cmdbuffer32)))
return -EFAULT;
cmdbuffer = compat_alloc_user_space(sizeof(*cmdbuffer));
if (!access_ok(VERIFY_WRITE, cmdbuffer, sizeof(*cmdbuffer))
|| __put_user((int __user *)(unsigned long)cmdbuffer32.buf,
&cmdbuffer->buf)
|| __put_user(cmdbuffer32.sz, &cmdbuffer->sz)
|| __put_user(cmdbuffer32.DR1, &cmdbuffer->DR1)
|| __put_user(cmdbuffer32.DR4, &cmdbuffer->DR4)
|| __put_user(cmdbuffer32.num_cliprects, &cmdbuffer->num_cliprects)
|| __put_user((int __user *)(unsigned long)cmdbuffer32.cliprects,
&cmdbuffer->cliprects))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_I915_CMDBUFFER,
(unsigned long)cmdbuffer);
}
typedef struct drm_i915_irq_emit32 {
u32 irq_seq;
} drm_i915_irq_emit32_t;
static int compat_i915_irq_emit(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_i915_irq_emit32_t req32;
drm_i915_irq_emit_t __user *request;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user((int __user *)(unsigned long)req32.irq_seq,
&request->irq_seq))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_I915_IRQ_EMIT,
(unsigned long)request);
}
typedef struct drm_i915_getparam32 {
int param;
u32 value;
} drm_i915_getparam32_t;
static int compat_i915_getparam(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_i915_getparam32_t req32;
drm_i915_getparam_t __user *request;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.param, &request->param)
|| __put_user((void __user *)(unsigned long)req32.value,
&request->value))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_I915_GETPARAM,
(unsigned long)request);
}
typedef struct drm_i915_mem_alloc32 {
int region;
int alignment;
int size;
u32 region_offset; /* offset from start of fb or agp */
} drm_i915_mem_alloc32_t;
static int compat_i915_alloc(struct file *file, unsigned int cmd,
unsigned long arg)
{
drm_i915_mem_alloc32_t req32;
drm_i915_mem_alloc_t __user *request;
if (copy_from_user(&req32, (void __user *)arg, sizeof(req32)))
return -EFAULT;
request = compat_alloc_user_space(sizeof(*request));
if (!access_ok(VERIFY_WRITE, request, sizeof(*request))
|| __put_user(req32.region, &request->region)
|| __put_user(req32.alignment, &request->alignment)
|| __put_user(req32.size, &request->size)
|| __put_user((void __user *)(unsigned long)req32.region_offset,
&request->region_offset))
return -EFAULT;
return drm_ioctl(file, DRM_IOCTL_I915_ALLOC,
(unsigned long)request);
}
drm_ioctl_compat_t *i915_compat_ioctls[] = {
[DRM_I915_BATCHBUFFER] = compat_i915_batchbuffer,
[DRM_I915_CMDBUFFER] = compat_i915_cmdbuffer,
[DRM_I915_GETPARAM] = compat_i915_getparam,
[DRM_I915_IRQ_EMIT] = compat_i915_irq_emit,
[DRM_I915_ALLOC] = compat_i915_alloc
};
/**
* Called whenever a 32-bit process running under a 64-bit kernel
* performs an ioctl on /dev/dri/card<n>.
*
* \param filp file pointer.
* \param cmd command.
* \param arg user argument.
* \return zero on success or negative number on failure.
*/
long i915_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
unsigned int nr = DRM_IOCTL_NR(cmd);
drm_ioctl_compat_t *fn = NULL;
int ret;
if (nr < DRM_COMMAND_BASE)
return drm_compat_ioctl(filp, cmd, arg);
if (nr < DRM_COMMAND_BASE + DRM_ARRAY_SIZE(i915_compat_ioctls))
fn = i915_compat_ioctls[nr - DRM_COMMAND_BASE];
if (fn != NULL)
ret = (*fn) (filp, cmd, arg);
else
ret = drm_ioctl(filp, cmd, arg);
return ret;
}
| gpl-2.0 |
Icenowy/linux-kernel-lichee-a33 | arch/x86/mm/dump_pagetables.c | 9181 | 9278 | /*
* Debug helper to dump the current kernel pagetables of the system
* so that we can see what the various memory ranges are set to.
*
* (C) Copyright 2008 Intel Corporation
*
* Author: Arjan van de Ven <arjan@linux.intel.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; version 2
* of the License.
*/
#include <linux/debugfs.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/seq_file.h>
#include <asm/pgtable.h>
/*
* The dumper groups pagetable entries of the same type into one, and for
* that it needs to keep some state when walking, and flush this state
* when a "break" in the continuity is found.
*/
struct pg_state {
int level;
pgprot_t current_prot;
unsigned long start_address;
unsigned long current_address;
const struct addr_marker *marker;
};
struct addr_marker {
unsigned long start_address;
const char *name;
};
/* indices for address_markers; keep sync'd w/ address_markers below */
enum address_markers_idx {
USER_SPACE_NR = 0,
#ifdef CONFIG_X86_64
KERNEL_SPACE_NR,
LOW_KERNEL_NR,
VMALLOC_START_NR,
VMEMMAP_START_NR,
HIGH_KERNEL_NR,
MODULES_VADDR_NR,
MODULES_END_NR,
#else
KERNEL_SPACE_NR,
VMALLOC_START_NR,
VMALLOC_END_NR,
# ifdef CONFIG_HIGHMEM
PKMAP_BASE_NR,
# endif
FIXADDR_START_NR,
#endif
};
/* Address space markers hints */
static struct addr_marker address_markers[] = {
{ 0, "User Space" },
#ifdef CONFIG_X86_64
{ 0x8000000000000000UL, "Kernel Space" },
{ PAGE_OFFSET, "Low Kernel Mapping" },
{ VMALLOC_START, "vmalloc() Area" },
{ VMEMMAP_START, "Vmemmap" },
{ __START_KERNEL_map, "High Kernel Mapping" },
{ MODULES_VADDR, "Modules" },
{ MODULES_END, "End Modules" },
#else
{ PAGE_OFFSET, "Kernel Mapping" },
{ 0/* VMALLOC_START */, "vmalloc() Area" },
{ 0/*VMALLOC_END*/, "vmalloc() End" },
# ifdef CONFIG_HIGHMEM
{ 0/*PKMAP_BASE*/, "Persisent kmap() Area" },
# endif
{ 0/*FIXADDR_START*/, "Fixmap Area" },
#endif
{ -1, NULL } /* End of list */
};
/* Multipliers for offsets within the PTEs */
#define PTE_LEVEL_MULT (PAGE_SIZE)
#define PMD_LEVEL_MULT (PTRS_PER_PTE * PTE_LEVEL_MULT)
#define PUD_LEVEL_MULT (PTRS_PER_PMD * PMD_LEVEL_MULT)
#define PGD_LEVEL_MULT (PTRS_PER_PUD * PUD_LEVEL_MULT)
/*
* Print a readable form of a pgprot_t to the seq_file
*/
static void printk_prot(struct seq_file *m, pgprot_t prot, int level)
{
pgprotval_t pr = pgprot_val(prot);
static const char * const level_name[] =
{ "cr3", "pgd", "pud", "pmd", "pte" };
if (!pgprot_val(prot)) {
/* Not present */
seq_printf(m, " ");
} else {
if (pr & _PAGE_USER)
seq_printf(m, "USR ");
else
seq_printf(m, " ");
if (pr & _PAGE_RW)
seq_printf(m, "RW ");
else
seq_printf(m, "ro ");
if (pr & _PAGE_PWT)
seq_printf(m, "PWT ");
else
seq_printf(m, " ");
if (pr & _PAGE_PCD)
seq_printf(m, "PCD ");
else
seq_printf(m, " ");
/* Bit 9 has a different meaning on level 3 vs 4 */
if (level <= 3) {
if (pr & _PAGE_PSE)
seq_printf(m, "PSE ");
else
seq_printf(m, " ");
} else {
if (pr & _PAGE_PAT)
seq_printf(m, "pat ");
else
seq_printf(m, " ");
}
if (pr & _PAGE_GLOBAL)
seq_printf(m, "GLB ");
else
seq_printf(m, " ");
if (pr & _PAGE_NX)
seq_printf(m, "NX ");
else
seq_printf(m, "x ");
}
seq_printf(m, "%s\n", level_name[level]);
}
/*
* On 64 bits, sign-extend the 48 bit address to 64 bit
*/
static unsigned long normalize_addr(unsigned long u)
{
#ifdef CONFIG_X86_64
return (signed long)(u << 16) >> 16;
#else
return u;
#endif
}
/*
* This function gets called on a break in a continuous series
* of PTE entries; the next one is different so we need to
* print what we collected so far.
*/
static void note_page(struct seq_file *m, struct pg_state *st,
pgprot_t new_prot, int level)
{
pgprotval_t prot, cur;
static const char units[] = "KMGTPE";
/*
* If we have a "break" in the series, we need to flush the state that
* we have now. "break" is either changing perms, levels or
* address space marker.
*/
prot = pgprot_val(new_prot) & PTE_FLAGS_MASK;
cur = pgprot_val(st->current_prot) & PTE_FLAGS_MASK;
if (!st->level) {
/* First entry */
st->current_prot = new_prot;
st->level = level;
st->marker = address_markers;
seq_printf(m, "---[ %s ]---\n", st->marker->name);
} else if (prot != cur || level != st->level ||
st->current_address >= st->marker[1].start_address) {
const char *unit = units;
unsigned long delta;
int width = sizeof(unsigned long) * 2;
/*
* Now print the actual finished series
*/
seq_printf(m, "0x%0*lx-0x%0*lx ",
width, st->start_address,
width, st->current_address);
delta = (st->current_address - st->start_address) >> 10;
while (!(delta & 1023) && unit[1]) {
delta >>= 10;
unit++;
}
seq_printf(m, "%9lu%c ", delta, *unit);
printk_prot(m, st->current_prot, st->level);
/*
* We print markers for special areas of address space,
* such as the start of vmalloc space etc.
* This helps in the interpretation.
*/
if (st->current_address >= st->marker[1].start_address) {
st->marker++;
seq_printf(m, "---[ %s ]---\n", st->marker->name);
}
st->start_address = st->current_address;
st->current_prot = new_prot;
st->level = level;
}
}
static void walk_pte_level(struct seq_file *m, struct pg_state *st, pmd_t addr,
unsigned long P)
{
int i;
pte_t *start;
start = (pte_t *) pmd_page_vaddr(addr);
for (i = 0; i < PTRS_PER_PTE; i++) {
pgprot_t prot = pte_pgprot(*start);
st->current_address = normalize_addr(P + i * PTE_LEVEL_MULT);
note_page(m, st, prot, 4);
start++;
}
}
#if PTRS_PER_PMD > 1
static void walk_pmd_level(struct seq_file *m, struct pg_state *st, pud_t addr,
unsigned long P)
{
int i;
pmd_t *start;
start = (pmd_t *) pud_page_vaddr(addr);
for (i = 0; i < PTRS_PER_PMD; i++) {
st->current_address = normalize_addr(P + i * PMD_LEVEL_MULT);
if (!pmd_none(*start)) {
pgprotval_t prot = pmd_val(*start) & PTE_FLAGS_MASK;
if (pmd_large(*start) || !pmd_present(*start))
note_page(m, st, __pgprot(prot), 3);
else
walk_pte_level(m, st, *start,
P + i * PMD_LEVEL_MULT);
} else
note_page(m, st, __pgprot(0), 3);
start++;
}
}
#else
#define walk_pmd_level(m,s,a,p) walk_pte_level(m,s,__pmd(pud_val(a)),p)
#define pud_large(a) pmd_large(__pmd(pud_val(a)))
#define pud_none(a) pmd_none(__pmd(pud_val(a)))
#endif
#if PTRS_PER_PUD > 1
static void walk_pud_level(struct seq_file *m, struct pg_state *st, pgd_t addr,
unsigned long P)
{
int i;
pud_t *start;
start = (pud_t *) pgd_page_vaddr(addr);
for (i = 0; i < PTRS_PER_PUD; i++) {
st->current_address = normalize_addr(P + i * PUD_LEVEL_MULT);
if (!pud_none(*start)) {
pgprotval_t prot = pud_val(*start) & PTE_FLAGS_MASK;
if (pud_large(*start) || !pud_present(*start))
note_page(m, st, __pgprot(prot), 2);
else
walk_pmd_level(m, st, *start,
P + i * PUD_LEVEL_MULT);
} else
note_page(m, st, __pgprot(0), 2);
start++;
}
}
#else
#define walk_pud_level(m,s,a,p) walk_pmd_level(m,s,__pud(pgd_val(a)),p)
#define pgd_large(a) pud_large(__pud(pgd_val(a)))
#define pgd_none(a) pud_none(__pud(pgd_val(a)))
#endif
static void walk_pgd_level(struct seq_file *m)
{
#ifdef CONFIG_X86_64
pgd_t *start = (pgd_t *) &init_level4_pgt;
#else
pgd_t *start = swapper_pg_dir;
#endif
int i;
struct pg_state st;
memset(&st, 0, sizeof(st));
for (i = 0; i < PTRS_PER_PGD; i++) {
st.current_address = normalize_addr(i * PGD_LEVEL_MULT);
if (!pgd_none(*start)) {
pgprotval_t prot = pgd_val(*start) & PTE_FLAGS_MASK;
if (pgd_large(*start) || !pgd_present(*start))
note_page(m, &st, __pgprot(prot), 1);
else
walk_pud_level(m, &st, *start,
i * PGD_LEVEL_MULT);
} else
note_page(m, &st, __pgprot(0), 1);
start++;
}
/* Flush out the last page */
st.current_address = normalize_addr(PTRS_PER_PGD*PGD_LEVEL_MULT);
note_page(m, &st, __pgprot(0), 0);
}
static int ptdump_show(struct seq_file *m, void *v)
{
walk_pgd_level(m);
return 0;
}
static int ptdump_open(struct inode *inode, struct file *filp)
{
return single_open(filp, ptdump_show, NULL);
}
static const struct file_operations ptdump_fops = {
.open = ptdump_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int pt_dump_init(void)
{
struct dentry *pe;
#ifdef CONFIG_X86_32
/* Not a compile-time constant on x86-32 */
address_markers[VMALLOC_START_NR].start_address = VMALLOC_START;
address_markers[VMALLOC_END_NR].start_address = VMALLOC_END;
# ifdef CONFIG_HIGHMEM
address_markers[PKMAP_BASE_NR].start_address = PKMAP_BASE;
# endif
address_markers[FIXADDR_START_NR].start_address = FIXADDR_START;
#endif
pe = debugfs_create_file("kernel_page_tables", 0600, NULL, NULL,
&ptdump_fops);
if (!pe)
return -ENOMEM;
return 0;
}
__initcall(pt_dump_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Arjan van de Ven <arjan@linux.intel.com>");
MODULE_DESCRIPTION("Kernel debugging helper that dumps pagetables");
| gpl-2.0 |
felipesanches/linux-sunxi | drivers/tty/n_tty.c | 222 | 53306 | /*
* n_tty.c --- implements the N_TTY line discipline.
*
* This code used to be in tty_io.c, but things are getting hairy
* enough that it made sense to split things off. (The N_TTY
* processing has changed so much that it's hardly recognizable,
* anyway...)
*
* Note that the open routine for N_TTY is guaranteed never to return
* an error. This is because Linux will fall back to setting a line
* to N_TTY if it can not switch to any other line discipline.
*
* Written by Theodore Ts'o, Copyright 1994.
*
* This file also contains code originally written by Linus Torvalds,
* Copyright 1991, 1992, 1993, and by Julian Cowley, Copyright 1994.
*
* This file may be redistributed under the terms of the GNU General Public
* License.
*
* Reduced memory usage for older ARM systems - Russell King.
*
* 2000/01/20 Fixed SMP locking on put_tty_queue using bits of
* the patch by Andrew J. Kroll <ag784@freenet.buffalo.edu>
* who actually finally proved there really was a race.
*
* 2002/03/18 Implemented n_tty_wakeup to send SIGIO POLL_OUTs to
* waiting writing processes-Sapan Bhatia <sapan@corewars.org>.
* Also fixed a bug in BLOCKING mode where n_tty_write returns
* EAGAIN
*/
#include <linux/types.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/fcntl.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/timer.h>
#include <linux/ctype.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/bitops.h>
#include <linux/audit.h>
#include <linux/file.h>
#include <linux/uaccess.h>
#include <linux/module.h>
/* number of characters left in xmit buffer before select has we have room */
#define WAKEUP_CHARS 256
/*
* This defines the low- and high-watermarks for throttling and
* unthrottling the TTY driver. These watermarks are used for
* controlling the space in the read buffer.
*/
#define TTY_THRESHOLD_THROTTLE 128 /* now based on remaining room */
#define TTY_THRESHOLD_UNTHROTTLE 128
/*
* Special byte codes used in the echo buffer to represent operations
* or special handling of characters. Bytes in the echo buffer that
* are not part of such special blocks are treated as normal character
* codes.
*/
#define ECHO_OP_START 0xff
#define ECHO_OP_MOVE_BACK_COL 0x80
#define ECHO_OP_SET_CANON_COL 0x81
#define ECHO_OP_ERASE_TAB 0x82
static inline int tty_put_user(struct tty_struct *tty, unsigned char x,
unsigned char __user *ptr)
{
tty_audit_add_data(tty, &x, 1);
return put_user(x, ptr);
}
/**
* n_tty_set__room - receive space
* @tty: terminal
*
* Called by the driver to find out how much data it is
* permitted to feed to the line discipline without any being lost
* and thus to manage flow control. Not serialized. Answers for the
* "instant".
*/
static void n_tty_set_room(struct tty_struct *tty)
{
/* tty->read_cnt is not read locked ? */
int left = N_TTY_BUF_SIZE - tty->read_cnt - 1;
int old_left;
/*
* If we are doing input canonicalization, and there are no
* pending newlines, let characters through without limit, so
* that erase characters will be handled. Other excess
* characters will be beeped.
*/
if (left <= 0)
left = tty->icanon && !tty->canon_data;
old_left = tty->receive_room;
tty->receive_room = left;
/* Did this open up the receive buffer? We may need to flip */
if (left && !old_left)
schedule_work(&tty->buf.work);
}
static void put_tty_queue_nolock(unsigned char c, struct tty_struct *tty)
{
if (tty->read_cnt < N_TTY_BUF_SIZE) {
tty->read_buf[tty->read_head] = c;
tty->read_head = (tty->read_head + 1) & (N_TTY_BUF_SIZE-1);
tty->read_cnt++;
}
}
/**
* put_tty_queue - add character to tty
* @c: character
* @tty: tty device
*
* Add a character to the tty read_buf queue. This is done under the
* read_lock to serialize character addition and also to protect us
* against parallel reads or flushes
*/
static void put_tty_queue(unsigned char c, struct tty_struct *tty)
{
unsigned long flags;
/*
* The problem of stomping on the buffers ends here.
* Why didn't anyone see this one coming? --AJK
*/
spin_lock_irqsave(&tty->read_lock, flags);
put_tty_queue_nolock(c, tty);
spin_unlock_irqrestore(&tty->read_lock, flags);
}
/**
* check_unthrottle - allow new receive data
* @tty; tty device
*
* Check whether to call the driver unthrottle functions
*
* Can sleep, may be called under the atomic_read_lock mutex but
* this is not guaranteed.
*/
static void check_unthrottle(struct tty_struct *tty)
{
if (tty->count)
tty_unthrottle(tty);
}
/**
* reset_buffer_flags - reset buffer state
* @tty: terminal to reset
*
* Reset the read buffer counters, clear the flags,
* and make sure the driver is unthrottled. Called
* from n_tty_open() and n_tty_flush_buffer().
*
* Locking: tty_read_lock for read fields.
*/
static void reset_buffer_flags(struct tty_struct *tty)
{
unsigned long flags;
spin_lock_irqsave(&tty->read_lock, flags);
tty->read_head = tty->read_tail = tty->read_cnt = 0;
spin_unlock_irqrestore(&tty->read_lock, flags);
mutex_lock(&tty->echo_lock);
tty->echo_pos = tty->echo_cnt = tty->echo_overrun = 0;
mutex_unlock(&tty->echo_lock);
tty->canon_head = tty->canon_data = tty->erasing = 0;
memset(&tty->read_flags, 0, sizeof tty->read_flags);
n_tty_set_room(tty);
}
/**
* n_tty_flush_buffer - clean input queue
* @tty: terminal device
*
* Flush the input buffer. Called when the line discipline is
* being closed, when the tty layer wants the buffer flushed (eg
* at hangup) or when the N_TTY line discipline internally has to
* clean the pending queue (for example some signals).
*
* Locking: ctrl_lock, read_lock.
*/
static void n_tty_flush_buffer(struct tty_struct *tty)
{
unsigned long flags;
/* clear everything and unthrottle the driver */
reset_buffer_flags(tty);
if (!tty->link)
return;
spin_lock_irqsave(&tty->ctrl_lock, flags);
if (tty->link->packet) {
tty->ctrl_status |= TIOCPKT_FLUSHREAD;
wake_up_interruptible(&tty->link->read_wait);
}
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
}
/**
* n_tty_chars_in_buffer - report available bytes
* @tty: tty device
*
* Report the number of characters buffered to be delivered to user
* at this instant in time.
*
* Locking: read_lock
*/
static ssize_t n_tty_chars_in_buffer(struct tty_struct *tty)
{
unsigned long flags;
ssize_t n = 0;
spin_lock_irqsave(&tty->read_lock, flags);
if (!tty->icanon) {
n = tty->read_cnt;
} else if (tty->canon_data) {
n = (tty->canon_head > tty->read_tail) ?
tty->canon_head - tty->read_tail :
tty->canon_head + (N_TTY_BUF_SIZE - tty->read_tail);
}
spin_unlock_irqrestore(&tty->read_lock, flags);
return n;
}
/**
* is_utf8_continuation - utf8 multibyte check
* @c: byte to check
*
* Returns true if the utf8 character 'c' is a multibyte continuation
* character. We use this to correctly compute the on screen size
* of the character when printing
*/
static inline int is_utf8_continuation(unsigned char c)
{
return (c & 0xc0) == 0x80;
}
/**
* is_continuation - multibyte check
* @c: byte to check
*
* Returns true if the utf8 character 'c' is a multibyte continuation
* character and the terminal is in unicode mode.
*/
static inline int is_continuation(unsigned char c, struct tty_struct *tty)
{
return I_IUTF8(tty) && is_utf8_continuation(c);
}
/**
* do_output_char - output one character
* @c: character (or partial unicode symbol)
* @tty: terminal device
* @space: space available in tty driver write buffer
*
* This is a helper function that handles one output character
* (including special characters like TAB, CR, LF, etc.),
* doing OPOST processing and putting the results in the
* tty driver's write buffer.
*
* Note that Linux currently ignores TABDLY, CRDLY, VTDLY, FFDLY
* and NLDLY. They simply aren't relevant in the world today.
* If you ever need them, add them here.
*
* Returns the number of bytes of buffer space used or -1 if
* no space left.
*
* Locking: should be called under the output_lock to protect
* the column state and space left in the buffer
*/
static int do_output_char(unsigned char c, struct tty_struct *tty, int space)
{
int spaces;
if (!space)
return -1;
switch (c) {
case '\n':
if (O_ONLRET(tty))
tty->column = 0;
if (O_ONLCR(tty)) {
if (space < 2)
return -1;
tty->canon_column = tty->column = 0;
tty->ops->write(tty, "\r\n", 2);
return 2;
}
tty->canon_column = tty->column;
break;
case '\r':
if (O_ONOCR(tty) && tty->column == 0)
return 0;
if (O_OCRNL(tty)) {
c = '\n';
if (O_ONLRET(tty))
tty->canon_column = tty->column = 0;
break;
}
tty->canon_column = tty->column = 0;
break;
case '\t':
spaces = 8 - (tty->column & 7);
if (O_TABDLY(tty) == XTABS) {
if (space < spaces)
return -1;
tty->column += spaces;
tty->ops->write(tty, " ", spaces);
return spaces;
}
tty->column += spaces;
break;
case '\b':
if (tty->column > 0)
tty->column--;
break;
default:
if (!iscntrl(c)) {
if (O_OLCUC(tty))
c = toupper(c);
if (!is_continuation(c, tty))
tty->column++;
}
break;
}
tty_put_char(tty, c);
return 1;
}
/**
* process_output - output post processor
* @c: character (or partial unicode symbol)
* @tty: terminal device
*
* Output one character with OPOST processing.
* Returns -1 when the output device is full and the character
* must be retried.
*
* Locking: output_lock to protect column state and space left
* (also, this is called from n_tty_write under the
* tty layer write lock)
*/
static int process_output(unsigned char c, struct tty_struct *tty)
{
int space, retval;
mutex_lock(&tty->output_lock);
space = tty_write_room(tty);
retval = do_output_char(c, tty, space);
mutex_unlock(&tty->output_lock);
if (retval < 0)
return -1;
else
return 0;
}
/**
* process_output_block - block post processor
* @tty: terminal device
* @buf: character buffer
* @nr: number of bytes to output
*
* Output a block of characters with OPOST processing.
* Returns the number of characters output.
*
* This path is used to speed up block console writes, among other
* things when processing blocks of output data. It handles only
* the simple cases normally found and helps to generate blocks of
* symbols for the console driver and thus improve performance.
*
* Locking: output_lock to protect column state and space left
* (also, this is called from n_tty_write under the
* tty layer write lock)
*/
static ssize_t process_output_block(struct tty_struct *tty,
const unsigned char *buf, unsigned int nr)
{
int space;
int i;
const unsigned char *cp;
mutex_lock(&tty->output_lock);
space = tty_write_room(tty);
if (!space) {
mutex_unlock(&tty->output_lock);
return 0;
}
if (nr > space)
nr = space;
for (i = 0, cp = buf; i < nr; i++, cp++) {
unsigned char c = *cp;
switch (c) {
case '\n':
if (O_ONLRET(tty))
tty->column = 0;
if (O_ONLCR(tty))
goto break_out;
tty->canon_column = tty->column;
break;
case '\r':
if (O_ONOCR(tty) && tty->column == 0)
goto break_out;
if (O_OCRNL(tty))
goto break_out;
tty->canon_column = tty->column = 0;
break;
case '\t':
goto break_out;
case '\b':
if (tty->column > 0)
tty->column--;
break;
default:
if (!iscntrl(c)) {
if (O_OLCUC(tty))
goto break_out;
if (!is_continuation(c, tty))
tty->column++;
}
break;
}
}
break_out:
i = tty->ops->write(tty, buf, i);
mutex_unlock(&tty->output_lock);
return i;
}
/**
* process_echoes - write pending echo characters
* @tty: terminal device
*
* Write previously buffered echo (and other ldisc-generated)
* characters to the tty.
*
* Characters generated by the ldisc (including echoes) need to
* be buffered because the driver's write buffer can fill during
* heavy program output. Echoing straight to the driver will
* often fail under these conditions, causing lost characters and
* resulting mismatches of ldisc state information.
*
* Since the ldisc state must represent the characters actually sent
* to the driver at the time of the write, operations like certain
* changes in column state are also saved in the buffer and executed
* here.
*
* A circular fifo buffer is used so that the most recent characters
* are prioritized. Also, when control characters are echoed with a
* prefixed "^", the pair is treated atomically and thus not separated.
*
* Locking: output_lock to protect column state and space left,
* echo_lock to protect the echo buffer
*/
static void process_echoes(struct tty_struct *tty)
{
int space, nr;
unsigned char c;
unsigned char *cp, *buf_end;
if (!tty->echo_cnt)
return;
mutex_lock(&tty->output_lock);
mutex_lock(&tty->echo_lock);
space = tty_write_room(tty);
buf_end = tty->echo_buf + N_TTY_BUF_SIZE;
cp = tty->echo_buf + tty->echo_pos;
nr = tty->echo_cnt;
while (nr > 0) {
c = *cp;
if (c == ECHO_OP_START) {
unsigned char op;
unsigned char *opp;
int no_space_left = 0;
/*
* If the buffer byte is the start of a multi-byte
* operation, get the next byte, which is either the
* op code or a control character value.
*/
opp = cp + 1;
if (opp == buf_end)
opp -= N_TTY_BUF_SIZE;
op = *opp;
switch (op) {
unsigned int num_chars, num_bs;
case ECHO_OP_ERASE_TAB:
if (++opp == buf_end)
opp -= N_TTY_BUF_SIZE;
num_chars = *opp;
/*
* Determine how many columns to go back
* in order to erase the tab.
* This depends on the number of columns
* used by other characters within the tab
* area. If this (modulo 8) count is from
* the start of input rather than from a
* previous tab, we offset by canon column.
* Otherwise, tab spacing is normal.
*/
if (!(num_chars & 0x80))
num_chars += tty->canon_column;
num_bs = 8 - (num_chars & 7);
if (num_bs > space) {
no_space_left = 1;
break;
}
space -= num_bs;
while (num_bs--) {
tty_put_char(tty, '\b');
if (tty->column > 0)
tty->column--;
}
cp += 3;
nr -= 3;
break;
case ECHO_OP_SET_CANON_COL:
tty->canon_column = tty->column;
cp += 2;
nr -= 2;
break;
case ECHO_OP_MOVE_BACK_COL:
if (tty->column > 0)
tty->column--;
cp += 2;
nr -= 2;
break;
case ECHO_OP_START:
/* This is an escaped echo op start code */
if (!space) {
no_space_left = 1;
break;
}
tty_put_char(tty, ECHO_OP_START);
tty->column++;
space--;
cp += 2;
nr -= 2;
break;
default:
/*
* If the op is not a special byte code,
* it is a ctrl char tagged to be echoed
* as "^X" (where X is the letter
* representing the control char).
* Note that we must ensure there is
* enough space for the whole ctrl pair.
*
*/
if (space < 2) {
no_space_left = 1;
break;
}
tty_put_char(tty, '^');
tty_put_char(tty, op ^ 0100);
tty->column += 2;
space -= 2;
cp += 2;
nr -= 2;
}
if (no_space_left)
break;
} else {
if (O_OPOST(tty) &&
!(test_bit(TTY_HW_COOK_OUT, &tty->flags))) {
int retval = do_output_char(c, tty, space);
if (retval < 0)
break;
space -= retval;
} else {
if (!space)
break;
tty_put_char(tty, c);
space -= 1;
}
cp += 1;
nr -= 1;
}
/* When end of circular buffer reached, wrap around */
if (cp >= buf_end)
cp -= N_TTY_BUF_SIZE;
}
if (nr == 0) {
tty->echo_pos = 0;
tty->echo_cnt = 0;
tty->echo_overrun = 0;
} else {
int num_processed = tty->echo_cnt - nr;
tty->echo_pos += num_processed;
tty->echo_pos &= N_TTY_BUF_SIZE - 1;
tty->echo_cnt = nr;
if (num_processed > 0)
tty->echo_overrun = 0;
}
mutex_unlock(&tty->echo_lock);
mutex_unlock(&tty->output_lock);
if (tty->ops->flush_chars)
tty->ops->flush_chars(tty);
}
/**
* add_echo_byte - add a byte to the echo buffer
* @c: unicode byte to echo
* @tty: terminal device
*
* Add a character or operation byte to the echo buffer.
*
* Should be called under the echo lock to protect the echo buffer.
*/
static void add_echo_byte(unsigned char c, struct tty_struct *tty)
{
int new_byte_pos;
if (tty->echo_cnt == N_TTY_BUF_SIZE) {
/* Circular buffer is already at capacity */
new_byte_pos = tty->echo_pos;
/*
* Since the buffer start position needs to be advanced,
* be sure to step by a whole operation byte group.
*/
if (tty->echo_buf[tty->echo_pos] == ECHO_OP_START) {
if (tty->echo_buf[(tty->echo_pos + 1) &
(N_TTY_BUF_SIZE - 1)] ==
ECHO_OP_ERASE_TAB) {
tty->echo_pos += 3;
tty->echo_cnt -= 2;
} else {
tty->echo_pos += 2;
tty->echo_cnt -= 1;
}
} else {
tty->echo_pos++;
}
tty->echo_pos &= N_TTY_BUF_SIZE - 1;
tty->echo_overrun = 1;
} else {
new_byte_pos = tty->echo_pos + tty->echo_cnt;
new_byte_pos &= N_TTY_BUF_SIZE - 1;
tty->echo_cnt++;
}
tty->echo_buf[new_byte_pos] = c;
}
/**
* echo_move_back_col - add operation to move back a column
* @tty: terminal device
*
* Add an operation to the echo buffer to move back one column.
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_move_back_col(struct tty_struct *tty)
{
mutex_lock(&tty->echo_lock);
add_echo_byte(ECHO_OP_START, tty);
add_echo_byte(ECHO_OP_MOVE_BACK_COL, tty);
mutex_unlock(&tty->echo_lock);
}
/**
* echo_set_canon_col - add operation to set the canon column
* @tty: terminal device
*
* Add an operation to the echo buffer to set the canon column
* to the current column.
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_set_canon_col(struct tty_struct *tty)
{
mutex_lock(&tty->echo_lock);
add_echo_byte(ECHO_OP_START, tty);
add_echo_byte(ECHO_OP_SET_CANON_COL, tty);
mutex_unlock(&tty->echo_lock);
}
/**
* echo_erase_tab - add operation to erase a tab
* @num_chars: number of character columns already used
* @after_tab: true if num_chars starts after a previous tab
* @tty: terminal device
*
* Add an operation to the echo buffer to erase a tab.
*
* Called by the eraser function, which knows how many character
* columns have been used since either a previous tab or the start
* of input. This information will be used later, along with
* canon column (if applicable), to go back the correct number
* of columns.
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_erase_tab(unsigned int num_chars, int after_tab,
struct tty_struct *tty)
{
mutex_lock(&tty->echo_lock);
add_echo_byte(ECHO_OP_START, tty);
add_echo_byte(ECHO_OP_ERASE_TAB, tty);
/* We only need to know this modulo 8 (tab spacing) */
num_chars &= 7;
/* Set the high bit as a flag if num_chars is after a previous tab */
if (after_tab)
num_chars |= 0x80;
add_echo_byte(num_chars, tty);
mutex_unlock(&tty->echo_lock);
}
/**
* echo_char_raw - echo a character raw
* @c: unicode byte to echo
* @tty: terminal device
*
* Echo user input back onto the screen. This must be called only when
* L_ECHO(tty) is true. Called from the driver receive_buf path.
*
* This variant does not treat control characters specially.
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_char_raw(unsigned char c, struct tty_struct *tty)
{
mutex_lock(&tty->echo_lock);
if (c == ECHO_OP_START) {
add_echo_byte(ECHO_OP_START, tty);
add_echo_byte(ECHO_OP_START, tty);
} else {
add_echo_byte(c, tty);
}
mutex_unlock(&tty->echo_lock);
}
/**
* echo_char - echo a character
* @c: unicode byte to echo
* @tty: terminal device
*
* Echo user input back onto the screen. This must be called only when
* L_ECHO(tty) is true. Called from the driver receive_buf path.
*
* This variant tags control characters to be echoed as "^X"
* (where X is the letter representing the control char).
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_char(unsigned char c, struct tty_struct *tty)
{
mutex_lock(&tty->echo_lock);
if (c == ECHO_OP_START) {
add_echo_byte(ECHO_OP_START, tty);
add_echo_byte(ECHO_OP_START, tty);
} else {
if (L_ECHOCTL(tty) && iscntrl(c) && c != '\t')
add_echo_byte(ECHO_OP_START, tty);
add_echo_byte(c, tty);
}
mutex_unlock(&tty->echo_lock);
}
/**
* finish_erasing - complete erase
* @tty: tty doing the erase
*/
static inline void finish_erasing(struct tty_struct *tty)
{
if (tty->erasing) {
echo_char_raw('/', tty);
tty->erasing = 0;
}
}
/**
* eraser - handle erase function
* @c: character input
* @tty: terminal device
*
* Perform erase and necessary output when an erase character is
* present in the stream from the driver layer. Handles the complexities
* of UTF-8 multibyte symbols.
*
* Locking: read_lock for tty buffers
*/
static void eraser(unsigned char c, struct tty_struct *tty)
{
enum { ERASE, WERASE, KILL } kill_type;
int head, seen_alnums, cnt;
unsigned long flags;
/* FIXME: locking needed ? */
if (tty->read_head == tty->canon_head) {
/* process_output('\a', tty); */ /* what do you think? */
return;
}
if (c == ERASE_CHAR(tty))
kill_type = ERASE;
else if (c == WERASE_CHAR(tty))
kill_type = WERASE;
else {
if (!L_ECHO(tty)) {
spin_lock_irqsave(&tty->read_lock, flags);
tty->read_cnt -= ((tty->read_head - tty->canon_head) &
(N_TTY_BUF_SIZE - 1));
tty->read_head = tty->canon_head;
spin_unlock_irqrestore(&tty->read_lock, flags);
return;
}
if (!L_ECHOK(tty) || !L_ECHOKE(tty) || !L_ECHOE(tty)) {
spin_lock_irqsave(&tty->read_lock, flags);
tty->read_cnt -= ((tty->read_head - tty->canon_head) &
(N_TTY_BUF_SIZE - 1));
tty->read_head = tty->canon_head;
spin_unlock_irqrestore(&tty->read_lock, flags);
finish_erasing(tty);
echo_char(KILL_CHAR(tty), tty);
/* Add a newline if ECHOK is on and ECHOKE is off. */
if (L_ECHOK(tty))
echo_char_raw('\n', tty);
return;
}
kill_type = KILL;
}
seen_alnums = 0;
/* FIXME: Locking ?? */
while (tty->read_head != tty->canon_head) {
head = tty->read_head;
/* erase a single possibly multibyte character */
do {
head = (head - 1) & (N_TTY_BUF_SIZE-1);
c = tty->read_buf[head];
} while (is_continuation(c, tty) && head != tty->canon_head);
/* do not partially erase */
if (is_continuation(c, tty))
break;
if (kill_type == WERASE) {
/* Equivalent to BSD's ALTWERASE. */
if (isalnum(c) || c == '_')
seen_alnums++;
else if (seen_alnums)
break;
}
cnt = (tty->read_head - head) & (N_TTY_BUF_SIZE-1);
spin_lock_irqsave(&tty->read_lock, flags);
tty->read_head = head;
tty->read_cnt -= cnt;
spin_unlock_irqrestore(&tty->read_lock, flags);
if (L_ECHO(tty)) {
if (L_ECHOPRT(tty)) {
if (!tty->erasing) {
echo_char_raw('\\', tty);
tty->erasing = 1;
}
/* if cnt > 1, output a multi-byte character */
echo_char(c, tty);
while (--cnt > 0) {
head = (head+1) & (N_TTY_BUF_SIZE-1);
echo_char_raw(tty->read_buf[head], tty);
echo_move_back_col(tty);
}
} else if (kill_type == ERASE && !L_ECHOE(tty)) {
echo_char(ERASE_CHAR(tty), tty);
} else if (c == '\t') {
unsigned int num_chars = 0;
int after_tab = 0;
unsigned long tail = tty->read_head;
/*
* Count the columns used for characters
* since the start of input or after a
* previous tab.
* This info is used to go back the correct
* number of columns.
*/
while (tail != tty->canon_head) {
tail = (tail-1) & (N_TTY_BUF_SIZE-1);
c = tty->read_buf[tail];
if (c == '\t') {
after_tab = 1;
break;
} else if (iscntrl(c)) {
if (L_ECHOCTL(tty))
num_chars += 2;
} else if (!is_continuation(c, tty)) {
num_chars++;
}
}
echo_erase_tab(num_chars, after_tab, tty);
} else {
if (iscntrl(c) && L_ECHOCTL(tty)) {
echo_char_raw('\b', tty);
echo_char_raw(' ', tty);
echo_char_raw('\b', tty);
}
if (!iscntrl(c) || L_ECHOCTL(tty)) {
echo_char_raw('\b', tty);
echo_char_raw(' ', tty);
echo_char_raw('\b', tty);
}
}
}
if (kill_type == ERASE)
break;
}
if (tty->read_head == tty->canon_head && L_ECHO(tty))
finish_erasing(tty);
}
/**
* isig - handle the ISIG optio
* @sig: signal
* @tty: terminal
* @flush: force flush
*
* Called when a signal is being sent due to terminal input. This
* may caus terminal flushing to take place according to the termios
* settings and character used. Called from the driver receive_buf
* path so serialized.
*
* Locking: ctrl_lock, read_lock (both via flush buffer)
*/
static inline void isig(int sig, struct tty_struct *tty, int flush)
{
if (tty->pgrp)
kill_pgrp(tty->pgrp, sig, 1);
if (flush || !L_NOFLSH(tty)) {
n_tty_flush_buffer(tty);
tty_driver_flush_buffer(tty);
}
}
/**
* n_tty_receive_break - handle break
* @tty: terminal
*
* An RS232 break event has been hit in the incoming bitstream. This
* can cause a variety of events depending upon the termios settings.
*
* Called from the receive_buf path so single threaded.
*/
static inline void n_tty_receive_break(struct tty_struct *tty)
{
if (I_IGNBRK(tty))
return;
if (I_BRKINT(tty)) {
isig(SIGINT, tty, 1);
return;
}
if (I_PARMRK(tty)) {
put_tty_queue('\377', tty);
put_tty_queue('\0', tty);
}
put_tty_queue('\0', tty);
wake_up_interruptible(&tty->read_wait);
}
/**
* n_tty_receive_overrun - handle overrun reporting
* @tty: terminal
*
* Data arrived faster than we could process it. While the tty
* driver has flagged this the bits that were missed are gone
* forever.
*
* Called from the receive_buf path so single threaded. Does not
* need locking as num_overrun and overrun_time are function
* private.
*/
static inline void n_tty_receive_overrun(struct tty_struct *tty)
{
char buf[64];
tty->num_overrun++;
if (time_before(tty->overrun_time, jiffies - HZ) ||
time_after(tty->overrun_time, jiffies)) {
printk(KERN_WARNING "%s: %d input overrun(s)\n",
tty_name(tty, buf),
tty->num_overrun);
tty->overrun_time = jiffies;
tty->num_overrun = 0;
}
}
/**
* n_tty_receive_parity_error - error notifier
* @tty: terminal device
* @c: character
*
* Process a parity error and queue the right data to indicate
* the error case if necessary. Locking as per n_tty_receive_buf.
*/
static inline void n_tty_receive_parity_error(struct tty_struct *tty,
unsigned char c)
{
if (I_IGNPAR(tty))
return;
if (I_PARMRK(tty)) {
put_tty_queue('\377', tty);
put_tty_queue('\0', tty);
put_tty_queue(c, tty);
} else if (I_INPCK(tty))
put_tty_queue('\0', tty);
else
put_tty_queue(c, tty);
wake_up_interruptible(&tty->read_wait);
}
/**
* n_tty_receive_char - perform processing
* @tty: terminal device
* @c: character
*
* Process an individual character of input received from the driver.
* This is serialized with respect to itself by the rules for the
* driver above.
*/
static inline void n_tty_receive_char(struct tty_struct *tty, unsigned char c)
{
unsigned long flags;
int parmrk;
if (tty->raw) {
put_tty_queue(c, tty);
return;
}
if (I_ISTRIP(tty))
c &= 0x7f;
if (I_IUCLC(tty) && L_IEXTEN(tty))
c = tolower(c);
if (L_EXTPROC(tty)) {
put_tty_queue(c, tty);
return;
}
if (tty->stopped && !tty->flow_stopped && I_IXON(tty) &&
I_IXANY(tty) && c != START_CHAR(tty) && c != STOP_CHAR(tty) &&
c != INTR_CHAR(tty) && c != QUIT_CHAR(tty) && c != SUSP_CHAR(tty)) {
start_tty(tty);
process_echoes(tty);
}
if (tty->closing) {
if (I_IXON(tty)) {
if (c == START_CHAR(tty)) {
start_tty(tty);
process_echoes(tty);
} else if (c == STOP_CHAR(tty))
stop_tty(tty);
}
return;
}
/*
* If the previous character was LNEXT, or we know that this
* character is not one of the characters that we'll have to
* handle specially, do shortcut processing to speed things
* up.
*/
if (!test_bit(c, tty->process_char_map) || tty->lnext) {
tty->lnext = 0;
parmrk = (c == (unsigned char) '\377' && I_PARMRK(tty)) ? 1 : 0;
if (tty->read_cnt >= (N_TTY_BUF_SIZE - parmrk - 1)) {
/* beep if no space */
if (L_ECHO(tty))
process_output('\a', tty);
return;
}
if (L_ECHO(tty)) {
finish_erasing(tty);
/* Record the column of first canon char. */
if (tty->canon_head == tty->read_head)
echo_set_canon_col(tty);
echo_char(c, tty);
process_echoes(tty);
}
if (parmrk)
put_tty_queue(c, tty);
put_tty_queue(c, tty);
return;
}
if (I_IXON(tty)) {
if (c == START_CHAR(tty)) {
start_tty(tty);
process_echoes(tty);
return;
}
if (c == STOP_CHAR(tty)) {
stop_tty(tty);
return;
}
}
if (L_ISIG(tty)) {
int signal;
signal = SIGINT;
if (c == INTR_CHAR(tty))
goto send_signal;
signal = SIGQUIT;
if (c == QUIT_CHAR(tty))
goto send_signal;
signal = SIGTSTP;
if (c == SUSP_CHAR(tty)) {
send_signal:
/*
* Note that we do not use isig() here because we want
* the order to be:
* 1) flush, 2) echo, 3) signal
*/
if (!L_NOFLSH(tty)) {
n_tty_flush_buffer(tty);
tty_driver_flush_buffer(tty);
}
if (I_IXON(tty))
start_tty(tty);
if (L_ECHO(tty)) {
echo_char(c, tty);
process_echoes(tty);
}
if (tty->pgrp)
kill_pgrp(tty->pgrp, signal, 1);
return;
}
}
if (c == '\r') {
if (I_IGNCR(tty))
return;
if (I_ICRNL(tty))
c = '\n';
} else if (c == '\n' && I_INLCR(tty))
c = '\r';
if (tty->icanon) {
if (c == ERASE_CHAR(tty) || c == KILL_CHAR(tty) ||
(c == WERASE_CHAR(tty) && L_IEXTEN(tty))) {
eraser(c, tty);
process_echoes(tty);
return;
}
if (c == LNEXT_CHAR(tty) && L_IEXTEN(tty)) {
tty->lnext = 1;
if (L_ECHO(tty)) {
finish_erasing(tty);
if (L_ECHOCTL(tty)) {
echo_char_raw('^', tty);
echo_char_raw('\b', tty);
process_echoes(tty);
}
}
return;
}
if (c == REPRINT_CHAR(tty) && L_ECHO(tty) &&
L_IEXTEN(tty)) {
unsigned long tail = tty->canon_head;
finish_erasing(tty);
echo_char(c, tty);
echo_char_raw('\n', tty);
while (tail != tty->read_head) {
echo_char(tty->read_buf[tail], tty);
tail = (tail+1) & (N_TTY_BUF_SIZE-1);
}
process_echoes(tty);
return;
}
if (c == '\n') {
if (tty->read_cnt >= N_TTY_BUF_SIZE) {
if (L_ECHO(tty))
process_output('\a', tty);
return;
}
if (L_ECHO(tty) || L_ECHONL(tty)) {
echo_char_raw('\n', tty);
process_echoes(tty);
}
goto handle_newline;
}
if (c == EOF_CHAR(tty)) {
if (tty->read_cnt >= N_TTY_BUF_SIZE)
return;
if (tty->canon_head != tty->read_head)
set_bit(TTY_PUSH, &tty->flags);
c = __DISABLED_CHAR;
goto handle_newline;
}
if ((c == EOL_CHAR(tty)) ||
(c == EOL2_CHAR(tty) && L_IEXTEN(tty))) {
parmrk = (c == (unsigned char) '\377' && I_PARMRK(tty))
? 1 : 0;
if (tty->read_cnt >= (N_TTY_BUF_SIZE - parmrk)) {
if (L_ECHO(tty))
process_output('\a', tty);
return;
}
/*
* XXX are EOL_CHAR and EOL2_CHAR echoed?!?
*/
if (L_ECHO(tty)) {
/* Record the column of first canon char. */
if (tty->canon_head == tty->read_head)
echo_set_canon_col(tty);
echo_char(c, tty);
process_echoes(tty);
}
/*
* XXX does PARMRK doubling happen for
* EOL_CHAR and EOL2_CHAR?
*/
if (parmrk)
put_tty_queue(c, tty);
handle_newline:
spin_lock_irqsave(&tty->read_lock, flags);
set_bit(tty->read_head, tty->read_flags);
put_tty_queue_nolock(c, tty);
tty->canon_head = tty->read_head;
tty->canon_data++;
spin_unlock_irqrestore(&tty->read_lock, flags);
kill_fasync(&tty->fasync, SIGIO, POLL_IN);
if (waitqueue_active(&tty->read_wait))
wake_up_interruptible(&tty->read_wait);
return;
}
}
parmrk = (c == (unsigned char) '\377' && I_PARMRK(tty)) ? 1 : 0;
if (tty->read_cnt >= (N_TTY_BUF_SIZE - parmrk - 1)) {
/* beep if no space */
if (L_ECHO(tty))
process_output('\a', tty);
return;
}
if (L_ECHO(tty)) {
finish_erasing(tty);
if (c == '\n')
echo_char_raw('\n', tty);
else {
/* Record the column of first canon char. */
if (tty->canon_head == tty->read_head)
echo_set_canon_col(tty);
echo_char(c, tty);
}
process_echoes(tty);
}
if (parmrk)
put_tty_queue(c, tty);
put_tty_queue(c, tty);
}
/**
* n_tty_write_wakeup - asynchronous I/O notifier
* @tty: tty device
*
* Required for the ptys, serial driver etc. since processes
* that attach themselves to the master and rely on ASYNC
* IO must be woken up
*/
static void n_tty_write_wakeup(struct tty_struct *tty)
{
if (tty->fasync && test_and_clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags))
kill_fasync(&tty->fasync, SIGIO, POLL_OUT);
}
/**
* n_tty_receive_buf - data receive
* @tty: terminal device
* @cp: buffer
* @fp: flag buffer
* @count: characters
*
* Called by the terminal driver when a block of characters has
* been received. This function must be called from soft contexts
* not from interrupt context. The driver is responsible for making
* calls one at a time and in order (or using flush_to_ldisc)
*/
static void n_tty_receive_buf(struct tty_struct *tty, const unsigned char *cp,
char *fp, int count)
{
const unsigned char *p;
char *f, flags = TTY_NORMAL;
int i;
char buf[64];
unsigned long cpuflags;
if (!tty->read_buf)
return;
if (tty->real_raw) {
spin_lock_irqsave(&tty->read_lock, cpuflags);
i = min(N_TTY_BUF_SIZE - tty->read_cnt,
N_TTY_BUF_SIZE - tty->read_head);
i = min(count, i);
memcpy(tty->read_buf + tty->read_head, cp, i);
tty->read_head = (tty->read_head + i) & (N_TTY_BUF_SIZE-1);
tty->read_cnt += i;
cp += i;
count -= i;
i = min(N_TTY_BUF_SIZE - tty->read_cnt,
N_TTY_BUF_SIZE - tty->read_head);
i = min(count, i);
memcpy(tty->read_buf + tty->read_head, cp, i);
tty->read_head = (tty->read_head + i) & (N_TTY_BUF_SIZE-1);
tty->read_cnt += i;
spin_unlock_irqrestore(&tty->read_lock, cpuflags);
} else {
for (i = count, p = cp, f = fp; i; i--, p++) {
if (f)
flags = *f++;
switch (flags) {
case TTY_NORMAL:
n_tty_receive_char(tty, *p);
break;
case TTY_BREAK:
n_tty_receive_break(tty);
break;
case TTY_PARITY:
case TTY_FRAME:
n_tty_receive_parity_error(tty, *p);
break;
case TTY_OVERRUN:
n_tty_receive_overrun(tty);
break;
default:
printk(KERN_ERR "%s: unknown flag %d\n",
tty_name(tty, buf), flags);
break;
}
}
if (tty->ops->flush_chars)
tty->ops->flush_chars(tty);
}
n_tty_set_room(tty);
if ((!tty->icanon && (tty->read_cnt >= tty->minimum_to_wake)) ||
L_EXTPROC(tty)) {
kill_fasync(&tty->fasync, SIGIO, POLL_IN);
if (waitqueue_active(&tty->read_wait))
wake_up_interruptible(&tty->read_wait);
}
/*
* Check the remaining room for the input canonicalization
* mode. We don't want to throttle the driver if we're in
* canonical mode and don't have a newline yet!
*/
if (tty->receive_room < TTY_THRESHOLD_THROTTLE)
tty_throttle(tty);
}
int is_ignored(int sig)
{
return (sigismember(¤t->blocked, sig) ||
current->sighand->action[sig-1].sa.sa_handler == SIG_IGN);
}
/**
* n_tty_set_termios - termios data changed
* @tty: terminal
* @old: previous data
*
* Called by the tty layer when the user changes termios flags so
* that the line discipline can plan ahead. This function cannot sleep
* and is protected from re-entry by the tty layer. The user is
* guaranteed that this function will not be re-entered or in progress
* when the ldisc is closed.
*
* Locking: Caller holds tty->termios_mutex
*/
static void n_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
{
int canon_change = 1;
BUG_ON(!tty);
if (old)
canon_change = (old->c_lflag ^ tty->termios->c_lflag) & ICANON;
if (canon_change) {
memset(&tty->read_flags, 0, sizeof tty->read_flags);
tty->canon_head = tty->read_tail;
tty->canon_data = 0;
tty->erasing = 0;
}
if (canon_change && !L_ICANON(tty) && tty->read_cnt)
wake_up_interruptible(&tty->read_wait);
tty->icanon = (L_ICANON(tty) != 0);
if (test_bit(TTY_HW_COOK_IN, &tty->flags)) {
tty->raw = 1;
tty->real_raw = 1;
n_tty_set_room(tty);
return;
}
if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
I_PARMRK(tty)) {
memset(tty->process_char_map, 0, 256/8);
if (I_IGNCR(tty) || I_ICRNL(tty))
set_bit('\r', tty->process_char_map);
if (I_INLCR(tty))
set_bit('\n', tty->process_char_map);
if (L_ICANON(tty)) {
set_bit(ERASE_CHAR(tty), tty->process_char_map);
set_bit(KILL_CHAR(tty), tty->process_char_map);
set_bit(EOF_CHAR(tty), tty->process_char_map);
set_bit('\n', tty->process_char_map);
set_bit(EOL_CHAR(tty), tty->process_char_map);
if (L_IEXTEN(tty)) {
set_bit(WERASE_CHAR(tty),
tty->process_char_map);
set_bit(LNEXT_CHAR(tty),
tty->process_char_map);
set_bit(EOL2_CHAR(tty),
tty->process_char_map);
if (L_ECHO(tty))
set_bit(REPRINT_CHAR(tty),
tty->process_char_map);
}
}
if (I_IXON(tty)) {
set_bit(START_CHAR(tty), tty->process_char_map);
set_bit(STOP_CHAR(tty), tty->process_char_map);
}
if (L_ISIG(tty)) {
set_bit(INTR_CHAR(tty), tty->process_char_map);
set_bit(QUIT_CHAR(tty), tty->process_char_map);
set_bit(SUSP_CHAR(tty), tty->process_char_map);
}
clear_bit(__DISABLED_CHAR, tty->process_char_map);
tty->raw = 0;
tty->real_raw = 0;
} else {
tty->raw = 1;
if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
(I_IGNPAR(tty) || !I_INPCK(tty)) &&
(tty->driver->flags & TTY_DRIVER_REAL_RAW))
tty->real_raw = 1;
else
tty->real_raw = 0;
}
n_tty_set_room(tty);
/*
* Fix tty hang when I_IXON(tty) is cleared, but the tty
* been stopped by STOP_CHAR(tty) before it.
*/
if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow_stopped) {
start_tty(tty);
}
/* The termios change make the tty ready for I/O */
wake_up_interruptible(&tty->write_wait);
wake_up_interruptible(&tty->read_wait);
}
/**
* n_tty_close - close the ldisc for this tty
* @tty: device
*
* Called from the terminal layer when this line discipline is
* being shut down, either because of a close or becsuse of a
* discipline change. The function will not be called while other
* ldisc methods are in progress.
*/
static void n_tty_close(struct tty_struct *tty)
{
n_tty_flush_buffer(tty);
if (tty->read_buf) {
kfree(tty->read_buf);
tty->read_buf = NULL;
}
if (tty->echo_buf) {
kfree(tty->echo_buf);
tty->echo_buf = NULL;
}
}
/**
* n_tty_open - open an ldisc
* @tty: terminal to open
*
* Called when this line discipline is being attached to the
* terminal device. Can sleep. Called serialized so that no
* other events will occur in parallel. No further open will occur
* until a close.
*/
static int n_tty_open(struct tty_struct *tty)
{
if (!tty)
return -EINVAL;
/* These are ugly. Currently a malloc failure here can panic */
if (!tty->read_buf) {
tty->read_buf = kzalloc(N_TTY_BUF_SIZE, GFP_KERNEL);
if (!tty->read_buf)
return -ENOMEM;
}
if (!tty->echo_buf) {
tty->echo_buf = kzalloc(N_TTY_BUF_SIZE, GFP_KERNEL);
if (!tty->echo_buf)
return -ENOMEM;
}
reset_buffer_flags(tty);
tty_unthrottle(tty);
tty->column = 0;
n_tty_set_termios(tty, NULL);
tty->minimum_to_wake = 1;
tty->closing = 0;
return 0;
}
static inline int input_available_p(struct tty_struct *tty, int amt)
{
tty_flush_to_ldisc(tty);
if (tty->icanon && !L_EXTPROC(tty)) {
if (tty->canon_data)
return 1;
} else if (tty->read_cnt >= (amt ? amt : 1))
return 1;
return 0;
}
/**
* copy_from_read_buf - copy read data directly
* @tty: terminal device
* @b: user data
* @nr: size of data
*
* Helper function to speed up n_tty_read. It is only called when
* ICANON is off; it copies characters straight from the tty queue to
* user space directly. It can be profitably called twice; once to
* drain the space from the tail pointer to the (physical) end of the
* buffer, and once to drain the space from the (physical) beginning of
* the buffer to head pointer.
*
* Called under the tty->atomic_read_lock sem
*
*/
static int copy_from_read_buf(struct tty_struct *tty,
unsigned char __user **b,
size_t *nr)
{
int retval;
size_t n;
unsigned long flags;
retval = 0;
spin_lock_irqsave(&tty->read_lock, flags);
n = min(tty->read_cnt, N_TTY_BUF_SIZE - tty->read_tail);
n = min(*nr, n);
spin_unlock_irqrestore(&tty->read_lock, flags);
if (n) {
retval = copy_to_user(*b, &tty->read_buf[tty->read_tail], n);
n -= retval;
tty_audit_add_data(tty, &tty->read_buf[tty->read_tail], n);
spin_lock_irqsave(&tty->read_lock, flags);
tty->read_tail = (tty->read_tail + n) & (N_TTY_BUF_SIZE-1);
tty->read_cnt -= n;
/* Turn single EOF into zero-length read */
if (L_EXTPROC(tty) && tty->icanon && n == 1) {
if (!tty->read_cnt && (*b)[n-1] == EOF_CHAR(tty))
n--;
}
spin_unlock_irqrestore(&tty->read_lock, flags);
*b += n;
*nr -= n;
}
return retval;
}
extern ssize_t redirected_tty_write(struct file *, const char __user *,
size_t, loff_t *);
/**
* job_control - check job control
* @tty: tty
* @file: file handle
*
* Perform job control management checks on this file/tty descriptor
* and if appropriate send any needed signals and return a negative
* error code if action should be taken.
*
* FIXME:
* Locking: None - redirected write test is safe, testing
* current->signal should possibly lock current->sighand
* pgrp locking ?
*/
static int job_control(struct tty_struct *tty, struct file *file)
{
/* Job control check -- must be done at start and after
every sleep (POSIX.1 7.1.1.4). */
/* NOTE: not yet done after every sleep pending a thorough
check of the logic of this change. -- jlc */
/* don't stop on /dev/console */
if (file->f_op->write != redirected_tty_write &&
current->signal->tty == tty) {
if (!tty->pgrp)
printk(KERN_ERR "n_tty_read: no tty->pgrp!\n");
else if (task_pgrp(current) != tty->pgrp) {
if (is_ignored(SIGTTIN) ||
is_current_pgrp_orphaned())
return -EIO;
kill_pgrp(task_pgrp(current), SIGTTIN, 1);
set_thread_flag(TIF_SIGPENDING);
return -ERESTARTSYS;
}
}
return 0;
}
/**
* n_tty_read - read function for tty
* @tty: tty device
* @file: file object
* @buf: userspace buffer pointer
* @nr: size of I/O
*
* Perform reads for the line discipline. We are guaranteed that the
* line discipline will not be closed under us but we may get multiple
* parallel readers and must handle this ourselves. We may also get
* a hangup. Always called in user context, may sleep.
*
* This code must be sure never to sleep through a hangup.
*/
static ssize_t n_tty_read(struct tty_struct *tty, struct file *file,
unsigned char __user *buf, size_t nr)
{
unsigned char __user *b = buf;
DECLARE_WAITQUEUE(wait, current);
int c;
int minimum, time;
ssize_t retval = 0;
ssize_t size;
long timeout;
unsigned long flags;
int packet;
do_it_again:
if (WARN_ON(!tty->read_buf))
return -EAGAIN;
c = job_control(tty, file);
if (c < 0)
return c;
minimum = time = 0;
timeout = MAX_SCHEDULE_TIMEOUT;
if (!tty->icanon) {
time = (HZ / 10) * TIME_CHAR(tty);
minimum = MIN_CHAR(tty);
if (minimum) {
if (time)
tty->minimum_to_wake = 1;
else if (!waitqueue_active(&tty->read_wait) ||
(tty->minimum_to_wake > minimum))
tty->minimum_to_wake = minimum;
} else {
timeout = 0;
if (time) {
timeout = time;
time = 0;
}
tty->minimum_to_wake = minimum = 1;
}
}
/*
* Internal serialization of reads.
*/
if (file->f_flags & O_NONBLOCK) {
if (!mutex_trylock(&tty->atomic_read_lock))
return -EAGAIN;
} else {
if (mutex_lock_interruptible(&tty->atomic_read_lock))
return -ERESTARTSYS;
}
packet = tty->packet;
add_wait_queue(&tty->read_wait, &wait);
while (nr) {
/* First test for status change. */
if (packet && tty->link->ctrl_status) {
unsigned char cs;
if (b != buf)
break;
spin_lock_irqsave(&tty->link->ctrl_lock, flags);
cs = tty->link->ctrl_status;
tty->link->ctrl_status = 0;
spin_unlock_irqrestore(&tty->link->ctrl_lock, flags);
if (tty_put_user(tty, cs, b++)) {
retval = -EFAULT;
b--;
break;
}
nr--;
break;
}
/* This statement must be first before checking for input
so that any interrupt will set the state back to
TASK_RUNNING. */
set_current_state(TASK_INTERRUPTIBLE);
if (((minimum - (b - buf)) < tty->minimum_to_wake) &&
((minimum - (b - buf)) >= 1))
tty->minimum_to_wake = (minimum - (b - buf));
if (!input_available_p(tty, 0)) {
if (test_bit(TTY_OTHER_CLOSED, &tty->flags)) {
retval = -EIO;
break;
}
if (tty_hung_up_p(file))
break;
if (!timeout)
break;
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
/* FIXME: does n_tty_set_room need locking ? */
n_tty_set_room(tty);
timeout = schedule_timeout(timeout);
BUG_ON(!tty->read_buf);
continue;
}
__set_current_state(TASK_RUNNING);
/* Deal with packet mode. */
if (packet && b == buf) {
if (tty_put_user(tty, TIOCPKT_DATA, b++)) {
retval = -EFAULT;
b--;
break;
}
nr--;
}
if (tty->icanon && !L_EXTPROC(tty)) {
/* N.B. avoid overrun if nr == 0 */
while (nr && tty->read_cnt) {
int eol;
eol = test_and_clear_bit(tty->read_tail,
tty->read_flags);
c = tty->read_buf[tty->read_tail];
spin_lock_irqsave(&tty->read_lock, flags);
tty->read_tail = ((tty->read_tail+1) &
(N_TTY_BUF_SIZE-1));
tty->read_cnt--;
if (eol) {
/* this test should be redundant:
* we shouldn't be reading data if
* canon_data is 0
*/
if (--tty->canon_data < 0)
tty->canon_data = 0;
}
spin_unlock_irqrestore(&tty->read_lock, flags);
if (!eol || (c != __DISABLED_CHAR)) {
if (tty_put_user(tty, c, b++)) {
retval = -EFAULT;
b--;
break;
}
nr--;
}
if (eol) {
tty_audit_push(tty);
break;
}
}
if (retval)
break;
} else {
int uncopied;
/* The copy function takes the read lock and handles
locking internally for this case */
uncopied = copy_from_read_buf(tty, &b, &nr);
uncopied += copy_from_read_buf(tty, &b, &nr);
if (uncopied) {
retval = -EFAULT;
break;
}
}
/* If there is enough space in the read buffer now, let the
* low-level driver know. We use n_tty_chars_in_buffer() to
* check the buffer, as it now knows about canonical mode.
* Otherwise, if the driver is throttled and the line is
* longer than TTY_THRESHOLD_UNTHROTTLE in canonical mode,
* we won't get any more characters.
*/
if (n_tty_chars_in_buffer(tty) <= TTY_THRESHOLD_UNTHROTTLE) {
n_tty_set_room(tty);
check_unthrottle(tty);
}
if (b - buf >= minimum)
break;
if (time)
timeout = time;
}
mutex_unlock(&tty->atomic_read_lock);
remove_wait_queue(&tty->read_wait, &wait);
if (!waitqueue_active(&tty->read_wait))
tty->minimum_to_wake = minimum;
__set_current_state(TASK_RUNNING);
size = b - buf;
if (size) {
retval = size;
if (nr)
clear_bit(TTY_PUSH, &tty->flags);
} else if (test_and_clear_bit(TTY_PUSH, &tty->flags))
goto do_it_again;
n_tty_set_room(tty);
return retval;
}
/**
* n_tty_write - write function for tty
* @tty: tty device
* @file: file object
* @buf: userspace buffer pointer
* @nr: size of I/O
*
* Write function of the terminal device. This is serialized with
* respect to other write callers but not to termios changes, reads
* and other such events. Since the receive code will echo characters,
* thus calling driver write methods, the output_lock is used in
* the output processing functions called here as well as in the
* echo processing function to protect the column state and space
* left in the buffer.
*
* This code must be sure never to sleep through a hangup.
*
* Locking: output_lock to protect column state and space left
* (note that the process_output*() functions take this
* lock themselves)
*/
static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
const unsigned char *buf, size_t nr)
{
const unsigned char *b = buf;
DECLARE_WAITQUEUE(wait, current);
int c;
ssize_t retval = 0;
/* Job control check -- must be done at start (POSIX.1 7.1.1.4). */
if (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) {
retval = tty_check_change(tty);
if (retval)
return retval;
}
/* Write out any echoed characters that are still pending */
process_echoes(tty);
add_wait_queue(&tty->write_wait, &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
retval = -EIO;
break;
}
if (O_OPOST(tty) && !(test_bit(TTY_HW_COOK_OUT, &tty->flags))) {
while (nr > 0) {
ssize_t num = process_output_block(tty, b, nr);
if (num < 0) {
if (num == -EAGAIN)
break;
retval = num;
goto break_out;
}
b += num;
nr -= num;
if (nr == 0)
break;
c = *b;
if (process_output(c, tty) < 0)
break;
b++; nr--;
}
if (tty->ops->flush_chars)
tty->ops->flush_chars(tty);
} else {
while (nr > 0) {
c = tty->ops->write(tty, b, nr);
if (c < 0) {
retval = c;
goto break_out;
}
if (!c)
break;
b += c;
nr -= c;
}
}
if (!nr)
break;
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
schedule();
}
break_out:
__set_current_state(TASK_RUNNING);
remove_wait_queue(&tty->write_wait, &wait);
if (b - buf != nr && tty->fasync)
set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
return (b - buf) ? b - buf : retval;
}
/**
* n_tty_poll - poll method for N_TTY
* @tty: terminal device
* @file: file accessing it
* @wait: poll table
*
* Called when the line discipline is asked to poll() for data or
* for special events. This code is not serialized with respect to
* other events save open/close.
*
* This code must be sure never to sleep through a hangup.
* Called without the kernel lock held - fine
*/
static unsigned int n_tty_poll(struct tty_struct *tty, struct file *file,
poll_table *wait)
{
unsigned int mask = 0;
poll_wait(file, &tty->read_wait, wait);
poll_wait(file, &tty->write_wait, wait);
if (input_available_p(tty, TIME_CHAR(tty) ? 0 : MIN_CHAR(tty)))
mask |= POLLIN | POLLRDNORM;
if (tty->packet && tty->link->ctrl_status)
mask |= POLLPRI | POLLIN | POLLRDNORM;
if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
mask |= POLLHUP;
if (tty_hung_up_p(file))
mask |= POLLHUP;
if (!(mask & (POLLHUP | POLLIN | POLLRDNORM))) {
if (MIN_CHAR(tty) && !TIME_CHAR(tty))
tty->minimum_to_wake = MIN_CHAR(tty);
else
tty->minimum_to_wake = 1;
}
if (tty->ops->write && !tty_is_writelocked(tty) &&
tty_chars_in_buffer(tty) < WAKEUP_CHARS &&
tty_write_room(tty) > 0)
mask |= POLLOUT | POLLWRNORM;
return mask;
}
static unsigned long inq_canon(struct tty_struct *tty)
{
int nr, head, tail;
if (!tty->canon_data)
return 0;
head = tty->canon_head;
tail = tty->read_tail;
nr = (head - tail) & (N_TTY_BUF_SIZE-1);
/* Skip EOF-chars.. */
while (head != tail) {
if (test_bit(tail, tty->read_flags) &&
tty->read_buf[tail] == __DISABLED_CHAR)
nr--;
tail = (tail+1) & (N_TTY_BUF_SIZE-1);
}
return nr;
}
static int n_tty_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
int retval;
switch (cmd) {
case TIOCOUTQ:
return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
case TIOCINQ:
/* FIXME: Locking */
retval = tty->read_cnt;
if (L_ICANON(tty))
retval = inq_canon(tty);
return put_user(retval, (unsigned int __user *) arg);
default:
return n_tty_ioctl_helper(tty, file, cmd, arg);
}
}
struct tty_ldisc_ops tty_ldisc_N_TTY = {
.magic = TTY_LDISC_MAGIC,
.name = "n_tty",
.open = n_tty_open,
.close = n_tty_close,
.flush_buffer = n_tty_flush_buffer,
.chars_in_buffer = n_tty_chars_in_buffer,
.read = n_tty_read,
.write = n_tty_write,
.ioctl = n_tty_ioctl,
.set_termios = n_tty_set_termios,
.poll = n_tty_poll,
.receive_buf = n_tty_receive_buf,
.write_wakeup = n_tty_write_wakeup
};
/**
* n_tty_inherit_ops - inherit N_TTY methods
* @ops: struct tty_ldisc_ops where to save N_TTY methods
*
* Used by a generic struct tty_ldisc_ops to easily inherit N_TTY
* methods.
*/
void n_tty_inherit_ops(struct tty_ldisc_ops *ops)
{
*ops = tty_ldisc_N_TTY;
ops->owner = NULL;
ops->refcount = ops->flags = 0;
}
EXPORT_SYMBOL_GPL(n_tty_inherit_ops);
| gpl-2.0 |
Renzo-Olivares/android_422_kernel_htc_monarudo | net/wireless/scan.c | 222 | 30543 | /*
* cfg80211 scan result handling
*
* Copyright 2008 Johannes Berg <johannes@sipsolutions.net>
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/wireless.h>
#include <linux/nl80211.h>
#include <linux/etherdevice.h>
#include <net/arp.h>
#include <net/cfg80211.h>
#include <net/cfg80211-wext.h>
#include <net/iw_handler.h>
#include "core.h"
#include "nl80211.h"
#include "wext-compat.h"
#define IEEE80211_SCAN_RESULT_EXPIRE (3 * HZ)
void ___cfg80211_scan_done(struct cfg80211_registered_device *rdev, bool leak)
{
struct cfg80211_scan_request *request;
struct net_device *dev;
#ifdef CONFIG_CFG80211_WEXT
union iwreq_data wrqu;
#endif
ASSERT_RDEV_LOCK(rdev);
request = rdev->scan_req;
if (!request)
return;
dev = request->dev;
cfg80211_sme_scan_done(dev);
if (request->aborted)
nl80211_send_scan_aborted(rdev, dev);
else
nl80211_send_scan_done(rdev, dev);
#ifdef CONFIG_CFG80211_WEXT
if (!request->aborted) {
memset(&wrqu, 0, sizeof(wrqu));
wireless_send_event(dev, SIOCGIWSCAN, &wrqu, NULL);
}
#endif
dev_put(dev);
rdev->scan_req = NULL;
if (!leak) {
request->magic = 0;
kfree(request);
}
}
void __cfg80211_scan_done(struct work_struct *wk)
{
struct cfg80211_registered_device *rdev;
rdev = container_of(wk, struct cfg80211_registered_device,
scan_done_wk);
cfg80211_lock_rdev(rdev);
___cfg80211_scan_done(rdev, false);
cfg80211_unlock_rdev(rdev);
}
void cfg80211_scan_done(struct cfg80211_scan_request *request, bool aborted)
{
WARN_ON(request != wiphy_to_dev(request->wiphy)->scan_req);
request->aborted = aborted;
queue_work(cfg80211_wq, &wiphy_to_dev(request->wiphy)->scan_done_wk);
}
EXPORT_SYMBOL(cfg80211_scan_done);
void __cfg80211_sched_scan_results(struct work_struct *wk)
{
struct cfg80211_registered_device *rdev;
rdev = container_of(wk, struct cfg80211_registered_device,
sched_scan_results_wk);
mutex_lock(&rdev->sched_scan_mtx);
if (rdev->sched_scan_req)
nl80211_send_sched_scan_results(rdev,
rdev->sched_scan_req->dev);
mutex_unlock(&rdev->sched_scan_mtx);
}
void cfg80211_sched_scan_results(struct wiphy *wiphy)
{
if (wiphy_to_dev(wiphy)->sched_scan_req)
queue_work(cfg80211_wq,
&wiphy_to_dev(wiphy)->sched_scan_results_wk);
}
EXPORT_SYMBOL(cfg80211_sched_scan_results);
void cfg80211_sched_scan_stopped(struct wiphy *wiphy)
{
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
mutex_lock(&rdev->sched_scan_mtx);
__cfg80211_stop_sched_scan(rdev, true);
mutex_unlock(&rdev->sched_scan_mtx);
}
EXPORT_SYMBOL(cfg80211_sched_scan_stopped);
int __cfg80211_stop_sched_scan(struct cfg80211_registered_device *rdev,
bool driver_initiated)
{
struct net_device *dev;
lockdep_assert_held(&rdev->sched_scan_mtx);
if (!rdev->sched_scan_req)
return -ENOENT;
dev = rdev->sched_scan_req->dev;
if (!driver_initiated) {
int err = rdev->ops->sched_scan_stop(&rdev->wiphy, dev);
if (err)
return err;
}
nl80211_send_sched_scan(rdev, dev, NL80211_CMD_SCHED_SCAN_STOPPED);
kfree(rdev->sched_scan_req);
rdev->sched_scan_req = NULL;
return 0;
}
static void bss_release(struct kref *ref)
{
struct cfg80211_internal_bss *bss;
bss = container_of(ref, struct cfg80211_internal_bss, ref);
if (bss->pub.free_priv)
bss->pub.free_priv(&bss->pub);
if (bss->beacon_ies_allocated)
kfree(bss->pub.beacon_ies);
if (bss->proberesp_ies_allocated)
kfree(bss->pub.proberesp_ies);
BUG_ON(atomic_read(&bss->hold));
kfree(bss);
}
void cfg80211_bss_age(struct cfg80211_registered_device *dev,
unsigned long age_secs)
{
struct cfg80211_internal_bss *bss;
unsigned long age_jiffies = msecs_to_jiffies(age_secs * MSEC_PER_SEC);
list_for_each_entry(bss, &dev->bss_list, list) {
bss->ts -= age_jiffies;
}
}
static void __cfg80211_unlink_bss(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *bss)
{
list_del_init(&bss->list);
rb_erase(&bss->rbn, &dev->bss_tree);
kref_put(&bss->ref, bss_release);
}
void cfg80211_bss_expire(struct cfg80211_registered_device *dev)
{
struct cfg80211_internal_bss *bss, *tmp;
bool expired = false;
list_for_each_entry_safe(bss, tmp, &dev->bss_list, list) {
if (atomic_read(&bss->hold))
continue;
if (!time_after(jiffies, bss->ts + IEEE80211_SCAN_RESULT_EXPIRE))
continue;
__cfg80211_unlink_bss(dev, bss);
expired = true;
}
if (expired)
dev->bss_generation++;
}
const u8 *cfg80211_find_ie(u8 eid, const u8 *ies, int len)
{
while (len > 2 && ies[0] != eid) {
len -= ies[1] + 2;
ies += ies[1] + 2;
}
if (len < 2)
return NULL;
if (len < 2 + ies[1])
return NULL;
return ies;
}
EXPORT_SYMBOL(cfg80211_find_ie);
const u8 *cfg80211_find_vendor_ie(unsigned int oui, u8 oui_type,
const u8 *ies, int len)
{
struct ieee80211_vendor_ie *ie;
const u8 *pos = ies, *end = ies + len;
int ie_oui;
while (pos < end) {
pos = cfg80211_find_ie(WLAN_EID_VENDOR_SPECIFIC, pos,
end - pos);
if (!pos)
return NULL;
if (end - pos < sizeof(*ie))
return NULL;
ie = (struct ieee80211_vendor_ie *)pos;
ie_oui = ie->oui[0] << 16 | ie->oui[1] << 8 | ie->oui[2];
if (ie_oui == oui && ie->oui_type == oui_type)
return pos;
pos += 2 + ie->len;
}
return NULL;
}
EXPORT_SYMBOL(cfg80211_find_vendor_ie);
static int cmp_ies(u8 num, u8 *ies1, size_t len1, u8 *ies2, size_t len2)
{
const u8 *ie1 = cfg80211_find_ie(num, ies1, len1);
const u8 *ie2 = cfg80211_find_ie(num, ies2, len2);
if (!ie1 && !ie2)
return 0;
if (!ie1)
return -1;
if (!ie2)
return 1;
if (ie1[1] != ie2[1])
return ie2[1] - ie1[1];
return memcmp(ie1 + 2, ie2 + 2, ie1[1]);
}
static bool is_bss(struct cfg80211_bss *a,
const u8 *bssid,
const u8 *ssid, size_t ssid_len)
{
const u8 *ssidie;
if (bssid && compare_ether_addr(a->bssid, bssid))
return false;
if (!ssid)
return true;
ssidie = cfg80211_find_ie(WLAN_EID_SSID,
a->information_elements,
a->len_information_elements);
if (!ssidie)
return false;
if (ssidie[1] != ssid_len)
return false;
return memcmp(ssidie + 2, ssid, ssid_len) == 0;
}
static bool is_mesh_bss(struct cfg80211_bss *a)
{
const u8 *ie;
if (!WLAN_CAPABILITY_IS_STA_BSS(a->capability))
return false;
ie = cfg80211_find_ie(WLAN_EID_MESH_ID,
a->information_elements,
a->len_information_elements);
if (!ie)
return false;
ie = cfg80211_find_ie(WLAN_EID_MESH_CONFIG,
a->information_elements,
a->len_information_elements);
if (!ie)
return false;
return true;
}
static bool is_mesh(struct cfg80211_bss *a,
const u8 *meshid, size_t meshidlen,
const u8 *meshcfg)
{
const u8 *ie;
if (!WLAN_CAPABILITY_IS_STA_BSS(a->capability))
return false;
ie = cfg80211_find_ie(WLAN_EID_MESH_ID,
a->information_elements,
a->len_information_elements);
if (!ie)
return false;
if (ie[1] != meshidlen)
return false;
if (memcmp(ie + 2, meshid, meshidlen))
return false;
ie = cfg80211_find_ie(WLAN_EID_MESH_CONFIG,
a->information_elements,
a->len_information_elements);
if (!ie)
return false;
if (ie[1] != sizeof(struct ieee80211_meshconf_ie))
return false;
return memcmp(ie + 2, meshcfg,
sizeof(struct ieee80211_meshconf_ie) - 2) == 0;
}
static int cmp_bss_core(struct cfg80211_bss *a,
struct cfg80211_bss *b)
{
int r;
if (a->channel != b->channel)
return b->channel->center_freq - a->channel->center_freq;
if (is_mesh_bss(a) && is_mesh_bss(b)) {
r = cmp_ies(WLAN_EID_MESH_ID,
a->information_elements,
a->len_information_elements,
b->information_elements,
b->len_information_elements);
if (r)
return r;
return cmp_ies(WLAN_EID_MESH_CONFIG,
a->information_elements,
a->len_information_elements,
b->information_elements,
b->len_information_elements);
}
return memcmp(a->bssid, b->bssid, ETH_ALEN);
}
static int cmp_bss(struct cfg80211_bss *a,
struct cfg80211_bss *b)
{
int r;
r = cmp_bss_core(a, b);
if (r)
return r;
return cmp_ies(WLAN_EID_SSID,
a->information_elements,
a->len_information_elements,
b->information_elements,
b->len_information_elements);
}
static int cmp_hidden_bss(struct cfg80211_bss *a,
struct cfg80211_bss *b)
{
const u8 *ie1;
const u8 *ie2;
int i;
int r;
r = cmp_bss_core(a, b);
if (r)
return r;
ie1 = cfg80211_find_ie(WLAN_EID_SSID,
a->information_elements,
a->len_information_elements);
ie2 = cfg80211_find_ie(WLAN_EID_SSID,
b->information_elements,
b->len_information_elements);
if (!ie1)
return -1;
if (!ie2)
return 1;
if (!ie2[1])
return 0;
if (ie1[1] != ie2[1])
return ie2[1] - ie1[1];
for (i = 0; i < ie2[1]; i++)
if (ie2[i + 2])
return -1;
return 0;
}
struct cfg80211_bss *cfg80211_get_bss(struct wiphy *wiphy,
struct ieee80211_channel *channel,
const u8 *bssid,
const u8 *ssid, size_t ssid_len,
u16 capa_mask, u16 capa_val)
{
struct cfg80211_registered_device *dev = wiphy_to_dev(wiphy);
struct cfg80211_internal_bss *bss, *res = NULL;
unsigned long now = jiffies;
spin_lock_bh(&dev->bss_lock);
list_for_each_entry(bss, &dev->bss_list, list) {
if ((bss->pub.capability & capa_mask) != capa_val)
continue;
if (channel && bss->pub.channel != channel)
continue;
if (time_after(now, bss->ts + IEEE80211_SCAN_RESULT_EXPIRE) &&
!atomic_read(&bss->hold))
continue;
if (is_bss(&bss->pub, bssid, ssid, ssid_len)) {
res = bss;
kref_get(&res->ref);
break;
}
}
spin_unlock_bh(&dev->bss_lock);
if (!res)
return NULL;
return &res->pub;
}
EXPORT_SYMBOL(cfg80211_get_bss);
struct cfg80211_bss *cfg80211_get_mesh(struct wiphy *wiphy,
struct ieee80211_channel *channel,
const u8 *meshid, size_t meshidlen,
const u8 *meshcfg)
{
struct cfg80211_registered_device *dev = wiphy_to_dev(wiphy);
struct cfg80211_internal_bss *bss, *res = NULL;
spin_lock_bh(&dev->bss_lock);
list_for_each_entry(bss, &dev->bss_list, list) {
if (channel && bss->pub.channel != channel)
continue;
if (is_mesh(&bss->pub, meshid, meshidlen, meshcfg)) {
res = bss;
kref_get(&res->ref);
break;
}
}
spin_unlock_bh(&dev->bss_lock);
if (!res)
return NULL;
return &res->pub;
}
EXPORT_SYMBOL(cfg80211_get_mesh);
static void rb_insert_bss(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *bss)
{
struct rb_node **p = &dev->bss_tree.rb_node;
struct rb_node *parent = NULL;
struct cfg80211_internal_bss *tbss;
int cmp;
while (*p) {
parent = *p;
tbss = rb_entry(parent, struct cfg80211_internal_bss, rbn);
cmp = cmp_bss(&bss->pub, &tbss->pub);
if (WARN_ON(!cmp)) {
return;
}
if (cmp < 0)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
rb_link_node(&bss->rbn, parent, p);
rb_insert_color(&bss->rbn, &dev->bss_tree);
}
static struct cfg80211_internal_bss *
rb_find_bss(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *res)
{
struct rb_node *n = dev->bss_tree.rb_node;
struct cfg80211_internal_bss *bss;
int r;
while (n) {
bss = rb_entry(n, struct cfg80211_internal_bss, rbn);
r = cmp_bss(&res->pub, &bss->pub);
if (r == 0)
return bss;
else if (r < 0)
n = n->rb_left;
else
n = n->rb_right;
}
return NULL;
}
static struct cfg80211_internal_bss *
rb_find_hidden_bss(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *res)
{
struct rb_node *n = dev->bss_tree.rb_node;
struct cfg80211_internal_bss *bss;
int r;
while (n) {
bss = rb_entry(n, struct cfg80211_internal_bss, rbn);
r = cmp_hidden_bss(&res->pub, &bss->pub);
if (r == 0)
return bss;
else if (r < 0)
n = n->rb_left;
else
n = n->rb_right;
}
return NULL;
}
static void
copy_hidden_ies(struct cfg80211_internal_bss *res,
struct cfg80211_internal_bss *hidden)
{
if (unlikely(res->pub.beacon_ies))
return;
if (WARN_ON(!hidden->pub.beacon_ies))
return;
res->pub.beacon_ies = kmalloc(hidden->pub.len_beacon_ies, GFP_ATOMIC);
if (unlikely(!res->pub.beacon_ies))
return;
res->beacon_ies_allocated = true;
res->pub.len_beacon_ies = hidden->pub.len_beacon_ies;
memcpy(res->pub.beacon_ies, hidden->pub.beacon_ies,
res->pub.len_beacon_ies);
}
static struct cfg80211_internal_bss *
cfg80211_bss_update(struct cfg80211_registered_device *dev,
struct cfg80211_internal_bss *res)
{
struct cfg80211_internal_bss *found = NULL;
if (WARN_ON(!res->pub.channel)) {
kref_put(&res->ref, bss_release);
return NULL;
}
res->ts = jiffies;
spin_lock_bh(&dev->bss_lock);
found = rb_find_bss(dev, res);
if (found) {
found->pub.beacon_interval = res->pub.beacon_interval;
found->pub.tsf = res->pub.tsf;
found->pub.signal = res->pub.signal;
found->pub.capability = res->pub.capability;
found->ts = res->ts;
if (res->pub.proberesp_ies) {
size_t used = dev->wiphy.bss_priv_size + sizeof(*res);
size_t ielen = res->pub.len_proberesp_ies;
if (found->pub.proberesp_ies &&
!found->proberesp_ies_allocated &&
ksize(found) >= used + ielen) {
memcpy(found->pub.proberesp_ies,
res->pub.proberesp_ies, ielen);
found->pub.len_proberesp_ies = ielen;
} else {
u8 *ies = found->pub.proberesp_ies;
if (found->proberesp_ies_allocated)
ies = krealloc(ies, ielen, GFP_ATOMIC);
else
ies = kmalloc(ielen, GFP_ATOMIC);
if (ies) {
memcpy(ies, res->pub.proberesp_ies,
ielen);
found->proberesp_ies_allocated = true;
found->pub.proberesp_ies = ies;
found->pub.len_proberesp_ies = ielen;
}
}
found->pub.information_elements =
found->pub.proberesp_ies;
found->pub.len_information_elements =
found->pub.len_proberesp_ies;
}
if (res->pub.beacon_ies) {
size_t used = dev->wiphy.bss_priv_size + sizeof(*res);
size_t ielen = res->pub.len_beacon_ies;
bool information_elements_is_beacon_ies =
(found->pub.information_elements ==
found->pub.beacon_ies);
if (found->pub.beacon_ies &&
!found->beacon_ies_allocated &&
ksize(found) >= used + ielen) {
memcpy(found->pub.beacon_ies,
res->pub.beacon_ies, ielen);
found->pub.len_beacon_ies = ielen;
} else {
u8 *ies = found->pub.beacon_ies;
if (found->beacon_ies_allocated)
ies = krealloc(ies, ielen, GFP_ATOMIC);
else
ies = kmalloc(ielen, GFP_ATOMIC);
if (ies) {
memcpy(ies, res->pub.beacon_ies,
ielen);
found->beacon_ies_allocated = true;
found->pub.beacon_ies = ies;
found->pub.len_beacon_ies = ielen;
}
}
if (information_elements_is_beacon_ies) {
found->pub.information_elements =
found->pub.beacon_ies;
found->pub.len_information_elements =
found->pub.len_beacon_ies;
}
}
kref_put(&res->ref, bss_release);
} else {
struct cfg80211_internal_bss *hidden;
hidden = rb_find_hidden_bss(dev, res);
if (hidden)
copy_hidden_ies(res, hidden);
list_add_tail(&res->list, &dev->bss_list);
rb_insert_bss(dev, res);
found = res;
}
dev->bss_generation++;
spin_unlock_bh(&dev->bss_lock);
kref_get(&found->ref);
return found;
}
struct cfg80211_bss*
cfg80211_inform_bss(struct wiphy *wiphy,
struct ieee80211_channel *channel,
const u8 *bssid, u64 tsf, u16 capability,
u16 beacon_interval, const u8 *ie, size_t ielen,
s32 signal, gfp_t gfp)
{
struct cfg80211_internal_bss *res;
size_t privsz;
if (WARN_ON(!wiphy))
return NULL;
privsz = wiphy->bss_priv_size;
if (WARN_ON(wiphy->signal_type == CFG80211_SIGNAL_TYPE_UNSPEC &&
(signal < 0 || signal > 100)))
return NULL;
res = kzalloc(sizeof(*res) + privsz + ielen, gfp);
if (!res)
return NULL;
memcpy(res->pub.bssid, bssid, ETH_ALEN);
res->pub.channel = channel;
res->pub.signal = signal;
res->pub.tsf = tsf;
res->pub.beacon_interval = beacon_interval;
res->pub.capability = capability;
res->pub.beacon_ies = (u8 *)res + sizeof(*res) + privsz;
memcpy(res->pub.beacon_ies, ie, ielen);
res->pub.len_beacon_ies = ielen;
res->pub.information_elements = res->pub.beacon_ies;
res->pub.len_information_elements = res->pub.len_beacon_ies;
kref_init(&res->ref);
res = cfg80211_bss_update(wiphy_to_dev(wiphy), res);
if (!res)
return NULL;
if (res->pub.capability & WLAN_CAPABILITY_ESS)
regulatory_hint_found_beacon(wiphy, channel, gfp);
return &res->pub;
}
EXPORT_SYMBOL(cfg80211_inform_bss);
struct cfg80211_bss *
cfg80211_inform_bss_frame(struct wiphy *wiphy,
struct ieee80211_channel *channel,
struct ieee80211_mgmt *mgmt, size_t len,
s32 signal, gfp_t gfp)
{
struct cfg80211_internal_bss *res;
size_t ielen = len - offsetof(struct ieee80211_mgmt,
u.probe_resp.variable);
size_t privsz;
if (WARN_ON(!mgmt))
return NULL;
if (WARN_ON(!wiphy))
return NULL;
if (WARN_ON(wiphy->signal_type == CFG80211_SIGNAL_TYPE_UNSPEC &&
(signal < 0 || signal > 100)))
return NULL;
if (WARN_ON(len < offsetof(struct ieee80211_mgmt, u.probe_resp.variable)))
return NULL;
privsz = wiphy->bss_priv_size;
res = kzalloc(sizeof(*res) + privsz + ielen, gfp);
if (!res)
return NULL;
memcpy(res->pub.bssid, mgmt->bssid, ETH_ALEN);
res->pub.channel = channel;
res->pub.signal = signal;
res->pub.tsf = le64_to_cpu(mgmt->u.probe_resp.timestamp);
res->pub.beacon_interval = le16_to_cpu(mgmt->u.probe_resp.beacon_int);
res->pub.capability = le16_to_cpu(mgmt->u.probe_resp.capab_info);
if (ieee80211_is_probe_resp(mgmt->frame_control)) {
res->pub.proberesp_ies = (u8 *) res + sizeof(*res) + privsz;
memcpy(res->pub.proberesp_ies, mgmt->u.probe_resp.variable,
ielen);
res->pub.len_proberesp_ies = ielen;
res->pub.information_elements = res->pub.proberesp_ies;
res->pub.len_information_elements = res->pub.len_proberesp_ies;
} else {
res->pub.beacon_ies = (u8 *) res + sizeof(*res) + privsz;
memcpy(res->pub.beacon_ies, mgmt->u.beacon.variable, ielen);
res->pub.len_beacon_ies = ielen;
res->pub.information_elements = res->pub.beacon_ies;
res->pub.len_information_elements = res->pub.len_beacon_ies;
}
kref_init(&res->ref);
res = cfg80211_bss_update(wiphy_to_dev(wiphy), res);
if (!res)
return NULL;
if (res->pub.capability & WLAN_CAPABILITY_ESS)
regulatory_hint_found_beacon(wiphy, channel, gfp);
return &res->pub;
}
EXPORT_SYMBOL(cfg80211_inform_bss_frame);
void cfg80211_ref_bss(struct cfg80211_bss *pub)
{
struct cfg80211_internal_bss *bss;
if (!pub)
return;
bss = container_of(pub, struct cfg80211_internal_bss, pub);
kref_get(&bss->ref);
}
EXPORT_SYMBOL(cfg80211_ref_bss);
void cfg80211_put_bss(struct cfg80211_bss *pub)
{
struct cfg80211_internal_bss *bss;
if (!pub)
return;
bss = container_of(pub, struct cfg80211_internal_bss, pub);
kref_put(&bss->ref, bss_release);
}
EXPORT_SYMBOL(cfg80211_put_bss);
void cfg80211_unlink_bss(struct wiphy *wiphy, struct cfg80211_bss *pub)
{
struct cfg80211_registered_device *dev = wiphy_to_dev(wiphy);
struct cfg80211_internal_bss *bss;
if (WARN_ON(!pub))
return;
bss = container_of(pub, struct cfg80211_internal_bss, pub);
spin_lock_bh(&dev->bss_lock);
if (!list_empty(&bss->list)) {
__cfg80211_unlink_bss(dev, bss);
dev->bss_generation++;
}
spin_unlock_bh(&dev->bss_lock);
}
EXPORT_SYMBOL(cfg80211_unlink_bss);
#ifdef CONFIG_CFG80211_WEXT
int cfg80211_wext_siwscan(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct cfg80211_registered_device *rdev;
struct wiphy *wiphy;
struct iw_scan_req *wreq = NULL;
struct cfg80211_scan_request *creq = NULL;
int i, err, n_channels = 0;
enum ieee80211_band band;
if (!netif_running(dev))
return -ENETDOWN;
if (wrqu->data.length == sizeof(struct iw_scan_req))
wreq = (struct iw_scan_req *)extra;
rdev = cfg80211_get_dev_from_ifindex(dev_net(dev), dev->ifindex);
if (IS_ERR(rdev))
return PTR_ERR(rdev);
if (rdev->scan_req) {
err = -EBUSY;
goto out;
}
wiphy = &rdev->wiphy;
if (wreq && wreq->num_channels)
n_channels = wreq->num_channels;
else {
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
creq = kzalloc(sizeof(*creq) + sizeof(struct cfg80211_ssid) +
n_channels * sizeof(void *),
GFP_ATOMIC);
if (!creq) {
err = -ENOMEM;
goto out;
}
creq->wiphy = wiphy;
creq->dev = dev;
creq->ssids = (void *)&creq->channels[n_channels];
creq->n_channels = n_channels;
creq->n_ssids = 1;
i = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
if (wiphy->bands[band]->channels[j].flags &
IEEE80211_CHAN_DISABLED)
continue;
if (wreq && wreq->num_channels) {
int k;
int wiphy_freq = wiphy->bands[band]->channels[j].center_freq;
for (k = 0; k < wreq->num_channels; k++) {
int wext_freq = cfg80211_wext_freq(wiphy, &wreq->channel_list[k]);
if (wext_freq == wiphy_freq)
goto wext_freq_found;
}
goto wext_freq_not_found;
}
wext_freq_found:
creq->channels[i] = &wiphy->bands[band]->channels[j];
i++;
wext_freq_not_found: ;
}
}
if (!i) {
err = -EINVAL;
goto out;
}
creq->n_channels = i;
if (wreq) {
if (wrqu->data.flags & IW_SCAN_THIS_ESSID) {
if (wreq->essid_len > IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out;
}
memcpy(creq->ssids[0].ssid, wreq->essid, wreq->essid_len);
creq->ssids[0].ssid_len = wreq->essid_len;
}
if (wreq->scan_type == IW_SCAN_TYPE_PASSIVE)
creq->n_ssids = 0;
}
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
creq->rates[i] = (1 << wiphy->bands[i]->n_bitrates) - 1;
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
if (wiphy->bands[i])
creq->rates[i] = (1 << wiphy->bands[i]->n_bitrates) - 1;
rdev->scan_req = creq;
err = rdev->ops->scan(wiphy, dev, creq);
if (err) {
rdev->scan_req = NULL;
} else {
nl80211_send_scan_start(rdev, dev);
creq = NULL;
dev_hold(dev);
}
out:
kfree(creq);
cfg80211_unlock_rdev(rdev);
return err;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwscan);
static void ieee80211_scan_add_ies(struct iw_request_info *info,
struct cfg80211_bss *bss,
char **current_ev, char *end_buf)
{
u8 *pos, *end, *next;
struct iw_event iwe;
if (!bss->information_elements ||
!bss->len_information_elements)
return;
pos = bss->information_elements;
end = pos + bss->len_information_elements;
while (end - pos > IW_GENERIC_IE_MAX) {
next = pos + 2 + pos[1];
while (next + 2 + next[1] - pos < IW_GENERIC_IE_MAX)
next = next + 2 + next[1];
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVGENIE;
iwe.u.data.length = next - pos;
*current_ev = iwe_stream_add_point(info, *current_ev,
end_buf, &iwe, pos);
pos = next;
}
if (end > pos) {
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVGENIE;
iwe.u.data.length = end - pos;
*current_ev = iwe_stream_add_point(info, *current_ev,
end_buf, &iwe, pos);
}
}
static inline unsigned int elapsed_jiffies_msecs(unsigned long start)
{
unsigned long end = jiffies;
if (end >= start)
return jiffies_to_msecs(end - start);
return jiffies_to_msecs(end + (MAX_JIFFY_OFFSET - start) + 1);
}
static char *
ieee80211_bss(struct wiphy *wiphy, struct iw_request_info *info,
struct cfg80211_internal_bss *bss, char *current_ev,
char *end_buf)
{
struct iw_event iwe;
u8 *buf, *cfg, *p;
u8 *ie = bss->pub.information_elements;
int rem = bss->pub.len_information_elements, i, sig;
bool ismesh = false;
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWAP;
iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
memcpy(iwe.u.ap_addr.sa_data, bss->pub.bssid, ETH_ALEN);
current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe,
IW_EV_ADDR_LEN);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWFREQ;
iwe.u.freq.m = ieee80211_frequency_to_channel(bss->pub.channel->center_freq);
iwe.u.freq.e = 0;
current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe,
IW_EV_FREQ_LEN);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWFREQ;
iwe.u.freq.m = bss->pub.channel->center_freq;
iwe.u.freq.e = 6;
current_ev = iwe_stream_add_event(info, current_ev, end_buf, &iwe,
IW_EV_FREQ_LEN);
if (wiphy->signal_type != CFG80211_SIGNAL_TYPE_NONE) {
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVQUAL;
iwe.u.qual.updated = IW_QUAL_LEVEL_UPDATED |
IW_QUAL_NOISE_INVALID |
IW_QUAL_QUAL_UPDATED;
switch (wiphy->signal_type) {
case CFG80211_SIGNAL_TYPE_MBM:
sig = bss->pub.signal / 100;
iwe.u.qual.level = sig;
iwe.u.qual.updated |= IW_QUAL_DBM;
if (sig < -110)
sig = -110;
else if (sig > -40)
sig = -40;
iwe.u.qual.qual = sig + 110;
break;
case CFG80211_SIGNAL_TYPE_UNSPEC:
iwe.u.qual.level = bss->pub.signal;
iwe.u.qual.qual = bss->pub.signal;
break;
default:
break;
}
current_ev = iwe_stream_add_event(info, current_ev, end_buf,
&iwe, IW_EV_QUAL_LEN);
}
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWENCODE;
if (bss->pub.capability & WLAN_CAPABILITY_PRIVACY)
iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
else
iwe.u.data.flags = IW_ENCODE_DISABLED;
iwe.u.data.length = 0;
current_ev = iwe_stream_add_point(info, current_ev, end_buf,
&iwe, "");
while (rem >= 2) {
if (ie[1] > rem - 2)
break;
switch (ie[0]) {
case WLAN_EID_SSID:
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWESSID;
iwe.u.data.length = ie[1];
iwe.u.data.flags = 1;
current_ev = iwe_stream_add_point(info, current_ev, end_buf,
&iwe, ie + 2);
break;
case WLAN_EID_MESH_ID:
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWESSID;
iwe.u.data.length = ie[1];
iwe.u.data.flags = 1;
current_ev = iwe_stream_add_point(info, current_ev, end_buf,
&iwe, ie + 2);
break;
case WLAN_EID_MESH_CONFIG:
ismesh = true;
if (ie[1] != sizeof(struct ieee80211_meshconf_ie))
break;
buf = kmalloc(50, GFP_ATOMIC);
if (!buf)
break;
cfg = ie + 2;
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVCUSTOM;
sprintf(buf, "Mesh Network Path Selection Protocol ID: "
"0x%02X", cfg[0]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Path Selection Metric ID: 0x%02X",
cfg[1]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Congestion Control Mode ID: 0x%02X",
cfg[2]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Synchronization ID: 0x%02X", cfg[3]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Authentication ID: 0x%02X", cfg[4]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Formation Info: 0x%02X", cfg[5]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
sprintf(buf, "Capabilities: 0x%02X", cfg[6]);
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf,
&iwe, buf);
kfree(buf);
break;
case WLAN_EID_SUPP_RATES:
case WLAN_EID_EXT_SUPP_RATES:
p = current_ev + iwe_stream_lcp_len(info);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWRATE;
iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0;
for (i = 0; i < ie[1]; i++) {
iwe.u.bitrate.value =
((ie[i + 2] & 0x7f) * 500000);
p = iwe_stream_add_value(info, current_ev, p,
end_buf, &iwe, IW_EV_PARAM_LEN);
}
current_ev = p;
break;
}
rem -= ie[1] + 2;
ie += ie[1] + 2;
}
if (bss->pub.capability & (WLAN_CAPABILITY_ESS | WLAN_CAPABILITY_IBSS) ||
ismesh) {
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = SIOCGIWMODE;
if (ismesh)
iwe.u.mode = IW_MODE_MESH;
else if (bss->pub.capability & WLAN_CAPABILITY_ESS)
iwe.u.mode = IW_MODE_MASTER;
else
iwe.u.mode = IW_MODE_ADHOC;
current_ev = iwe_stream_add_event(info, current_ev, end_buf,
&iwe, IW_EV_UINT_LEN);
}
buf = kmalloc(30, GFP_ATOMIC);
if (buf) {
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVCUSTOM;
sprintf(buf, "tsf=%016llx", (unsigned long long)(bss->pub.tsf));
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev, end_buf,
&iwe, buf);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVCUSTOM;
sprintf(buf, " Last beacon: %ums ago",
elapsed_jiffies_msecs(bss->ts));
iwe.u.data.length = strlen(buf);
current_ev = iwe_stream_add_point(info, current_ev,
end_buf, &iwe, buf);
kfree(buf);
}
ieee80211_scan_add_ies(info, &bss->pub, ¤t_ev, end_buf);
return current_ev;
}
static int ieee80211_scan_results(struct cfg80211_registered_device *dev,
struct iw_request_info *info,
char *buf, size_t len)
{
char *current_ev = buf;
char *end_buf = buf + len;
struct cfg80211_internal_bss *bss;
spin_lock_bh(&dev->bss_lock);
cfg80211_bss_expire(dev);
list_for_each_entry(bss, &dev->bss_list, list) {
if (buf + len - current_ev <= IW_EV_ADDR_LEN) {
spin_unlock_bh(&dev->bss_lock);
return -E2BIG;
}
current_ev = ieee80211_bss(&dev->wiphy, info, bss,
current_ev, end_buf);
}
spin_unlock_bh(&dev->bss_lock);
return current_ev - buf;
}
int cfg80211_wext_giwscan(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *extra)
{
struct cfg80211_registered_device *rdev;
int res;
if (!netif_running(dev))
return -ENETDOWN;
rdev = cfg80211_get_dev_from_ifindex(dev_net(dev), dev->ifindex);
if (IS_ERR(rdev))
return PTR_ERR(rdev);
if (rdev->scan_req) {
res = -EAGAIN;
goto out;
}
res = ieee80211_scan_results(rdev, info, extra, data->length);
data->length = 0;
if (res >= 0) {
data->length = res;
res = 0;
}
out:
cfg80211_unlock_rdev(rdev);
return res;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwscan);
#endif
| gpl-2.0 |
manashmndl/CHIP-linux | drivers/staging/rtl8188eu/hal/rtl8188eu_led.c | 1246 | 2872 | /******************************************************************************
*
* Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License 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, USA
*
*
******************************************************************************/
#include <osdep_service.h>
#include <drv_types.h>
#include <rtl8188e_hal.h>
#include <rtl8188e_led.h>
#include <usb_ops_linux.h>
/* LED object. */
/* LED_819xUsb routines. */
/* Description: */
/* Turn on LED according to LedPin specified. */
void SwLedOn(struct adapter *padapter, struct LED_871x *pLed)
{
u8 LedCfg;
if (padapter->bSurpriseRemoved || padapter->bDriverStopped)
return;
LedCfg = usb_read8(padapter, REG_LEDCFG2);
usb_write8(padapter, REG_LEDCFG2, (LedCfg&0xf0)|BIT5|BIT6); /* SW control led0 on. */
pLed->bLedOn = true;
}
/* Description: */
/* Turn off LED according to LedPin specified. */
void SwLedOff(struct adapter *padapter, struct LED_871x *pLed)
{
u8 LedCfg;
struct hal_data_8188e *pHalData = GET_HAL_DATA(padapter);
if (padapter->bSurpriseRemoved || padapter->bDriverStopped)
goto exit;
LedCfg = usb_read8(padapter, REG_LEDCFG2);/* 0x4E */
if (pHalData->bLedOpenDrain) {
/* Open-drain arrangement for controlling the LED) */
LedCfg &= 0x90; /* Set to software control. */
usb_write8(padapter, REG_LEDCFG2, (LedCfg|BIT3));
LedCfg = usb_read8(padapter, REG_MAC_PINMUX_CFG);
LedCfg &= 0xFE;
usb_write8(padapter, REG_MAC_PINMUX_CFG, LedCfg);
} else {
usb_write8(padapter, REG_LEDCFG2, (LedCfg|BIT3|BIT5|BIT6));
}
exit:
pLed->bLedOn = false;
}
/* Interface to manipulate LED objects. */
/* Default LED behavior. */
/* Description: */
/* Initialize all LED_871x objects. */
void rtl8188eu_InitSwLeds(struct adapter *padapter)
{
struct led_priv *pledpriv = &(padapter->ledpriv);
struct hal_data_8188e *haldata = GET_HAL_DATA(padapter);
pledpriv->bRegUseLed = true;
pledpriv->LedControlHandler = LedControl8188eu;
haldata->bLedOpenDrain = true;
InitLed871x(padapter, &(pledpriv->SwLed0));
}
/* Description: */
/* DeInitialize all LED_819xUsb objects. */
void rtl8188eu_DeInitSwLeds(struct adapter *padapter)
{
struct led_priv *ledpriv = &(padapter->ledpriv);
DeInitLed871x(&(ledpriv->SwLed0));
}
| gpl-2.0 |
mickael-guene/kernel | fs/ocfs2/inode.c | 2270 | 40357 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* inode.c
*
* vfs' aops, fops, dops and iops
*
* Copyright (C) 2002, 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/fs.h>
#include <linux/types.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/quotaops.h>
#include <asm/byteorder.h>
#include <cluster/masklog.h>
#include "ocfs2.h"
#include "alloc.h"
#include "dir.h"
#include "blockcheck.h"
#include "dlmglue.h"
#include "extent_map.h"
#include "file.h"
#include "heartbeat.h"
#include "inode.h"
#include "journal.h"
#include "namei.h"
#include "suballoc.h"
#include "super.h"
#include "symlink.h"
#include "sysfile.h"
#include "uptodate.h"
#include "xattr.h"
#include "refcounttree.h"
#include "ocfs2_trace.h"
#include "buffer_head_io.h"
struct ocfs2_find_inode_args
{
u64 fi_blkno;
unsigned long fi_ino;
unsigned int fi_flags;
unsigned int fi_sysfile_type;
};
static struct lock_class_key ocfs2_sysfile_lock_key[NUM_SYSTEM_INODES];
static int ocfs2_read_locked_inode(struct inode *inode,
struct ocfs2_find_inode_args *args);
static int ocfs2_init_locked_inode(struct inode *inode, void *opaque);
static int ocfs2_find_actor(struct inode *inode, void *opaque);
static int ocfs2_truncate_for_delete(struct ocfs2_super *osb,
struct inode *inode,
struct buffer_head *fe_bh);
void ocfs2_set_inode_flags(struct inode *inode)
{
unsigned int flags = OCFS2_I(inode)->ip_attr;
inode->i_flags &= ~(S_IMMUTABLE |
S_SYNC | S_APPEND | S_NOATIME | S_DIRSYNC);
if (flags & OCFS2_IMMUTABLE_FL)
inode->i_flags |= S_IMMUTABLE;
if (flags & OCFS2_SYNC_FL)
inode->i_flags |= S_SYNC;
if (flags & OCFS2_APPEND_FL)
inode->i_flags |= S_APPEND;
if (flags & OCFS2_NOATIME_FL)
inode->i_flags |= S_NOATIME;
if (flags & OCFS2_DIRSYNC_FL)
inode->i_flags |= S_DIRSYNC;
}
/* Propagate flags from i_flags to OCFS2_I(inode)->ip_attr */
void ocfs2_get_inode_flags(struct ocfs2_inode_info *oi)
{
unsigned int flags = oi->vfs_inode.i_flags;
oi->ip_attr &= ~(OCFS2_SYNC_FL|OCFS2_APPEND_FL|
OCFS2_IMMUTABLE_FL|OCFS2_NOATIME_FL|OCFS2_DIRSYNC_FL);
if (flags & S_SYNC)
oi->ip_attr |= OCFS2_SYNC_FL;
if (flags & S_APPEND)
oi->ip_attr |= OCFS2_APPEND_FL;
if (flags & S_IMMUTABLE)
oi->ip_attr |= OCFS2_IMMUTABLE_FL;
if (flags & S_NOATIME)
oi->ip_attr |= OCFS2_NOATIME_FL;
if (flags & S_DIRSYNC)
oi->ip_attr |= OCFS2_DIRSYNC_FL;
}
struct inode *ocfs2_ilookup(struct super_block *sb, u64 blkno)
{
struct ocfs2_find_inode_args args;
args.fi_blkno = blkno;
args.fi_flags = 0;
args.fi_ino = ino_from_blkno(sb, blkno);
args.fi_sysfile_type = 0;
return ilookup5(sb, blkno, ocfs2_find_actor, &args);
}
struct inode *ocfs2_iget(struct ocfs2_super *osb, u64 blkno, unsigned flags,
int sysfile_type)
{
struct inode *inode = NULL;
struct super_block *sb = osb->sb;
struct ocfs2_find_inode_args args;
trace_ocfs2_iget_begin((unsigned long long)blkno, flags,
sysfile_type);
/* Ok. By now we've either got the offsets passed to us by the
* caller, or we just pulled them off the bh. Lets do some
* sanity checks to make sure they're OK. */
if (blkno == 0) {
inode = ERR_PTR(-EINVAL);
mlog_errno(PTR_ERR(inode));
goto bail;
}
args.fi_blkno = blkno;
args.fi_flags = flags;
args.fi_ino = ino_from_blkno(sb, blkno);
args.fi_sysfile_type = sysfile_type;
inode = iget5_locked(sb, args.fi_ino, ocfs2_find_actor,
ocfs2_init_locked_inode, &args);
/* inode was *not* in the inode cache. 2.6.x requires
* us to do our own read_inode call and unlock it
* afterwards. */
if (inode == NULL) {
inode = ERR_PTR(-ENOMEM);
mlog_errno(PTR_ERR(inode));
goto bail;
}
trace_ocfs2_iget5_locked(inode->i_state);
if (inode->i_state & I_NEW) {
ocfs2_read_locked_inode(inode, &args);
unlock_new_inode(inode);
}
if (is_bad_inode(inode)) {
iput(inode);
inode = ERR_PTR(-ESTALE);
goto bail;
}
bail:
if (!IS_ERR(inode)) {
trace_ocfs2_iget_end(inode,
(unsigned long long)OCFS2_I(inode)->ip_blkno);
}
return inode;
}
/*
* here's how inodes get read from disk:
* iget5_locked -> find_actor -> OCFS2_FIND_ACTOR
* found? : return the in-memory inode
* not found? : get_new_inode -> OCFS2_INIT_LOCKED_INODE
*/
static int ocfs2_find_actor(struct inode *inode, void *opaque)
{
struct ocfs2_find_inode_args *args = NULL;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
int ret = 0;
args = opaque;
mlog_bug_on_msg(!inode, "No inode in find actor!\n");
trace_ocfs2_find_actor(inode, inode->i_ino, opaque, args->fi_blkno);
if (oi->ip_blkno != args->fi_blkno)
goto bail;
ret = 1;
bail:
return ret;
}
/*
* initialize the new inode, but don't do anything that would cause
* us to sleep.
* return 0 on success, 1 on failure
*/
static int ocfs2_init_locked_inode(struct inode *inode, void *opaque)
{
struct ocfs2_find_inode_args *args = opaque;
static struct lock_class_key ocfs2_quota_ip_alloc_sem_key,
ocfs2_file_ip_alloc_sem_key;
inode->i_ino = args->fi_ino;
OCFS2_I(inode)->ip_blkno = args->fi_blkno;
if (args->fi_sysfile_type != 0)
lockdep_set_class(&inode->i_mutex,
&ocfs2_sysfile_lock_key[args->fi_sysfile_type]);
if (args->fi_sysfile_type == USER_QUOTA_SYSTEM_INODE ||
args->fi_sysfile_type == GROUP_QUOTA_SYSTEM_INODE ||
args->fi_sysfile_type == LOCAL_USER_QUOTA_SYSTEM_INODE ||
args->fi_sysfile_type == LOCAL_GROUP_QUOTA_SYSTEM_INODE)
lockdep_set_class(&OCFS2_I(inode)->ip_alloc_sem,
&ocfs2_quota_ip_alloc_sem_key);
else
lockdep_set_class(&OCFS2_I(inode)->ip_alloc_sem,
&ocfs2_file_ip_alloc_sem_key);
return 0;
}
void ocfs2_populate_inode(struct inode *inode, struct ocfs2_dinode *fe,
int create_ino)
{
struct super_block *sb;
struct ocfs2_super *osb;
int use_plocks = 1;
sb = inode->i_sb;
osb = OCFS2_SB(sb);
if ((osb->s_mount_opt & OCFS2_MOUNT_LOCALFLOCKS) ||
ocfs2_mount_local(osb) || !ocfs2_stack_supports_plocks())
use_plocks = 0;
/*
* These have all been checked by ocfs2_read_inode_block() or set
* by ocfs2_mknod_locked(), so a failure is a code bug.
*/
BUG_ON(!OCFS2_IS_VALID_DINODE(fe)); /* This means that read_inode
cannot create a superblock
inode today. change if
that is needed. */
BUG_ON(!(fe->i_flags & cpu_to_le32(OCFS2_VALID_FL)));
BUG_ON(le32_to_cpu(fe->i_fs_generation) != osb->fs_generation);
OCFS2_I(inode)->ip_clusters = le32_to_cpu(fe->i_clusters);
OCFS2_I(inode)->ip_attr = le32_to_cpu(fe->i_attr);
OCFS2_I(inode)->ip_dyn_features = le16_to_cpu(fe->i_dyn_features);
inode->i_version = 1;
inode->i_generation = le32_to_cpu(fe->i_generation);
inode->i_rdev = huge_decode_dev(le64_to_cpu(fe->id1.dev1.i_rdev));
inode->i_mode = le16_to_cpu(fe->i_mode);
i_uid_write(inode, le32_to_cpu(fe->i_uid));
i_gid_write(inode, le32_to_cpu(fe->i_gid));
/* Fast symlinks will have i_size but no allocated clusters. */
if (S_ISLNK(inode->i_mode) && !fe->i_clusters) {
inode->i_blocks = 0;
inode->i_mapping->a_ops = &ocfs2_fast_symlink_aops;
} else {
inode->i_blocks = ocfs2_inode_sector_count(inode);
inode->i_mapping->a_ops = &ocfs2_aops;
}
inode->i_atime.tv_sec = le64_to_cpu(fe->i_atime);
inode->i_atime.tv_nsec = le32_to_cpu(fe->i_atime_nsec);
inode->i_mtime.tv_sec = le64_to_cpu(fe->i_mtime);
inode->i_mtime.tv_nsec = le32_to_cpu(fe->i_mtime_nsec);
inode->i_ctime.tv_sec = le64_to_cpu(fe->i_ctime);
inode->i_ctime.tv_nsec = le32_to_cpu(fe->i_ctime_nsec);
if (OCFS2_I(inode)->ip_blkno != le64_to_cpu(fe->i_blkno))
mlog(ML_ERROR,
"ip_blkno %llu != i_blkno %llu!\n",
(unsigned long long)OCFS2_I(inode)->ip_blkno,
(unsigned long long)le64_to_cpu(fe->i_blkno));
set_nlink(inode, ocfs2_read_links_count(fe));
trace_ocfs2_populate_inode(OCFS2_I(inode)->ip_blkno,
le32_to_cpu(fe->i_flags));
if (fe->i_flags & cpu_to_le32(OCFS2_SYSTEM_FL)) {
OCFS2_I(inode)->ip_flags |= OCFS2_INODE_SYSTEM_FILE;
inode->i_flags |= S_NOQUOTA;
}
if (fe->i_flags & cpu_to_le32(OCFS2_LOCAL_ALLOC_FL)) {
OCFS2_I(inode)->ip_flags |= OCFS2_INODE_BITMAP;
} else if (fe->i_flags & cpu_to_le32(OCFS2_BITMAP_FL)) {
OCFS2_I(inode)->ip_flags |= OCFS2_INODE_BITMAP;
} else if (fe->i_flags & cpu_to_le32(OCFS2_QUOTA_FL)) {
inode->i_flags |= S_NOQUOTA;
} else if (fe->i_flags & cpu_to_le32(OCFS2_SUPER_BLOCK_FL)) {
/* we can't actually hit this as read_inode can't
* handle superblocks today ;-) */
BUG();
}
switch (inode->i_mode & S_IFMT) {
case S_IFREG:
if (use_plocks)
inode->i_fop = &ocfs2_fops;
else
inode->i_fop = &ocfs2_fops_no_plocks;
inode->i_op = &ocfs2_file_iops;
i_size_write(inode, le64_to_cpu(fe->i_size));
break;
case S_IFDIR:
inode->i_op = &ocfs2_dir_iops;
if (use_plocks)
inode->i_fop = &ocfs2_dops;
else
inode->i_fop = &ocfs2_dops_no_plocks;
i_size_write(inode, le64_to_cpu(fe->i_size));
OCFS2_I(inode)->ip_dir_lock_gen = 1;
break;
case S_IFLNK:
inode->i_op = &ocfs2_symlink_inode_operations;
i_size_write(inode, le64_to_cpu(fe->i_size));
break;
default:
inode->i_op = &ocfs2_special_file_iops;
init_special_inode(inode, inode->i_mode,
inode->i_rdev);
break;
}
if (create_ino) {
inode->i_ino = ino_from_blkno(inode->i_sb,
le64_to_cpu(fe->i_blkno));
/*
* If we ever want to create system files from kernel,
* the generation argument to
* ocfs2_inode_lock_res_init() will have to change.
*/
BUG_ON(le32_to_cpu(fe->i_flags) & OCFS2_SYSTEM_FL);
ocfs2_inode_lock_res_init(&OCFS2_I(inode)->ip_inode_lockres,
OCFS2_LOCK_TYPE_META, 0, inode);
ocfs2_inode_lock_res_init(&OCFS2_I(inode)->ip_open_lockres,
OCFS2_LOCK_TYPE_OPEN, 0, inode);
}
ocfs2_inode_lock_res_init(&OCFS2_I(inode)->ip_rw_lockres,
OCFS2_LOCK_TYPE_RW, inode->i_generation,
inode);
ocfs2_set_inode_flags(inode);
OCFS2_I(inode)->ip_last_used_slot = 0;
OCFS2_I(inode)->ip_last_used_group = 0;
if (S_ISDIR(inode->i_mode))
ocfs2_resv_set_type(&OCFS2_I(inode)->ip_la_data_resv,
OCFS2_RESV_FLAG_DIR);
}
static int ocfs2_read_locked_inode(struct inode *inode,
struct ocfs2_find_inode_args *args)
{
struct super_block *sb;
struct ocfs2_super *osb;
struct ocfs2_dinode *fe;
struct buffer_head *bh = NULL;
int status, can_lock;
u32 generation = 0;
status = -EINVAL;
if (inode == NULL || inode->i_sb == NULL) {
mlog(ML_ERROR, "bad inode\n");
return status;
}
sb = inode->i_sb;
osb = OCFS2_SB(sb);
if (!args) {
mlog(ML_ERROR, "bad inode args\n");
make_bad_inode(inode);
return status;
}
/*
* To improve performance of cold-cache inode stats, we take
* the cluster lock here if possible.
*
* Generally, OCFS2 never trusts the contents of an inode
* unless it's holding a cluster lock, so taking it here isn't
* a correctness issue as much as it is a performance
* improvement.
*
* There are three times when taking the lock is not a good idea:
*
* 1) During startup, before we have initialized the DLM.
*
* 2) If we are reading certain system files which never get
* cluster locks (local alloc, truncate log).
*
* 3) If the process doing the iget() is responsible for
* orphan dir recovery. We're holding the orphan dir lock and
* can get into a deadlock with another process on another
* node in ->delete_inode().
*
* #1 and #2 can be simply solved by never taking the lock
* here for system files (which are the only type we read
* during mount). It's a heavier approach, but our main
* concern is user-accessible files anyway.
*
* #3 works itself out because we'll eventually take the
* cluster lock before trusting anything anyway.
*/
can_lock = !(args->fi_flags & OCFS2_FI_FLAG_SYSFILE)
&& !(args->fi_flags & OCFS2_FI_FLAG_ORPHAN_RECOVERY)
&& !ocfs2_mount_local(osb);
trace_ocfs2_read_locked_inode(
(unsigned long long)OCFS2_I(inode)->ip_blkno, can_lock);
/*
* To maintain backwards compatibility with older versions of
* ocfs2-tools, we still store the generation value for system
* files. The only ones that actually matter to userspace are
* the journals, but it's easier and inexpensive to just flag
* all system files similarly.
*/
if (args->fi_flags & OCFS2_FI_FLAG_SYSFILE)
generation = osb->fs_generation;
ocfs2_inode_lock_res_init(&OCFS2_I(inode)->ip_inode_lockres,
OCFS2_LOCK_TYPE_META,
generation, inode);
ocfs2_inode_lock_res_init(&OCFS2_I(inode)->ip_open_lockres,
OCFS2_LOCK_TYPE_OPEN,
0, inode);
if (can_lock) {
status = ocfs2_open_lock(inode);
if (status) {
make_bad_inode(inode);
mlog_errno(status);
return status;
}
status = ocfs2_inode_lock(inode, NULL, 0);
if (status) {
make_bad_inode(inode);
mlog_errno(status);
return status;
}
}
if (args->fi_flags & OCFS2_FI_FLAG_ORPHAN_RECOVERY) {
status = ocfs2_try_open_lock(inode, 0);
if (status) {
make_bad_inode(inode);
return status;
}
}
if (can_lock) {
status = ocfs2_read_inode_block_full(inode, &bh,
OCFS2_BH_IGNORE_CACHE);
} else {
status = ocfs2_read_blocks_sync(osb, args->fi_blkno, 1, &bh);
/*
* If buffer is in jbd, then its checksum may not have been
* computed as yet.
*/
if (!status && !buffer_jbd(bh))
status = ocfs2_validate_inode_block(osb->sb, bh);
}
if (status < 0) {
mlog_errno(status);
goto bail;
}
status = -EINVAL;
fe = (struct ocfs2_dinode *) bh->b_data;
/*
* This is a code bug. Right now the caller needs to
* understand whether it is asking for a system file inode or
* not so the proper lock names can be built.
*/
mlog_bug_on_msg(!!(fe->i_flags & cpu_to_le32(OCFS2_SYSTEM_FL)) !=
!!(args->fi_flags & OCFS2_FI_FLAG_SYSFILE),
"Inode %llu: system file state is ambigous\n",
(unsigned long long)args->fi_blkno);
if (S_ISCHR(le16_to_cpu(fe->i_mode)) ||
S_ISBLK(le16_to_cpu(fe->i_mode)))
inode->i_rdev = huge_decode_dev(le64_to_cpu(fe->id1.dev1.i_rdev));
ocfs2_populate_inode(inode, fe, 0);
BUG_ON(args->fi_blkno != le64_to_cpu(fe->i_blkno));
status = 0;
bail:
if (can_lock)
ocfs2_inode_unlock(inode, 0);
if (status < 0)
make_bad_inode(inode);
if (args && bh)
brelse(bh);
return status;
}
void ocfs2_sync_blockdev(struct super_block *sb)
{
sync_blockdev(sb->s_bdev);
}
static int ocfs2_truncate_for_delete(struct ocfs2_super *osb,
struct inode *inode,
struct buffer_head *fe_bh)
{
int status = 0;
struct ocfs2_dinode *fe;
handle_t *handle = NULL;
fe = (struct ocfs2_dinode *) fe_bh->b_data;
/*
* This check will also skip truncate of inodes with inline
* data and fast symlinks.
*/
if (fe->i_clusters) {
if (ocfs2_should_order_data(inode))
ocfs2_begin_ordered_truncate(inode, 0);
handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
handle = NULL;
mlog_errno(status);
goto out;
}
status = ocfs2_journal_access_di(handle, INODE_CACHE(inode),
fe_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto out;
}
i_size_write(inode, 0);
status = ocfs2_mark_inode_dirty(handle, inode, fe_bh);
if (status < 0) {
mlog_errno(status);
goto out;
}
ocfs2_commit_trans(osb, handle);
handle = NULL;
status = ocfs2_commit_truncate(osb, inode, fe_bh);
if (status < 0) {
mlog_errno(status);
goto out;
}
}
out:
if (handle)
ocfs2_commit_trans(osb, handle);
return status;
}
static int ocfs2_remove_inode(struct inode *inode,
struct buffer_head *di_bh,
struct inode *orphan_dir_inode,
struct buffer_head *orphan_dir_bh)
{
int status;
struct inode *inode_alloc_inode = NULL;
struct buffer_head *inode_alloc_bh = NULL;
handle_t *handle;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_dinode *di = (struct ocfs2_dinode *) di_bh->b_data;
inode_alloc_inode =
ocfs2_get_system_file_inode(osb, INODE_ALLOC_SYSTEM_INODE,
le16_to_cpu(di->i_suballoc_slot));
if (!inode_alloc_inode) {
status = -EEXIST;
mlog_errno(status);
goto bail;
}
mutex_lock(&inode_alloc_inode->i_mutex);
status = ocfs2_inode_lock(inode_alloc_inode, &inode_alloc_bh, 1);
if (status < 0) {
mutex_unlock(&inode_alloc_inode->i_mutex);
mlog_errno(status);
goto bail;
}
handle = ocfs2_start_trans(osb, OCFS2_DELETE_INODE_CREDITS +
ocfs2_quota_trans_credits(inode->i_sb));
if (IS_ERR(handle)) {
status = PTR_ERR(handle);
mlog_errno(status);
goto bail_unlock;
}
if (!(OCFS2_I(inode)->ip_flags & OCFS2_INODE_SKIP_ORPHAN_DIR)) {
status = ocfs2_orphan_del(osb, handle, orphan_dir_inode, inode,
orphan_dir_bh);
if (status < 0) {
mlog_errno(status);
goto bail_commit;
}
}
/* set the inodes dtime */
status = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto bail_commit;
}
di->i_dtime = cpu_to_le64(CURRENT_TIME.tv_sec);
di->i_flags &= cpu_to_le32(~(OCFS2_VALID_FL | OCFS2_ORPHANED_FL));
ocfs2_journal_dirty(handle, di_bh);
ocfs2_remove_from_cache(INODE_CACHE(inode), di_bh);
dquot_free_inode(inode);
status = ocfs2_free_dinode(handle, inode_alloc_inode,
inode_alloc_bh, di);
if (status < 0)
mlog_errno(status);
bail_commit:
ocfs2_commit_trans(osb, handle);
bail_unlock:
ocfs2_inode_unlock(inode_alloc_inode, 1);
mutex_unlock(&inode_alloc_inode->i_mutex);
brelse(inode_alloc_bh);
bail:
iput(inode_alloc_inode);
return status;
}
/*
* Serialize with orphan dir recovery. If the process doing
* recovery on this orphan dir does an iget() with the dir
* i_mutex held, we'll deadlock here. Instead we detect this
* and exit early - recovery will wipe this inode for us.
*/
static int ocfs2_check_orphan_recovery_state(struct ocfs2_super *osb,
int slot)
{
int ret = 0;
spin_lock(&osb->osb_lock);
if (ocfs2_node_map_test_bit(osb, &osb->osb_recovering_orphan_dirs, slot)) {
ret = -EDEADLK;
goto out;
}
/* This signals to the orphan recovery process that it should
* wait for us to handle the wipe. */
osb->osb_orphan_wipes[slot]++;
out:
spin_unlock(&osb->osb_lock);
trace_ocfs2_check_orphan_recovery_state(slot, ret);
return ret;
}
static void ocfs2_signal_wipe_completion(struct ocfs2_super *osb,
int slot)
{
spin_lock(&osb->osb_lock);
osb->osb_orphan_wipes[slot]--;
spin_unlock(&osb->osb_lock);
wake_up(&osb->osb_wipe_event);
}
static int ocfs2_wipe_inode(struct inode *inode,
struct buffer_head *di_bh)
{
int status, orphaned_slot = -1;
struct inode *orphan_dir_inode = NULL;
struct buffer_head *orphan_dir_bh = NULL;
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
struct ocfs2_dinode *di = (struct ocfs2_dinode *) di_bh->b_data;
if (!(OCFS2_I(inode)->ip_flags & OCFS2_INODE_SKIP_ORPHAN_DIR)) {
orphaned_slot = le16_to_cpu(di->i_orphaned_slot);
status = ocfs2_check_orphan_recovery_state(osb, orphaned_slot);
if (status)
return status;
orphan_dir_inode = ocfs2_get_system_file_inode(osb,
ORPHAN_DIR_SYSTEM_INODE,
orphaned_slot);
if (!orphan_dir_inode) {
status = -EEXIST;
mlog_errno(status);
goto bail;
}
/* Lock the orphan dir. The lock will be held for the entire
* delete_inode operation. We do this now to avoid races with
* recovery completion on other nodes. */
mutex_lock(&orphan_dir_inode->i_mutex);
status = ocfs2_inode_lock(orphan_dir_inode, &orphan_dir_bh, 1);
if (status < 0) {
mutex_unlock(&orphan_dir_inode->i_mutex);
mlog_errno(status);
goto bail;
}
}
/* we do this while holding the orphan dir lock because we
* don't want recovery being run from another node to try an
* inode delete underneath us -- this will result in two nodes
* truncating the same file! */
status = ocfs2_truncate_for_delete(osb, inode, di_bh);
if (status < 0) {
mlog_errno(status);
goto bail_unlock_dir;
}
/* Remove any dir index tree */
if (S_ISDIR(inode->i_mode)) {
status = ocfs2_dx_dir_truncate(inode, di_bh);
if (status) {
mlog_errno(status);
goto bail_unlock_dir;
}
}
/*Free extended attribute resources associated with this inode.*/
status = ocfs2_xattr_remove(inode, di_bh);
if (status < 0) {
mlog_errno(status);
goto bail_unlock_dir;
}
status = ocfs2_remove_refcount_tree(inode, di_bh);
if (status < 0) {
mlog_errno(status);
goto bail_unlock_dir;
}
status = ocfs2_remove_inode(inode, di_bh, orphan_dir_inode,
orphan_dir_bh);
if (status < 0)
mlog_errno(status);
bail_unlock_dir:
if (OCFS2_I(inode)->ip_flags & OCFS2_INODE_SKIP_ORPHAN_DIR)
return status;
ocfs2_inode_unlock(orphan_dir_inode, 1);
mutex_unlock(&orphan_dir_inode->i_mutex);
brelse(orphan_dir_bh);
bail:
iput(orphan_dir_inode);
ocfs2_signal_wipe_completion(osb, orphaned_slot);
return status;
}
/* There is a series of simple checks that should be done before a
* trylock is even considered. Encapsulate those in this function. */
static int ocfs2_inode_is_valid_to_delete(struct inode *inode)
{
int ret = 0;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
trace_ocfs2_inode_is_valid_to_delete(current, osb->dc_task,
(unsigned long long)oi->ip_blkno,
oi->ip_flags);
/* We shouldn't be getting here for the root directory
* inode.. */
if (inode == osb->root_inode) {
mlog(ML_ERROR, "Skipping delete of root inode.\n");
goto bail;
}
/* If we're coming from downconvert_thread we can't go into our own
* voting [hello, deadlock city!], so unforuntately we just
* have to skip deleting this guy. That's OK though because
* the node who's doing the actual deleting should handle it
* anyway. */
if (current == osb->dc_task)
goto bail;
spin_lock(&oi->ip_lock);
/* OCFS2 *never* deletes system files. This should technically
* never get here as system file inodes should always have a
* positive link count. */
if (oi->ip_flags & OCFS2_INODE_SYSTEM_FILE) {
mlog(ML_ERROR, "Skipping delete of system file %llu\n",
(unsigned long long)oi->ip_blkno);
goto bail_unlock;
}
/* If we have allowd wipe of this inode for another node, it
* will be marked here so we can safely skip it. Recovery will
* cleanup any inodes we might inadvertently skip here. */
if (oi->ip_flags & OCFS2_INODE_SKIP_DELETE)
goto bail_unlock;
ret = 1;
bail_unlock:
spin_unlock(&oi->ip_lock);
bail:
return ret;
}
/* Query the cluster to determine whether we should wipe an inode from
* disk or not.
*
* Requires the inode to have the cluster lock. */
static int ocfs2_query_inode_wipe(struct inode *inode,
struct buffer_head *di_bh,
int *wipe)
{
int status = 0, reason = 0;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
struct ocfs2_dinode *di;
*wipe = 0;
trace_ocfs2_query_inode_wipe_begin((unsigned long long)oi->ip_blkno,
inode->i_nlink);
/* While we were waiting for the cluster lock in
* ocfs2_delete_inode, another node might have asked to delete
* the inode. Recheck our flags to catch this. */
if (!ocfs2_inode_is_valid_to_delete(inode)) {
reason = 1;
goto bail;
}
/* Now that we have an up to date inode, we can double check
* the link count. */
if (inode->i_nlink)
goto bail;
/* Do some basic inode verification... */
di = (struct ocfs2_dinode *) di_bh->b_data;
if (!(di->i_flags & cpu_to_le32(OCFS2_ORPHANED_FL)) &&
!(oi->ip_flags & OCFS2_INODE_SKIP_ORPHAN_DIR)) {
/*
* Inodes in the orphan dir must have ORPHANED_FL. The only
* inodes that come back out of the orphan dir are reflink
* targets. A reflink target may be moved out of the orphan
* dir between the time we scan the directory and the time we
* process it. This would lead to HAS_REFCOUNT_FL being set but
* ORPHANED_FL not.
*/
if (di->i_dyn_features & cpu_to_le16(OCFS2_HAS_REFCOUNT_FL)) {
reason = 2;
goto bail;
}
/* for lack of a better error? */
status = -EEXIST;
mlog(ML_ERROR,
"Inode %llu (on-disk %llu) not orphaned! "
"Disk flags 0x%x, inode flags 0x%x\n",
(unsigned long long)oi->ip_blkno,
(unsigned long long)le64_to_cpu(di->i_blkno),
le32_to_cpu(di->i_flags), oi->ip_flags);
goto bail;
}
/* has someone already deleted us?! baaad... */
if (di->i_dtime) {
status = -EEXIST;
mlog_errno(status);
goto bail;
}
/*
* This is how ocfs2 determines whether an inode is still live
* within the cluster. Every node takes a shared read lock on
* the inode open lock in ocfs2_read_locked_inode(). When we
* get to ->delete_inode(), each node tries to convert it's
* lock to an exclusive. Trylocks are serialized by the inode
* meta data lock. If the upconvert succeeds, we know the inode
* is no longer live and can be deleted.
*
* Though we call this with the meta data lock held, the
* trylock keeps us from ABBA deadlock.
*/
status = ocfs2_try_open_lock(inode, 1);
if (status == -EAGAIN) {
status = 0;
reason = 3;
goto bail;
}
if (status < 0) {
mlog_errno(status);
goto bail;
}
*wipe = 1;
trace_ocfs2_query_inode_wipe_succ(le16_to_cpu(di->i_orphaned_slot));
bail:
trace_ocfs2_query_inode_wipe_end(status, reason);
return status;
}
/* Support function for ocfs2_delete_inode. Will help us keep the
* inode data in a consistent state for clear_inode. Always truncates
* pages, optionally sync's them first. */
static void ocfs2_cleanup_delete_inode(struct inode *inode,
int sync_data)
{
trace_ocfs2_cleanup_delete_inode(
(unsigned long long)OCFS2_I(inode)->ip_blkno, sync_data);
if (sync_data)
filemap_write_and_wait(inode->i_mapping);
truncate_inode_pages(&inode->i_data, 0);
}
static void ocfs2_delete_inode(struct inode *inode)
{
int wipe, status;
sigset_t oldset;
struct buffer_head *di_bh = NULL;
trace_ocfs2_delete_inode(inode->i_ino,
(unsigned long long)OCFS2_I(inode)->ip_blkno,
is_bad_inode(inode));
/* When we fail in read_inode() we mark inode as bad. The second test
* catches the case when inode allocation fails before allocating
* a block for inode. */
if (is_bad_inode(inode) || !OCFS2_I(inode)->ip_blkno)
goto bail;
dquot_initialize(inode);
if (!ocfs2_inode_is_valid_to_delete(inode)) {
/* It's probably not necessary to truncate_inode_pages
* here but we do it for safety anyway (it will most
* likely be a no-op anyway) */
ocfs2_cleanup_delete_inode(inode, 0);
goto bail;
}
/* We want to block signals in delete_inode as the lock and
* messaging paths may return us -ERESTARTSYS. Which would
* cause us to exit early, resulting in inodes being orphaned
* forever. */
ocfs2_block_signals(&oldset);
/*
* Synchronize us against ocfs2_get_dentry. We take this in
* shared mode so that all nodes can still concurrently
* process deletes.
*/
status = ocfs2_nfs_sync_lock(OCFS2_SB(inode->i_sb), 0);
if (status < 0) {
mlog(ML_ERROR, "getting nfs sync lock(PR) failed %d\n", status);
ocfs2_cleanup_delete_inode(inode, 0);
goto bail_unblock;
}
/* Lock down the inode. This gives us an up to date view of
* it's metadata (for verification), and allows us to
* serialize delete_inode on multiple nodes.
*
* Even though we might be doing a truncate, we don't take the
* allocation lock here as it won't be needed - nobody will
* have the file open.
*/
status = ocfs2_inode_lock(inode, &di_bh, 1);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
ocfs2_cleanup_delete_inode(inode, 0);
goto bail_unlock_nfs_sync;
}
/* Query the cluster. This will be the final decision made
* before we go ahead and wipe the inode. */
status = ocfs2_query_inode_wipe(inode, di_bh, &wipe);
if (!wipe || status < 0) {
/* Error and remote inode busy both mean we won't be
* removing the inode, so they take almost the same
* path. */
if (status < 0)
mlog_errno(status);
/* Someone in the cluster has disallowed a wipe of
* this inode, or it was never completely
* orphaned. Write out the pages and exit now. */
ocfs2_cleanup_delete_inode(inode, 1);
goto bail_unlock_inode;
}
ocfs2_cleanup_delete_inode(inode, 0);
status = ocfs2_wipe_inode(inode, di_bh);
if (status < 0) {
if (status != -EDEADLK)
mlog_errno(status);
goto bail_unlock_inode;
}
/*
* Mark the inode as successfully deleted.
*
* This is important for ocfs2_clear_inode() as it will check
* this flag and skip any checkpointing work
*
* ocfs2_stuff_meta_lvb() also uses this flag to invalidate
* the LVB for other nodes.
*/
OCFS2_I(inode)->ip_flags |= OCFS2_INODE_DELETED;
bail_unlock_inode:
ocfs2_inode_unlock(inode, 1);
brelse(di_bh);
bail_unlock_nfs_sync:
ocfs2_nfs_sync_unlock(OCFS2_SB(inode->i_sb), 0);
bail_unblock:
ocfs2_unblock_signals(&oldset);
bail:
return;
}
static void ocfs2_clear_inode(struct inode *inode)
{
int status;
struct ocfs2_inode_info *oi = OCFS2_I(inode);
clear_inode(inode);
trace_ocfs2_clear_inode((unsigned long long)oi->ip_blkno,
inode->i_nlink);
mlog_bug_on_msg(OCFS2_SB(inode->i_sb) == NULL,
"Inode=%lu\n", inode->i_ino);
dquot_drop(inode);
/* To preven remote deletes we hold open lock before, now it
* is time to unlock PR and EX open locks. */
ocfs2_open_unlock(inode);
/* Do these before all the other work so that we don't bounce
* the downconvert thread while waiting to destroy the locks. */
ocfs2_mark_lockres_freeing(&oi->ip_rw_lockres);
ocfs2_mark_lockres_freeing(&oi->ip_inode_lockres);
ocfs2_mark_lockres_freeing(&oi->ip_open_lockres);
ocfs2_resv_discard(&OCFS2_SB(inode->i_sb)->osb_la_resmap,
&oi->ip_la_data_resv);
ocfs2_resv_init_once(&oi->ip_la_data_resv);
/* We very well may get a clear_inode before all an inodes
* metadata has hit disk. Of course, we can't drop any cluster
* locks until the journal has finished with it. The only
* exception here are successfully wiped inodes - their
* metadata can now be considered to be part of the system
* inodes from which it came. */
if (!(OCFS2_I(inode)->ip_flags & OCFS2_INODE_DELETED))
ocfs2_checkpoint_inode(inode);
mlog_bug_on_msg(!list_empty(&oi->ip_io_markers),
"Clear inode of %llu, inode has io markers\n",
(unsigned long long)oi->ip_blkno);
ocfs2_extent_map_trunc(inode, 0);
status = ocfs2_drop_inode_locks(inode);
if (status < 0)
mlog_errno(status);
ocfs2_lock_res_free(&oi->ip_rw_lockres);
ocfs2_lock_res_free(&oi->ip_inode_lockres);
ocfs2_lock_res_free(&oi->ip_open_lockres);
ocfs2_metadata_cache_exit(INODE_CACHE(inode));
mlog_bug_on_msg(INODE_CACHE(inode)->ci_num_cached,
"Clear inode of %llu, inode has %u cache items\n",
(unsigned long long)oi->ip_blkno,
INODE_CACHE(inode)->ci_num_cached);
mlog_bug_on_msg(!(INODE_CACHE(inode)->ci_flags & OCFS2_CACHE_FL_INLINE),
"Clear inode of %llu, inode has a bad flag\n",
(unsigned long long)oi->ip_blkno);
mlog_bug_on_msg(spin_is_locked(&oi->ip_lock),
"Clear inode of %llu, inode is locked\n",
(unsigned long long)oi->ip_blkno);
mlog_bug_on_msg(!mutex_trylock(&oi->ip_io_mutex),
"Clear inode of %llu, io_mutex is locked\n",
(unsigned long long)oi->ip_blkno);
mutex_unlock(&oi->ip_io_mutex);
/*
* down_trylock() returns 0, down_write_trylock() returns 1
* kernel 1, world 0
*/
mlog_bug_on_msg(!down_write_trylock(&oi->ip_alloc_sem),
"Clear inode of %llu, alloc_sem is locked\n",
(unsigned long long)oi->ip_blkno);
up_write(&oi->ip_alloc_sem);
mlog_bug_on_msg(oi->ip_open_count,
"Clear inode of %llu has open count %d\n",
(unsigned long long)oi->ip_blkno, oi->ip_open_count);
/* Clear all other flags. */
oi->ip_flags = 0;
oi->ip_dir_start_lookup = 0;
oi->ip_blkno = 0ULL;
/*
* ip_jinode is used to track txns against this inode. We ensure that
* the journal is flushed before journal shutdown. Thus it is safe to
* have inodes get cleaned up after journal shutdown.
*/
jbd2_journal_release_jbd_inode(OCFS2_SB(inode->i_sb)->journal->j_journal,
&oi->ip_jinode);
}
void ocfs2_evict_inode(struct inode *inode)
{
if (!inode->i_nlink ||
(OCFS2_I(inode)->ip_flags & OCFS2_INODE_MAYBE_ORPHANED)) {
ocfs2_delete_inode(inode);
} else {
truncate_inode_pages(&inode->i_data, 0);
}
ocfs2_clear_inode(inode);
}
/* Called under inode_lock, with no more references on the
* struct inode, so it's safe here to check the flags field
* and to manipulate i_nlink without any other locks. */
int ocfs2_drop_inode(struct inode *inode)
{
struct ocfs2_inode_info *oi = OCFS2_I(inode);
int res;
trace_ocfs2_drop_inode((unsigned long long)oi->ip_blkno,
inode->i_nlink, oi->ip_flags);
if (oi->ip_flags & OCFS2_INODE_MAYBE_ORPHANED)
res = 1;
else
res = generic_drop_inode(inode);
return res;
}
/*
* This is called from our getattr.
*/
int ocfs2_inode_revalidate(struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
int status = 0;
trace_ocfs2_inode_revalidate(inode,
inode ? (unsigned long long)OCFS2_I(inode)->ip_blkno : 0ULL,
inode ? (unsigned long long)OCFS2_I(inode)->ip_flags : 0);
if (!inode) {
status = -ENOENT;
goto bail;
}
spin_lock(&OCFS2_I(inode)->ip_lock);
if (OCFS2_I(inode)->ip_flags & OCFS2_INODE_DELETED) {
spin_unlock(&OCFS2_I(inode)->ip_lock);
status = -ENOENT;
goto bail;
}
spin_unlock(&OCFS2_I(inode)->ip_lock);
/* Let ocfs2_inode_lock do the work of updating our struct
* inode for us. */
status = ocfs2_inode_lock(inode, NULL, 0);
if (status < 0) {
if (status != -ENOENT)
mlog_errno(status);
goto bail;
}
ocfs2_inode_unlock(inode, 0);
bail:
return status;
}
/*
* Updates a disk inode from a
* struct inode.
* Only takes ip_lock.
*/
int ocfs2_mark_inode_dirty(handle_t *handle,
struct inode *inode,
struct buffer_head *bh)
{
int status;
struct ocfs2_dinode *fe = (struct ocfs2_dinode *) bh->b_data;
trace_ocfs2_mark_inode_dirty((unsigned long long)OCFS2_I(inode)->ip_blkno);
status = ocfs2_journal_access_di(handle, INODE_CACHE(inode), bh,
OCFS2_JOURNAL_ACCESS_WRITE);
if (status < 0) {
mlog_errno(status);
goto leave;
}
spin_lock(&OCFS2_I(inode)->ip_lock);
fe->i_clusters = cpu_to_le32(OCFS2_I(inode)->ip_clusters);
ocfs2_get_inode_flags(OCFS2_I(inode));
fe->i_attr = cpu_to_le32(OCFS2_I(inode)->ip_attr);
fe->i_dyn_features = cpu_to_le16(OCFS2_I(inode)->ip_dyn_features);
spin_unlock(&OCFS2_I(inode)->ip_lock);
fe->i_size = cpu_to_le64(i_size_read(inode));
ocfs2_set_links_count(fe, inode->i_nlink);
fe->i_uid = cpu_to_le32(i_uid_read(inode));
fe->i_gid = cpu_to_le32(i_gid_read(inode));
fe->i_mode = cpu_to_le16(inode->i_mode);
fe->i_atime = cpu_to_le64(inode->i_atime.tv_sec);
fe->i_atime_nsec = cpu_to_le32(inode->i_atime.tv_nsec);
fe->i_ctime = cpu_to_le64(inode->i_ctime.tv_sec);
fe->i_ctime_nsec = cpu_to_le32(inode->i_ctime.tv_nsec);
fe->i_mtime = cpu_to_le64(inode->i_mtime.tv_sec);
fe->i_mtime_nsec = cpu_to_le32(inode->i_mtime.tv_nsec);
ocfs2_journal_dirty(handle, bh);
leave:
return status;
}
/*
*
* Updates a struct inode from a disk inode.
* does no i/o, only takes ip_lock.
*/
void ocfs2_refresh_inode(struct inode *inode,
struct ocfs2_dinode *fe)
{
spin_lock(&OCFS2_I(inode)->ip_lock);
OCFS2_I(inode)->ip_clusters = le32_to_cpu(fe->i_clusters);
OCFS2_I(inode)->ip_attr = le32_to_cpu(fe->i_attr);
OCFS2_I(inode)->ip_dyn_features = le16_to_cpu(fe->i_dyn_features);
ocfs2_set_inode_flags(inode);
i_size_write(inode, le64_to_cpu(fe->i_size));
set_nlink(inode, ocfs2_read_links_count(fe));
i_uid_write(inode, le32_to_cpu(fe->i_uid));
i_gid_write(inode, le32_to_cpu(fe->i_gid));
inode->i_mode = le16_to_cpu(fe->i_mode);
if (S_ISLNK(inode->i_mode) && le32_to_cpu(fe->i_clusters) == 0)
inode->i_blocks = 0;
else
inode->i_blocks = ocfs2_inode_sector_count(inode);
inode->i_atime.tv_sec = le64_to_cpu(fe->i_atime);
inode->i_atime.tv_nsec = le32_to_cpu(fe->i_atime_nsec);
inode->i_mtime.tv_sec = le64_to_cpu(fe->i_mtime);
inode->i_mtime.tv_nsec = le32_to_cpu(fe->i_mtime_nsec);
inode->i_ctime.tv_sec = le64_to_cpu(fe->i_ctime);
inode->i_ctime.tv_nsec = le32_to_cpu(fe->i_ctime_nsec);
spin_unlock(&OCFS2_I(inode)->ip_lock);
}
int ocfs2_validate_inode_block(struct super_block *sb,
struct buffer_head *bh)
{
int rc;
struct ocfs2_dinode *di = (struct ocfs2_dinode *)bh->b_data;
trace_ocfs2_validate_inode_block((unsigned long long)bh->b_blocknr);
BUG_ON(!buffer_uptodate(bh));
/*
* If the ecc fails, we return the error but otherwise
* leave the filesystem running. We know any error is
* local to this block.
*/
rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &di->i_check);
if (rc) {
mlog(ML_ERROR, "Checksum failed for dinode %llu\n",
(unsigned long long)bh->b_blocknr);
goto bail;
}
/*
* Errors after here are fatal.
*/
rc = -EINVAL;
if (!OCFS2_IS_VALID_DINODE(di)) {
ocfs2_error(sb, "Invalid dinode #%llu: signature = %.*s\n",
(unsigned long long)bh->b_blocknr, 7,
di->i_signature);
goto bail;
}
if (le64_to_cpu(di->i_blkno) != bh->b_blocknr) {
ocfs2_error(sb, "Invalid dinode #%llu: i_blkno is %llu\n",
(unsigned long long)bh->b_blocknr,
(unsigned long long)le64_to_cpu(di->i_blkno));
goto bail;
}
if (!(di->i_flags & cpu_to_le32(OCFS2_VALID_FL))) {
ocfs2_error(sb,
"Invalid dinode #%llu: OCFS2_VALID_FL not set\n",
(unsigned long long)bh->b_blocknr);
goto bail;
}
if (le32_to_cpu(di->i_fs_generation) !=
OCFS2_SB(sb)->fs_generation) {
ocfs2_error(sb,
"Invalid dinode #%llu: fs_generation is %u\n",
(unsigned long long)bh->b_blocknr,
le32_to_cpu(di->i_fs_generation));
goto bail;
}
rc = 0;
bail:
return rc;
}
int ocfs2_read_inode_block_full(struct inode *inode, struct buffer_head **bh,
int flags)
{
int rc;
struct buffer_head *tmp = *bh;
rc = ocfs2_read_blocks(INODE_CACHE(inode), OCFS2_I(inode)->ip_blkno,
1, &tmp, flags, ocfs2_validate_inode_block);
/* If ocfs2_read_blocks() got us a new bh, pass it up. */
if (!rc && !*bh)
*bh = tmp;
return rc;
}
int ocfs2_read_inode_block(struct inode *inode, struct buffer_head **bh)
{
return ocfs2_read_inode_block_full(inode, bh, 0);
}
static u64 ocfs2_inode_cache_owner(struct ocfs2_caching_info *ci)
{
struct ocfs2_inode_info *oi = cache_info_to_inode(ci);
return oi->ip_blkno;
}
static struct super_block *ocfs2_inode_cache_get_super(struct ocfs2_caching_info *ci)
{
struct ocfs2_inode_info *oi = cache_info_to_inode(ci);
return oi->vfs_inode.i_sb;
}
static void ocfs2_inode_cache_lock(struct ocfs2_caching_info *ci)
{
struct ocfs2_inode_info *oi = cache_info_to_inode(ci);
spin_lock(&oi->ip_lock);
}
static void ocfs2_inode_cache_unlock(struct ocfs2_caching_info *ci)
{
struct ocfs2_inode_info *oi = cache_info_to_inode(ci);
spin_unlock(&oi->ip_lock);
}
static void ocfs2_inode_cache_io_lock(struct ocfs2_caching_info *ci)
{
struct ocfs2_inode_info *oi = cache_info_to_inode(ci);
mutex_lock(&oi->ip_io_mutex);
}
static void ocfs2_inode_cache_io_unlock(struct ocfs2_caching_info *ci)
{
struct ocfs2_inode_info *oi = cache_info_to_inode(ci);
mutex_unlock(&oi->ip_io_mutex);
}
const struct ocfs2_caching_operations ocfs2_inode_caching_ops = {
.co_owner = ocfs2_inode_cache_owner,
.co_get_super = ocfs2_inode_cache_get_super,
.co_cache_lock = ocfs2_inode_cache_lock,
.co_cache_unlock = ocfs2_inode_cache_unlock,
.co_io_lock = ocfs2_inode_cache_io_lock,
.co_io_unlock = ocfs2_inode_cache_io_unlock,
};
| gpl-2.0 |
peterzhu0503/kernel_rk3168_86v_yk | drivers/firewire/core-iso.c | 2782 | 9843 | /*
* Isochronous I/O functionality:
* - Isochronous DMA context management
* - Isochronous bus resource management (channels, bandwidth), client side
*
* Copyright (C) 2006 Kristian Hoegsberg <krh@bitplanet.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 <linux/dma-mapping.h>
#include <linux/errno.h>
#include <linux/firewire.h>
#include <linux/firewire-constants.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/vmalloc.h>
#include <asm/byteorder.h>
#include "core.h"
/*
* Isochronous DMA context management
*/
int fw_iso_buffer_init(struct fw_iso_buffer *buffer, struct fw_card *card,
int page_count, enum dma_data_direction direction)
{
int i, j;
dma_addr_t address;
buffer->page_count = page_count;
buffer->direction = direction;
buffer->pages = kmalloc(page_count * sizeof(buffer->pages[0]),
GFP_KERNEL);
if (buffer->pages == NULL)
goto out;
for (i = 0; i < buffer->page_count; i++) {
buffer->pages[i] = alloc_page(GFP_KERNEL | GFP_DMA32 | __GFP_ZERO);
if (buffer->pages[i] == NULL)
goto out_pages;
address = dma_map_page(card->device, buffer->pages[i],
0, PAGE_SIZE, direction);
if (dma_mapping_error(card->device, address)) {
__free_page(buffer->pages[i]);
goto out_pages;
}
set_page_private(buffer->pages[i], address);
}
return 0;
out_pages:
for (j = 0; j < i; j++) {
address = page_private(buffer->pages[j]);
dma_unmap_page(card->device, address,
PAGE_SIZE, direction);
__free_page(buffer->pages[j]);
}
kfree(buffer->pages);
out:
buffer->pages = NULL;
return -ENOMEM;
}
EXPORT_SYMBOL(fw_iso_buffer_init);
int fw_iso_buffer_map(struct fw_iso_buffer *buffer, struct vm_area_struct *vma)
{
unsigned long uaddr;
int i, err;
uaddr = vma->vm_start;
for (i = 0; i < buffer->page_count; i++) {
err = vm_insert_page(vma, uaddr, buffer->pages[i]);
if (err)
return err;
uaddr += PAGE_SIZE;
}
return 0;
}
void fw_iso_buffer_destroy(struct fw_iso_buffer *buffer,
struct fw_card *card)
{
int i;
dma_addr_t address;
for (i = 0; i < buffer->page_count; i++) {
address = page_private(buffer->pages[i]);
dma_unmap_page(card->device, address,
PAGE_SIZE, buffer->direction);
__free_page(buffer->pages[i]);
}
kfree(buffer->pages);
buffer->pages = NULL;
}
EXPORT_SYMBOL(fw_iso_buffer_destroy);
/* Convert DMA address to offset into virtually contiguous buffer. */
size_t fw_iso_buffer_lookup(struct fw_iso_buffer *buffer, dma_addr_t completed)
{
int i;
dma_addr_t address;
ssize_t offset;
for (i = 0; i < buffer->page_count; i++) {
address = page_private(buffer->pages[i]);
offset = (ssize_t)completed - (ssize_t)address;
if (offset > 0 && offset <= PAGE_SIZE)
return (i << PAGE_SHIFT) + offset;
}
return 0;
}
struct fw_iso_context *fw_iso_context_create(struct fw_card *card,
int type, int channel, int speed, size_t header_size,
fw_iso_callback_t callback, void *callback_data)
{
struct fw_iso_context *ctx;
ctx = card->driver->allocate_iso_context(card,
type, channel, header_size);
if (IS_ERR(ctx))
return ctx;
ctx->card = card;
ctx->type = type;
ctx->channel = channel;
ctx->speed = speed;
ctx->header_size = header_size;
ctx->callback.sc = callback;
ctx->callback_data = callback_data;
return ctx;
}
EXPORT_SYMBOL(fw_iso_context_create);
void fw_iso_context_destroy(struct fw_iso_context *ctx)
{
ctx->card->driver->free_iso_context(ctx);
}
EXPORT_SYMBOL(fw_iso_context_destroy);
int fw_iso_context_start(struct fw_iso_context *ctx,
int cycle, int sync, int tags)
{
return ctx->card->driver->start_iso(ctx, cycle, sync, tags);
}
EXPORT_SYMBOL(fw_iso_context_start);
int fw_iso_context_set_channels(struct fw_iso_context *ctx, u64 *channels)
{
return ctx->card->driver->set_iso_channels(ctx, channels);
}
int fw_iso_context_queue(struct fw_iso_context *ctx,
struct fw_iso_packet *packet,
struct fw_iso_buffer *buffer,
unsigned long payload)
{
return ctx->card->driver->queue_iso(ctx, packet, buffer, payload);
}
EXPORT_SYMBOL(fw_iso_context_queue);
void fw_iso_context_queue_flush(struct fw_iso_context *ctx)
{
ctx->card->driver->flush_queue_iso(ctx);
}
EXPORT_SYMBOL(fw_iso_context_queue_flush);
int fw_iso_context_stop(struct fw_iso_context *ctx)
{
return ctx->card->driver->stop_iso(ctx);
}
EXPORT_SYMBOL(fw_iso_context_stop);
/*
* Isochronous bus resource management (channels, bandwidth), client side
*/
static int manage_bandwidth(struct fw_card *card, int irm_id, int generation,
int bandwidth, bool allocate)
{
int try, new, old = allocate ? BANDWIDTH_AVAILABLE_INITIAL : 0;
__be32 data[2];
/*
* On a 1394a IRM with low contention, try < 1 is enough.
* On a 1394-1995 IRM, we need at least try < 2.
* Let's just do try < 5.
*/
for (try = 0; try < 5; try++) {
new = allocate ? old - bandwidth : old + bandwidth;
if (new < 0 || new > BANDWIDTH_AVAILABLE_INITIAL)
return -EBUSY;
data[0] = cpu_to_be32(old);
data[1] = cpu_to_be32(new);
switch (fw_run_transaction(card, TCODE_LOCK_COMPARE_SWAP,
irm_id, generation, SCODE_100,
CSR_REGISTER_BASE + CSR_BANDWIDTH_AVAILABLE,
data, 8)) {
case RCODE_GENERATION:
/* A generation change frees all bandwidth. */
return allocate ? -EAGAIN : bandwidth;
case RCODE_COMPLETE:
if (be32_to_cpup(data) == old)
return bandwidth;
old = be32_to_cpup(data);
/* Fall through. */
}
}
return -EIO;
}
static int manage_channel(struct fw_card *card, int irm_id, int generation,
u32 channels_mask, u64 offset, bool allocate)
{
__be32 bit, all, old;
__be32 data[2];
int channel, ret = -EIO, retry = 5;
old = all = allocate ? cpu_to_be32(~0) : 0;
for (channel = 0; channel < 32; channel++) {
if (!(channels_mask & 1 << channel))
continue;
ret = -EBUSY;
bit = cpu_to_be32(1 << (31 - channel));
if ((old & bit) != (all & bit))
continue;
data[0] = old;
data[1] = old ^ bit;
switch (fw_run_transaction(card, TCODE_LOCK_COMPARE_SWAP,
irm_id, generation, SCODE_100,
offset, data, 8)) {
case RCODE_GENERATION:
/* A generation change frees all channels. */
return allocate ? -EAGAIN : channel;
case RCODE_COMPLETE:
if (data[0] == old)
return channel;
old = data[0];
/* Is the IRM 1394a-2000 compliant? */
if ((data[0] & bit) == (data[1] & bit))
continue;
/* 1394-1995 IRM, fall through to retry. */
default:
if (retry) {
retry--;
channel--;
} else {
ret = -EIO;
}
}
}
return ret;
}
static void deallocate_channel(struct fw_card *card, int irm_id,
int generation, int channel)
{
u32 mask;
u64 offset;
mask = channel < 32 ? 1 << channel : 1 << (channel - 32);
offset = channel < 32 ? CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_HI :
CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_LO;
manage_channel(card, irm_id, generation, mask, offset, false);
}
/**
* fw_iso_resource_manage() - Allocate or deallocate a channel and/or bandwidth
*
* In parameters: card, generation, channels_mask, bandwidth, allocate
* Out parameters: channel, bandwidth
* This function blocks (sleeps) during communication with the IRM.
*
* Allocates or deallocates at most one channel out of channels_mask.
* channels_mask is a bitfield with MSB for channel 63 and LSB for channel 0.
* (Note, the IRM's CHANNELS_AVAILABLE is a big-endian bitfield with MSB for
* channel 0 and LSB for channel 63.)
* Allocates or deallocates as many bandwidth allocation units as specified.
*
* Returns channel < 0 if no channel was allocated or deallocated.
* Returns bandwidth = 0 if no bandwidth was allocated or deallocated.
*
* If generation is stale, deallocations succeed but allocations fail with
* channel = -EAGAIN.
*
* If channel allocation fails, no bandwidth will be allocated either.
* If bandwidth allocation fails, no channel will be allocated either.
* But deallocations of channel and bandwidth are tried independently
* of each other's success.
*/
void fw_iso_resource_manage(struct fw_card *card, int generation,
u64 channels_mask, int *channel, int *bandwidth,
bool allocate)
{
u32 channels_hi = channels_mask; /* channels 31...0 */
u32 channels_lo = channels_mask >> 32; /* channels 63...32 */
int irm_id, ret, c = -EINVAL;
spin_lock_irq(&card->lock);
irm_id = card->irm_node->node_id;
spin_unlock_irq(&card->lock);
if (channels_hi)
c = manage_channel(card, irm_id, generation, channels_hi,
CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_HI,
allocate);
if (channels_lo && c < 0) {
c = manage_channel(card, irm_id, generation, channels_lo,
CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_LO,
allocate);
if (c >= 0)
c += 32;
}
*channel = c;
if (allocate && channels_mask != 0 && c < 0)
*bandwidth = 0;
if (*bandwidth == 0)
return;
ret = manage_bandwidth(card, irm_id, generation, *bandwidth, allocate);
if (ret < 0)
*bandwidth = 0;
if (allocate && ret < 0) {
if (c >= 0)
deallocate_channel(card, irm_id, generation, c);
*channel = ret;
}
}
EXPORT_SYMBOL(fw_iso_resource_manage);
| gpl-2.0 |
manfromnn/kernel-roamer2 | drivers/scsi/qla4xxx/ql4_attr.c | 2782 | 2026 | /*
* QLogic iSCSI HBA Driver
* Copyright (c) 2003-2011 QLogic Corporation
*
* See LICENSE.qla4xxx for copyright and licensing details.
*/
#include "ql4_def.h"
#include "ql4_glbl.h"
#include "ql4_dbg.h"
/* Scsi_Host attributes. */
static ssize_t
qla4xxx_fw_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct scsi_qla_host *ha = to_qla_host(class_to_shost(dev));
if (is_qla8022(ha))
return snprintf(buf, PAGE_SIZE, "%d.%02d.%02d (%x)\n",
ha->firmware_version[0],
ha->firmware_version[1],
ha->patch_number, ha->build_number);
else
return snprintf(buf, PAGE_SIZE, "%d.%02d.%02d.%02d\n",
ha->firmware_version[0],
ha->firmware_version[1],
ha->patch_number, ha->build_number);
}
static ssize_t
qla4xxx_serial_num_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct scsi_qla_host *ha = to_qla_host(class_to_shost(dev));
return snprintf(buf, PAGE_SIZE, "%s\n", ha->serial_number);
}
static ssize_t
qla4xxx_iscsi_version_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct scsi_qla_host *ha = to_qla_host(class_to_shost(dev));
return snprintf(buf, PAGE_SIZE, "%d.%02d\n", ha->iscsi_major,
ha->iscsi_minor);
}
static ssize_t
qla4xxx_optrom_version_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct scsi_qla_host *ha = to_qla_host(class_to_shost(dev));
return snprintf(buf, PAGE_SIZE, "%d.%02d.%02d.%02d\n",
ha->bootload_major, ha->bootload_minor,
ha->bootload_patch, ha->bootload_build);
}
static DEVICE_ATTR(fw_version, S_IRUGO, qla4xxx_fw_version_show, NULL);
static DEVICE_ATTR(serial_num, S_IRUGO, qla4xxx_serial_num_show, NULL);
static DEVICE_ATTR(iscsi_version, S_IRUGO, qla4xxx_iscsi_version_show, NULL);
static DEVICE_ATTR(optrom_version, S_IRUGO, qla4xxx_optrom_version_show, NULL);
struct device_attribute *qla4xxx_host_attrs[] = {
&dev_attr_fw_version,
&dev_attr_serial_num,
&dev_attr_iscsi_version,
&dev_attr_optrom_version,
NULL,
};
| gpl-2.0 |
AICP/kernel_samsung_tuna | drivers/infiniband/core/ucma.c | 2782 | 32830 | /*
* Copyright (c) 2005-2006 Intel Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/completion.h>
#include <linux/file.h>
#include <linux/mutex.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/idr.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/miscdevice.h>
#include <linux/slab.h>
#include <linux/sysctl.h>
#include <rdma/rdma_user_cm.h>
#include <rdma/ib_marshall.h>
#include <rdma/rdma_cm.h>
#include <rdma/rdma_cm_ib.h>
MODULE_AUTHOR("Sean Hefty");
MODULE_DESCRIPTION("RDMA Userspace Connection Manager Access");
MODULE_LICENSE("Dual BSD/GPL");
static unsigned int max_backlog = 1024;
static struct ctl_table_header *ucma_ctl_table_hdr;
static ctl_table ucma_ctl_table[] = {
{
.procname = "max_backlog",
.data = &max_backlog,
.maxlen = sizeof max_backlog,
.mode = 0644,
.proc_handler = proc_dointvec,
},
{ }
};
static struct ctl_path ucma_ctl_path[] = {
{ .procname = "net" },
{ .procname = "rdma_ucm" },
{ }
};
struct ucma_file {
struct mutex mut;
struct file *filp;
struct list_head ctx_list;
struct list_head event_list;
wait_queue_head_t poll_wait;
};
struct ucma_context {
int id;
struct completion comp;
atomic_t ref;
int events_reported;
int backlog;
struct ucma_file *file;
struct rdma_cm_id *cm_id;
u64 uid;
struct list_head list;
struct list_head mc_list;
};
struct ucma_multicast {
struct ucma_context *ctx;
int id;
int events_reported;
u64 uid;
struct list_head list;
struct sockaddr_storage addr;
};
struct ucma_event {
struct ucma_context *ctx;
struct ucma_multicast *mc;
struct list_head list;
struct rdma_cm_id *cm_id;
struct rdma_ucm_event_resp resp;
};
static DEFINE_MUTEX(mut);
static DEFINE_IDR(ctx_idr);
static DEFINE_IDR(multicast_idr);
static inline struct ucma_context *_ucma_find_context(int id,
struct ucma_file *file)
{
struct ucma_context *ctx;
ctx = idr_find(&ctx_idr, id);
if (!ctx)
ctx = ERR_PTR(-ENOENT);
else if (ctx->file != file)
ctx = ERR_PTR(-EINVAL);
return ctx;
}
static struct ucma_context *ucma_get_ctx(struct ucma_file *file, int id)
{
struct ucma_context *ctx;
mutex_lock(&mut);
ctx = _ucma_find_context(id, file);
if (!IS_ERR(ctx))
atomic_inc(&ctx->ref);
mutex_unlock(&mut);
return ctx;
}
static void ucma_put_ctx(struct ucma_context *ctx)
{
if (atomic_dec_and_test(&ctx->ref))
complete(&ctx->comp);
}
static struct ucma_context *ucma_alloc_ctx(struct ucma_file *file)
{
struct ucma_context *ctx;
int ret;
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return NULL;
atomic_set(&ctx->ref, 1);
init_completion(&ctx->comp);
INIT_LIST_HEAD(&ctx->mc_list);
ctx->file = file;
do {
ret = idr_pre_get(&ctx_idr, GFP_KERNEL);
if (!ret)
goto error;
mutex_lock(&mut);
ret = idr_get_new(&ctx_idr, ctx, &ctx->id);
mutex_unlock(&mut);
} while (ret == -EAGAIN);
if (ret)
goto error;
list_add_tail(&ctx->list, &file->ctx_list);
return ctx;
error:
kfree(ctx);
return NULL;
}
static struct ucma_multicast* ucma_alloc_multicast(struct ucma_context *ctx)
{
struct ucma_multicast *mc;
int ret;
mc = kzalloc(sizeof(*mc), GFP_KERNEL);
if (!mc)
return NULL;
do {
ret = idr_pre_get(&multicast_idr, GFP_KERNEL);
if (!ret)
goto error;
mutex_lock(&mut);
ret = idr_get_new(&multicast_idr, mc, &mc->id);
mutex_unlock(&mut);
} while (ret == -EAGAIN);
if (ret)
goto error;
mc->ctx = ctx;
list_add_tail(&mc->list, &ctx->mc_list);
return mc;
error:
kfree(mc);
return NULL;
}
static void ucma_copy_conn_event(struct rdma_ucm_conn_param *dst,
struct rdma_conn_param *src)
{
if (src->private_data_len)
memcpy(dst->private_data, src->private_data,
src->private_data_len);
dst->private_data_len = src->private_data_len;
dst->responder_resources =src->responder_resources;
dst->initiator_depth = src->initiator_depth;
dst->flow_control = src->flow_control;
dst->retry_count = src->retry_count;
dst->rnr_retry_count = src->rnr_retry_count;
dst->srq = src->srq;
dst->qp_num = src->qp_num;
}
static void ucma_copy_ud_event(struct rdma_ucm_ud_param *dst,
struct rdma_ud_param *src)
{
if (src->private_data_len)
memcpy(dst->private_data, src->private_data,
src->private_data_len);
dst->private_data_len = src->private_data_len;
ib_copy_ah_attr_to_user(&dst->ah_attr, &src->ah_attr);
dst->qp_num = src->qp_num;
dst->qkey = src->qkey;
}
static void ucma_set_event_context(struct ucma_context *ctx,
struct rdma_cm_event *event,
struct ucma_event *uevent)
{
uevent->ctx = ctx;
switch (event->event) {
case RDMA_CM_EVENT_MULTICAST_JOIN:
case RDMA_CM_EVENT_MULTICAST_ERROR:
uevent->mc = (struct ucma_multicast *)
event->param.ud.private_data;
uevent->resp.uid = uevent->mc->uid;
uevent->resp.id = uevent->mc->id;
break;
default:
uevent->resp.uid = ctx->uid;
uevent->resp.id = ctx->id;
break;
}
}
static int ucma_event_handler(struct rdma_cm_id *cm_id,
struct rdma_cm_event *event)
{
struct ucma_event *uevent;
struct ucma_context *ctx = cm_id->context;
int ret = 0;
uevent = kzalloc(sizeof(*uevent), GFP_KERNEL);
if (!uevent)
return event->event == RDMA_CM_EVENT_CONNECT_REQUEST;
uevent->cm_id = cm_id;
ucma_set_event_context(ctx, event, uevent);
uevent->resp.event = event->event;
uevent->resp.status = event->status;
if (cm_id->ps == RDMA_PS_UDP || cm_id->ps == RDMA_PS_IPOIB)
ucma_copy_ud_event(&uevent->resp.param.ud, &event->param.ud);
else
ucma_copy_conn_event(&uevent->resp.param.conn,
&event->param.conn);
mutex_lock(&ctx->file->mut);
if (event->event == RDMA_CM_EVENT_CONNECT_REQUEST) {
if (!ctx->backlog) {
ret = -ENOMEM;
kfree(uevent);
goto out;
}
ctx->backlog--;
} else if (!ctx->uid) {
/*
* We ignore events for new connections until userspace has set
* their context. This can only happen if an error occurs on a
* new connection before the user accepts it. This is okay,
* since the accept will just fail later.
*/
kfree(uevent);
goto out;
}
list_add_tail(&uevent->list, &ctx->file->event_list);
wake_up_interruptible(&ctx->file->poll_wait);
out:
mutex_unlock(&ctx->file->mut);
return ret;
}
static ssize_t ucma_get_event(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct ucma_context *ctx;
struct rdma_ucm_get_event cmd;
struct ucma_event *uevent;
int ret = 0;
DEFINE_WAIT(wait);
if (out_len < sizeof uevent->resp)
return -ENOSPC;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
mutex_lock(&file->mut);
while (list_empty(&file->event_list)) {
mutex_unlock(&file->mut);
if (file->filp->f_flags & O_NONBLOCK)
return -EAGAIN;
if (wait_event_interruptible(file->poll_wait,
!list_empty(&file->event_list)))
return -ERESTARTSYS;
mutex_lock(&file->mut);
}
uevent = list_entry(file->event_list.next, struct ucma_event, list);
if (uevent->resp.event == RDMA_CM_EVENT_CONNECT_REQUEST) {
ctx = ucma_alloc_ctx(file);
if (!ctx) {
ret = -ENOMEM;
goto done;
}
uevent->ctx->backlog++;
ctx->cm_id = uevent->cm_id;
ctx->cm_id->context = ctx;
uevent->resp.id = ctx->id;
}
if (copy_to_user((void __user *)(unsigned long)cmd.response,
&uevent->resp, sizeof uevent->resp)) {
ret = -EFAULT;
goto done;
}
list_del(&uevent->list);
uevent->ctx->events_reported++;
if (uevent->mc)
uevent->mc->events_reported++;
kfree(uevent);
done:
mutex_unlock(&file->mut);
return ret;
}
static int ucma_get_qp_type(struct rdma_ucm_create_id *cmd, enum ib_qp_type *qp_type)
{
switch (cmd->ps) {
case RDMA_PS_TCP:
*qp_type = IB_QPT_RC;
return 0;
case RDMA_PS_UDP:
case RDMA_PS_IPOIB:
*qp_type = IB_QPT_UD;
return 0;
default:
return -EINVAL;
}
}
static ssize_t ucma_create_id(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_create_id cmd;
struct rdma_ucm_create_id_resp resp;
struct ucma_context *ctx;
enum ib_qp_type qp_type;
int ret;
if (out_len < sizeof(resp))
return -ENOSPC;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ret = ucma_get_qp_type(&cmd, &qp_type);
if (ret)
return ret;
mutex_lock(&file->mut);
ctx = ucma_alloc_ctx(file);
mutex_unlock(&file->mut);
if (!ctx)
return -ENOMEM;
ctx->uid = cmd.uid;
ctx->cm_id = rdma_create_id(ucma_event_handler, ctx, cmd.ps, qp_type);
if (IS_ERR(ctx->cm_id)) {
ret = PTR_ERR(ctx->cm_id);
goto err1;
}
resp.id = ctx->id;
if (copy_to_user((void __user *)(unsigned long)cmd.response,
&resp, sizeof(resp))) {
ret = -EFAULT;
goto err2;
}
return 0;
err2:
rdma_destroy_id(ctx->cm_id);
err1:
mutex_lock(&mut);
idr_remove(&ctx_idr, ctx->id);
mutex_unlock(&mut);
kfree(ctx);
return ret;
}
static void ucma_cleanup_multicast(struct ucma_context *ctx)
{
struct ucma_multicast *mc, *tmp;
mutex_lock(&mut);
list_for_each_entry_safe(mc, tmp, &ctx->mc_list, list) {
list_del(&mc->list);
idr_remove(&multicast_idr, mc->id);
kfree(mc);
}
mutex_unlock(&mut);
}
static void ucma_cleanup_events(struct ucma_context *ctx)
{
struct ucma_event *uevent, *tmp;
list_for_each_entry_safe(uevent, tmp, &ctx->file->event_list, list) {
if (uevent->ctx != ctx)
continue;
list_del(&uevent->list);
/* clear incoming connections. */
if (uevent->resp.event == RDMA_CM_EVENT_CONNECT_REQUEST)
rdma_destroy_id(uevent->cm_id);
kfree(uevent);
}
}
static void ucma_cleanup_mc_events(struct ucma_multicast *mc)
{
struct ucma_event *uevent, *tmp;
list_for_each_entry_safe(uevent, tmp, &mc->ctx->file->event_list, list) {
if (uevent->mc != mc)
continue;
list_del(&uevent->list);
kfree(uevent);
}
}
static int ucma_free_ctx(struct ucma_context *ctx)
{
int events_reported;
/* No new events will be generated after destroying the id. */
rdma_destroy_id(ctx->cm_id);
ucma_cleanup_multicast(ctx);
/* Cleanup events not yet reported to the user. */
mutex_lock(&ctx->file->mut);
ucma_cleanup_events(ctx);
list_del(&ctx->list);
mutex_unlock(&ctx->file->mut);
events_reported = ctx->events_reported;
kfree(ctx);
return events_reported;
}
static ssize_t ucma_destroy_id(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_destroy_id cmd;
struct rdma_ucm_destroy_id_resp resp;
struct ucma_context *ctx;
int ret = 0;
if (out_len < sizeof(resp))
return -ENOSPC;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
mutex_lock(&mut);
ctx = _ucma_find_context(cmd.id, file);
if (!IS_ERR(ctx))
idr_remove(&ctx_idr, ctx->id);
mutex_unlock(&mut);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ucma_put_ctx(ctx);
wait_for_completion(&ctx->comp);
resp.events_reported = ucma_free_ctx(ctx);
if (copy_to_user((void __user *)(unsigned long)cmd.response,
&resp, sizeof(resp)))
ret = -EFAULT;
return ret;
}
static ssize_t ucma_bind_addr(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_bind_addr cmd;
struct ucma_context *ctx;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ret = rdma_bind_addr(ctx->cm_id, (struct sockaddr *) &cmd.addr);
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_resolve_addr(struct ucma_file *file,
const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_resolve_addr cmd;
struct ucma_context *ctx;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ret = rdma_resolve_addr(ctx->cm_id, (struct sockaddr *) &cmd.src_addr,
(struct sockaddr *) &cmd.dst_addr,
cmd.timeout_ms);
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_resolve_route(struct ucma_file *file,
const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_resolve_route cmd;
struct ucma_context *ctx;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ret = rdma_resolve_route(ctx->cm_id, cmd.timeout_ms);
ucma_put_ctx(ctx);
return ret;
}
static void ucma_copy_ib_route(struct rdma_ucm_query_route_resp *resp,
struct rdma_route *route)
{
struct rdma_dev_addr *dev_addr;
resp->num_paths = route->num_paths;
switch (route->num_paths) {
case 0:
dev_addr = &route->addr.dev_addr;
rdma_addr_get_dgid(dev_addr,
(union ib_gid *) &resp->ib_route[0].dgid);
rdma_addr_get_sgid(dev_addr,
(union ib_gid *) &resp->ib_route[0].sgid);
resp->ib_route[0].pkey = cpu_to_be16(ib_addr_get_pkey(dev_addr));
break;
case 2:
ib_copy_path_rec_to_user(&resp->ib_route[1],
&route->path_rec[1]);
/* fall through */
case 1:
ib_copy_path_rec_to_user(&resp->ib_route[0],
&route->path_rec[0]);
break;
default:
break;
}
}
static void ucma_copy_iboe_route(struct rdma_ucm_query_route_resp *resp,
struct rdma_route *route)
{
struct rdma_dev_addr *dev_addr;
struct net_device *dev;
u16 vid = 0;
resp->num_paths = route->num_paths;
switch (route->num_paths) {
case 0:
dev_addr = &route->addr.dev_addr;
dev = dev_get_by_index(&init_net, dev_addr->bound_dev_if);
if (dev) {
vid = rdma_vlan_dev_vlan_id(dev);
dev_put(dev);
}
iboe_mac_vlan_to_ll((union ib_gid *) &resp->ib_route[0].dgid,
dev_addr->dst_dev_addr, vid);
iboe_addr_get_sgid(dev_addr,
(union ib_gid *) &resp->ib_route[0].sgid);
resp->ib_route[0].pkey = cpu_to_be16(0xffff);
break;
case 2:
ib_copy_path_rec_to_user(&resp->ib_route[1],
&route->path_rec[1]);
/* fall through */
case 1:
ib_copy_path_rec_to_user(&resp->ib_route[0],
&route->path_rec[0]);
break;
default:
break;
}
}
static void ucma_copy_iw_route(struct rdma_ucm_query_route_resp *resp,
struct rdma_route *route)
{
struct rdma_dev_addr *dev_addr;
dev_addr = &route->addr.dev_addr;
rdma_addr_get_dgid(dev_addr, (union ib_gid *) &resp->ib_route[0].dgid);
rdma_addr_get_sgid(dev_addr, (union ib_gid *) &resp->ib_route[0].sgid);
}
static ssize_t ucma_query_route(struct ucma_file *file,
const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_query_route cmd;
struct rdma_ucm_query_route_resp resp;
struct ucma_context *ctx;
struct sockaddr *addr;
int ret = 0;
if (out_len < sizeof(resp))
return -ENOSPC;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
memset(&resp, 0, sizeof resp);
addr = (struct sockaddr *) &ctx->cm_id->route.addr.src_addr;
memcpy(&resp.src_addr, addr, addr->sa_family == AF_INET ?
sizeof(struct sockaddr_in) :
sizeof(struct sockaddr_in6));
addr = (struct sockaddr *) &ctx->cm_id->route.addr.dst_addr;
memcpy(&resp.dst_addr, addr, addr->sa_family == AF_INET ?
sizeof(struct sockaddr_in) :
sizeof(struct sockaddr_in6));
if (!ctx->cm_id->device)
goto out;
resp.node_guid = (__force __u64) ctx->cm_id->device->node_guid;
resp.port_num = ctx->cm_id->port_num;
switch (rdma_node_get_transport(ctx->cm_id->device->node_type)) {
case RDMA_TRANSPORT_IB:
switch (rdma_port_get_link_layer(ctx->cm_id->device,
ctx->cm_id->port_num)) {
case IB_LINK_LAYER_INFINIBAND:
ucma_copy_ib_route(&resp, &ctx->cm_id->route);
break;
case IB_LINK_LAYER_ETHERNET:
ucma_copy_iboe_route(&resp, &ctx->cm_id->route);
break;
default:
break;
}
break;
case RDMA_TRANSPORT_IWARP:
ucma_copy_iw_route(&resp, &ctx->cm_id->route);
break;
default:
break;
}
out:
if (copy_to_user((void __user *)(unsigned long)cmd.response,
&resp, sizeof(resp)))
ret = -EFAULT;
ucma_put_ctx(ctx);
return ret;
}
static void ucma_copy_conn_param(struct rdma_conn_param *dst,
struct rdma_ucm_conn_param *src)
{
dst->private_data = src->private_data;
dst->private_data_len = src->private_data_len;
dst->responder_resources =src->responder_resources;
dst->initiator_depth = src->initiator_depth;
dst->flow_control = src->flow_control;
dst->retry_count = src->retry_count;
dst->rnr_retry_count = src->rnr_retry_count;
dst->srq = src->srq;
dst->qp_num = src->qp_num;
}
static ssize_t ucma_connect(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_connect cmd;
struct rdma_conn_param conn_param;
struct ucma_context *ctx;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
if (!cmd.conn_param.valid)
return -EINVAL;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ucma_copy_conn_param(&conn_param, &cmd.conn_param);
ret = rdma_connect(ctx->cm_id, &conn_param);
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_listen(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_listen cmd;
struct ucma_context *ctx;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ctx->backlog = cmd.backlog > 0 && cmd.backlog < max_backlog ?
cmd.backlog : max_backlog;
ret = rdma_listen(ctx->cm_id, ctx->backlog);
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_accept(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_accept cmd;
struct rdma_conn_param conn_param;
struct ucma_context *ctx;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
if (cmd.conn_param.valid) {
ctx->uid = cmd.uid;
ucma_copy_conn_param(&conn_param, &cmd.conn_param);
ret = rdma_accept(ctx->cm_id, &conn_param);
} else
ret = rdma_accept(ctx->cm_id, NULL);
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_reject(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_reject cmd;
struct ucma_context *ctx;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ret = rdma_reject(ctx->cm_id, cmd.private_data, cmd.private_data_len);
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_disconnect(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_disconnect cmd;
struct ucma_context *ctx;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ret = rdma_disconnect(ctx->cm_id);
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_init_qp_attr(struct ucma_file *file,
const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_init_qp_attr cmd;
struct ib_uverbs_qp_attr resp;
struct ucma_context *ctx;
struct ib_qp_attr qp_attr;
int ret;
if (out_len < sizeof(resp))
return -ENOSPC;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
resp.qp_attr_mask = 0;
memset(&qp_attr, 0, sizeof qp_attr);
qp_attr.qp_state = cmd.qp_state;
ret = rdma_init_qp_attr(ctx->cm_id, &qp_attr, &resp.qp_attr_mask);
if (ret)
goto out;
ib_copy_qp_attr_to_user(&resp, &qp_attr);
if (copy_to_user((void __user *)(unsigned long)cmd.response,
&resp, sizeof(resp)))
ret = -EFAULT;
out:
ucma_put_ctx(ctx);
return ret;
}
static int ucma_set_option_id(struct ucma_context *ctx, int optname,
void *optval, size_t optlen)
{
int ret = 0;
switch (optname) {
case RDMA_OPTION_ID_TOS:
if (optlen != sizeof(u8)) {
ret = -EINVAL;
break;
}
rdma_set_service_type(ctx->cm_id, *((u8 *) optval));
break;
case RDMA_OPTION_ID_REUSEADDR:
if (optlen != sizeof(int)) {
ret = -EINVAL;
break;
}
ret = rdma_set_reuseaddr(ctx->cm_id, *((int *) optval) ? 1 : 0);
break;
default:
ret = -ENOSYS;
}
return ret;
}
static int ucma_set_ib_path(struct ucma_context *ctx,
struct ib_path_rec_data *path_data, size_t optlen)
{
struct ib_sa_path_rec sa_path;
struct rdma_cm_event event;
int ret;
if (optlen % sizeof(*path_data))
return -EINVAL;
for (; optlen; optlen -= sizeof(*path_data), path_data++) {
if (path_data->flags == (IB_PATH_GMP | IB_PATH_PRIMARY |
IB_PATH_BIDIRECTIONAL))
break;
}
if (!optlen)
return -EINVAL;
ib_sa_unpack_path(path_data->path_rec, &sa_path);
ret = rdma_set_ib_paths(ctx->cm_id, &sa_path, 1);
if (ret)
return ret;
memset(&event, 0, sizeof event);
event.event = RDMA_CM_EVENT_ROUTE_RESOLVED;
return ucma_event_handler(ctx->cm_id, &event);
}
static int ucma_set_option_ib(struct ucma_context *ctx, int optname,
void *optval, size_t optlen)
{
int ret;
switch (optname) {
case RDMA_OPTION_IB_PATH:
ret = ucma_set_ib_path(ctx, optval, optlen);
break;
default:
ret = -ENOSYS;
}
return ret;
}
static int ucma_set_option_level(struct ucma_context *ctx, int level,
int optname, void *optval, size_t optlen)
{
int ret;
switch (level) {
case RDMA_OPTION_ID:
ret = ucma_set_option_id(ctx, optname, optval, optlen);
break;
case RDMA_OPTION_IB:
ret = ucma_set_option_ib(ctx, optname, optval, optlen);
break;
default:
ret = -ENOSYS;
}
return ret;
}
static ssize_t ucma_set_option(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_set_option cmd;
struct ucma_context *ctx;
void *optval;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
optval = kmalloc(cmd.optlen, GFP_KERNEL);
if (!optval) {
ret = -ENOMEM;
goto out1;
}
if (copy_from_user(optval, (void __user *) (unsigned long) cmd.optval,
cmd.optlen)) {
ret = -EFAULT;
goto out2;
}
ret = ucma_set_option_level(ctx, cmd.level, cmd.optname, optval,
cmd.optlen);
out2:
kfree(optval);
out1:
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_notify(struct ucma_file *file, const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_notify cmd;
struct ucma_context *ctx;
int ret;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
ret = rdma_notify(ctx->cm_id, (enum ib_event_type) cmd.event);
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_join_multicast(struct ucma_file *file,
const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_join_mcast cmd;
struct rdma_ucm_create_id_resp resp;
struct ucma_context *ctx;
struct ucma_multicast *mc;
int ret;
if (out_len < sizeof(resp))
return -ENOSPC;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
ctx = ucma_get_ctx(file, cmd.id);
if (IS_ERR(ctx))
return PTR_ERR(ctx);
mutex_lock(&file->mut);
mc = ucma_alloc_multicast(ctx);
if (!mc) {
ret = -ENOMEM;
goto err1;
}
mc->uid = cmd.uid;
memcpy(&mc->addr, &cmd.addr, sizeof cmd.addr);
ret = rdma_join_multicast(ctx->cm_id, (struct sockaddr *) &mc->addr, mc);
if (ret)
goto err2;
resp.id = mc->id;
if (copy_to_user((void __user *)(unsigned long)cmd.response,
&resp, sizeof(resp))) {
ret = -EFAULT;
goto err3;
}
mutex_unlock(&file->mut);
ucma_put_ctx(ctx);
return 0;
err3:
rdma_leave_multicast(ctx->cm_id, (struct sockaddr *) &mc->addr);
ucma_cleanup_mc_events(mc);
err2:
mutex_lock(&mut);
idr_remove(&multicast_idr, mc->id);
mutex_unlock(&mut);
list_del(&mc->list);
kfree(mc);
err1:
mutex_unlock(&file->mut);
ucma_put_ctx(ctx);
return ret;
}
static ssize_t ucma_leave_multicast(struct ucma_file *file,
const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_destroy_id cmd;
struct rdma_ucm_destroy_id_resp resp;
struct ucma_multicast *mc;
int ret = 0;
if (out_len < sizeof(resp))
return -ENOSPC;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
mutex_lock(&mut);
mc = idr_find(&multicast_idr, cmd.id);
if (!mc)
mc = ERR_PTR(-ENOENT);
else if (mc->ctx->file != file)
mc = ERR_PTR(-EINVAL);
else {
idr_remove(&multicast_idr, mc->id);
atomic_inc(&mc->ctx->ref);
}
mutex_unlock(&mut);
if (IS_ERR(mc)) {
ret = PTR_ERR(mc);
goto out;
}
rdma_leave_multicast(mc->ctx->cm_id, (struct sockaddr *) &mc->addr);
mutex_lock(&mc->ctx->file->mut);
ucma_cleanup_mc_events(mc);
list_del(&mc->list);
mutex_unlock(&mc->ctx->file->mut);
ucma_put_ctx(mc->ctx);
resp.events_reported = mc->events_reported;
kfree(mc);
if (copy_to_user((void __user *)(unsigned long)cmd.response,
&resp, sizeof(resp)))
ret = -EFAULT;
out:
return ret;
}
static void ucma_lock_files(struct ucma_file *file1, struct ucma_file *file2)
{
/* Acquire mutex's based on pointer comparison to prevent deadlock. */
if (file1 < file2) {
mutex_lock(&file1->mut);
mutex_lock(&file2->mut);
} else {
mutex_lock(&file2->mut);
mutex_lock(&file1->mut);
}
}
static void ucma_unlock_files(struct ucma_file *file1, struct ucma_file *file2)
{
if (file1 < file2) {
mutex_unlock(&file2->mut);
mutex_unlock(&file1->mut);
} else {
mutex_unlock(&file1->mut);
mutex_unlock(&file2->mut);
}
}
static void ucma_move_events(struct ucma_context *ctx, struct ucma_file *file)
{
struct ucma_event *uevent, *tmp;
list_for_each_entry_safe(uevent, tmp, &ctx->file->event_list, list)
if (uevent->ctx == ctx)
list_move_tail(&uevent->list, &file->event_list);
}
static ssize_t ucma_migrate_id(struct ucma_file *new_file,
const char __user *inbuf,
int in_len, int out_len)
{
struct rdma_ucm_migrate_id cmd;
struct rdma_ucm_migrate_resp resp;
struct ucma_context *ctx;
struct file *filp;
struct ucma_file *cur_file;
int ret = 0;
if (copy_from_user(&cmd, inbuf, sizeof(cmd)))
return -EFAULT;
/* Get current fd to protect against it being closed */
filp = fget(cmd.fd);
if (!filp)
return -ENOENT;
/* Validate current fd and prevent destruction of id. */
ctx = ucma_get_ctx(filp->private_data, cmd.id);
if (IS_ERR(ctx)) {
ret = PTR_ERR(ctx);
goto file_put;
}
cur_file = ctx->file;
if (cur_file == new_file) {
resp.events_reported = ctx->events_reported;
goto response;
}
/*
* Migrate events between fd's, maintaining order, and avoiding new
* events being added before existing events.
*/
ucma_lock_files(cur_file, new_file);
mutex_lock(&mut);
list_move_tail(&ctx->list, &new_file->ctx_list);
ucma_move_events(ctx, new_file);
ctx->file = new_file;
resp.events_reported = ctx->events_reported;
mutex_unlock(&mut);
ucma_unlock_files(cur_file, new_file);
response:
if (copy_to_user((void __user *)(unsigned long)cmd.response,
&resp, sizeof(resp)))
ret = -EFAULT;
ucma_put_ctx(ctx);
file_put:
fput(filp);
return ret;
}
static ssize_t (*ucma_cmd_table[])(struct ucma_file *file,
const char __user *inbuf,
int in_len, int out_len) = {
[RDMA_USER_CM_CMD_CREATE_ID] = ucma_create_id,
[RDMA_USER_CM_CMD_DESTROY_ID] = ucma_destroy_id,
[RDMA_USER_CM_CMD_BIND_ADDR] = ucma_bind_addr,
[RDMA_USER_CM_CMD_RESOLVE_ADDR] = ucma_resolve_addr,
[RDMA_USER_CM_CMD_RESOLVE_ROUTE]= ucma_resolve_route,
[RDMA_USER_CM_CMD_QUERY_ROUTE] = ucma_query_route,
[RDMA_USER_CM_CMD_CONNECT] = ucma_connect,
[RDMA_USER_CM_CMD_LISTEN] = ucma_listen,
[RDMA_USER_CM_CMD_ACCEPT] = ucma_accept,
[RDMA_USER_CM_CMD_REJECT] = ucma_reject,
[RDMA_USER_CM_CMD_DISCONNECT] = ucma_disconnect,
[RDMA_USER_CM_CMD_INIT_QP_ATTR] = ucma_init_qp_attr,
[RDMA_USER_CM_CMD_GET_EVENT] = ucma_get_event,
[RDMA_USER_CM_CMD_GET_OPTION] = NULL,
[RDMA_USER_CM_CMD_SET_OPTION] = ucma_set_option,
[RDMA_USER_CM_CMD_NOTIFY] = ucma_notify,
[RDMA_USER_CM_CMD_JOIN_MCAST] = ucma_join_multicast,
[RDMA_USER_CM_CMD_LEAVE_MCAST] = ucma_leave_multicast,
[RDMA_USER_CM_CMD_MIGRATE_ID] = ucma_migrate_id
};
static ssize_t ucma_write(struct file *filp, const char __user *buf,
size_t len, loff_t *pos)
{
struct ucma_file *file = filp->private_data;
struct rdma_ucm_cmd_hdr hdr;
ssize_t ret;
if (len < sizeof(hdr))
return -EINVAL;
if (copy_from_user(&hdr, buf, sizeof(hdr)))
return -EFAULT;
if (hdr.cmd < 0 || hdr.cmd >= ARRAY_SIZE(ucma_cmd_table))
return -EINVAL;
if (hdr.in + sizeof(hdr) > len)
return -EINVAL;
if (!ucma_cmd_table[hdr.cmd])
return -ENOSYS;
ret = ucma_cmd_table[hdr.cmd](file, buf + sizeof(hdr), hdr.in, hdr.out);
if (!ret)
ret = len;
return ret;
}
static unsigned int ucma_poll(struct file *filp, struct poll_table_struct *wait)
{
struct ucma_file *file = filp->private_data;
unsigned int mask = 0;
poll_wait(filp, &file->poll_wait, wait);
if (!list_empty(&file->event_list))
mask = POLLIN | POLLRDNORM;
return mask;
}
/*
* ucma_open() does not need the BKL:
*
* - no global state is referred to;
* - there is no ioctl method to race against;
* - no further module initialization is required for open to work
* after the device is registered.
*/
static int ucma_open(struct inode *inode, struct file *filp)
{
struct ucma_file *file;
file = kmalloc(sizeof *file, GFP_KERNEL);
if (!file)
return -ENOMEM;
INIT_LIST_HEAD(&file->event_list);
INIT_LIST_HEAD(&file->ctx_list);
init_waitqueue_head(&file->poll_wait);
mutex_init(&file->mut);
filp->private_data = file;
file->filp = filp;
return nonseekable_open(inode, filp);
}
static int ucma_close(struct inode *inode, struct file *filp)
{
struct ucma_file *file = filp->private_data;
struct ucma_context *ctx, *tmp;
mutex_lock(&file->mut);
list_for_each_entry_safe(ctx, tmp, &file->ctx_list, list) {
mutex_unlock(&file->mut);
mutex_lock(&mut);
idr_remove(&ctx_idr, ctx->id);
mutex_unlock(&mut);
ucma_free_ctx(ctx);
mutex_lock(&file->mut);
}
mutex_unlock(&file->mut);
kfree(file);
return 0;
}
static const struct file_operations ucma_fops = {
.owner = THIS_MODULE,
.open = ucma_open,
.release = ucma_close,
.write = ucma_write,
.poll = ucma_poll,
.llseek = no_llseek,
};
static struct miscdevice ucma_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "rdma_cm",
.nodename = "infiniband/rdma_cm",
.mode = 0666,
.fops = &ucma_fops,
};
static ssize_t show_abi_version(struct device *dev,
struct device_attribute *attr,
char *buf)
{
return sprintf(buf, "%d\n", RDMA_USER_CM_ABI_VERSION);
}
static DEVICE_ATTR(abi_version, S_IRUGO, show_abi_version, NULL);
static int __init ucma_init(void)
{
int ret;
ret = misc_register(&ucma_misc);
if (ret)
return ret;
ret = device_create_file(ucma_misc.this_device, &dev_attr_abi_version);
if (ret) {
printk(KERN_ERR "rdma_ucm: couldn't create abi_version attr\n");
goto err1;
}
ucma_ctl_table_hdr = register_sysctl_paths(ucma_ctl_path, ucma_ctl_table);
if (!ucma_ctl_table_hdr) {
printk(KERN_ERR "rdma_ucm: couldn't register sysctl paths\n");
ret = -ENOMEM;
goto err2;
}
return 0;
err2:
device_remove_file(ucma_misc.this_device, &dev_attr_abi_version);
err1:
misc_deregister(&ucma_misc);
return ret;
}
static void __exit ucma_cleanup(void)
{
unregister_sysctl_table(ucma_ctl_table_hdr);
device_remove_file(ucma_misc.this_device, &dev_attr_abi_version);
misc_deregister(&ucma_misc);
idr_destroy(&ctx_idr);
}
module_init(ucma_init);
module_exit(ucma_cleanup);
| gpl-2.0 |
Evervolv/android_kernel_htc_msm7x30-3.0 | drivers/firewire/core-iso.c | 2782 | 9843 | /*
* Isochronous I/O functionality:
* - Isochronous DMA context management
* - Isochronous bus resource management (channels, bandwidth), client side
*
* Copyright (C) 2006 Kristian Hoegsberg <krh@bitplanet.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 <linux/dma-mapping.h>
#include <linux/errno.h>
#include <linux/firewire.h>
#include <linux/firewire-constants.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/vmalloc.h>
#include <asm/byteorder.h>
#include "core.h"
/*
* Isochronous DMA context management
*/
int fw_iso_buffer_init(struct fw_iso_buffer *buffer, struct fw_card *card,
int page_count, enum dma_data_direction direction)
{
int i, j;
dma_addr_t address;
buffer->page_count = page_count;
buffer->direction = direction;
buffer->pages = kmalloc(page_count * sizeof(buffer->pages[0]),
GFP_KERNEL);
if (buffer->pages == NULL)
goto out;
for (i = 0; i < buffer->page_count; i++) {
buffer->pages[i] = alloc_page(GFP_KERNEL | GFP_DMA32 | __GFP_ZERO);
if (buffer->pages[i] == NULL)
goto out_pages;
address = dma_map_page(card->device, buffer->pages[i],
0, PAGE_SIZE, direction);
if (dma_mapping_error(card->device, address)) {
__free_page(buffer->pages[i]);
goto out_pages;
}
set_page_private(buffer->pages[i], address);
}
return 0;
out_pages:
for (j = 0; j < i; j++) {
address = page_private(buffer->pages[j]);
dma_unmap_page(card->device, address,
PAGE_SIZE, direction);
__free_page(buffer->pages[j]);
}
kfree(buffer->pages);
out:
buffer->pages = NULL;
return -ENOMEM;
}
EXPORT_SYMBOL(fw_iso_buffer_init);
int fw_iso_buffer_map(struct fw_iso_buffer *buffer, struct vm_area_struct *vma)
{
unsigned long uaddr;
int i, err;
uaddr = vma->vm_start;
for (i = 0; i < buffer->page_count; i++) {
err = vm_insert_page(vma, uaddr, buffer->pages[i]);
if (err)
return err;
uaddr += PAGE_SIZE;
}
return 0;
}
void fw_iso_buffer_destroy(struct fw_iso_buffer *buffer,
struct fw_card *card)
{
int i;
dma_addr_t address;
for (i = 0; i < buffer->page_count; i++) {
address = page_private(buffer->pages[i]);
dma_unmap_page(card->device, address,
PAGE_SIZE, buffer->direction);
__free_page(buffer->pages[i]);
}
kfree(buffer->pages);
buffer->pages = NULL;
}
EXPORT_SYMBOL(fw_iso_buffer_destroy);
/* Convert DMA address to offset into virtually contiguous buffer. */
size_t fw_iso_buffer_lookup(struct fw_iso_buffer *buffer, dma_addr_t completed)
{
int i;
dma_addr_t address;
ssize_t offset;
for (i = 0; i < buffer->page_count; i++) {
address = page_private(buffer->pages[i]);
offset = (ssize_t)completed - (ssize_t)address;
if (offset > 0 && offset <= PAGE_SIZE)
return (i << PAGE_SHIFT) + offset;
}
return 0;
}
struct fw_iso_context *fw_iso_context_create(struct fw_card *card,
int type, int channel, int speed, size_t header_size,
fw_iso_callback_t callback, void *callback_data)
{
struct fw_iso_context *ctx;
ctx = card->driver->allocate_iso_context(card,
type, channel, header_size);
if (IS_ERR(ctx))
return ctx;
ctx->card = card;
ctx->type = type;
ctx->channel = channel;
ctx->speed = speed;
ctx->header_size = header_size;
ctx->callback.sc = callback;
ctx->callback_data = callback_data;
return ctx;
}
EXPORT_SYMBOL(fw_iso_context_create);
void fw_iso_context_destroy(struct fw_iso_context *ctx)
{
ctx->card->driver->free_iso_context(ctx);
}
EXPORT_SYMBOL(fw_iso_context_destroy);
int fw_iso_context_start(struct fw_iso_context *ctx,
int cycle, int sync, int tags)
{
return ctx->card->driver->start_iso(ctx, cycle, sync, tags);
}
EXPORT_SYMBOL(fw_iso_context_start);
int fw_iso_context_set_channels(struct fw_iso_context *ctx, u64 *channels)
{
return ctx->card->driver->set_iso_channels(ctx, channels);
}
int fw_iso_context_queue(struct fw_iso_context *ctx,
struct fw_iso_packet *packet,
struct fw_iso_buffer *buffer,
unsigned long payload)
{
return ctx->card->driver->queue_iso(ctx, packet, buffer, payload);
}
EXPORT_SYMBOL(fw_iso_context_queue);
void fw_iso_context_queue_flush(struct fw_iso_context *ctx)
{
ctx->card->driver->flush_queue_iso(ctx);
}
EXPORT_SYMBOL(fw_iso_context_queue_flush);
int fw_iso_context_stop(struct fw_iso_context *ctx)
{
return ctx->card->driver->stop_iso(ctx);
}
EXPORT_SYMBOL(fw_iso_context_stop);
/*
* Isochronous bus resource management (channels, bandwidth), client side
*/
static int manage_bandwidth(struct fw_card *card, int irm_id, int generation,
int bandwidth, bool allocate)
{
int try, new, old = allocate ? BANDWIDTH_AVAILABLE_INITIAL : 0;
__be32 data[2];
/*
* On a 1394a IRM with low contention, try < 1 is enough.
* On a 1394-1995 IRM, we need at least try < 2.
* Let's just do try < 5.
*/
for (try = 0; try < 5; try++) {
new = allocate ? old - bandwidth : old + bandwidth;
if (new < 0 || new > BANDWIDTH_AVAILABLE_INITIAL)
return -EBUSY;
data[0] = cpu_to_be32(old);
data[1] = cpu_to_be32(new);
switch (fw_run_transaction(card, TCODE_LOCK_COMPARE_SWAP,
irm_id, generation, SCODE_100,
CSR_REGISTER_BASE + CSR_BANDWIDTH_AVAILABLE,
data, 8)) {
case RCODE_GENERATION:
/* A generation change frees all bandwidth. */
return allocate ? -EAGAIN : bandwidth;
case RCODE_COMPLETE:
if (be32_to_cpup(data) == old)
return bandwidth;
old = be32_to_cpup(data);
/* Fall through. */
}
}
return -EIO;
}
static int manage_channel(struct fw_card *card, int irm_id, int generation,
u32 channels_mask, u64 offset, bool allocate)
{
__be32 bit, all, old;
__be32 data[2];
int channel, ret = -EIO, retry = 5;
old = all = allocate ? cpu_to_be32(~0) : 0;
for (channel = 0; channel < 32; channel++) {
if (!(channels_mask & 1 << channel))
continue;
ret = -EBUSY;
bit = cpu_to_be32(1 << (31 - channel));
if ((old & bit) != (all & bit))
continue;
data[0] = old;
data[1] = old ^ bit;
switch (fw_run_transaction(card, TCODE_LOCK_COMPARE_SWAP,
irm_id, generation, SCODE_100,
offset, data, 8)) {
case RCODE_GENERATION:
/* A generation change frees all channels. */
return allocate ? -EAGAIN : channel;
case RCODE_COMPLETE:
if (data[0] == old)
return channel;
old = data[0];
/* Is the IRM 1394a-2000 compliant? */
if ((data[0] & bit) == (data[1] & bit))
continue;
/* 1394-1995 IRM, fall through to retry. */
default:
if (retry) {
retry--;
channel--;
} else {
ret = -EIO;
}
}
}
return ret;
}
static void deallocate_channel(struct fw_card *card, int irm_id,
int generation, int channel)
{
u32 mask;
u64 offset;
mask = channel < 32 ? 1 << channel : 1 << (channel - 32);
offset = channel < 32 ? CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_HI :
CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_LO;
manage_channel(card, irm_id, generation, mask, offset, false);
}
/**
* fw_iso_resource_manage() - Allocate or deallocate a channel and/or bandwidth
*
* In parameters: card, generation, channels_mask, bandwidth, allocate
* Out parameters: channel, bandwidth
* This function blocks (sleeps) during communication with the IRM.
*
* Allocates or deallocates at most one channel out of channels_mask.
* channels_mask is a bitfield with MSB for channel 63 and LSB for channel 0.
* (Note, the IRM's CHANNELS_AVAILABLE is a big-endian bitfield with MSB for
* channel 0 and LSB for channel 63.)
* Allocates or deallocates as many bandwidth allocation units as specified.
*
* Returns channel < 0 if no channel was allocated or deallocated.
* Returns bandwidth = 0 if no bandwidth was allocated or deallocated.
*
* If generation is stale, deallocations succeed but allocations fail with
* channel = -EAGAIN.
*
* If channel allocation fails, no bandwidth will be allocated either.
* If bandwidth allocation fails, no channel will be allocated either.
* But deallocations of channel and bandwidth are tried independently
* of each other's success.
*/
void fw_iso_resource_manage(struct fw_card *card, int generation,
u64 channels_mask, int *channel, int *bandwidth,
bool allocate)
{
u32 channels_hi = channels_mask; /* channels 31...0 */
u32 channels_lo = channels_mask >> 32; /* channels 63...32 */
int irm_id, ret, c = -EINVAL;
spin_lock_irq(&card->lock);
irm_id = card->irm_node->node_id;
spin_unlock_irq(&card->lock);
if (channels_hi)
c = manage_channel(card, irm_id, generation, channels_hi,
CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_HI,
allocate);
if (channels_lo && c < 0) {
c = manage_channel(card, irm_id, generation, channels_lo,
CSR_REGISTER_BASE + CSR_CHANNELS_AVAILABLE_LO,
allocate);
if (c >= 0)
c += 32;
}
*channel = c;
if (allocate && channels_mask != 0 && c < 0)
*bandwidth = 0;
if (*bandwidth == 0)
return;
ret = manage_bandwidth(card, irm_id, generation, *bandwidth, allocate);
if (ret < 0)
*bandwidth = 0;
if (allocate && ret < 0) {
if (c >= 0)
deallocate_channel(card, irm_id, generation, c);
*channel = ret;
}
}
EXPORT_SYMBOL(fw_iso_resource_manage);
| gpl-2.0 |
rutvik95/android_kernel_frostbite | drivers/net/wireless/orinoco/scan.c | 3038 | 5765 | /* Helpers for managing scan queues
*
* See copyright notice in main.c
*/
#include <linux/gfp.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/ieee80211.h>
#include <net/cfg80211.h>
#include "hermes.h"
#include "orinoco.h"
#include "main.h"
#include "scan.h"
#define ZERO_DBM_OFFSET 0x95
#define MAX_SIGNAL_LEVEL 0x8A
#define MIN_SIGNAL_LEVEL 0x2F
#define SIGNAL_TO_DBM(x) \
(clamp_t(s32, (x), MIN_SIGNAL_LEVEL, MAX_SIGNAL_LEVEL) \
- ZERO_DBM_OFFSET)
#define SIGNAL_TO_MBM(x) (SIGNAL_TO_DBM(x) * 100)
static int symbol_build_supp_rates(u8 *buf, const __le16 *rates)
{
int i;
u8 rate;
buf[0] = WLAN_EID_SUPP_RATES;
for (i = 0; i < 5; i++) {
rate = le16_to_cpu(rates[i]);
/* NULL terminated */
if (rate == 0x0)
break;
buf[i + 2] = rate;
}
buf[1] = i;
return i + 2;
}
static int prism_build_supp_rates(u8 *buf, const u8 *rates)
{
int i;
buf[0] = WLAN_EID_SUPP_RATES;
for (i = 0; i < 8; i++) {
/* NULL terminated */
if (rates[i] == 0x0)
break;
buf[i + 2] = rates[i];
}
buf[1] = i;
/* We might still have another 2 rates, which need to go in
* extended supported rates */
if (i == 8 && rates[i] > 0) {
buf[10] = WLAN_EID_EXT_SUPP_RATES;
for (; i < 10; i++) {
/* NULL terminated */
if (rates[i] == 0x0)
break;
buf[i + 2] = rates[i];
}
buf[11] = i - 8;
}
return (i < 8) ? i + 2 : i + 4;
}
static void orinoco_add_hostscan_result(struct orinoco_private *priv,
const union hermes_scan_info *bss)
{
struct wiphy *wiphy = priv_to_wiphy(priv);
struct ieee80211_channel *channel;
u8 *ie;
u8 ie_buf[46];
u64 timestamp;
s32 signal;
u16 capability;
u16 beacon_interval;
int ie_len;
int freq;
int len;
len = le16_to_cpu(bss->a.essid_len);
/* Reconstruct SSID and bitrate IEs to pass up */
ie_buf[0] = WLAN_EID_SSID;
ie_buf[1] = len;
memcpy(&ie_buf[2], bss->a.essid, len);
ie = ie_buf + len + 2;
ie_len = ie_buf[1] + 2;
switch (priv->firmware_type) {
case FIRMWARE_TYPE_SYMBOL:
ie_len += symbol_build_supp_rates(ie, bss->s.rates);
break;
case FIRMWARE_TYPE_INTERSIL:
ie_len += prism_build_supp_rates(ie, bss->p.rates);
break;
case FIRMWARE_TYPE_AGERE:
default:
break;
}
freq = ieee80211_dsss_chan_to_freq(le16_to_cpu(bss->a.channel));
channel = ieee80211_get_channel(wiphy, freq);
if (!channel) {
printk(KERN_DEBUG "Invalid channel designation %04X(%04X)",
bss->a.channel, freq);
return; /* Then ignore it for now */
}
timestamp = 0;
capability = le16_to_cpu(bss->a.capabilities);
beacon_interval = le16_to_cpu(bss->a.beacon_interv);
signal = SIGNAL_TO_MBM(le16_to_cpu(bss->a.level));
cfg80211_inform_bss(wiphy, channel, bss->a.bssid, timestamp,
capability, beacon_interval, ie_buf, ie_len,
signal, GFP_KERNEL);
}
void orinoco_add_extscan_result(struct orinoco_private *priv,
struct agere_ext_scan_info *bss,
size_t len)
{
struct wiphy *wiphy = priv_to_wiphy(priv);
struct ieee80211_channel *channel;
const u8 *ie;
u64 timestamp;
s32 signal;
u16 capability;
u16 beacon_interval;
size_t ie_len;
int chan, freq;
ie_len = len - sizeof(*bss);
ie = cfg80211_find_ie(WLAN_EID_DS_PARAMS, bss->data, ie_len);
chan = ie ? ie[2] : 0;
freq = ieee80211_dsss_chan_to_freq(chan);
channel = ieee80211_get_channel(wiphy, freq);
timestamp = le64_to_cpu(bss->timestamp);
capability = le16_to_cpu(bss->capabilities);
beacon_interval = le16_to_cpu(bss->beacon_interval);
ie = bss->data;
signal = SIGNAL_TO_MBM(bss->level);
cfg80211_inform_bss(wiphy, channel, bss->bssid, timestamp,
capability, beacon_interval, ie, ie_len,
signal, GFP_KERNEL);
}
void orinoco_add_hostscan_results(struct orinoco_private *priv,
unsigned char *buf,
size_t len)
{
int offset; /* In the scan data */
size_t atom_len;
bool abort = false;
switch (priv->firmware_type) {
case FIRMWARE_TYPE_AGERE:
atom_len = sizeof(struct agere_scan_apinfo);
offset = 0;
break;
case FIRMWARE_TYPE_SYMBOL:
/* Lack of documentation necessitates this hack.
* Different firmwares have 68 or 76 byte long atoms.
* We try modulo first. If the length divides by both,
* we check what would be the channel in the second
* frame for a 68-byte atom. 76-byte atoms have 0 there.
* Valid channel cannot be 0. */
if (len % 76)
atom_len = 68;
else if (len % 68)
atom_len = 76;
else if (len >= 1292 && buf[68] == 0)
atom_len = 76;
else
atom_len = 68;
offset = 0;
break;
case FIRMWARE_TYPE_INTERSIL:
offset = 4;
if (priv->has_hostscan) {
atom_len = le16_to_cpup((__le16 *)buf);
/* Sanity check for atom_len */
if (atom_len < sizeof(struct prism2_scan_apinfo)) {
printk(KERN_ERR "%s: Invalid atom_len in scan "
"data: %zu\n", priv->ndev->name,
atom_len);
abort = true;
goto scan_abort;
}
} else
atom_len = offsetof(struct prism2_scan_apinfo, atim);
break;
default:
abort = true;
goto scan_abort;
}
/* Check that we got an whole number of atoms */
if ((len - offset) % atom_len) {
printk(KERN_ERR "%s: Unexpected scan data length %zu, "
"atom_len %zu, offset %d\n", priv->ndev->name, len,
atom_len, offset);
abort = true;
goto scan_abort;
}
/* Process the entries one by one */
for (; offset + atom_len <= len; offset += atom_len) {
union hermes_scan_info *atom;
atom = (union hermes_scan_info *) (buf + offset);
orinoco_add_hostscan_result(priv, atom);
}
scan_abort:
if (priv->scan_request) {
cfg80211_scan_done(priv->scan_request, abort);
priv->scan_request = NULL;
}
}
void orinoco_scan_done(struct orinoco_private *priv, bool abort)
{
if (priv->scan_request) {
cfg80211_scan_done(priv->scan_request, abort);
priv->scan_request = NULL;
}
}
| gpl-2.0 |
heicrd/android_kernel_motorola_omap4-common | drivers/net/ehea/ehea_phyp.c | 3294 | 19311 | /*
* linux/drivers/net/ehea/ehea_phyp.c
*
* eHEA ethernet device driver for IBM eServer System p
*
* (C) Copyright IBM Corp. 2006
*
* Authors:
* Christoph Raisch <raisch@de.ibm.com>
* Jan-Bernd Themann <themann@de.ibm.com>
* Thomas Klein <tklein@de.ibm.com>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "ehea_phyp.h"
static inline u16 get_order_of_qentries(u16 queue_entries)
{
u8 ld = 1; /* logarithmus dualis */
while (((1U << ld) - 1) < queue_entries)
ld++;
return ld - 1;
}
/* Defines for H_CALL H_ALLOC_RESOURCE */
#define H_ALL_RES_TYPE_QP 1
#define H_ALL_RES_TYPE_CQ 2
#define H_ALL_RES_TYPE_EQ 3
#define H_ALL_RES_TYPE_MR 5
#define H_ALL_RES_TYPE_MW 6
static long ehea_plpar_hcall_norets(unsigned long opcode,
unsigned long arg1,
unsigned long arg2,
unsigned long arg3,
unsigned long arg4,
unsigned long arg5,
unsigned long arg6,
unsigned long arg7)
{
long ret;
int i, sleep_msecs;
for (i = 0; i < 5; i++) {
ret = plpar_hcall_norets(opcode, arg1, arg2, arg3, arg4,
arg5, arg6, arg7);
if (H_IS_LONG_BUSY(ret)) {
sleep_msecs = get_longbusy_msecs(ret);
msleep_interruptible(sleep_msecs);
continue;
}
if (ret < H_SUCCESS)
pr_err("opcode=%lx ret=%lx"
" arg1=%lx arg2=%lx arg3=%lx arg4=%lx"
" arg5=%lx arg6=%lx arg7=%lx\n",
opcode, ret,
arg1, arg2, arg3, arg4, arg5, arg6, arg7);
return ret;
}
return H_BUSY;
}
static long ehea_plpar_hcall9(unsigned long opcode,
unsigned long *outs, /* array of 9 outputs */
unsigned long arg1,
unsigned long arg2,
unsigned long arg3,
unsigned long arg4,
unsigned long arg5,
unsigned long arg6,
unsigned long arg7,
unsigned long arg8,
unsigned long arg9)
{
long ret;
int i, sleep_msecs;
u8 cb_cat;
for (i = 0; i < 5; i++) {
ret = plpar_hcall9(opcode, outs,
arg1, arg2, arg3, arg4, arg5,
arg6, arg7, arg8, arg9);
if (H_IS_LONG_BUSY(ret)) {
sleep_msecs = get_longbusy_msecs(ret);
msleep_interruptible(sleep_msecs);
continue;
}
cb_cat = EHEA_BMASK_GET(H_MEHEAPORT_CAT, arg2);
if ((ret < H_SUCCESS) && !(((ret == H_AUTHORITY)
&& (opcode == H_MODIFY_HEA_PORT))
&& (((cb_cat == H_PORT_CB4) && ((arg3 == H_PORT_CB4_JUMBO)
|| (arg3 == H_PORT_CB4_SPEED))) || ((cb_cat == H_PORT_CB7)
&& (arg3 == H_PORT_CB7_DUCQPN)))))
pr_err("opcode=%lx ret=%lx"
" arg1=%lx arg2=%lx arg3=%lx arg4=%lx"
" arg5=%lx arg6=%lx arg7=%lx arg8=%lx"
" arg9=%lx"
" out1=%lx out2=%lx out3=%lx out4=%lx"
" out5=%lx out6=%lx out7=%lx out8=%lx"
" out9=%lx\n",
opcode, ret,
arg1, arg2, arg3, arg4, arg5,
arg6, arg7, arg8, arg9,
outs[0], outs[1], outs[2], outs[3], outs[4],
outs[5], outs[6], outs[7], outs[8]);
return ret;
}
return H_BUSY;
}
u64 ehea_h_query_ehea_qp(const u64 adapter_handle, const u8 qp_category,
const u64 qp_handle, const u64 sel_mask, void *cb_addr)
{
return ehea_plpar_hcall_norets(H_QUERY_HEA_QP,
adapter_handle, /* R4 */
qp_category, /* R5 */
qp_handle, /* R6 */
sel_mask, /* R7 */
virt_to_abs(cb_addr), /* R8 */
0, 0);
}
/* input param R5 */
#define H_ALL_RES_QP_EQPO EHEA_BMASK_IBM(9, 11)
#define H_ALL_RES_QP_QPP EHEA_BMASK_IBM(12, 12)
#define H_ALL_RES_QP_RQR EHEA_BMASK_IBM(13, 15)
#define H_ALL_RES_QP_EQEG EHEA_BMASK_IBM(16, 16)
#define H_ALL_RES_QP_LL_QP EHEA_BMASK_IBM(17, 17)
#define H_ALL_RES_QP_DMA128 EHEA_BMASK_IBM(19, 19)
#define H_ALL_RES_QP_HSM EHEA_BMASK_IBM(20, 21)
#define H_ALL_RES_QP_SIGT EHEA_BMASK_IBM(22, 23)
#define H_ALL_RES_QP_TENURE EHEA_BMASK_IBM(48, 55)
#define H_ALL_RES_QP_RES_TYP EHEA_BMASK_IBM(56, 63)
/* input param R9 */
#define H_ALL_RES_QP_TOKEN EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_PD EHEA_BMASK_IBM(32, 63)
/* input param R10 */
#define H_ALL_RES_QP_MAX_SWQE EHEA_BMASK_IBM(4, 7)
#define H_ALL_RES_QP_MAX_R1WQE EHEA_BMASK_IBM(12, 15)
#define H_ALL_RES_QP_MAX_R2WQE EHEA_BMASK_IBM(20, 23)
#define H_ALL_RES_QP_MAX_R3WQE EHEA_BMASK_IBM(28, 31)
/* Max Send Scatter Gather Elements */
#define H_ALL_RES_QP_MAX_SSGE EHEA_BMASK_IBM(37, 39)
#define H_ALL_RES_QP_MAX_R1SGE EHEA_BMASK_IBM(45, 47)
/* Max Receive SG Elements RQ1 */
#define H_ALL_RES_QP_MAX_R2SGE EHEA_BMASK_IBM(53, 55)
#define H_ALL_RES_QP_MAX_R3SGE EHEA_BMASK_IBM(61, 63)
/* input param R11 */
#define H_ALL_RES_QP_SWQE_IDL EHEA_BMASK_IBM(0, 7)
/* max swqe immediate data length */
#define H_ALL_RES_QP_PORT_NUM EHEA_BMASK_IBM(48, 63)
/* input param R12 */
#define H_ALL_RES_QP_TH_RQ2 EHEA_BMASK_IBM(0, 15)
/* Threshold RQ2 */
#define H_ALL_RES_QP_TH_RQ3 EHEA_BMASK_IBM(16, 31)
/* Threshold RQ3 */
/* output param R6 */
#define H_ALL_RES_QP_ACT_SWQE EHEA_BMASK_IBM(0, 15)
#define H_ALL_RES_QP_ACT_R1WQE EHEA_BMASK_IBM(16, 31)
#define H_ALL_RES_QP_ACT_R2WQE EHEA_BMASK_IBM(32, 47)
#define H_ALL_RES_QP_ACT_R3WQE EHEA_BMASK_IBM(48, 63)
/* output param, R7 */
#define H_ALL_RES_QP_ACT_SSGE EHEA_BMASK_IBM(0, 7)
#define H_ALL_RES_QP_ACT_R1SGE EHEA_BMASK_IBM(8, 15)
#define H_ALL_RES_QP_ACT_R2SGE EHEA_BMASK_IBM(16, 23)
#define H_ALL_RES_QP_ACT_R3SGE EHEA_BMASK_IBM(24, 31)
#define H_ALL_RES_QP_ACT_SWQE_IDL EHEA_BMASK_IBM(32, 39)
/* output param R8,R9 */
#define H_ALL_RES_QP_SIZE_SQ EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_SIZE_RQ1 EHEA_BMASK_IBM(32, 63)
#define H_ALL_RES_QP_SIZE_RQ2 EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_SIZE_RQ3 EHEA_BMASK_IBM(32, 63)
/* output param R11,R12 */
#define H_ALL_RES_QP_LIOBN_SQ EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_LIOBN_RQ1 EHEA_BMASK_IBM(32, 63)
#define H_ALL_RES_QP_LIOBN_RQ2 EHEA_BMASK_IBM(0, 31)
#define H_ALL_RES_QP_LIOBN_RQ3 EHEA_BMASK_IBM(32, 63)
u64 ehea_h_alloc_resource_qp(const u64 adapter_handle,
struct ehea_qp_init_attr *init_attr, const u32 pd,
u64 *qp_handle, struct h_epas *h_epas)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
u64 allocate_controls =
EHEA_BMASK_SET(H_ALL_RES_QP_EQPO, init_attr->low_lat_rq1 ? 1 : 0)
| EHEA_BMASK_SET(H_ALL_RES_QP_QPP, 0)
| EHEA_BMASK_SET(H_ALL_RES_QP_RQR, 6) /* rq1 & rq2 & rq3 */
| EHEA_BMASK_SET(H_ALL_RES_QP_EQEG, 0) /* EQE gen. disabled */
| EHEA_BMASK_SET(H_ALL_RES_QP_LL_QP, init_attr->low_lat_rq1)
| EHEA_BMASK_SET(H_ALL_RES_QP_DMA128, 0)
| EHEA_BMASK_SET(H_ALL_RES_QP_HSM, 0)
| EHEA_BMASK_SET(H_ALL_RES_QP_SIGT, init_attr->signalingtype)
| EHEA_BMASK_SET(H_ALL_RES_QP_RES_TYP, H_ALL_RES_TYPE_QP);
u64 r9_reg = EHEA_BMASK_SET(H_ALL_RES_QP_PD, pd)
| EHEA_BMASK_SET(H_ALL_RES_QP_TOKEN, init_attr->qp_token);
u64 max_r10_reg =
EHEA_BMASK_SET(H_ALL_RES_QP_MAX_SWQE,
get_order_of_qentries(init_attr->max_nr_send_wqes))
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R1WQE,
get_order_of_qentries(init_attr->max_nr_rwqes_rq1))
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R2WQE,
get_order_of_qentries(init_attr->max_nr_rwqes_rq2))
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R3WQE,
get_order_of_qentries(init_attr->max_nr_rwqes_rq3))
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_SSGE, init_attr->wqe_size_enc_sq)
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R1SGE,
init_attr->wqe_size_enc_rq1)
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R2SGE,
init_attr->wqe_size_enc_rq2)
| EHEA_BMASK_SET(H_ALL_RES_QP_MAX_R3SGE,
init_attr->wqe_size_enc_rq3);
u64 r11_in =
EHEA_BMASK_SET(H_ALL_RES_QP_SWQE_IDL, init_attr->swqe_imm_data_len)
| EHEA_BMASK_SET(H_ALL_RES_QP_PORT_NUM, init_attr->port_nr);
u64 threshold =
EHEA_BMASK_SET(H_ALL_RES_QP_TH_RQ2, init_attr->rq2_threshold)
| EHEA_BMASK_SET(H_ALL_RES_QP_TH_RQ3, init_attr->rq3_threshold);
hret = ehea_plpar_hcall9(H_ALLOC_HEA_RESOURCE,
outs,
adapter_handle, /* R4 */
allocate_controls, /* R5 */
init_attr->send_cq_handle, /* R6 */
init_attr->recv_cq_handle, /* R7 */
init_attr->aff_eq_handle, /* R8 */
r9_reg, /* R9 */
max_r10_reg, /* R10 */
r11_in, /* R11 */
threshold); /* R12 */
*qp_handle = outs[0];
init_attr->qp_nr = (u32)outs[1];
init_attr->act_nr_send_wqes =
(u16)EHEA_BMASK_GET(H_ALL_RES_QP_ACT_SWQE, outs[2]);
init_attr->act_nr_rwqes_rq1 =
(u16)EHEA_BMASK_GET(H_ALL_RES_QP_ACT_R1WQE, outs[2]);
init_attr->act_nr_rwqes_rq2 =
(u16)EHEA_BMASK_GET(H_ALL_RES_QP_ACT_R2WQE, outs[2]);
init_attr->act_nr_rwqes_rq3 =
(u16)EHEA_BMASK_GET(H_ALL_RES_QP_ACT_R3WQE, outs[2]);
init_attr->act_wqe_size_enc_sq = init_attr->wqe_size_enc_sq;
init_attr->act_wqe_size_enc_rq1 = init_attr->wqe_size_enc_rq1;
init_attr->act_wqe_size_enc_rq2 = init_attr->wqe_size_enc_rq2;
init_attr->act_wqe_size_enc_rq3 = init_attr->wqe_size_enc_rq3;
init_attr->nr_sq_pages =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_SIZE_SQ, outs[4]);
init_attr->nr_rq1_pages =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_SIZE_RQ1, outs[4]);
init_attr->nr_rq2_pages =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_SIZE_RQ2, outs[5]);
init_attr->nr_rq3_pages =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_SIZE_RQ3, outs[5]);
init_attr->liobn_sq =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_LIOBN_SQ, outs[7]);
init_attr->liobn_rq1 =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_LIOBN_RQ1, outs[7]);
init_attr->liobn_rq2 =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_LIOBN_RQ2, outs[8]);
init_attr->liobn_rq3 =
(u32)EHEA_BMASK_GET(H_ALL_RES_QP_LIOBN_RQ3, outs[8]);
if (!hret)
hcp_epas_ctor(h_epas, outs[6], outs[6]);
return hret;
}
u64 ehea_h_alloc_resource_cq(const u64 adapter_handle,
struct ehea_cq_attr *cq_attr,
u64 *cq_handle, struct h_epas *epas)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
hret = ehea_plpar_hcall9(H_ALLOC_HEA_RESOURCE,
outs,
adapter_handle, /* R4 */
H_ALL_RES_TYPE_CQ, /* R5 */
cq_attr->eq_handle, /* R6 */
cq_attr->cq_token, /* R7 */
cq_attr->max_nr_of_cqes, /* R8 */
0, 0, 0, 0); /* R9-R12 */
*cq_handle = outs[0];
cq_attr->act_nr_of_cqes = outs[3];
cq_attr->nr_pages = outs[4];
if (!hret)
hcp_epas_ctor(epas, outs[5], outs[6]);
return hret;
}
/* Defines for H_CALL H_ALLOC_RESOURCE */
#define H_ALL_RES_TYPE_QP 1
#define H_ALL_RES_TYPE_CQ 2
#define H_ALL_RES_TYPE_EQ 3
#define H_ALL_RES_TYPE_MR 5
#define H_ALL_RES_TYPE_MW 6
/* input param R5 */
#define H_ALL_RES_EQ_NEQ EHEA_BMASK_IBM(0, 0)
#define H_ALL_RES_EQ_NON_NEQ_ISN EHEA_BMASK_IBM(6, 7)
#define H_ALL_RES_EQ_INH_EQE_GEN EHEA_BMASK_IBM(16, 16)
#define H_ALL_RES_EQ_RES_TYPE EHEA_BMASK_IBM(56, 63)
/* input param R6 */
#define H_ALL_RES_EQ_MAX_EQE EHEA_BMASK_IBM(32, 63)
/* output param R6 */
#define H_ALL_RES_EQ_LIOBN EHEA_BMASK_IBM(32, 63)
/* output param R7 */
#define H_ALL_RES_EQ_ACT_EQE EHEA_BMASK_IBM(32, 63)
/* output param R8 */
#define H_ALL_RES_EQ_ACT_PS EHEA_BMASK_IBM(32, 63)
/* output param R9 */
#define H_ALL_RES_EQ_ACT_EQ_IST_C EHEA_BMASK_IBM(30, 31)
#define H_ALL_RES_EQ_ACT_EQ_IST_1 EHEA_BMASK_IBM(40, 63)
/* output param R10 */
#define H_ALL_RES_EQ_ACT_EQ_IST_2 EHEA_BMASK_IBM(40, 63)
/* output param R11 */
#define H_ALL_RES_EQ_ACT_EQ_IST_3 EHEA_BMASK_IBM(40, 63)
/* output param R12 */
#define H_ALL_RES_EQ_ACT_EQ_IST_4 EHEA_BMASK_IBM(40, 63)
u64 ehea_h_alloc_resource_eq(const u64 adapter_handle,
struct ehea_eq_attr *eq_attr, u64 *eq_handle)
{
u64 hret, allocate_controls;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
/* resource type */
allocate_controls =
EHEA_BMASK_SET(H_ALL_RES_EQ_RES_TYPE, H_ALL_RES_TYPE_EQ)
| EHEA_BMASK_SET(H_ALL_RES_EQ_NEQ, eq_attr->type ? 1 : 0)
| EHEA_BMASK_SET(H_ALL_RES_EQ_INH_EQE_GEN, !eq_attr->eqe_gen)
| EHEA_BMASK_SET(H_ALL_RES_EQ_NON_NEQ_ISN, 1);
hret = ehea_plpar_hcall9(H_ALLOC_HEA_RESOURCE,
outs,
adapter_handle, /* R4 */
allocate_controls, /* R5 */
eq_attr->max_nr_of_eqes, /* R6 */
0, 0, 0, 0, 0, 0); /* R7-R10 */
*eq_handle = outs[0];
eq_attr->act_nr_of_eqes = outs[3];
eq_attr->nr_pages = outs[4];
eq_attr->ist1 = outs[5];
eq_attr->ist2 = outs[6];
eq_attr->ist3 = outs[7];
eq_attr->ist4 = outs[8];
return hret;
}
u64 ehea_h_modify_ehea_qp(const u64 adapter_handle, const u8 cat,
const u64 qp_handle, const u64 sel_mask,
void *cb_addr, u64 *inv_attr_id, u64 *proc_mask,
u16 *out_swr, u16 *out_rwr)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
hret = ehea_plpar_hcall9(H_MODIFY_HEA_QP,
outs,
adapter_handle, /* R4 */
(u64) cat, /* R5 */
qp_handle, /* R6 */
sel_mask, /* R7 */
virt_to_abs(cb_addr), /* R8 */
0, 0, 0, 0); /* R9-R12 */
*inv_attr_id = outs[0];
*out_swr = outs[3];
*out_rwr = outs[4];
*proc_mask = outs[5];
return hret;
}
u64 ehea_h_register_rpage(const u64 adapter_handle, const u8 pagesize,
const u8 queue_type, const u64 resource_handle,
const u64 log_pageaddr, u64 count)
{
u64 reg_control;
reg_control = EHEA_BMASK_SET(H_REG_RPAGE_PAGE_SIZE, pagesize)
| EHEA_BMASK_SET(H_REG_RPAGE_QT, queue_type);
return ehea_plpar_hcall_norets(H_REGISTER_HEA_RPAGES,
adapter_handle, /* R4 */
reg_control, /* R5 */
resource_handle, /* R6 */
log_pageaddr, /* R7 */
count, /* R8 */
0, 0); /* R9-R10 */
}
u64 ehea_h_register_smr(const u64 adapter_handle, const u64 orig_mr_handle,
const u64 vaddr_in, const u32 access_ctrl, const u32 pd,
struct ehea_mr *mr)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
hret = ehea_plpar_hcall9(H_REGISTER_SMR,
outs,
adapter_handle , /* R4 */
orig_mr_handle, /* R5 */
vaddr_in, /* R6 */
(((u64)access_ctrl) << 32ULL), /* R7 */
pd, /* R8 */
0, 0, 0, 0); /* R9-R12 */
mr->handle = outs[0];
mr->lkey = (u32)outs[2];
return hret;
}
u64 ehea_h_disable_and_get_hea(const u64 adapter_handle, const u64 qp_handle)
{
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
return ehea_plpar_hcall9(H_DISABLE_AND_GET_HEA,
outs,
adapter_handle, /* R4 */
H_DISABLE_GET_EHEA_WQE_P, /* R5 */
qp_handle, /* R6 */
0, 0, 0, 0, 0, 0); /* R7-R12 */
}
u64 ehea_h_free_resource(const u64 adapter_handle, const u64 res_handle,
u64 force_bit)
{
return ehea_plpar_hcall_norets(H_FREE_RESOURCE,
adapter_handle, /* R4 */
res_handle, /* R5 */
force_bit,
0, 0, 0, 0); /* R7-R10 */
}
u64 ehea_h_alloc_resource_mr(const u64 adapter_handle, const u64 vaddr,
const u64 length, const u32 access_ctrl,
const u32 pd, u64 *mr_handle, u32 *lkey)
{
u64 hret;
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
hret = ehea_plpar_hcall9(H_ALLOC_HEA_RESOURCE,
outs,
adapter_handle, /* R4 */
5, /* R5 */
vaddr, /* R6 */
length, /* R7 */
(((u64) access_ctrl) << 32ULL), /* R8 */
pd, /* R9 */
0, 0, 0); /* R10-R12 */
*mr_handle = outs[0];
*lkey = (u32)outs[2];
return hret;
}
u64 ehea_h_register_rpage_mr(const u64 adapter_handle, const u64 mr_handle,
const u8 pagesize, const u8 queue_type,
const u64 log_pageaddr, const u64 count)
{
if ((count > 1) && (log_pageaddr & ~PAGE_MASK)) {
pr_err("not on pageboundary\n");
return H_PARAMETER;
}
return ehea_h_register_rpage(adapter_handle, pagesize,
queue_type, mr_handle,
log_pageaddr, count);
}
u64 ehea_h_query_ehea(const u64 adapter_handle, void *cb_addr)
{
u64 hret, cb_logaddr;
cb_logaddr = virt_to_abs(cb_addr);
hret = ehea_plpar_hcall_norets(H_QUERY_HEA,
adapter_handle, /* R4 */
cb_logaddr, /* R5 */
0, 0, 0, 0, 0); /* R6-R10 */
#ifdef DEBUG
ehea_dump(cb_addr, sizeof(struct hcp_query_ehea), "hcp_query_ehea");
#endif
return hret;
}
u64 ehea_h_query_ehea_port(const u64 adapter_handle, const u16 port_num,
const u8 cb_cat, const u64 select_mask,
void *cb_addr)
{
u64 port_info;
u64 cb_logaddr = virt_to_abs(cb_addr);
u64 arr_index = 0;
port_info = EHEA_BMASK_SET(H_MEHEAPORT_CAT, cb_cat)
| EHEA_BMASK_SET(H_MEHEAPORT_PN, port_num);
return ehea_plpar_hcall_norets(H_QUERY_HEA_PORT,
adapter_handle, /* R4 */
port_info, /* R5 */
select_mask, /* R6 */
arr_index, /* R7 */
cb_logaddr, /* R8 */
0, 0); /* R9-R10 */
}
u64 ehea_h_modify_ehea_port(const u64 adapter_handle, const u16 port_num,
const u8 cb_cat, const u64 select_mask,
void *cb_addr)
{
unsigned long outs[PLPAR_HCALL9_BUFSIZE];
u64 port_info;
u64 arr_index = 0;
u64 cb_logaddr = virt_to_abs(cb_addr);
port_info = EHEA_BMASK_SET(H_MEHEAPORT_CAT, cb_cat)
| EHEA_BMASK_SET(H_MEHEAPORT_PN, port_num);
#ifdef DEBUG
ehea_dump(cb_addr, sizeof(struct hcp_ehea_port_cb0), "Before HCALL");
#endif
return ehea_plpar_hcall9(H_MODIFY_HEA_PORT,
outs,
adapter_handle, /* R4 */
port_info, /* R5 */
select_mask, /* R6 */
arr_index, /* R7 */
cb_logaddr, /* R8 */
0, 0, 0, 0); /* R9-R12 */
}
u64 ehea_h_reg_dereg_bcmc(const u64 adapter_handle, const u16 port_num,
const u8 reg_type, const u64 mc_mac_addr,
const u16 vlan_id, const u32 hcall_id)
{
u64 r5_port_num, r6_reg_type, r7_mc_mac_addr, r8_vlan_id;
u64 mac_addr = mc_mac_addr >> 16;
r5_port_num = EHEA_BMASK_SET(H_REGBCMC_PN, port_num);
r6_reg_type = EHEA_BMASK_SET(H_REGBCMC_REGTYPE, reg_type);
r7_mc_mac_addr = EHEA_BMASK_SET(H_REGBCMC_MACADDR, mac_addr);
r8_vlan_id = EHEA_BMASK_SET(H_REGBCMC_VLANID, vlan_id);
return ehea_plpar_hcall_norets(hcall_id,
adapter_handle, /* R4 */
r5_port_num, /* R5 */
r6_reg_type, /* R6 */
r7_mc_mac_addr, /* R7 */
r8_vlan_id, /* R8 */
0, 0); /* R9-R12 */
}
u64 ehea_h_reset_events(const u64 adapter_handle, const u64 neq_handle,
const u64 event_mask)
{
return ehea_plpar_hcall_norets(H_RESET_EVENTS,
adapter_handle, /* R4 */
neq_handle, /* R5 */
event_mask, /* R6 */
0, 0, 0, 0); /* R7-R12 */
}
u64 ehea_h_error_data(const u64 adapter_handle, const u64 ressource_handle,
void *rblock)
{
return ehea_plpar_hcall_norets(H_ERROR_DATA,
adapter_handle, /* R4 */
ressource_handle, /* R5 */
virt_to_abs(rblock), /* R6 */
0, 0, 0, 0); /* R7-R12 */
}
| gpl-2.0 |
Jazz-823/kernel_sony_togari | arch/um/drivers/chan_kern.c | 4574 | 12563 | /*
* Copyright (C) 2000 - 2007 Jeff Dike (jdike@{linux.intel,addtoit}.com)
* Licensed under the GPL
*/
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include "chan.h"
#include "os.h"
#ifdef CONFIG_NOCONFIG_CHAN
static void *not_configged_init(char *str, int device,
const struct chan_opts *opts)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return NULL;
}
static int not_configged_open(int input, int output, int primary, void *data,
char **dev_out)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -ENODEV;
}
static void not_configged_close(int fd, void *data)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
}
static int not_configged_read(int fd, char *c_out, void *data)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -EIO;
}
static int not_configged_write(int fd, const char *buf, int len, void *data)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -EIO;
}
static int not_configged_console_write(int fd, const char *buf, int len)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -EIO;
}
static int not_configged_window_size(int fd, void *data, unsigned short *rows,
unsigned short *cols)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
return -ENODEV;
}
static void not_configged_free(void *data)
{
printk(KERN_ERR "Using a channel type which is configured out of "
"UML\n");
}
static const struct chan_ops not_configged_ops = {
.init = not_configged_init,
.open = not_configged_open,
.close = not_configged_close,
.read = not_configged_read,
.write = not_configged_write,
.console_write = not_configged_console_write,
.window_size = not_configged_window_size,
.free = not_configged_free,
.winch = 0,
};
#endif /* CONFIG_NOCONFIG_CHAN */
static void tty_receive_char(struct tty_struct *tty, char ch)
{
if (tty == NULL)
return;
if (I_IXON(tty) && !I_IXOFF(tty) && !tty->raw) {
if (ch == STOP_CHAR(tty)) {
stop_tty(tty);
return;
}
else if (ch == START_CHAR(tty)) {
start_tty(tty);
return;
}
}
tty_insert_flip_char(tty, ch, TTY_NORMAL);
}
static int open_one_chan(struct chan *chan)
{
int fd, err;
if (chan->opened)
return 0;
if (chan->ops->open == NULL)
fd = 0;
else fd = (*chan->ops->open)(chan->input, chan->output, chan->primary,
chan->data, &chan->dev);
if (fd < 0)
return fd;
err = os_set_fd_block(fd, 0);
if (err) {
(*chan->ops->close)(fd, chan->data);
return err;
}
chan->fd = fd;
chan->opened = 1;
return 0;
}
static int open_chan(struct list_head *chans)
{
struct list_head *ele;
struct chan *chan;
int ret, err = 0;
list_for_each(ele, chans) {
chan = list_entry(ele, struct chan, list);
ret = open_one_chan(chan);
if (chan->primary)
err = ret;
}
return err;
}
void chan_enable_winch(struct chan *chan, struct tty_struct *tty)
{
if (chan && chan->primary && chan->ops->winch)
register_winch(chan->fd, tty);
}
static void line_timer_cb(struct work_struct *work)
{
struct line *line = container_of(work, struct line, task.work);
if (!line->throttled)
chan_interrupt(line, line->tty, line->driver->read_irq);
}
int enable_chan(struct line *line)
{
struct list_head *ele;
struct chan *chan;
int err;
INIT_DELAYED_WORK(&line->task, line_timer_cb);
list_for_each(ele, &line->chan_list) {
chan = list_entry(ele, struct chan, list);
err = open_one_chan(chan);
if (err) {
if (chan->primary)
goto out_close;
continue;
}
if (chan->enabled)
continue;
err = line_setup_irq(chan->fd, chan->input, chan->output, line,
chan);
if (err)
goto out_close;
chan->enabled = 1;
}
return 0;
out_close:
close_chan(line);
return err;
}
/* Items are added in IRQ context, when free_irq can't be called, and
* removed in process context, when it can.
* This handles interrupt sources which disappear, and which need to
* be permanently disabled. This is discovered in IRQ context, but
* the freeing of the IRQ must be done later.
*/
static DEFINE_SPINLOCK(irqs_to_free_lock);
static LIST_HEAD(irqs_to_free);
void free_irqs(void)
{
struct chan *chan;
LIST_HEAD(list);
struct list_head *ele;
unsigned long flags;
spin_lock_irqsave(&irqs_to_free_lock, flags);
list_splice_init(&irqs_to_free, &list);
spin_unlock_irqrestore(&irqs_to_free_lock, flags);
list_for_each(ele, &list) {
chan = list_entry(ele, struct chan, free_list);
if (chan->input && chan->enabled)
free_irq(chan->line->driver->read_irq, chan);
if (chan->output && chan->enabled)
free_irq(chan->line->driver->write_irq, chan);
chan->enabled = 0;
}
}
static void close_one_chan(struct chan *chan, int delay_free_irq)
{
unsigned long flags;
if (!chan->opened)
return;
if (delay_free_irq) {
spin_lock_irqsave(&irqs_to_free_lock, flags);
list_add(&chan->free_list, &irqs_to_free);
spin_unlock_irqrestore(&irqs_to_free_lock, flags);
}
else {
if (chan->input && chan->enabled)
free_irq(chan->line->driver->read_irq, chan);
if (chan->output && chan->enabled)
free_irq(chan->line->driver->write_irq, chan);
chan->enabled = 0;
}
if (chan->ops->close != NULL)
(*chan->ops->close)(chan->fd, chan->data);
chan->opened = 0;
chan->fd = -1;
}
void close_chan(struct line *line)
{
struct chan *chan;
/* Close in reverse order as open in case more than one of them
* refers to the same device and they save and restore that device's
* state. Then, the first one opened will have the original state,
* so it must be the last closed.
*/
list_for_each_entry_reverse(chan, &line->chan_list, list) {
close_one_chan(chan, 0);
}
}
void deactivate_chan(struct chan *chan, int irq)
{
if (chan && chan->enabled)
deactivate_fd(chan->fd, irq);
}
void reactivate_chan(struct chan *chan, int irq)
{
if (chan && chan->enabled)
reactivate_fd(chan->fd, irq);
}
int write_chan(struct chan *chan, const char *buf, int len,
int write_irq)
{
int n, ret = 0;
if (len == 0 || !chan || !chan->ops->write)
return 0;
n = chan->ops->write(chan->fd, buf, len, chan->data);
if (chan->primary) {
ret = n;
if ((ret == -EAGAIN) || ((ret >= 0) && (ret < len)))
reactivate_fd(chan->fd, write_irq);
}
return ret;
}
int console_write_chan(struct chan *chan, const char *buf, int len)
{
int n, ret = 0;
if (!chan || !chan->ops->console_write)
return 0;
n = chan->ops->console_write(chan->fd, buf, len);
if (chan->primary)
ret = n;
return ret;
}
int console_open_chan(struct line *line, struct console *co)
{
int err;
err = open_chan(&line->chan_list);
if (err)
return err;
printk(KERN_INFO "Console initialized on /dev/%s%d\n", co->name,
co->index);
return 0;
}
int chan_window_size(struct line *line, unsigned short *rows_out,
unsigned short *cols_out)
{
struct chan *chan;
chan = line->chan_in;
if (chan && chan->primary) {
if (chan->ops->window_size == NULL)
return 0;
return chan->ops->window_size(chan->fd, chan->data,
rows_out, cols_out);
}
chan = line->chan_out;
if (chan && chan->primary) {
if (chan->ops->window_size == NULL)
return 0;
return chan->ops->window_size(chan->fd, chan->data,
rows_out, cols_out);
}
return 0;
}
static void free_one_chan(struct chan *chan)
{
list_del(&chan->list);
close_one_chan(chan, 0);
if (chan->ops->free != NULL)
(*chan->ops->free)(chan->data);
if (chan->primary && chan->output)
ignore_sigio_fd(chan->fd);
kfree(chan);
}
static void free_chan(struct list_head *chans)
{
struct list_head *ele, *next;
struct chan *chan;
list_for_each_safe(ele, next, chans) {
chan = list_entry(ele, struct chan, list);
free_one_chan(chan);
}
}
static int one_chan_config_string(struct chan *chan, char *str, int size,
char **error_out)
{
int n = 0;
if (chan == NULL) {
CONFIG_CHUNK(str, size, n, "none", 1);
return n;
}
CONFIG_CHUNK(str, size, n, chan->ops->type, 0);
if (chan->dev == NULL) {
CONFIG_CHUNK(str, size, n, "", 1);
return n;
}
CONFIG_CHUNK(str, size, n, ":", 0);
CONFIG_CHUNK(str, size, n, chan->dev, 0);
return n;
}
static int chan_pair_config_string(struct chan *in, struct chan *out,
char *str, int size, char **error_out)
{
int n;
n = one_chan_config_string(in, str, size, error_out);
str += n;
size -= n;
if (in == out) {
CONFIG_CHUNK(str, size, n, "", 1);
return n;
}
CONFIG_CHUNK(str, size, n, ",", 1);
n = one_chan_config_string(out, str, size, error_out);
str += n;
size -= n;
CONFIG_CHUNK(str, size, n, "", 1);
return n;
}
int chan_config_string(struct line *line, char *str, int size,
char **error_out)
{
struct chan *in = line->chan_in, *out = line->chan_out;
if (in && !in->primary)
in = NULL;
if (out && !out->primary)
out = NULL;
return chan_pair_config_string(in, out, str, size, error_out);
}
struct chan_type {
char *key;
const struct chan_ops *ops;
};
static const struct chan_type chan_table[] = {
{ "fd", &fd_ops },
#ifdef CONFIG_NULL_CHAN
{ "null", &null_ops },
#else
{ "null", ¬_configged_ops },
#endif
#ifdef CONFIG_PORT_CHAN
{ "port", &port_ops },
#else
{ "port", ¬_configged_ops },
#endif
#ifdef CONFIG_PTY_CHAN
{ "pty", &pty_ops },
{ "pts", &pts_ops },
#else
{ "pty", ¬_configged_ops },
{ "pts", ¬_configged_ops },
#endif
#ifdef CONFIG_TTY_CHAN
{ "tty", &tty_ops },
#else
{ "tty", ¬_configged_ops },
#endif
#ifdef CONFIG_XTERM_CHAN
{ "xterm", &xterm_ops },
#else
{ "xterm", ¬_configged_ops },
#endif
};
static struct chan *parse_chan(struct line *line, char *str, int device,
const struct chan_opts *opts, char **error_out)
{
const struct chan_type *entry;
const struct chan_ops *ops;
struct chan *chan;
void *data;
int i;
ops = NULL;
data = NULL;
for(i = 0; i < ARRAY_SIZE(chan_table); i++) {
entry = &chan_table[i];
if (!strncmp(str, entry->key, strlen(entry->key))) {
ops = entry->ops;
str += strlen(entry->key);
break;
}
}
if (ops == NULL) {
*error_out = "No match for configured backends";
return NULL;
}
data = (*ops->init)(str, device, opts);
if (data == NULL) {
*error_out = "Configuration failed";
return NULL;
}
chan = kmalloc(sizeof(*chan), GFP_ATOMIC);
if (chan == NULL) {
*error_out = "Memory allocation failed";
return NULL;
}
*chan = ((struct chan) { .list = LIST_HEAD_INIT(chan->list),
.free_list =
LIST_HEAD_INIT(chan->free_list),
.line = line,
.primary = 1,
.input = 0,
.output = 0,
.opened = 0,
.enabled = 0,
.fd = -1,
.ops = ops,
.data = data });
return chan;
}
int parse_chan_pair(char *str, struct line *line, int device,
const struct chan_opts *opts, char **error_out)
{
struct list_head *chans = &line->chan_list;
struct chan *new;
char *in, *out;
if (!list_empty(chans)) {
line->chan_in = line->chan_out = NULL;
free_chan(chans);
INIT_LIST_HEAD(chans);
}
if (!str)
return 0;
out = strchr(str, ',');
if (out != NULL) {
in = str;
*out = '\0';
out++;
new = parse_chan(line, in, device, opts, error_out);
if (new == NULL)
return -1;
new->input = 1;
list_add(&new->list, chans);
line->chan_in = new;
new = parse_chan(line, out, device, opts, error_out);
if (new == NULL)
return -1;
list_add(&new->list, chans);
new->output = 1;
line->chan_out = new;
}
else {
new = parse_chan(line, str, device, opts, error_out);
if (new == NULL)
return -1;
list_add(&new->list, chans);
new->input = 1;
new->output = 1;
line->chan_in = line->chan_out = new;
}
return 0;
}
void chan_interrupt(struct line *line, struct tty_struct *tty, int irq)
{
struct chan *chan = line->chan_in;
int err;
char c;
if (!chan || !chan->ops->read)
goto out;
do {
if (tty && !tty_buffer_request_room(tty, 1)) {
schedule_delayed_work(&line->task, 1);
goto out;
}
err = chan->ops->read(chan->fd, &c, chan->data);
if (err > 0)
tty_receive_char(tty, c);
} while (err > 0);
if (err == 0)
reactivate_fd(chan->fd, irq);
if (err == -EIO) {
if (chan->primary) {
if (tty != NULL)
tty_hangup(tty);
if (line->chan_out != chan)
close_one_chan(line->chan_out, 1);
}
close_one_chan(chan, 1);
if (chan->primary)
return;
}
out:
if (tty)
tty_flip_buffer_push(tty);
}
| gpl-2.0 |
revjunkie/galbi-g2 | arch/arm/mach-imx/mach-mx51_babbage.c | 4830 | 11120 | /*
* Copyright 2009-2010 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright (C) 2009-2010 Amit Kucheria <amit.kucheria@canonical.com>
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/input.h>
#include <linux/spi/flash.h>
#include <linux/spi/spi.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/iomux-mx51.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include "devices-imx51.h"
#include "cpu_op-mx51.h"
#define BABBAGE_USB_HUB_RESET IMX_GPIO_NR(1, 7)
#define BABBAGE_USBH1_STP IMX_GPIO_NR(1, 27)
#define BABBAGE_USB_PHY_RESET IMX_GPIO_NR(2, 5)
#define BABBAGE_FEC_PHY_RESET IMX_GPIO_NR(2, 14)
#define BABBAGE_POWER_KEY IMX_GPIO_NR(2, 21)
#define BABBAGE_ECSPI1_CS0 IMX_GPIO_NR(4, 24)
#define BABBAGE_ECSPI1_CS1 IMX_GPIO_NR(4, 25)
#define BABBAGE_SD2_CD IMX_GPIO_NR(1, 6)
#define BABBAGE_SD2_WP IMX_GPIO_NR(1, 5)
/* USB_CTRL_1 */
#define MX51_USB_CTRL_1_OFFSET 0x10
#define MX51_USB_CTRL_UH1_EXT_CLK_EN (1 << 25)
#define MX51_USB_PLLDIV_12_MHZ 0x00
#define MX51_USB_PLL_DIV_19_2_MHZ 0x01
#define MX51_USB_PLL_DIV_24_MHZ 0x02
static struct gpio_keys_button babbage_buttons[] = {
{
.gpio = BABBAGE_POWER_KEY,
.code = BTN_0,
.desc = "PWR",
.active_low = 1,
.wakeup = 1,
},
};
static const struct gpio_keys_platform_data imx_button_data __initconst = {
.buttons = babbage_buttons,
.nbuttons = ARRAY_SIZE(babbage_buttons),
};
static iomux_v3_cfg_t mx51babbage_pads[] = {
/* UART1 */
MX51_PAD_UART1_RXD__UART1_RXD,
MX51_PAD_UART1_TXD__UART1_TXD,
MX51_PAD_UART1_RTS__UART1_RTS,
MX51_PAD_UART1_CTS__UART1_CTS,
/* UART2 */
MX51_PAD_UART2_RXD__UART2_RXD,
MX51_PAD_UART2_TXD__UART2_TXD,
/* UART3 */
MX51_PAD_EIM_D25__UART3_RXD,
MX51_PAD_EIM_D26__UART3_TXD,
MX51_PAD_EIM_D27__UART3_RTS,
MX51_PAD_EIM_D24__UART3_CTS,
/* I2C1 */
MX51_PAD_EIM_D16__I2C1_SDA,
MX51_PAD_EIM_D19__I2C1_SCL,
/* I2C2 */
MX51_PAD_KEY_COL4__I2C2_SCL,
MX51_PAD_KEY_COL5__I2C2_SDA,
/* HSI2C */
MX51_PAD_I2C1_CLK__I2C1_CLK,
MX51_PAD_I2C1_DAT__I2C1_DAT,
/* USB HOST1 */
MX51_PAD_USBH1_CLK__USBH1_CLK,
MX51_PAD_USBH1_DIR__USBH1_DIR,
MX51_PAD_USBH1_NXT__USBH1_NXT,
MX51_PAD_USBH1_DATA0__USBH1_DATA0,
MX51_PAD_USBH1_DATA1__USBH1_DATA1,
MX51_PAD_USBH1_DATA2__USBH1_DATA2,
MX51_PAD_USBH1_DATA3__USBH1_DATA3,
MX51_PAD_USBH1_DATA4__USBH1_DATA4,
MX51_PAD_USBH1_DATA5__USBH1_DATA5,
MX51_PAD_USBH1_DATA6__USBH1_DATA6,
MX51_PAD_USBH1_DATA7__USBH1_DATA7,
/* USB HUB reset line*/
MX51_PAD_GPIO1_7__GPIO1_7,
/* USB PHY reset line */
MX51_PAD_EIM_D21__GPIO2_5,
/* FEC */
MX51_PAD_EIM_EB2__FEC_MDIO,
MX51_PAD_EIM_EB3__FEC_RDATA1,
MX51_PAD_EIM_CS2__FEC_RDATA2,
MX51_PAD_EIM_CS3__FEC_RDATA3,
MX51_PAD_EIM_CS4__FEC_RX_ER,
MX51_PAD_EIM_CS5__FEC_CRS,
MX51_PAD_NANDF_RB2__FEC_COL,
MX51_PAD_NANDF_RB3__FEC_RX_CLK,
MX51_PAD_NANDF_D9__FEC_RDATA0,
MX51_PAD_NANDF_D8__FEC_TDATA0,
MX51_PAD_NANDF_CS2__FEC_TX_ER,
MX51_PAD_NANDF_CS3__FEC_MDC,
MX51_PAD_NANDF_CS4__FEC_TDATA1,
MX51_PAD_NANDF_CS5__FEC_TDATA2,
MX51_PAD_NANDF_CS6__FEC_TDATA3,
MX51_PAD_NANDF_CS7__FEC_TX_EN,
MX51_PAD_NANDF_RDY_INT__FEC_TX_CLK,
/* FEC PHY reset line */
MX51_PAD_EIM_A20__GPIO2_14,
/* SD 1 */
MX51_PAD_SD1_CMD__SD1_CMD,
MX51_PAD_SD1_CLK__SD1_CLK,
MX51_PAD_SD1_DATA0__SD1_DATA0,
MX51_PAD_SD1_DATA1__SD1_DATA1,
MX51_PAD_SD1_DATA2__SD1_DATA2,
MX51_PAD_SD1_DATA3__SD1_DATA3,
/* CD/WP from controller */
MX51_PAD_GPIO1_0__SD1_CD,
MX51_PAD_GPIO1_1__SD1_WP,
/* SD 2 */
MX51_PAD_SD2_CMD__SD2_CMD,
MX51_PAD_SD2_CLK__SD2_CLK,
MX51_PAD_SD2_DATA0__SD2_DATA0,
MX51_PAD_SD2_DATA1__SD2_DATA1,
MX51_PAD_SD2_DATA2__SD2_DATA2,
MX51_PAD_SD2_DATA3__SD2_DATA3,
/* CD/WP gpio */
MX51_PAD_GPIO1_6__GPIO1_6,
MX51_PAD_GPIO1_5__GPIO1_5,
/* eCSPI1 */
MX51_PAD_CSPI1_MISO__ECSPI1_MISO,
MX51_PAD_CSPI1_MOSI__ECSPI1_MOSI,
MX51_PAD_CSPI1_SCLK__ECSPI1_SCLK,
MX51_PAD_CSPI1_SS0__GPIO4_24,
MX51_PAD_CSPI1_SS1__GPIO4_25,
};
/* Serial ports */
static const struct imxuart_platform_data uart_pdata __initconst = {
.flags = IMXUART_HAVE_RTSCTS,
};
static const struct imxi2c_platform_data babbage_i2c_data __initconst = {
.bitrate = 100000,
};
static const struct imxi2c_platform_data babbage_hsi2c_data __initconst = {
.bitrate = 400000,
};
static struct gpio mx51_babbage_usbh1_gpios[] = {
{ BABBAGE_USBH1_STP, GPIOF_OUT_INIT_LOW, "usbh1_stp" },
{ BABBAGE_USB_PHY_RESET, GPIOF_OUT_INIT_LOW, "usbh1_phy_reset" },
};
static int gpio_usbh1_active(void)
{
iomux_v3_cfg_t usbh1stp_gpio = MX51_PAD_USBH1_STP__GPIO1_27;
int ret;
/* Set USBH1_STP to GPIO and toggle it */
mxc_iomux_v3_setup_pad(usbh1stp_gpio);
ret = gpio_request_array(mx51_babbage_usbh1_gpios,
ARRAY_SIZE(mx51_babbage_usbh1_gpios));
if (ret) {
pr_debug("failed to get USBH1 pins: %d\n", ret);
return ret;
}
msleep(100);
gpio_set_value(BABBAGE_USBH1_STP, 1);
gpio_set_value(BABBAGE_USB_PHY_RESET, 1);
gpio_free_array(mx51_babbage_usbh1_gpios,
ARRAY_SIZE(mx51_babbage_usbh1_gpios));
return 0;
}
static inline void babbage_usbhub_reset(void)
{
int ret;
/* Reset USB hub */
ret = gpio_request_one(BABBAGE_USB_HUB_RESET,
GPIOF_OUT_INIT_LOW, "GPIO1_7");
if (ret) {
printk(KERN_ERR"failed to get GPIO_USB_HUB_RESET: %d\n", ret);
return;
}
msleep(2);
/* Deassert reset */
gpio_set_value(BABBAGE_USB_HUB_RESET, 1);
}
static inline void babbage_fec_reset(void)
{
int ret;
/* reset FEC PHY */
ret = gpio_request_one(BABBAGE_FEC_PHY_RESET,
GPIOF_OUT_INIT_LOW, "fec-phy-reset");
if (ret) {
printk(KERN_ERR"failed to get GPIO_FEC_PHY_RESET: %d\n", ret);
return;
}
msleep(1);
gpio_set_value(BABBAGE_FEC_PHY_RESET, 1);
}
/* This function is board specific as the bit mask for the plldiv will also
be different for other Freescale SoCs, thus a common bitmask is not
possible and cannot get place in /plat-mxc/ehci.c.*/
static int initialize_otg_port(struct platform_device *pdev)
{
u32 v;
void __iomem *usb_base;
void __iomem *usbother_base;
usb_base = ioremap(MX51_USB_OTG_BASE_ADDR, SZ_4K);
if (!usb_base)
return -ENOMEM;
usbother_base = usb_base + MX5_USBOTHER_REGS_OFFSET;
/* Set the PHY clock to 19.2MHz */
v = __raw_readl(usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET);
v &= ~MX5_USB_UTMI_PHYCTRL1_PLLDIV_MASK;
v |= MX51_USB_PLL_DIV_19_2_MHZ;
__raw_writel(v, usbother_base + MXC_USB_PHY_CTR_FUNC2_OFFSET);
iounmap(usb_base);
mdelay(10);
return mx51_initialize_usb_hw(0, MXC_EHCI_INTERNAL_PHY);
}
static int initialize_usbh1_port(struct platform_device *pdev)
{
u32 v;
void __iomem *usb_base;
void __iomem *usbother_base;
usb_base = ioremap(MX51_USB_OTG_BASE_ADDR, SZ_4K);
if (!usb_base)
return -ENOMEM;
usbother_base = usb_base + MX5_USBOTHER_REGS_OFFSET;
/* The clock for the USBH1 ULPI port will come externally from the PHY. */
v = __raw_readl(usbother_base + MX51_USB_CTRL_1_OFFSET);
__raw_writel(v | MX51_USB_CTRL_UH1_EXT_CLK_EN, usbother_base + MX51_USB_CTRL_1_OFFSET);
iounmap(usb_base);
mdelay(10);
return mx51_initialize_usb_hw(1, MXC_EHCI_POWER_PINS_ENABLED |
MXC_EHCI_ITC_NO_THRESHOLD);
}
static const struct mxc_usbh_platform_data dr_utmi_config __initconst = {
.init = initialize_otg_port,
.portsc = MXC_EHCI_UTMI_16BIT,
};
static const struct fsl_usb2_platform_data usb_pdata __initconst = {
.operating_mode = FSL_USB2_DR_DEVICE,
.phy_mode = FSL_USB2_PHY_UTMI_WIDE,
};
static const struct mxc_usbh_platform_data usbh1_config __initconst = {
.init = initialize_usbh1_port,
.portsc = MXC_EHCI_MODE_ULPI,
};
static int otg_mode_host;
static int __init babbage_otg_mode(char *options)
{
if (!strcmp(options, "host"))
otg_mode_host = 1;
else if (!strcmp(options, "device"))
otg_mode_host = 0;
else
pr_info("otg_mode neither \"host\" nor \"device\". "
"Defaulting to device\n");
return 0;
}
__setup("otg_mode=", babbage_otg_mode);
static struct spi_board_info mx51_babbage_spi_board_info[] __initdata = {
{
.modalias = "mtd_dataflash",
.max_speed_hz = 25000000,
.bus_num = 0,
.chip_select = 1,
.mode = SPI_MODE_0,
.platform_data = NULL,
},
};
static int mx51_babbage_spi_cs[] = {
BABBAGE_ECSPI1_CS0,
BABBAGE_ECSPI1_CS1,
};
static const struct spi_imx_master mx51_babbage_spi_pdata __initconst = {
.chipselect = mx51_babbage_spi_cs,
.num_chipselect = ARRAY_SIZE(mx51_babbage_spi_cs),
};
static const struct esdhc_platform_data mx51_babbage_sd1_data __initconst = {
.cd_type = ESDHC_CD_CONTROLLER,
.wp_type = ESDHC_WP_CONTROLLER,
};
static const struct esdhc_platform_data mx51_babbage_sd2_data __initconst = {
.cd_gpio = BABBAGE_SD2_CD,
.wp_gpio = BABBAGE_SD2_WP,
.cd_type = ESDHC_CD_GPIO,
.wp_type = ESDHC_WP_GPIO,
};
void __init imx51_babbage_common_init(void)
{
mxc_iomux_v3_setup_multiple_pads(mx51babbage_pads,
ARRAY_SIZE(mx51babbage_pads));
}
/*
* Board specific initialization.
*/
static void __init mx51_babbage_init(void)
{
iomux_v3_cfg_t usbh1stp = MX51_PAD_USBH1_STP__USBH1_STP;
iomux_v3_cfg_t power_key = NEW_PAD_CTRL(MX51_PAD_EIM_A27__GPIO2_21,
PAD_CTL_SRE_FAST | PAD_CTL_DSE_HIGH);
imx51_soc_init();
#if defined(CONFIG_CPU_FREQ_IMX)
get_cpu_op = mx51_get_cpu_op;
#endif
imx51_babbage_common_init();
imx51_add_imx_uart(0, &uart_pdata);
imx51_add_imx_uart(1, NULL);
imx51_add_imx_uart(2, &uart_pdata);
babbage_fec_reset();
imx51_add_fec(NULL);
/* Set the PAD settings for the pwr key. */
mxc_iomux_v3_setup_pad(power_key);
imx_add_gpio_keys(&imx_button_data);
imx51_add_imx_i2c(0, &babbage_i2c_data);
imx51_add_imx_i2c(1, &babbage_i2c_data);
imx51_add_hsi2c(&babbage_hsi2c_data);
if (otg_mode_host)
imx51_add_mxc_ehci_otg(&dr_utmi_config);
else {
initialize_otg_port(NULL);
imx51_add_fsl_usb2_udc(&usb_pdata);
}
gpio_usbh1_active();
imx51_add_mxc_ehci_hs(1, &usbh1_config);
/* setback USBH1_STP to be function */
mxc_iomux_v3_setup_pad(usbh1stp);
babbage_usbhub_reset();
imx51_add_sdhci_esdhc_imx(0, &mx51_babbage_sd1_data);
imx51_add_sdhci_esdhc_imx(1, &mx51_babbage_sd2_data);
spi_register_board_info(mx51_babbage_spi_board_info,
ARRAY_SIZE(mx51_babbage_spi_board_info));
imx51_add_ecspi(0, &mx51_babbage_spi_pdata);
imx51_add_imx2_wdt(0, NULL);
}
static void __init mx51_babbage_timer_init(void)
{
mx51_clocks_init(32768, 24000000, 22579200, 0);
}
static struct sys_timer mx51_babbage_timer = {
.init = mx51_babbage_timer_init,
};
MACHINE_START(MX51_BABBAGE, "Freescale MX51 Babbage Board")
/* Maintainer: Amit Kucheria <amit.kucheria@canonical.com> */
.atag_offset = 0x100,
.map_io = mx51_map_io,
.init_early = imx51_init_early,
.init_irq = mx51_init_irq,
.handle_irq = imx51_handle_irq,
.timer = &mx51_babbage_timer,
.init_machine = mx51_babbage_init,
.restart = mxc_restart,
MACHINE_END
| gpl-2.0 |
h2o64/kernel_msm | drivers/net/ethernet/micrel/ks8851_mll.c | 4830 | 42837 | /**
* drivers/net/ethernet/micrel/ks8851_mll.c
* Copyright (c) 2009 Micrel Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/**
* Supports:
* KS8851 16bit MLL chip from Micrel Inc.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/cache.h>
#include <linux/crc32.h>
#include <linux/mii.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <asm/io.h>
#define DRV_NAME "ks8851_mll"
static u8 KS_DEFAULT_MAC_ADDRESS[] = { 0x00, 0x10, 0xA1, 0x86, 0x95, 0x11 };
#define MAX_RECV_FRAMES 255
#define MAX_BUF_SIZE 2048
#define TX_BUF_SIZE 2000
#define RX_BUF_SIZE 2000
#define KS_CCR 0x08
#define CCR_EEPROM (1 << 9)
#define CCR_SPI (1 << 8)
#define CCR_8BIT (1 << 7)
#define CCR_16BIT (1 << 6)
#define CCR_32BIT (1 << 5)
#define CCR_SHARED (1 << 4)
#define CCR_32PIN (1 << 0)
/* MAC address registers */
#define KS_MARL 0x10
#define KS_MARM 0x12
#define KS_MARH 0x14
#define KS_OBCR 0x20
#define OBCR_ODS_16MA (1 << 6)
#define KS_EEPCR 0x22
#define EEPCR_EESA (1 << 4)
#define EEPCR_EESB (1 << 3)
#define EEPCR_EEDO (1 << 2)
#define EEPCR_EESCK (1 << 1)
#define EEPCR_EECS (1 << 0)
#define KS_MBIR 0x24
#define MBIR_TXMBF (1 << 12)
#define MBIR_TXMBFA (1 << 11)
#define MBIR_RXMBF (1 << 4)
#define MBIR_RXMBFA (1 << 3)
#define KS_GRR 0x26
#define GRR_QMU (1 << 1)
#define GRR_GSR (1 << 0)
#define KS_WFCR 0x2A
#define WFCR_MPRXE (1 << 7)
#define WFCR_WF3E (1 << 3)
#define WFCR_WF2E (1 << 2)
#define WFCR_WF1E (1 << 1)
#define WFCR_WF0E (1 << 0)
#define KS_WF0CRC0 0x30
#define KS_WF0CRC1 0x32
#define KS_WF0BM0 0x34
#define KS_WF0BM1 0x36
#define KS_WF0BM2 0x38
#define KS_WF0BM3 0x3A
#define KS_WF1CRC0 0x40
#define KS_WF1CRC1 0x42
#define KS_WF1BM0 0x44
#define KS_WF1BM1 0x46
#define KS_WF1BM2 0x48
#define KS_WF1BM3 0x4A
#define KS_WF2CRC0 0x50
#define KS_WF2CRC1 0x52
#define KS_WF2BM0 0x54
#define KS_WF2BM1 0x56
#define KS_WF2BM2 0x58
#define KS_WF2BM3 0x5A
#define KS_WF3CRC0 0x60
#define KS_WF3CRC1 0x62
#define KS_WF3BM0 0x64
#define KS_WF3BM1 0x66
#define KS_WF3BM2 0x68
#define KS_WF3BM3 0x6A
#define KS_TXCR 0x70
#define TXCR_TCGICMP (1 << 8)
#define TXCR_TCGUDP (1 << 7)
#define TXCR_TCGTCP (1 << 6)
#define TXCR_TCGIP (1 << 5)
#define TXCR_FTXQ (1 << 4)
#define TXCR_TXFCE (1 << 3)
#define TXCR_TXPE (1 << 2)
#define TXCR_TXCRC (1 << 1)
#define TXCR_TXE (1 << 0)
#define KS_TXSR 0x72
#define TXSR_TXLC (1 << 13)
#define TXSR_TXMC (1 << 12)
#define TXSR_TXFID_MASK (0x3f << 0)
#define TXSR_TXFID_SHIFT (0)
#define TXSR_TXFID_GET(_v) (((_v) >> 0) & 0x3f)
#define KS_RXCR1 0x74
#define RXCR1_FRXQ (1 << 15)
#define RXCR1_RXUDPFCC (1 << 14)
#define RXCR1_RXTCPFCC (1 << 13)
#define RXCR1_RXIPFCC (1 << 12)
#define RXCR1_RXPAFMA (1 << 11)
#define RXCR1_RXFCE (1 << 10)
#define RXCR1_RXEFE (1 << 9)
#define RXCR1_RXMAFMA (1 << 8)
#define RXCR1_RXBE (1 << 7)
#define RXCR1_RXME (1 << 6)
#define RXCR1_RXUE (1 << 5)
#define RXCR1_RXAE (1 << 4)
#define RXCR1_RXINVF (1 << 1)
#define RXCR1_RXE (1 << 0)
#define RXCR1_FILTER_MASK (RXCR1_RXINVF | RXCR1_RXAE | \
RXCR1_RXMAFMA | RXCR1_RXPAFMA)
#define KS_RXCR2 0x76
#define RXCR2_SRDBL_MASK (0x7 << 5)
#define RXCR2_SRDBL_SHIFT (5)
#define RXCR2_SRDBL_4B (0x0 << 5)
#define RXCR2_SRDBL_8B (0x1 << 5)
#define RXCR2_SRDBL_16B (0x2 << 5)
#define RXCR2_SRDBL_32B (0x3 << 5)
/* #define RXCR2_SRDBL_FRAME (0x4 << 5) */
#define RXCR2_IUFFP (1 << 4)
#define RXCR2_RXIUFCEZ (1 << 3)
#define RXCR2_UDPLFE (1 << 2)
#define RXCR2_RXICMPFCC (1 << 1)
#define RXCR2_RXSAF (1 << 0)
#define KS_TXMIR 0x78
#define KS_RXFHSR 0x7C
#define RXFSHR_RXFV (1 << 15)
#define RXFSHR_RXICMPFCS (1 << 13)
#define RXFSHR_RXIPFCS (1 << 12)
#define RXFSHR_RXTCPFCS (1 << 11)
#define RXFSHR_RXUDPFCS (1 << 10)
#define RXFSHR_RXBF (1 << 7)
#define RXFSHR_RXMF (1 << 6)
#define RXFSHR_RXUF (1 << 5)
#define RXFSHR_RXMR (1 << 4)
#define RXFSHR_RXFT (1 << 3)
#define RXFSHR_RXFTL (1 << 2)
#define RXFSHR_RXRF (1 << 1)
#define RXFSHR_RXCE (1 << 0)
#define RXFSHR_ERR (RXFSHR_RXCE | RXFSHR_RXRF |\
RXFSHR_RXFTL | RXFSHR_RXMR |\
RXFSHR_RXICMPFCS | RXFSHR_RXIPFCS |\
RXFSHR_RXTCPFCS)
#define KS_RXFHBCR 0x7E
#define RXFHBCR_CNT_MASK 0x0FFF
#define KS_TXQCR 0x80
#define TXQCR_AETFE (1 << 2)
#define TXQCR_TXQMAM (1 << 1)
#define TXQCR_METFE (1 << 0)
#define KS_RXQCR 0x82
#define RXQCR_RXDTTS (1 << 12)
#define RXQCR_RXDBCTS (1 << 11)
#define RXQCR_RXFCTS (1 << 10)
#define RXQCR_RXIPHTOE (1 << 9)
#define RXQCR_RXDTTE (1 << 7)
#define RXQCR_RXDBCTE (1 << 6)
#define RXQCR_RXFCTE (1 << 5)
#define RXQCR_ADRFE (1 << 4)
#define RXQCR_SDA (1 << 3)
#define RXQCR_RRXEF (1 << 0)
#define RXQCR_CMD_CNTL (RXQCR_RXFCTE|RXQCR_ADRFE)
#define KS_TXFDPR 0x84
#define TXFDPR_TXFPAI (1 << 14)
#define TXFDPR_TXFP_MASK (0x7ff << 0)
#define TXFDPR_TXFP_SHIFT (0)
#define KS_RXFDPR 0x86
#define RXFDPR_RXFPAI (1 << 14)
#define KS_RXDTTR 0x8C
#define KS_RXDBCTR 0x8E
#define KS_IER 0x90
#define KS_ISR 0x92
#define IRQ_LCI (1 << 15)
#define IRQ_TXI (1 << 14)
#define IRQ_RXI (1 << 13)
#define IRQ_RXOI (1 << 11)
#define IRQ_TXPSI (1 << 9)
#define IRQ_RXPSI (1 << 8)
#define IRQ_TXSAI (1 << 6)
#define IRQ_RXWFDI (1 << 5)
#define IRQ_RXMPDI (1 << 4)
#define IRQ_LDI (1 << 3)
#define IRQ_EDI (1 << 2)
#define IRQ_SPIBEI (1 << 1)
#define IRQ_DEDI (1 << 0)
#define KS_RXFCTR 0x9C
#define RXFCTR_THRESHOLD_MASK 0x00FF
#define KS_RXFC 0x9D
#define RXFCTR_RXFC_MASK (0xff << 8)
#define RXFCTR_RXFC_SHIFT (8)
#define RXFCTR_RXFC_GET(_v) (((_v) >> 8) & 0xff)
#define RXFCTR_RXFCT_MASK (0xff << 0)
#define RXFCTR_RXFCT_SHIFT (0)
#define KS_TXNTFSR 0x9E
#define KS_MAHTR0 0xA0
#define KS_MAHTR1 0xA2
#define KS_MAHTR2 0xA4
#define KS_MAHTR3 0xA6
#define KS_FCLWR 0xB0
#define KS_FCHWR 0xB2
#define KS_FCOWR 0xB4
#define KS_CIDER 0xC0
#define CIDER_ID 0x8870
#define CIDER_REV_MASK (0x7 << 1)
#define CIDER_REV_SHIFT (1)
#define CIDER_REV_GET(_v) (((_v) >> 1) & 0x7)
#define KS_CGCR 0xC6
#define KS_IACR 0xC8
#define IACR_RDEN (1 << 12)
#define IACR_TSEL_MASK (0x3 << 10)
#define IACR_TSEL_SHIFT (10)
#define IACR_TSEL_MIB (0x3 << 10)
#define IACR_ADDR_MASK (0x1f << 0)
#define IACR_ADDR_SHIFT (0)
#define KS_IADLR 0xD0
#define KS_IAHDR 0xD2
#define KS_PMECR 0xD4
#define PMECR_PME_DELAY (1 << 14)
#define PMECR_PME_POL (1 << 12)
#define PMECR_WOL_WAKEUP (1 << 11)
#define PMECR_WOL_MAGICPKT (1 << 10)
#define PMECR_WOL_LINKUP (1 << 9)
#define PMECR_WOL_ENERGY (1 << 8)
#define PMECR_AUTO_WAKE_EN (1 << 7)
#define PMECR_WAKEUP_NORMAL (1 << 6)
#define PMECR_WKEVT_MASK (0xf << 2)
#define PMECR_WKEVT_SHIFT (2)
#define PMECR_WKEVT_GET(_v) (((_v) >> 2) & 0xf)
#define PMECR_WKEVT_ENERGY (0x1 << 2)
#define PMECR_WKEVT_LINK (0x2 << 2)
#define PMECR_WKEVT_MAGICPKT (0x4 << 2)
#define PMECR_WKEVT_FRAME (0x8 << 2)
#define PMECR_PM_MASK (0x3 << 0)
#define PMECR_PM_SHIFT (0)
#define PMECR_PM_NORMAL (0x0 << 0)
#define PMECR_PM_ENERGY (0x1 << 0)
#define PMECR_PM_SOFTDOWN (0x2 << 0)
#define PMECR_PM_POWERSAVE (0x3 << 0)
/* Standard MII PHY data */
#define KS_P1MBCR 0xE4
#define P1MBCR_FORCE_FDX (1 << 8)
#define KS_P1MBSR 0xE6
#define P1MBSR_AN_COMPLETE (1 << 5)
#define P1MBSR_AN_CAPABLE (1 << 3)
#define P1MBSR_LINK_UP (1 << 2)
#define KS_PHY1ILR 0xE8
#define KS_PHY1IHR 0xEA
#define KS_P1ANAR 0xEC
#define KS_P1ANLPR 0xEE
#define KS_P1SCLMD 0xF4
#define P1SCLMD_LEDOFF (1 << 15)
#define P1SCLMD_TXIDS (1 << 14)
#define P1SCLMD_RESTARTAN (1 << 13)
#define P1SCLMD_DISAUTOMDIX (1 << 10)
#define P1SCLMD_FORCEMDIX (1 << 9)
#define P1SCLMD_AUTONEGEN (1 << 7)
#define P1SCLMD_FORCE100 (1 << 6)
#define P1SCLMD_FORCEFDX (1 << 5)
#define P1SCLMD_ADV_FLOW (1 << 4)
#define P1SCLMD_ADV_100BT_FDX (1 << 3)
#define P1SCLMD_ADV_100BT_HDX (1 << 2)
#define P1SCLMD_ADV_10BT_FDX (1 << 1)
#define P1SCLMD_ADV_10BT_HDX (1 << 0)
#define KS_P1CR 0xF6
#define P1CR_HP_MDIX (1 << 15)
#define P1CR_REV_POL (1 << 13)
#define P1CR_OP_100M (1 << 10)
#define P1CR_OP_FDX (1 << 9)
#define P1CR_OP_MDI (1 << 7)
#define P1CR_AN_DONE (1 << 6)
#define P1CR_LINK_GOOD (1 << 5)
#define P1CR_PNTR_FLOW (1 << 4)
#define P1CR_PNTR_100BT_FDX (1 << 3)
#define P1CR_PNTR_100BT_HDX (1 << 2)
#define P1CR_PNTR_10BT_FDX (1 << 1)
#define P1CR_PNTR_10BT_HDX (1 << 0)
/* TX Frame control */
#define TXFR_TXIC (1 << 15)
#define TXFR_TXFID_MASK (0x3f << 0)
#define TXFR_TXFID_SHIFT (0)
#define KS_P1SR 0xF8
#define P1SR_HP_MDIX (1 << 15)
#define P1SR_REV_POL (1 << 13)
#define P1SR_OP_100M (1 << 10)
#define P1SR_OP_FDX (1 << 9)
#define P1SR_OP_MDI (1 << 7)
#define P1SR_AN_DONE (1 << 6)
#define P1SR_LINK_GOOD (1 << 5)
#define P1SR_PNTR_FLOW (1 << 4)
#define P1SR_PNTR_100BT_FDX (1 << 3)
#define P1SR_PNTR_100BT_HDX (1 << 2)
#define P1SR_PNTR_10BT_FDX (1 << 1)
#define P1SR_PNTR_10BT_HDX (1 << 0)
#define ENUM_BUS_NONE 0
#define ENUM_BUS_8BIT 1
#define ENUM_BUS_16BIT 2
#define ENUM_BUS_32BIT 3
#define MAX_MCAST_LST 32
#define HW_MCAST_SIZE 8
/**
* union ks_tx_hdr - tx header data
* @txb: The header as bytes
* @txw: The header as 16bit, little-endian words
*
* A dual representation of the tx header data to allow
* access to individual bytes, and to allow 16bit accesses
* with 16bit alignment.
*/
union ks_tx_hdr {
u8 txb[4];
__le16 txw[2];
};
/**
* struct ks_net - KS8851 driver private data
* @net_device : The network device we're bound to
* @hw_addr : start address of data register.
* @hw_addr_cmd : start address of command register.
* @txh : temporaly buffer to save status/length.
* @lock : Lock to ensure that the device is not accessed when busy.
* @pdev : Pointer to platform device.
* @mii : The MII state information for the mii calls.
* @frame_head_info : frame header information for multi-pkt rx.
* @statelock : Lock on this structure for tx list.
* @msg_enable : The message flags controlling driver output (see ethtool).
* @frame_cnt : number of frames received.
* @bus_width : i/o bus width.
* @rc_rxqcr : Cached copy of KS_RXQCR.
* @rc_txcr : Cached copy of KS_TXCR.
* @rc_ier : Cached copy of KS_IER.
* @sharedbus : Multipex(addr and data bus) mode indicator.
* @cmd_reg_cache : command register cached.
* @cmd_reg_cache_int : command register cached. Used in the irq handler.
* @promiscuous : promiscuous mode indicator.
* @all_mcast : mutlicast indicator.
* @mcast_lst_size : size of multicast list.
* @mcast_lst : multicast list.
* @mcast_bits : multicast enabed.
* @mac_addr : MAC address assigned to this device.
* @fid : frame id.
* @extra_byte : number of extra byte prepended rx pkt.
* @enabled : indicator this device works.
*
* The @lock ensures that the chip is protected when certain operations are
* in progress. When the read or write packet transfer is in progress, most
* of the chip registers are not accessible until the transfer is finished and
* the DMA has been de-asserted.
*
* The @statelock is used to protect information in the structure which may
* need to be accessed via several sources, such as the network driver layer
* or one of the work queues.
*
*/
/* Receive multiplex framer header info */
struct type_frame_head {
u16 sts; /* Frame status */
u16 len; /* Byte count */
};
struct ks_net {
struct net_device *netdev;
void __iomem *hw_addr;
void __iomem *hw_addr_cmd;
union ks_tx_hdr txh ____cacheline_aligned;
struct mutex lock; /* spinlock to be interrupt safe */
struct platform_device *pdev;
struct mii_if_info mii;
struct type_frame_head *frame_head_info;
spinlock_t statelock;
u32 msg_enable;
u32 frame_cnt;
int bus_width;
u16 rc_rxqcr;
u16 rc_txcr;
u16 rc_ier;
u16 sharedbus;
u16 cmd_reg_cache;
u16 cmd_reg_cache_int;
u16 promiscuous;
u16 all_mcast;
u16 mcast_lst_size;
u8 mcast_lst[MAX_MCAST_LST][ETH_ALEN];
u8 mcast_bits[HW_MCAST_SIZE];
u8 mac_addr[6];
u8 fid;
u8 extra_byte;
u8 enabled;
};
static int msg_enable;
#define BE3 0x8000 /* Byte Enable 3 */
#define BE2 0x4000 /* Byte Enable 2 */
#define BE1 0x2000 /* Byte Enable 1 */
#define BE0 0x1000 /* Byte Enable 0 */
/**
* register read/write calls.
*
* All these calls issue transactions to access the chip's registers. They
* all require that the necessary lock is held to prevent accesses when the
* chip is busy transferring packet data (RX/TX FIFO accesses).
*/
/**
* ks_rdreg8 - read 8 bit register from device
* @ks : The chip information
* @offset: The register address
*
* Read a 8bit register from the chip, returning the result
*/
static u8 ks_rdreg8(struct ks_net *ks, int offset)
{
u16 data;
u8 shift_bit = offset & 0x03;
u8 shift_data = (offset & 1) << 3;
ks->cmd_reg_cache = (u16) offset | (u16)(BE0 << shift_bit);
iowrite16(ks->cmd_reg_cache, ks->hw_addr_cmd);
data = ioread16(ks->hw_addr);
return (u8)(data >> shift_data);
}
/**
* ks_rdreg16 - read 16 bit register from device
* @ks : The chip information
* @offset: The register address
*
* Read a 16bit register from the chip, returning the result
*/
static u16 ks_rdreg16(struct ks_net *ks, int offset)
{
ks->cmd_reg_cache = (u16)offset | ((BE1 | BE0) << (offset & 0x02));
iowrite16(ks->cmd_reg_cache, ks->hw_addr_cmd);
return ioread16(ks->hw_addr);
}
/**
* ks_wrreg8 - write 8bit register value to chip
* @ks: The chip information
* @offset: The register address
* @value: The value to write
*
*/
static void ks_wrreg8(struct ks_net *ks, int offset, u8 value)
{
u8 shift_bit = (offset & 0x03);
u16 value_write = (u16)(value << ((offset & 1) << 3));
ks->cmd_reg_cache = (u16)offset | (BE0 << shift_bit);
iowrite16(ks->cmd_reg_cache, ks->hw_addr_cmd);
iowrite16(value_write, ks->hw_addr);
}
/**
* ks_wrreg16 - write 16bit register value to chip
* @ks: The chip information
* @offset: The register address
* @value: The value to write
*
*/
static void ks_wrreg16(struct ks_net *ks, int offset, u16 value)
{
ks->cmd_reg_cache = (u16)offset | ((BE1 | BE0) << (offset & 0x02));
iowrite16(ks->cmd_reg_cache, ks->hw_addr_cmd);
iowrite16(value, ks->hw_addr);
}
/**
* ks_inblk - read a block of data from QMU. This is called after sudo DMA mode enabled.
* @ks: The chip state
* @wptr: buffer address to save data
* @len: length in byte to read
*
*/
static inline void ks_inblk(struct ks_net *ks, u16 *wptr, u32 len)
{
len >>= 1;
while (len--)
*wptr++ = (u16)ioread16(ks->hw_addr);
}
/**
* ks_outblk - write data to QMU. This is called after sudo DMA mode enabled.
* @ks: The chip information
* @wptr: buffer address
* @len: length in byte to write
*
*/
static inline void ks_outblk(struct ks_net *ks, u16 *wptr, u32 len)
{
len >>= 1;
while (len--)
iowrite16(*wptr++, ks->hw_addr);
}
static void ks_disable_int(struct ks_net *ks)
{
ks_wrreg16(ks, KS_IER, 0x0000);
} /* ks_disable_int */
static void ks_enable_int(struct ks_net *ks)
{
ks_wrreg16(ks, KS_IER, ks->rc_ier);
} /* ks_enable_int */
/**
* ks_tx_fifo_space - return the available hardware buffer size.
* @ks: The chip information
*
*/
static inline u16 ks_tx_fifo_space(struct ks_net *ks)
{
return ks_rdreg16(ks, KS_TXMIR) & 0x1fff;
}
/**
* ks_save_cmd_reg - save the command register from the cache.
* @ks: The chip information
*
*/
static inline void ks_save_cmd_reg(struct ks_net *ks)
{
/*ks8851 MLL has a bug to read back the command register.
* So rely on software to save the content of command register.
*/
ks->cmd_reg_cache_int = ks->cmd_reg_cache;
}
/**
* ks_restore_cmd_reg - restore the command register from the cache and
* write to hardware register.
* @ks: The chip information
*
*/
static inline void ks_restore_cmd_reg(struct ks_net *ks)
{
ks->cmd_reg_cache = ks->cmd_reg_cache_int;
iowrite16(ks->cmd_reg_cache, ks->hw_addr_cmd);
}
/**
* ks_set_powermode - set power mode of the device
* @ks: The chip information
* @pwrmode: The power mode value to write to KS_PMECR.
*
* Change the power mode of the chip.
*/
static void ks_set_powermode(struct ks_net *ks, unsigned pwrmode)
{
unsigned pmecr;
netif_dbg(ks, hw, ks->netdev, "setting power mode %d\n", pwrmode);
ks_rdreg16(ks, KS_GRR);
pmecr = ks_rdreg16(ks, KS_PMECR);
pmecr &= ~PMECR_PM_MASK;
pmecr |= pwrmode;
ks_wrreg16(ks, KS_PMECR, pmecr);
}
/**
* ks_read_config - read chip configuration of bus width.
* @ks: The chip information
*
*/
static void ks_read_config(struct ks_net *ks)
{
u16 reg_data = 0;
/* Regardless of bus width, 8 bit read should always work.*/
reg_data = ks_rdreg8(ks, KS_CCR) & 0x00FF;
reg_data |= ks_rdreg8(ks, KS_CCR+1) << 8;
/* addr/data bus are multiplexed */
ks->sharedbus = (reg_data & CCR_SHARED) == CCR_SHARED;
/* There are garbage data when reading data from QMU,
depending on bus-width.
*/
if (reg_data & CCR_8BIT) {
ks->bus_width = ENUM_BUS_8BIT;
ks->extra_byte = 1;
} else if (reg_data & CCR_16BIT) {
ks->bus_width = ENUM_BUS_16BIT;
ks->extra_byte = 2;
} else {
ks->bus_width = ENUM_BUS_32BIT;
ks->extra_byte = 4;
}
}
/**
* ks_soft_reset - issue one of the soft reset to the device
* @ks: The device state.
* @op: The bit(s) to set in the GRR
*
* Issue the relevant soft-reset command to the device's GRR register
* specified by @op.
*
* Note, the delays are in there as a caution to ensure that the reset
* has time to take effect and then complete. Since the datasheet does
* not currently specify the exact sequence, we have chosen something
* that seems to work with our device.
*/
static void ks_soft_reset(struct ks_net *ks, unsigned op)
{
/* Disable interrupt first */
ks_wrreg16(ks, KS_IER, 0x0000);
ks_wrreg16(ks, KS_GRR, op);
mdelay(10); /* wait a short time to effect reset */
ks_wrreg16(ks, KS_GRR, 0);
mdelay(1); /* wait for condition to clear */
}
void ks_enable_qmu(struct ks_net *ks)
{
u16 w;
w = ks_rdreg16(ks, KS_TXCR);
/* Enables QMU Transmit (TXCR). */
ks_wrreg16(ks, KS_TXCR, w | TXCR_TXE);
/*
* RX Frame Count Threshold Enable and Auto-Dequeue RXQ Frame
* Enable
*/
w = ks_rdreg16(ks, KS_RXQCR);
ks_wrreg16(ks, KS_RXQCR, w | RXQCR_RXFCTE);
/* Enables QMU Receive (RXCR1). */
w = ks_rdreg16(ks, KS_RXCR1);
ks_wrreg16(ks, KS_RXCR1, w | RXCR1_RXE);
ks->enabled = true;
} /* ks_enable_qmu */
static void ks_disable_qmu(struct ks_net *ks)
{
u16 w;
w = ks_rdreg16(ks, KS_TXCR);
/* Disables QMU Transmit (TXCR). */
w &= ~TXCR_TXE;
ks_wrreg16(ks, KS_TXCR, w);
/* Disables QMU Receive (RXCR1). */
w = ks_rdreg16(ks, KS_RXCR1);
w &= ~RXCR1_RXE ;
ks_wrreg16(ks, KS_RXCR1, w);
ks->enabled = false;
} /* ks_disable_qmu */
/**
* ks_read_qmu - read 1 pkt data from the QMU.
* @ks: The chip information
* @buf: buffer address to save 1 pkt
* @len: Pkt length
* Here is the sequence to read 1 pkt:
* 1. set sudo DMA mode
* 2. read prepend data
* 3. read pkt data
* 4. reset sudo DMA Mode
*/
static inline void ks_read_qmu(struct ks_net *ks, u16 *buf, u32 len)
{
u32 r = ks->extra_byte & 0x1 ;
u32 w = ks->extra_byte - r;
/* 1. set sudo DMA mode */
ks_wrreg16(ks, KS_RXFDPR, RXFDPR_RXFPAI);
ks_wrreg8(ks, KS_RXQCR, (ks->rc_rxqcr | RXQCR_SDA) & 0xff);
/* 2. read prepend data */
/**
* read 4 + extra bytes and discard them.
* extra bytes for dummy, 2 for status, 2 for len
*/
/* use likely(r) for 8 bit access for performance */
if (unlikely(r))
ioread8(ks->hw_addr);
ks_inblk(ks, buf, w + 2 + 2);
/* 3. read pkt data */
ks_inblk(ks, buf, ALIGN(len, 4));
/* 4. reset sudo DMA Mode */
ks_wrreg8(ks, KS_RXQCR, ks->rc_rxqcr);
}
/**
* ks_rcv - read multiple pkts data from the QMU.
* @ks: The chip information
* @netdev: The network device being opened.
*
* Read all of header information before reading pkt content.
* It is not allowed only port of pkts in QMU after issuing
* interrupt ack.
*/
static void ks_rcv(struct ks_net *ks, struct net_device *netdev)
{
u32 i;
struct type_frame_head *frame_hdr = ks->frame_head_info;
struct sk_buff *skb;
ks->frame_cnt = ks_rdreg16(ks, KS_RXFCTR) >> 8;
/* read all header information */
for (i = 0; i < ks->frame_cnt; i++) {
/* Checking Received packet status */
frame_hdr->sts = ks_rdreg16(ks, KS_RXFHSR);
/* Get packet len from hardware */
frame_hdr->len = ks_rdreg16(ks, KS_RXFHBCR);
frame_hdr++;
}
frame_hdr = ks->frame_head_info;
while (ks->frame_cnt--) {
skb = netdev_alloc_skb(netdev, frame_hdr->len + 16);
if (likely(skb && (frame_hdr->sts & RXFSHR_RXFV) &&
(frame_hdr->len < RX_BUF_SIZE) && frame_hdr->len)) {
skb_reserve(skb, 2);
/* read data block including CRC 4 bytes */
ks_read_qmu(ks, (u16 *)skb->data, frame_hdr->len);
skb_put(skb, frame_hdr->len);
skb->protocol = eth_type_trans(skb, netdev);
netif_rx(skb);
} else {
pr_err("%s: err:skb alloc\n", __func__);
ks_wrreg16(ks, KS_RXQCR, (ks->rc_rxqcr | RXQCR_RRXEF));
if (skb)
dev_kfree_skb_irq(skb);
}
frame_hdr++;
}
}
/**
* ks_update_link_status - link status update.
* @netdev: The network device being opened.
* @ks: The chip information
*
*/
static void ks_update_link_status(struct net_device *netdev, struct ks_net *ks)
{
/* check the status of the link */
u32 link_up_status;
if (ks_rdreg16(ks, KS_P1SR) & P1SR_LINK_GOOD) {
netif_carrier_on(netdev);
link_up_status = true;
} else {
netif_carrier_off(netdev);
link_up_status = false;
}
netif_dbg(ks, link, ks->netdev,
"%s: %s\n", __func__, link_up_status ? "UP" : "DOWN");
}
/**
* ks_irq - device interrupt handler
* @irq: Interrupt number passed from the IRQ handler.
* @pw: The private word passed to register_irq(), our struct ks_net.
*
* This is the handler invoked to find out what happened
*
* Read the interrupt status, work out what needs to be done and then clear
* any of the interrupts that are not needed.
*/
static irqreturn_t ks_irq(int irq, void *pw)
{
struct net_device *netdev = pw;
struct ks_net *ks = netdev_priv(netdev);
u16 status;
/*this should be the first in IRQ handler */
ks_save_cmd_reg(ks);
status = ks_rdreg16(ks, KS_ISR);
if (unlikely(!status)) {
ks_restore_cmd_reg(ks);
return IRQ_NONE;
}
ks_wrreg16(ks, KS_ISR, status);
if (likely(status & IRQ_RXI))
ks_rcv(ks, netdev);
if (unlikely(status & IRQ_LCI))
ks_update_link_status(netdev, ks);
if (unlikely(status & IRQ_TXI))
netif_wake_queue(netdev);
if (unlikely(status & IRQ_LDI)) {
u16 pmecr = ks_rdreg16(ks, KS_PMECR);
pmecr &= ~PMECR_WKEVT_MASK;
ks_wrreg16(ks, KS_PMECR, pmecr | PMECR_WKEVT_LINK);
}
/* this should be the last in IRQ handler*/
ks_restore_cmd_reg(ks);
return IRQ_HANDLED;
}
/**
* ks_net_open - open network device
* @netdev: The network device being opened.
*
* Called when the network device is marked active, such as a user executing
* 'ifconfig up' on the device.
*/
static int ks_net_open(struct net_device *netdev)
{
struct ks_net *ks = netdev_priv(netdev);
int err;
#define KS_INT_FLAGS (IRQF_DISABLED|IRQF_TRIGGER_LOW)
/* lock the card, even if we may not actually do anything
* else at the moment.
*/
netif_dbg(ks, ifup, ks->netdev, "%s - entry\n", __func__);
/* reset the HW */
err = request_irq(netdev->irq, ks_irq, KS_INT_FLAGS, DRV_NAME, netdev);
if (err) {
pr_err("Failed to request IRQ: %d: %d\n", netdev->irq, err);
return err;
}
/* wake up powermode to normal mode */
ks_set_powermode(ks, PMECR_PM_NORMAL);
mdelay(1); /* wait for normal mode to take effect */
ks_wrreg16(ks, KS_ISR, 0xffff);
ks_enable_int(ks);
ks_enable_qmu(ks);
netif_start_queue(ks->netdev);
netif_dbg(ks, ifup, ks->netdev, "network device up\n");
return 0;
}
/**
* ks_net_stop - close network device
* @netdev: The device being closed.
*
* Called to close down a network device which has been active. Cancell any
* work, shutdown the RX and TX process and then place the chip into a low
* power state whilst it is not being used.
*/
static int ks_net_stop(struct net_device *netdev)
{
struct ks_net *ks = netdev_priv(netdev);
netif_info(ks, ifdown, netdev, "shutting down\n");
netif_stop_queue(netdev);
mutex_lock(&ks->lock);
/* turn off the IRQs and ack any outstanding */
ks_wrreg16(ks, KS_IER, 0x0000);
ks_wrreg16(ks, KS_ISR, 0xffff);
/* shutdown RX/TX QMU */
ks_disable_qmu(ks);
/* set powermode to soft power down to save power */
ks_set_powermode(ks, PMECR_PM_SOFTDOWN);
free_irq(netdev->irq, netdev);
mutex_unlock(&ks->lock);
return 0;
}
/**
* ks_write_qmu - write 1 pkt data to the QMU.
* @ks: The chip information
* @pdata: buffer address to save 1 pkt
* @len: Pkt length in byte
* Here is the sequence to write 1 pkt:
* 1. set sudo DMA mode
* 2. write status/length
* 3. write pkt data
* 4. reset sudo DMA Mode
* 5. reset sudo DMA mode
* 6. Wait until pkt is out
*/
static void ks_write_qmu(struct ks_net *ks, u8 *pdata, u16 len)
{
/* start header at txb[0] to align txw entries */
ks->txh.txw[0] = 0;
ks->txh.txw[1] = cpu_to_le16(len);
/* 1. set sudo-DMA mode */
ks_wrreg8(ks, KS_RXQCR, (ks->rc_rxqcr | RXQCR_SDA) & 0xff);
/* 2. write status/lenth info */
ks_outblk(ks, ks->txh.txw, 4);
/* 3. write pkt data */
ks_outblk(ks, (u16 *)pdata, ALIGN(len, 4));
/* 4. reset sudo-DMA mode */
ks_wrreg8(ks, KS_RXQCR, ks->rc_rxqcr);
/* 5. Enqueue Tx(move the pkt from TX buffer into TXQ) */
ks_wrreg16(ks, KS_TXQCR, TXQCR_METFE);
/* 6. wait until TXQCR_METFE is auto-cleared */
while (ks_rdreg16(ks, KS_TXQCR) & TXQCR_METFE)
;
}
/**
* ks_start_xmit - transmit packet
* @skb : The buffer to transmit
* @netdev : The device used to transmit the packet.
*
* Called by the network layer to transmit the @skb.
* spin_lock_irqsave is required because tx and rx should be mutual exclusive.
* So while tx is in-progress, prevent IRQ interrupt from happenning.
*/
static int ks_start_xmit(struct sk_buff *skb, struct net_device *netdev)
{
int retv = NETDEV_TX_OK;
struct ks_net *ks = netdev_priv(netdev);
disable_irq(netdev->irq);
ks_disable_int(ks);
spin_lock(&ks->statelock);
/* Extra space are required:
* 4 byte for alignment, 4 for status/length, 4 for CRC
*/
if (likely(ks_tx_fifo_space(ks) >= skb->len + 12)) {
ks_write_qmu(ks, skb->data, skb->len);
dev_kfree_skb(skb);
} else
retv = NETDEV_TX_BUSY;
spin_unlock(&ks->statelock);
ks_enable_int(ks);
enable_irq(netdev->irq);
return retv;
}
/**
* ks_start_rx - ready to serve pkts
* @ks : The chip information
*
*/
static void ks_start_rx(struct ks_net *ks)
{
u16 cntl;
/* Enables QMU Receive (RXCR1). */
cntl = ks_rdreg16(ks, KS_RXCR1);
cntl |= RXCR1_RXE ;
ks_wrreg16(ks, KS_RXCR1, cntl);
} /* ks_start_rx */
/**
* ks_stop_rx - stop to serve pkts
* @ks : The chip information
*
*/
static void ks_stop_rx(struct ks_net *ks)
{
u16 cntl;
/* Disables QMU Receive (RXCR1). */
cntl = ks_rdreg16(ks, KS_RXCR1);
cntl &= ~RXCR1_RXE ;
ks_wrreg16(ks, KS_RXCR1, cntl);
} /* ks_stop_rx */
static unsigned long const ethernet_polynomial = 0x04c11db7U;
static unsigned long ether_gen_crc(int length, u8 *data)
{
long crc = -1;
while (--length >= 0) {
u8 current_octet = *data++;
int bit;
for (bit = 0; bit < 8; bit++, current_octet >>= 1) {
crc = (crc << 1) ^
((crc < 0) ^ (current_octet & 1) ?
ethernet_polynomial : 0);
}
}
return (unsigned long)crc;
} /* ether_gen_crc */
/**
* ks_set_grpaddr - set multicast information
* @ks : The chip information
*/
static void ks_set_grpaddr(struct ks_net *ks)
{
u8 i;
u32 index, position, value;
memset(ks->mcast_bits, 0, sizeof(u8) * HW_MCAST_SIZE);
for (i = 0; i < ks->mcast_lst_size; i++) {
position = (ether_gen_crc(6, ks->mcast_lst[i]) >> 26) & 0x3f;
index = position >> 3;
value = 1 << (position & 7);
ks->mcast_bits[index] |= (u8)value;
}
for (i = 0; i < HW_MCAST_SIZE; i++) {
if (i & 1) {
ks_wrreg16(ks, (u16)((KS_MAHTR0 + i) & ~1),
(ks->mcast_bits[i] << 8) |
ks->mcast_bits[i - 1]);
}
}
} /* ks_set_grpaddr */
/*
* ks_clear_mcast - clear multicast information
*
* @ks : The chip information
* This routine removes all mcast addresses set in the hardware.
*/
static void ks_clear_mcast(struct ks_net *ks)
{
u16 i, mcast_size;
for (i = 0; i < HW_MCAST_SIZE; i++)
ks->mcast_bits[i] = 0;
mcast_size = HW_MCAST_SIZE >> 2;
for (i = 0; i < mcast_size; i++)
ks_wrreg16(ks, KS_MAHTR0 + (2*i), 0);
}
static void ks_set_promis(struct ks_net *ks, u16 promiscuous_mode)
{
u16 cntl;
ks->promiscuous = promiscuous_mode;
ks_stop_rx(ks); /* Stop receiving for reconfiguration */
cntl = ks_rdreg16(ks, KS_RXCR1);
cntl &= ~RXCR1_FILTER_MASK;
if (promiscuous_mode)
/* Enable Promiscuous mode */
cntl |= RXCR1_RXAE | RXCR1_RXINVF;
else
/* Disable Promiscuous mode (default normal mode) */
cntl |= RXCR1_RXPAFMA;
ks_wrreg16(ks, KS_RXCR1, cntl);
if (ks->enabled)
ks_start_rx(ks);
} /* ks_set_promis */
static void ks_set_mcast(struct ks_net *ks, u16 mcast)
{
u16 cntl;
ks->all_mcast = mcast;
ks_stop_rx(ks); /* Stop receiving for reconfiguration */
cntl = ks_rdreg16(ks, KS_RXCR1);
cntl &= ~RXCR1_FILTER_MASK;
if (mcast)
/* Enable "Perfect with Multicast address passed mode" */
cntl |= (RXCR1_RXAE | RXCR1_RXMAFMA | RXCR1_RXPAFMA);
else
/**
* Disable "Perfect with Multicast address passed
* mode" (normal mode).
*/
cntl |= RXCR1_RXPAFMA;
ks_wrreg16(ks, KS_RXCR1, cntl);
if (ks->enabled)
ks_start_rx(ks);
} /* ks_set_mcast */
static void ks_set_rx_mode(struct net_device *netdev)
{
struct ks_net *ks = netdev_priv(netdev);
struct netdev_hw_addr *ha;
/* Turn on/off promiscuous mode. */
if ((netdev->flags & IFF_PROMISC) == IFF_PROMISC)
ks_set_promis(ks,
(u16)((netdev->flags & IFF_PROMISC) == IFF_PROMISC));
/* Turn on/off all mcast mode. */
else if ((netdev->flags & IFF_ALLMULTI) == IFF_ALLMULTI)
ks_set_mcast(ks,
(u16)((netdev->flags & IFF_ALLMULTI) == IFF_ALLMULTI));
else
ks_set_promis(ks, false);
if ((netdev->flags & IFF_MULTICAST) && netdev_mc_count(netdev)) {
if (netdev_mc_count(netdev) <= MAX_MCAST_LST) {
int i = 0;
netdev_for_each_mc_addr(ha, netdev) {
if (i >= MAX_MCAST_LST)
break;
memcpy(ks->mcast_lst[i++], ha->addr, ETH_ALEN);
}
ks->mcast_lst_size = (u8)i;
ks_set_grpaddr(ks);
} else {
/**
* List too big to support so
* turn on all mcast mode.
*/
ks->mcast_lst_size = MAX_MCAST_LST;
ks_set_mcast(ks, true);
}
} else {
ks->mcast_lst_size = 0;
ks_clear_mcast(ks);
}
} /* ks_set_rx_mode */
static void ks_set_mac(struct ks_net *ks, u8 *data)
{
u16 *pw = (u16 *)data;
u16 w, u;
ks_stop_rx(ks); /* Stop receiving for reconfiguration */
u = *pw++;
w = ((u & 0xFF) << 8) | ((u >> 8) & 0xFF);
ks_wrreg16(ks, KS_MARH, w);
u = *pw++;
w = ((u & 0xFF) << 8) | ((u >> 8) & 0xFF);
ks_wrreg16(ks, KS_MARM, w);
u = *pw;
w = ((u & 0xFF) << 8) | ((u >> 8) & 0xFF);
ks_wrreg16(ks, KS_MARL, w);
memcpy(ks->mac_addr, data, 6);
if (ks->enabled)
ks_start_rx(ks);
}
static int ks_set_mac_address(struct net_device *netdev, void *paddr)
{
struct ks_net *ks = netdev_priv(netdev);
struct sockaddr *addr = paddr;
u8 *da;
netdev->addr_assign_type &= ~NET_ADDR_RANDOM;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
da = (u8 *)netdev->dev_addr;
ks_set_mac(ks, da);
return 0;
}
static int ks_net_ioctl(struct net_device *netdev, struct ifreq *req, int cmd)
{
struct ks_net *ks = netdev_priv(netdev);
if (!netif_running(netdev))
return -EINVAL;
return generic_mii_ioctl(&ks->mii, if_mii(req), cmd, NULL);
}
static const struct net_device_ops ks_netdev_ops = {
.ndo_open = ks_net_open,
.ndo_stop = ks_net_stop,
.ndo_do_ioctl = ks_net_ioctl,
.ndo_start_xmit = ks_start_xmit,
.ndo_set_mac_address = ks_set_mac_address,
.ndo_set_rx_mode = ks_set_rx_mode,
.ndo_change_mtu = eth_change_mtu,
.ndo_validate_addr = eth_validate_addr,
};
/* ethtool support */
static void ks_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *di)
{
strlcpy(di->driver, DRV_NAME, sizeof(di->driver));
strlcpy(di->version, "1.00", sizeof(di->version));
strlcpy(di->bus_info, dev_name(netdev->dev.parent),
sizeof(di->bus_info));
}
static u32 ks_get_msglevel(struct net_device *netdev)
{
struct ks_net *ks = netdev_priv(netdev);
return ks->msg_enable;
}
static void ks_set_msglevel(struct net_device *netdev, u32 to)
{
struct ks_net *ks = netdev_priv(netdev);
ks->msg_enable = to;
}
static int ks_get_settings(struct net_device *netdev, struct ethtool_cmd *cmd)
{
struct ks_net *ks = netdev_priv(netdev);
return mii_ethtool_gset(&ks->mii, cmd);
}
static int ks_set_settings(struct net_device *netdev, struct ethtool_cmd *cmd)
{
struct ks_net *ks = netdev_priv(netdev);
return mii_ethtool_sset(&ks->mii, cmd);
}
static u32 ks_get_link(struct net_device *netdev)
{
struct ks_net *ks = netdev_priv(netdev);
return mii_link_ok(&ks->mii);
}
static int ks_nway_reset(struct net_device *netdev)
{
struct ks_net *ks = netdev_priv(netdev);
return mii_nway_restart(&ks->mii);
}
static const struct ethtool_ops ks_ethtool_ops = {
.get_drvinfo = ks_get_drvinfo,
.get_msglevel = ks_get_msglevel,
.set_msglevel = ks_set_msglevel,
.get_settings = ks_get_settings,
.set_settings = ks_set_settings,
.get_link = ks_get_link,
.nway_reset = ks_nway_reset,
};
/* MII interface controls */
/**
* ks_phy_reg - convert MII register into a KS8851 register
* @reg: MII register number.
*
* Return the KS8851 register number for the corresponding MII PHY register
* if possible. Return zero if the MII register has no direct mapping to the
* KS8851 register set.
*/
static int ks_phy_reg(int reg)
{
switch (reg) {
case MII_BMCR:
return KS_P1MBCR;
case MII_BMSR:
return KS_P1MBSR;
case MII_PHYSID1:
return KS_PHY1ILR;
case MII_PHYSID2:
return KS_PHY1IHR;
case MII_ADVERTISE:
return KS_P1ANAR;
case MII_LPA:
return KS_P1ANLPR;
}
return 0x0;
}
/**
* ks_phy_read - MII interface PHY register read.
* @netdev: The network device the PHY is on.
* @phy_addr: Address of PHY (ignored as we only have one)
* @reg: The register to read.
*
* This call reads data from the PHY register specified in @reg. Since the
* device does not support all the MII registers, the non-existent values
* are always returned as zero.
*
* We return zero for unsupported registers as the MII code does not check
* the value returned for any error status, and simply returns it to the
* caller. The mii-tool that the driver was tested with takes any -ve error
* as real PHY capabilities, thus displaying incorrect data to the user.
*/
static int ks_phy_read(struct net_device *netdev, int phy_addr, int reg)
{
struct ks_net *ks = netdev_priv(netdev);
int ksreg;
int result;
ksreg = ks_phy_reg(reg);
if (!ksreg)
return 0x0; /* no error return allowed, so use zero */
mutex_lock(&ks->lock);
result = ks_rdreg16(ks, ksreg);
mutex_unlock(&ks->lock);
return result;
}
static void ks_phy_write(struct net_device *netdev,
int phy, int reg, int value)
{
struct ks_net *ks = netdev_priv(netdev);
int ksreg;
ksreg = ks_phy_reg(reg);
if (ksreg) {
mutex_lock(&ks->lock);
ks_wrreg16(ks, ksreg, value);
mutex_unlock(&ks->lock);
}
}
/**
* ks_read_selftest - read the selftest memory info.
* @ks: The device state
*
* Read and check the TX/RX memory selftest information.
*/
static int ks_read_selftest(struct ks_net *ks)
{
unsigned both_done = MBIR_TXMBF | MBIR_RXMBF;
int ret = 0;
unsigned rd;
rd = ks_rdreg16(ks, KS_MBIR);
if ((rd & both_done) != both_done) {
netdev_warn(ks->netdev, "Memory selftest not finished\n");
return 0;
}
if (rd & MBIR_TXMBFA) {
netdev_err(ks->netdev, "TX memory selftest fails\n");
ret |= 1;
}
if (rd & MBIR_RXMBFA) {
netdev_err(ks->netdev, "RX memory selftest fails\n");
ret |= 2;
}
netdev_info(ks->netdev, "the selftest passes\n");
return ret;
}
static void ks_setup(struct ks_net *ks)
{
u16 w;
/**
* Configure QMU Transmit
*/
/* Setup Transmit Frame Data Pointer Auto-Increment (TXFDPR) */
ks_wrreg16(ks, KS_TXFDPR, TXFDPR_TXFPAI);
/* Setup Receive Frame Data Pointer Auto-Increment */
ks_wrreg16(ks, KS_RXFDPR, RXFDPR_RXFPAI);
/* Setup Receive Frame Threshold - 1 frame (RXFCTFC) */
ks_wrreg16(ks, KS_RXFCTR, 1 & RXFCTR_THRESHOLD_MASK);
/* Setup RxQ Command Control (RXQCR) */
ks->rc_rxqcr = RXQCR_CMD_CNTL;
ks_wrreg16(ks, KS_RXQCR, ks->rc_rxqcr);
/**
* set the force mode to half duplex, default is full duplex
* because if the auto-negotiation fails, most switch uses
* half-duplex.
*/
w = ks_rdreg16(ks, KS_P1MBCR);
w &= ~P1MBCR_FORCE_FDX;
ks_wrreg16(ks, KS_P1MBCR, w);
w = TXCR_TXFCE | TXCR_TXPE | TXCR_TXCRC | TXCR_TCGIP;
ks_wrreg16(ks, KS_TXCR, w);
w = RXCR1_RXFCE | RXCR1_RXBE | RXCR1_RXUE | RXCR1_RXME | RXCR1_RXIPFCC;
if (ks->promiscuous) /* bPromiscuous */
w |= (RXCR1_RXAE | RXCR1_RXINVF);
else if (ks->all_mcast) /* Multicast address passed mode */
w |= (RXCR1_RXAE | RXCR1_RXMAFMA | RXCR1_RXPAFMA);
else /* Normal mode */
w |= RXCR1_RXPAFMA;
ks_wrreg16(ks, KS_RXCR1, w);
} /*ks_setup */
static void ks_setup_int(struct ks_net *ks)
{
ks->rc_ier = 0x00;
/* Clear the interrupts status of the hardware. */
ks_wrreg16(ks, KS_ISR, 0xffff);
/* Enables the interrupts of the hardware. */
ks->rc_ier = (IRQ_LCI | IRQ_TXI | IRQ_RXI);
} /* ks_setup_int */
static int ks_hw_init(struct ks_net *ks)
{
#define MHEADER_SIZE (sizeof(struct type_frame_head) * MAX_RECV_FRAMES)
ks->promiscuous = 0;
ks->all_mcast = 0;
ks->mcast_lst_size = 0;
ks->frame_head_info = kmalloc(MHEADER_SIZE, GFP_KERNEL);
if (!ks->frame_head_info)
return false;
ks_set_mac(ks, KS_DEFAULT_MAC_ADDRESS);
return true;
}
static int __devinit ks8851_probe(struct platform_device *pdev)
{
int err = -ENOMEM;
struct resource *io_d, *io_c;
struct net_device *netdev;
struct ks_net *ks;
u16 id, data;
io_d = platform_get_resource(pdev, IORESOURCE_MEM, 0);
io_c = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!request_mem_region(io_d->start, resource_size(io_d), DRV_NAME))
goto err_mem_region;
if (!request_mem_region(io_c->start, resource_size(io_c), DRV_NAME))
goto err_mem_region1;
netdev = alloc_etherdev(sizeof(struct ks_net));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
ks = netdev_priv(netdev);
ks->netdev = netdev;
ks->hw_addr = ioremap(io_d->start, resource_size(io_d));
if (!ks->hw_addr)
goto err_ioremap;
ks->hw_addr_cmd = ioremap(io_c->start, resource_size(io_c));
if (!ks->hw_addr_cmd)
goto err_ioremap1;
netdev->irq = platform_get_irq(pdev, 0);
if ((int)netdev->irq < 0) {
err = netdev->irq;
goto err_get_irq;
}
ks->pdev = pdev;
mutex_init(&ks->lock);
spin_lock_init(&ks->statelock);
netdev->netdev_ops = &ks_netdev_ops;
netdev->ethtool_ops = &ks_ethtool_ops;
/* setup mii state */
ks->mii.dev = netdev;
ks->mii.phy_id = 1,
ks->mii.phy_id_mask = 1;
ks->mii.reg_num_mask = 0xf;
ks->mii.mdio_read = ks_phy_read;
ks->mii.mdio_write = ks_phy_write;
netdev_info(netdev, "message enable is %d\n", msg_enable);
/* set the default message enable */
ks->msg_enable = netif_msg_init(msg_enable, (NETIF_MSG_DRV |
NETIF_MSG_PROBE |
NETIF_MSG_LINK));
ks_read_config(ks);
/* simple check for a valid chip being connected to the bus */
if ((ks_rdreg16(ks, KS_CIDER) & ~CIDER_REV_MASK) != CIDER_ID) {
netdev_err(netdev, "failed to read device ID\n");
err = -ENODEV;
goto err_register;
}
if (ks_read_selftest(ks)) {
netdev_err(netdev, "failed to read device ID\n");
err = -ENODEV;
goto err_register;
}
err = register_netdev(netdev);
if (err)
goto err_register;
platform_set_drvdata(pdev, netdev);
ks_soft_reset(ks, GRR_GSR);
ks_hw_init(ks);
ks_disable_qmu(ks);
ks_setup(ks);
ks_setup_int(ks);
memcpy(netdev->dev_addr, ks->mac_addr, 6);
data = ks_rdreg16(ks, KS_OBCR);
ks_wrreg16(ks, KS_OBCR, data | OBCR_ODS_16MA);
/**
* If you want to use the default MAC addr,
* comment out the 2 functions below.
*/
random_ether_addr(netdev->dev_addr);
ks_set_mac(ks, netdev->dev_addr);
id = ks_rdreg16(ks, KS_CIDER);
netdev_info(netdev, "Found chip, family: 0x%x, id: 0x%x, rev: 0x%x\n",
(id >> 8) & 0xff, (id >> 4) & 0xf, (id >> 1) & 0x7);
return 0;
err_register:
err_get_irq:
iounmap(ks->hw_addr_cmd);
err_ioremap1:
iounmap(ks->hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
release_mem_region(io_c->start, resource_size(io_c));
err_mem_region1:
release_mem_region(io_d->start, resource_size(io_d));
err_mem_region:
return err;
}
static int __devexit ks8851_remove(struct platform_device *pdev)
{
struct net_device *netdev = platform_get_drvdata(pdev);
struct ks_net *ks = netdev_priv(netdev);
struct resource *iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
kfree(ks->frame_head_info);
unregister_netdev(netdev);
iounmap(ks->hw_addr);
free_netdev(netdev);
release_mem_region(iomem->start, resource_size(iomem));
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver ks8851_platform_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = ks8851_probe,
.remove = __devexit_p(ks8851_remove),
};
module_platform_driver(ks8851_platform_driver);
MODULE_DESCRIPTION("KS8851 MLL Network driver");
MODULE_AUTHOR("David Choi <david.choi@micrel.com>");
MODULE_LICENSE("GPL");
module_param_named(message, msg_enable, int, 0);
MODULE_PARM_DESC(message, "Message verbosity level (0=none, 31=all)");
| gpl-2.0 |
dsb9938/Rezound-ICS-Kernel-Old | net/ax25/ax25_std_timer.c | 5086 | 4335 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Copyright (C) Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk)
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
* Copyright (C) Joerg Reuter DL1BKE (jreuter@yaina.de)
* Copyright (C) Frederic Rible F1OAT (frible@teaser.fr)
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
void ax25_std_heartbeat_expiry(ax25_cb *ax25)
{
struct sock *sk = ax25->sk;
if (sk)
bh_lock_sock(sk);
switch (ax25->state) {
case AX25_STATE_0:
/* Magic here: If we listen() and a new link dies before it
is accepted() it isn't 'dead' so doesn't get removed. */
if (!sk || sock_flag(sk, SOCK_DESTROY) ||
(sk->sk_state == TCP_LISTEN &&
sock_flag(sk, SOCK_DEAD))) {
if (sk) {
sock_hold(sk);
ax25_destroy_socket(ax25);
bh_unlock_sock(sk);
sock_put(sk);
} else
ax25_destroy_socket(ax25);
return;
}
break;
case AX25_STATE_3:
case AX25_STATE_4:
/*
* Check the state of the receive buffer.
*/
if (sk != NULL) {
if (atomic_read(&sk->sk_rmem_alloc) <
(sk->sk_rcvbuf >> 1) &&
(ax25->condition & AX25_COND_OWN_RX_BUSY)) {
ax25->condition &= ~AX25_COND_OWN_RX_BUSY;
ax25->condition &= ~AX25_COND_ACK_PENDING;
ax25_send_control(ax25, AX25_RR, AX25_POLLOFF, AX25_RESPONSE);
break;
}
}
}
if (sk)
bh_unlock_sock(sk);
ax25_start_heartbeat(ax25);
}
void ax25_std_t2timer_expiry(ax25_cb *ax25)
{
if (ax25->condition & AX25_COND_ACK_PENDING) {
ax25->condition &= ~AX25_COND_ACK_PENDING;
ax25_std_timeout_response(ax25);
}
}
void ax25_std_t3timer_expiry(ax25_cb *ax25)
{
ax25->n2count = 0;
ax25_std_transmit_enquiry(ax25);
ax25->state = AX25_STATE_4;
}
void ax25_std_idletimer_expiry(ax25_cb *ax25)
{
ax25_clear_queues(ax25);
ax25->n2count = 0;
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
ax25->state = AX25_STATE_2;
ax25_calculate_t1(ax25);
ax25_start_t1timer(ax25);
ax25_stop_t2timer(ax25);
ax25_stop_t3timer(ax25);
if (ax25->sk != NULL) {
bh_lock_sock(ax25->sk);
ax25->sk->sk_state = TCP_CLOSE;
ax25->sk->sk_err = 0;
ax25->sk->sk_shutdown |= SEND_SHUTDOWN;
if (!sock_flag(ax25->sk, SOCK_DEAD)) {
ax25->sk->sk_state_change(ax25->sk);
sock_set_flag(ax25->sk, SOCK_DEAD);
}
bh_unlock_sock(ax25->sk);
}
}
void ax25_std_t1timer_expiry(ax25_cb *ax25)
{
switch (ax25->state) {
case AX25_STATE_1:
if (ax25->n2count == ax25->n2) {
if (ax25->modulus == AX25_MODULUS) {
ax25_disconnect(ax25, ETIMEDOUT);
return;
} else {
ax25->modulus = AX25_MODULUS;
ax25->window = ax25->ax25_dev->values[AX25_VALUES_WINDOW];
ax25->n2count = 0;
ax25_send_control(ax25, AX25_SABM, AX25_POLLON, AX25_COMMAND);
}
} else {
ax25->n2count++;
if (ax25->modulus == AX25_MODULUS)
ax25_send_control(ax25, AX25_SABM, AX25_POLLON, AX25_COMMAND);
else
ax25_send_control(ax25, AX25_SABME, AX25_POLLON, AX25_COMMAND);
}
break;
case AX25_STATE_2:
if (ax25->n2count == ax25->n2) {
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
ax25_disconnect(ax25, ETIMEDOUT);
return;
} else {
ax25->n2count++;
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
}
break;
case AX25_STATE_3:
ax25->n2count = 1;
ax25_std_transmit_enquiry(ax25);
ax25->state = AX25_STATE_4;
break;
case AX25_STATE_4:
if (ax25->n2count == ax25->n2) {
ax25_send_control(ax25, AX25_DM, AX25_POLLON, AX25_RESPONSE);
ax25_disconnect(ax25, ETIMEDOUT);
return;
} else {
ax25->n2count++;
ax25_std_transmit_enquiry(ax25);
}
break;
}
ax25_calculate_t1(ax25);
ax25_start_t1timer(ax25);
}
| gpl-2.0 |
hiikezoe/android_kernel_stm_st3200 | arch/arm/kernel/kprobes-thumb.c | 5086 | 48287 | /*
* arch/arm/kernel/kprobes-thumb.c
*
* Copyright (C) 2011 Jon Medhurst <tixy@yxit.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.
*/
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/module.h>
#include "kprobes.h"
/*
* True if current instruction is in an IT block.
*/
#define in_it_block(cpsr) ((cpsr & 0x06000c00) != 0x00000000)
/*
* Return the condition code to check for the currently executing instruction.
* This is in ITSTATE<7:4> which is in CPSR<15:12> but is only valid if
* in_it_block returns true.
*/
#define current_cond(cpsr) ((cpsr >> 12) & 0xf)
/*
* Return the PC value for a probe in thumb code.
* This is the address of the probed instruction plus 4.
* We subtract one because the address will have bit zero set to indicate
* a pointer to thumb code.
*/
static inline unsigned long __kprobes thumb_probe_pc(struct kprobe *p)
{
return (unsigned long)p->addr - 1 + 4;
}
static void __kprobes
t32_simulate_table_branch(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long pc = thumb_probe_pc(p);
int rn = (insn >> 16) & 0xf;
int rm = insn & 0xf;
unsigned long rnv = (rn == 15) ? pc : regs->uregs[rn];
unsigned long rmv = regs->uregs[rm];
unsigned int halfwords;
if (insn & 0x10) /* TBH */
halfwords = ((u16 *)rnv)[rmv];
else /* TBB */
halfwords = ((u8 *)rnv)[rmv];
regs->ARM_pc = pc + 2 * halfwords;
}
static void __kprobes
t32_simulate_mrs(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
int rd = (insn >> 8) & 0xf;
unsigned long mask = 0xf8ff03df; /* Mask out execution state */
regs->uregs[rd] = regs->ARM_cpsr & mask;
}
static void __kprobes
t32_simulate_cond_branch(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long pc = thumb_probe_pc(p);
long offset = insn & 0x7ff; /* imm11 */
offset += (insn & 0x003f0000) >> 5; /* imm6 */
offset += (insn & 0x00002000) << 4; /* J1 */
offset += (insn & 0x00000800) << 7; /* J2 */
offset -= (insn & 0x04000000) >> 7; /* Apply sign bit */
regs->ARM_pc = pc + (offset * 2);
}
static enum kprobe_insn __kprobes
t32_decode_cond_branch(kprobe_opcode_t insn, struct arch_specific_insn *asi)
{
int cc = (insn >> 22) & 0xf;
asi->insn_check_cc = kprobe_condition_checks[cc];
asi->insn_handler = t32_simulate_cond_branch;
return INSN_GOOD_NO_SLOT;
}
static void __kprobes
t32_simulate_branch(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long pc = thumb_probe_pc(p);
long offset = insn & 0x7ff; /* imm11 */
offset += (insn & 0x03ff0000) >> 5; /* imm10 */
offset += (insn & 0x00002000) << 9; /* J1 */
offset += (insn & 0x00000800) << 10; /* J2 */
if (insn & 0x04000000)
offset -= 0x00800000; /* Apply sign bit */
else
offset ^= 0x00600000; /* Invert J1 and J2 */
if (insn & (1 << 14)) {
/* BL or BLX */
regs->ARM_lr = (unsigned long)p->addr + 4;
if (!(insn & (1 << 12))) {
/* BLX so switch to ARM mode */
regs->ARM_cpsr &= ~PSR_T_BIT;
pc &= ~3;
}
}
regs->ARM_pc = pc + (offset * 2);
}
static void __kprobes
t32_simulate_ldr_literal(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long addr = thumb_probe_pc(p) & ~3;
int rt = (insn >> 12) & 0xf;
unsigned long rtv;
long offset = insn & 0xfff;
if (insn & 0x00800000)
addr += offset;
else
addr -= offset;
if (insn & 0x00400000) {
/* LDR */
rtv = *(unsigned long *)addr;
if (rt == 15) {
bx_write_pc(rtv, regs);
return;
}
} else if (insn & 0x00200000) {
/* LDRH */
if (insn & 0x01000000)
rtv = *(s16 *)addr;
else
rtv = *(u16 *)addr;
} else {
/* LDRB */
if (insn & 0x01000000)
rtv = *(s8 *)addr;
else
rtv = *(u8 *)addr;
}
regs->uregs[rt] = rtv;
}
static enum kprobe_insn __kprobes
t32_decode_ldmstm(kprobe_opcode_t insn, struct arch_specific_insn *asi)
{
enum kprobe_insn ret = kprobe_decode_ldmstm(insn, asi);
/* Fixup modified instruction to have halfwords in correct order...*/
insn = asi->insn[0];
((u16 *)asi->insn)[0] = insn >> 16;
((u16 *)asi->insn)[1] = insn & 0xffff;
return ret;
}
static void __kprobes
t32_emulate_ldrdstrd(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long pc = thumb_probe_pc(p) & ~3;
int rt1 = (insn >> 12) & 0xf;
int rt2 = (insn >> 8) & 0xf;
int rn = (insn >> 16) & 0xf;
register unsigned long rt1v asm("r0") = regs->uregs[rt1];
register unsigned long rt2v asm("r1") = regs->uregs[rt2];
register unsigned long rnv asm("r2") = (rn == 15) ? pc
: regs->uregs[rn];
__asm__ __volatile__ (
"blx %[fn]"
: "=r" (rt1v), "=r" (rt2v), "=r" (rnv)
: "0" (rt1v), "1" (rt2v), "2" (rnv), [fn] "r" (p->ainsn.insn_fn)
: "lr", "memory", "cc"
);
if (rn != 15)
regs->uregs[rn] = rnv; /* Writeback base register */
regs->uregs[rt1] = rt1v;
regs->uregs[rt2] = rt2v;
}
static void __kprobes
t32_emulate_ldrstr(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
int rt = (insn >> 12) & 0xf;
int rn = (insn >> 16) & 0xf;
int rm = insn & 0xf;
register unsigned long rtv asm("r0") = regs->uregs[rt];
register unsigned long rnv asm("r2") = regs->uregs[rn];
register unsigned long rmv asm("r3") = regs->uregs[rm];
__asm__ __volatile__ (
"blx %[fn]"
: "=r" (rtv), "=r" (rnv)
: "0" (rtv), "1" (rnv), "r" (rmv), [fn] "r" (p->ainsn.insn_fn)
: "lr", "memory", "cc"
);
regs->uregs[rn] = rnv; /* Writeback base register */
if (rt == 15) /* Can't be true for a STR as they aren't allowed */
bx_write_pc(rtv, regs);
else
regs->uregs[rt] = rtv;
}
static void __kprobes
t32_emulate_rd8rn16rm0_rwflags(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
int rd = (insn >> 8) & 0xf;
int rn = (insn >> 16) & 0xf;
int rm = insn & 0xf;
register unsigned long rdv asm("r1") = regs->uregs[rd];
register unsigned long rnv asm("r2") = regs->uregs[rn];
register unsigned long rmv asm("r3") = regs->uregs[rm];
unsigned long cpsr = regs->ARM_cpsr;
__asm__ __volatile__ (
"msr cpsr_fs, %[cpsr] \n\t"
"blx %[fn] \n\t"
"mrs %[cpsr], cpsr \n\t"
: "=r" (rdv), [cpsr] "=r" (cpsr)
: "0" (rdv), "r" (rnv), "r" (rmv),
"1" (cpsr), [fn] "r" (p->ainsn.insn_fn)
: "lr", "memory", "cc"
);
regs->uregs[rd] = rdv;
regs->ARM_cpsr = (regs->ARM_cpsr & ~APSR_MASK) | (cpsr & APSR_MASK);
}
static void __kprobes
t32_emulate_rd8pc16_noflags(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long pc = thumb_probe_pc(p);
int rd = (insn >> 8) & 0xf;
register unsigned long rdv asm("r1") = regs->uregs[rd];
register unsigned long rnv asm("r2") = pc & ~3;
__asm__ __volatile__ (
"blx %[fn]"
: "=r" (rdv)
: "0" (rdv), "r" (rnv), [fn] "r" (p->ainsn.insn_fn)
: "lr", "memory", "cc"
);
regs->uregs[rd] = rdv;
}
static void __kprobes
t32_emulate_rd8rn16_noflags(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
int rd = (insn >> 8) & 0xf;
int rn = (insn >> 16) & 0xf;
register unsigned long rdv asm("r1") = regs->uregs[rd];
register unsigned long rnv asm("r2") = regs->uregs[rn];
__asm__ __volatile__ (
"blx %[fn]"
: "=r" (rdv)
: "0" (rdv), "r" (rnv), [fn] "r" (p->ainsn.insn_fn)
: "lr", "memory", "cc"
);
regs->uregs[rd] = rdv;
}
static void __kprobes
t32_emulate_rdlo12rdhi8rn16rm0_noflags(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
int rdlo = (insn >> 12) & 0xf;
int rdhi = (insn >> 8) & 0xf;
int rn = (insn >> 16) & 0xf;
int rm = insn & 0xf;
register unsigned long rdlov asm("r0") = regs->uregs[rdlo];
register unsigned long rdhiv asm("r1") = regs->uregs[rdhi];
register unsigned long rnv asm("r2") = regs->uregs[rn];
register unsigned long rmv asm("r3") = regs->uregs[rm];
__asm__ __volatile__ (
"blx %[fn]"
: "=r" (rdlov), "=r" (rdhiv)
: "0" (rdlov), "1" (rdhiv), "r" (rnv), "r" (rmv),
[fn] "r" (p->ainsn.insn_fn)
: "lr", "memory", "cc"
);
regs->uregs[rdlo] = rdlov;
regs->uregs[rdhi] = rdhiv;
}
/* These emulation encodings are functionally equivalent... */
#define t32_emulate_rd8rn16rm0ra12_noflags \
t32_emulate_rdlo12rdhi8rn16rm0_noflags
static const union decode_item t32_table_1110_100x_x0xx[] = {
/* Load/store multiple instructions */
/* Rn is PC 1110 100x x0xx 1111 xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xfe4f0000, 0xe80f0000),
/* SRS 1110 1000 00x0 xxxx xxxx xxxx xxxx xxxx */
/* RFE 1110 1000 00x1 xxxx xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xffc00000, 0xe8000000),
/* SRS 1110 1001 10x0 xxxx xxxx xxxx xxxx xxxx */
/* RFE 1110 1001 10x1 xxxx xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xffc00000, 0xe9800000),
/* STM Rn, {...pc} 1110 100x x0x0 xxxx 1xxx xxxx xxxx xxxx */
DECODE_REJECT (0xfe508000, 0xe8008000),
/* LDM Rn, {...lr,pc} 1110 100x x0x1 xxxx 11xx xxxx xxxx xxxx */
DECODE_REJECT (0xfe50c000, 0xe810c000),
/* LDM/STM Rn, {...sp} 1110 100x x0xx xxxx xx1x xxxx xxxx xxxx */
DECODE_REJECT (0xfe402000, 0xe8002000),
/* STMIA 1110 1000 10x0 xxxx xxxx xxxx xxxx xxxx */
/* LDMIA 1110 1000 10x1 xxxx xxxx xxxx xxxx xxxx */
/* STMDB 1110 1001 00x0 xxxx xxxx xxxx xxxx xxxx */
/* LDMDB 1110 1001 00x1 xxxx xxxx xxxx xxxx xxxx */
DECODE_CUSTOM (0xfe400000, 0xe8000000, t32_decode_ldmstm),
DECODE_END
};
static const union decode_item t32_table_1110_100x_x1xx[] = {
/* Load/store dual, load/store exclusive, table branch */
/* STRD (immediate) 1110 1000 x110 xxxx xxxx xxxx xxxx xxxx */
/* LDRD (immediate) 1110 1000 x111 xxxx xxxx xxxx xxxx xxxx */
DECODE_OR (0xff600000, 0xe8600000),
/* STRD (immediate) 1110 1001 x1x0 xxxx xxxx xxxx xxxx xxxx */
/* LDRD (immediate) 1110 1001 x1x1 xxxx xxxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xff400000, 0xe9400000, t32_emulate_ldrdstrd,
REGS(NOPCWB, NOSPPC, NOSPPC, 0, 0)),
/* TBB 1110 1000 1101 xxxx xxxx xxxx 0000 xxxx */
/* TBH 1110 1000 1101 xxxx xxxx xxxx 0001 xxxx */
DECODE_SIMULATEX(0xfff000e0, 0xe8d00000, t32_simulate_table_branch,
REGS(NOSP, 0, 0, 0, NOSPPC)),
/* STREX 1110 1000 0100 xxxx xxxx xxxx xxxx xxxx */
/* LDREX 1110 1000 0101 xxxx xxxx xxxx xxxx xxxx */
/* STREXB 1110 1000 1100 xxxx xxxx xxxx 0100 xxxx */
/* STREXH 1110 1000 1100 xxxx xxxx xxxx 0101 xxxx */
/* STREXD 1110 1000 1100 xxxx xxxx xxxx 0111 xxxx */
/* LDREXB 1110 1000 1101 xxxx xxxx xxxx 0100 xxxx */
/* LDREXH 1110 1000 1101 xxxx xxxx xxxx 0101 xxxx */
/* LDREXD 1110 1000 1101 xxxx xxxx xxxx 0111 xxxx */
/* And unallocated instructions... */
DECODE_END
};
static const union decode_item t32_table_1110_101x[] = {
/* Data-processing (shifted register) */
/* TST 1110 1010 0001 xxxx xxxx 1111 xxxx xxxx */
/* TEQ 1110 1010 1001 xxxx xxxx 1111 xxxx xxxx */
DECODE_EMULATEX (0xff700f00, 0xea100f00, t32_emulate_rd8rn16rm0_rwflags,
REGS(NOSPPC, 0, 0, 0, NOSPPC)),
/* CMN 1110 1011 0001 xxxx xxxx 1111 xxxx xxxx */
DECODE_OR (0xfff00f00, 0xeb100f00),
/* CMP 1110 1011 1011 xxxx xxxx 1111 xxxx xxxx */
DECODE_EMULATEX (0xfff00f00, 0xebb00f00, t32_emulate_rd8rn16rm0_rwflags,
REGS(NOPC, 0, 0, 0, NOSPPC)),
/* MOV 1110 1010 010x 1111 xxxx xxxx xxxx xxxx */
/* MVN 1110 1010 011x 1111 xxxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xffcf0000, 0xea4f0000, t32_emulate_rd8rn16rm0_rwflags,
REGS(0, 0, NOSPPC, 0, NOSPPC)),
/* ??? 1110 1010 101x xxxx xxxx xxxx xxxx xxxx */
/* ??? 1110 1010 111x xxxx xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xffa00000, 0xeaa00000),
/* ??? 1110 1011 001x xxxx xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xffe00000, 0xeb200000),
/* ??? 1110 1011 100x xxxx xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xffe00000, 0xeb800000),
/* ??? 1110 1011 111x xxxx xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xffe00000, 0xebe00000),
/* ADD/SUB SP, SP, Rm, LSL #0..3 */
/* 1110 1011 x0xx 1101 x000 1101 xx00 xxxx */
DECODE_EMULATEX (0xff4f7f30, 0xeb0d0d00, t32_emulate_rd8rn16rm0_rwflags,
REGS(SP, 0, SP, 0, NOSPPC)),
/* ADD/SUB SP, SP, Rm, shift */
/* 1110 1011 x0xx 1101 xxxx 1101 xxxx xxxx */
DECODE_REJECT (0xff4f0f00, 0xeb0d0d00),
/* ADD/SUB Rd, SP, Rm, shift */
/* 1110 1011 x0xx 1101 xxxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xff4f0000, 0xeb0d0000, t32_emulate_rd8rn16rm0_rwflags,
REGS(SP, 0, NOPC, 0, NOSPPC)),
/* AND 1110 1010 000x xxxx xxxx xxxx xxxx xxxx */
/* BIC 1110 1010 001x xxxx xxxx xxxx xxxx xxxx */
/* ORR 1110 1010 010x xxxx xxxx xxxx xxxx xxxx */
/* ORN 1110 1010 011x xxxx xxxx xxxx xxxx xxxx */
/* EOR 1110 1010 100x xxxx xxxx xxxx xxxx xxxx */
/* PKH 1110 1010 110x xxxx xxxx xxxx xxxx xxxx */
/* ADD 1110 1011 000x xxxx xxxx xxxx xxxx xxxx */
/* ADC 1110 1011 010x xxxx xxxx xxxx xxxx xxxx */
/* SBC 1110 1011 011x xxxx xxxx xxxx xxxx xxxx */
/* SUB 1110 1011 101x xxxx xxxx xxxx xxxx xxxx */
/* RSB 1110 1011 110x xxxx xxxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfe000000, 0xea000000, t32_emulate_rd8rn16rm0_rwflags,
REGS(NOSPPC, 0, NOSPPC, 0, NOSPPC)),
DECODE_END
};
static const union decode_item t32_table_1111_0x0x___0[] = {
/* Data-processing (modified immediate) */
/* TST 1111 0x00 0001 xxxx 0xxx 1111 xxxx xxxx */
/* TEQ 1111 0x00 1001 xxxx 0xxx 1111 xxxx xxxx */
DECODE_EMULATEX (0xfb708f00, 0xf0100f00, t32_emulate_rd8rn16rm0_rwflags,
REGS(NOSPPC, 0, 0, 0, 0)),
/* CMN 1111 0x01 0001 xxxx 0xxx 1111 xxxx xxxx */
DECODE_OR (0xfbf08f00, 0xf1100f00),
/* CMP 1111 0x01 1011 xxxx 0xxx 1111 xxxx xxxx */
DECODE_EMULATEX (0xfbf08f00, 0xf1b00f00, t32_emulate_rd8rn16rm0_rwflags,
REGS(NOPC, 0, 0, 0, 0)),
/* MOV 1111 0x00 010x 1111 0xxx xxxx xxxx xxxx */
/* MVN 1111 0x00 011x 1111 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfbcf8000, 0xf04f0000, t32_emulate_rd8rn16rm0_rwflags,
REGS(0, 0, NOSPPC, 0, 0)),
/* ??? 1111 0x00 101x xxxx 0xxx xxxx xxxx xxxx */
DECODE_REJECT (0xfbe08000, 0xf0a00000),
/* ??? 1111 0x00 110x xxxx 0xxx xxxx xxxx xxxx */
/* ??? 1111 0x00 111x xxxx 0xxx xxxx xxxx xxxx */
DECODE_REJECT (0xfbc08000, 0xf0c00000),
/* ??? 1111 0x01 001x xxxx 0xxx xxxx xxxx xxxx */
DECODE_REJECT (0xfbe08000, 0xf1200000),
/* ??? 1111 0x01 100x xxxx 0xxx xxxx xxxx xxxx */
DECODE_REJECT (0xfbe08000, 0xf1800000),
/* ??? 1111 0x01 111x xxxx 0xxx xxxx xxxx xxxx */
DECODE_REJECT (0xfbe08000, 0xf1e00000),
/* ADD Rd, SP, #imm 1111 0x01 000x 1101 0xxx xxxx xxxx xxxx */
/* SUB Rd, SP, #imm 1111 0x01 101x 1101 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfb4f8000, 0xf10d0000, t32_emulate_rd8rn16rm0_rwflags,
REGS(SP, 0, NOPC, 0, 0)),
/* AND 1111 0x00 000x xxxx 0xxx xxxx xxxx xxxx */
/* BIC 1111 0x00 001x xxxx 0xxx xxxx xxxx xxxx */
/* ORR 1111 0x00 010x xxxx 0xxx xxxx xxxx xxxx */
/* ORN 1111 0x00 011x xxxx 0xxx xxxx xxxx xxxx */
/* EOR 1111 0x00 100x xxxx 0xxx xxxx xxxx xxxx */
/* ADD 1111 0x01 000x xxxx 0xxx xxxx xxxx xxxx */
/* ADC 1111 0x01 010x xxxx 0xxx xxxx xxxx xxxx */
/* SBC 1111 0x01 011x xxxx 0xxx xxxx xxxx xxxx */
/* SUB 1111 0x01 101x xxxx 0xxx xxxx xxxx xxxx */
/* RSB 1111 0x01 110x xxxx 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfa008000, 0xf0000000, t32_emulate_rd8rn16rm0_rwflags,
REGS(NOSPPC, 0, NOSPPC, 0, 0)),
DECODE_END
};
static const union decode_item t32_table_1111_0x1x___0[] = {
/* Data-processing (plain binary immediate) */
/* ADDW Rd, PC, #imm 1111 0x10 0000 1111 0xxx xxxx xxxx xxxx */
DECODE_OR (0xfbff8000, 0xf20f0000),
/* SUBW Rd, PC, #imm 1111 0x10 1010 1111 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfbff8000, 0xf2af0000, t32_emulate_rd8pc16_noflags,
REGS(PC, 0, NOSPPC, 0, 0)),
/* ADDW SP, SP, #imm 1111 0x10 0000 1101 0xxx 1101 xxxx xxxx */
DECODE_OR (0xfbff8f00, 0xf20d0d00),
/* SUBW SP, SP, #imm 1111 0x10 1010 1101 0xxx 1101 xxxx xxxx */
DECODE_EMULATEX (0xfbff8f00, 0xf2ad0d00, t32_emulate_rd8rn16_noflags,
REGS(SP, 0, SP, 0, 0)),
/* ADDW 1111 0x10 0000 xxxx 0xxx xxxx xxxx xxxx */
DECODE_OR (0xfbf08000, 0xf2000000),
/* SUBW 1111 0x10 1010 xxxx 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfbf08000, 0xf2a00000, t32_emulate_rd8rn16_noflags,
REGS(NOPCX, 0, NOSPPC, 0, 0)),
/* MOVW 1111 0x10 0100 xxxx 0xxx xxxx xxxx xxxx */
/* MOVT 1111 0x10 1100 xxxx 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfb708000, 0xf2400000, t32_emulate_rd8rn16_noflags,
REGS(0, 0, NOSPPC, 0, 0)),
/* SSAT16 1111 0x11 0010 xxxx 0000 xxxx 00xx xxxx */
/* SSAT 1111 0x11 00x0 xxxx 0xxx xxxx xxxx xxxx */
/* USAT16 1111 0x11 1010 xxxx 0000 xxxx 00xx xxxx */
/* USAT 1111 0x11 10x0 xxxx 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfb508000, 0xf3000000, t32_emulate_rd8rn16rm0_rwflags,
REGS(NOSPPC, 0, NOSPPC, 0, 0)),
/* SFBX 1111 0x11 0100 xxxx 0xxx xxxx xxxx xxxx */
/* UFBX 1111 0x11 1100 xxxx 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfb708000, 0xf3400000, t32_emulate_rd8rn16_noflags,
REGS(NOSPPC, 0, NOSPPC, 0, 0)),
/* BFC 1111 0x11 0110 1111 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfbff8000, 0xf36f0000, t32_emulate_rd8rn16_noflags,
REGS(0, 0, NOSPPC, 0, 0)),
/* BFI 1111 0x11 0110 xxxx 0xxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfbf08000, 0xf3600000, t32_emulate_rd8rn16_noflags,
REGS(NOSPPCX, 0, NOSPPC, 0, 0)),
DECODE_END
};
static const union decode_item t32_table_1111_0xxx___1[] = {
/* Branches and miscellaneous control */
/* YIELD 1111 0011 1010 xxxx 10x0 x000 0000 0001 */
DECODE_OR (0xfff0d7ff, 0xf3a08001),
/* SEV 1111 0011 1010 xxxx 10x0 x000 0000 0100 */
DECODE_EMULATE (0xfff0d7ff, 0xf3a08004, kprobe_emulate_none),
/* NOP 1111 0011 1010 xxxx 10x0 x000 0000 0000 */
/* WFE 1111 0011 1010 xxxx 10x0 x000 0000 0010 */
/* WFI 1111 0011 1010 xxxx 10x0 x000 0000 0011 */
DECODE_SIMULATE (0xfff0d7fc, 0xf3a08000, kprobe_simulate_nop),
/* MRS Rd, CPSR 1111 0011 1110 xxxx 10x0 xxxx xxxx xxxx */
DECODE_SIMULATEX(0xfff0d000, 0xf3e08000, t32_simulate_mrs,
REGS(0, 0, NOSPPC, 0, 0)),
/*
* Unsupported instructions
* 1111 0x11 1xxx xxxx 10x0 xxxx xxxx xxxx
*
* MSR 1111 0011 100x xxxx 10x0 xxxx xxxx xxxx
* DBG hint 1111 0011 1010 xxxx 10x0 x000 1111 xxxx
* Unallocated hints 1111 0011 1010 xxxx 10x0 x000 xxxx xxxx
* CPS 1111 0011 1010 xxxx 10x0 xxxx xxxx xxxx
* CLREX/DSB/DMB/ISB 1111 0011 1011 xxxx 10x0 xxxx xxxx xxxx
* BXJ 1111 0011 1100 xxxx 10x0 xxxx xxxx xxxx
* SUBS PC,LR,#<imm8> 1111 0011 1101 xxxx 10x0 xxxx xxxx xxxx
* MRS Rd, SPSR 1111 0011 1111 xxxx 10x0 xxxx xxxx xxxx
* SMC 1111 0111 1111 xxxx 1000 xxxx xxxx xxxx
* UNDEFINED 1111 0111 1111 xxxx 1010 xxxx xxxx xxxx
* ??? 1111 0111 1xxx xxxx 1010 xxxx xxxx xxxx
*/
DECODE_REJECT (0xfb80d000, 0xf3808000),
/* Bcc 1111 0xxx xxxx xxxx 10x0 xxxx xxxx xxxx */
DECODE_CUSTOM (0xf800d000, 0xf0008000, t32_decode_cond_branch),
/* BLX 1111 0xxx xxxx xxxx 11x0 xxxx xxxx xxx0 */
DECODE_OR (0xf800d001, 0xf000c000),
/* B 1111 0xxx xxxx xxxx 10x1 xxxx xxxx xxxx */
/* BL 1111 0xxx xxxx xxxx 11x1 xxxx xxxx xxxx */
DECODE_SIMULATE (0xf8009000, 0xf0009000, t32_simulate_branch),
DECODE_END
};
static const union decode_item t32_table_1111_100x_x0x1__1111[] = {
/* Memory hints */
/* PLD (literal) 1111 1000 x001 1111 1111 xxxx xxxx xxxx */
/* PLI (literal) 1111 1001 x001 1111 1111 xxxx xxxx xxxx */
DECODE_SIMULATE (0xfe7ff000, 0xf81ff000, kprobe_simulate_nop),
/* PLD{W} (immediate) 1111 1000 10x1 xxxx 1111 xxxx xxxx xxxx */
DECODE_OR (0xffd0f000, 0xf890f000),
/* PLD{W} (immediate) 1111 1000 00x1 xxxx 1111 1100 xxxx xxxx */
DECODE_OR (0xffd0ff00, 0xf810fc00),
/* PLI (immediate) 1111 1001 1001 xxxx 1111 xxxx xxxx xxxx */
DECODE_OR (0xfff0f000, 0xf990f000),
/* PLI (immediate) 1111 1001 0001 xxxx 1111 1100 xxxx xxxx */
DECODE_SIMULATEX(0xfff0ff00, 0xf910fc00, kprobe_simulate_nop,
REGS(NOPCX, 0, 0, 0, 0)),
/* PLD{W} (register) 1111 1000 00x1 xxxx 1111 0000 00xx xxxx */
DECODE_OR (0xffd0ffc0, 0xf810f000),
/* PLI (register) 1111 1001 0001 xxxx 1111 0000 00xx xxxx */
DECODE_SIMULATEX(0xfff0ffc0, 0xf910f000, kprobe_simulate_nop,
REGS(NOPCX, 0, 0, 0, NOSPPC)),
/* Other unallocated instructions... */
DECODE_END
};
static const union decode_item t32_table_1111_100x[] = {
/* Store/Load single data item */
/* ??? 1111 100x x11x xxxx xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xfe600000, 0xf8600000),
/* ??? 1111 1001 0101 xxxx xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xfff00000, 0xf9500000),
/* ??? 1111 100x 0xxx xxxx xxxx 10x0 xxxx xxxx */
DECODE_REJECT (0xfe800d00, 0xf8000800),
/* STRBT 1111 1000 0000 xxxx xxxx 1110 xxxx xxxx */
/* STRHT 1111 1000 0010 xxxx xxxx 1110 xxxx xxxx */
/* STRT 1111 1000 0100 xxxx xxxx 1110 xxxx xxxx */
/* LDRBT 1111 1000 0001 xxxx xxxx 1110 xxxx xxxx */
/* LDRSBT 1111 1001 0001 xxxx xxxx 1110 xxxx xxxx */
/* LDRHT 1111 1000 0011 xxxx xxxx 1110 xxxx xxxx */
/* LDRSHT 1111 1001 0011 xxxx xxxx 1110 xxxx xxxx */
/* LDRT 1111 1000 0101 xxxx xxxx 1110 xxxx xxxx */
DECODE_REJECT (0xfe800f00, 0xf8000e00),
/* STR{,B,H} Rn,[PC...] 1111 1000 xxx0 1111 xxxx xxxx xxxx xxxx */
DECODE_REJECT (0xff1f0000, 0xf80f0000),
/* STR{,B,H} PC,[Rn...] 1111 1000 xxx0 xxxx 1111 xxxx xxxx xxxx */
DECODE_REJECT (0xff10f000, 0xf800f000),
/* LDR (literal) 1111 1000 x101 1111 xxxx xxxx xxxx xxxx */
DECODE_SIMULATEX(0xff7f0000, 0xf85f0000, t32_simulate_ldr_literal,
REGS(PC, ANY, 0, 0, 0)),
/* STR (immediate) 1111 1000 0100 xxxx xxxx 1xxx xxxx xxxx */
/* LDR (immediate) 1111 1000 0101 xxxx xxxx 1xxx xxxx xxxx */
DECODE_OR (0xffe00800, 0xf8400800),
/* STR (immediate) 1111 1000 1100 xxxx xxxx xxxx xxxx xxxx */
/* LDR (immediate) 1111 1000 1101 xxxx xxxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xffe00000, 0xf8c00000, t32_emulate_ldrstr,
REGS(NOPCX, ANY, 0, 0, 0)),
/* STR (register) 1111 1000 0100 xxxx xxxx 0000 00xx xxxx */
/* LDR (register) 1111 1000 0101 xxxx xxxx 0000 00xx xxxx */
DECODE_EMULATEX (0xffe00fc0, 0xf8400000, t32_emulate_ldrstr,
REGS(NOPCX, ANY, 0, 0, NOSPPC)),
/* LDRB (literal) 1111 1000 x001 1111 xxxx xxxx xxxx xxxx */
/* LDRSB (literal) 1111 1001 x001 1111 xxxx xxxx xxxx xxxx */
/* LDRH (literal) 1111 1000 x011 1111 xxxx xxxx xxxx xxxx */
/* LDRSH (literal) 1111 1001 x011 1111 xxxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfe5f0000, 0xf81f0000, t32_simulate_ldr_literal,
REGS(PC, NOSPPCX, 0, 0, 0)),
/* STRB (immediate) 1111 1000 0000 xxxx xxxx 1xxx xxxx xxxx */
/* STRH (immediate) 1111 1000 0010 xxxx xxxx 1xxx xxxx xxxx */
/* LDRB (immediate) 1111 1000 0001 xxxx xxxx 1xxx xxxx xxxx */
/* LDRSB (immediate) 1111 1001 0001 xxxx xxxx 1xxx xxxx xxxx */
/* LDRH (immediate) 1111 1000 0011 xxxx xxxx 1xxx xxxx xxxx */
/* LDRSH (immediate) 1111 1001 0011 xxxx xxxx 1xxx xxxx xxxx */
DECODE_OR (0xfec00800, 0xf8000800),
/* STRB (immediate) 1111 1000 1000 xxxx xxxx xxxx xxxx xxxx */
/* STRH (immediate) 1111 1000 1010 xxxx xxxx xxxx xxxx xxxx */
/* LDRB (immediate) 1111 1000 1001 xxxx xxxx xxxx xxxx xxxx */
/* LDRSB (immediate) 1111 1001 1001 xxxx xxxx xxxx xxxx xxxx */
/* LDRH (immediate) 1111 1000 1011 xxxx xxxx xxxx xxxx xxxx */
/* LDRSH (immediate) 1111 1001 1011 xxxx xxxx xxxx xxxx xxxx */
DECODE_EMULATEX (0xfec00000, 0xf8800000, t32_emulate_ldrstr,
REGS(NOPCX, NOSPPCX, 0, 0, 0)),
/* STRB (register) 1111 1000 0000 xxxx xxxx 0000 00xx xxxx */
/* STRH (register) 1111 1000 0010 xxxx xxxx 0000 00xx xxxx */
/* LDRB (register) 1111 1000 0001 xxxx xxxx 0000 00xx xxxx */
/* LDRSB (register) 1111 1001 0001 xxxx xxxx 0000 00xx xxxx */
/* LDRH (register) 1111 1000 0011 xxxx xxxx 0000 00xx xxxx */
/* LDRSH (register) 1111 1001 0011 xxxx xxxx 0000 00xx xxxx */
DECODE_EMULATEX (0xfe800fc0, 0xf8000000, t32_emulate_ldrstr,
REGS(NOPCX, NOSPPCX, 0, 0, NOSPPC)),
/* Other unallocated instructions... */
DECODE_END
};
static const union decode_item t32_table_1111_1010___1111[] = {
/* Data-processing (register) */
/* ??? 1111 1010 011x xxxx 1111 xxxx 1xxx xxxx */
DECODE_REJECT (0xffe0f080, 0xfa60f080),
/* SXTH 1111 1010 0000 1111 1111 xxxx 1xxx xxxx */
/* UXTH 1111 1010 0001 1111 1111 xxxx 1xxx xxxx */
/* SXTB16 1111 1010 0010 1111 1111 xxxx 1xxx xxxx */
/* UXTB16 1111 1010 0011 1111 1111 xxxx 1xxx xxxx */
/* SXTB 1111 1010 0100 1111 1111 xxxx 1xxx xxxx */
/* UXTB 1111 1010 0101 1111 1111 xxxx 1xxx xxxx */
DECODE_EMULATEX (0xff8ff080, 0xfa0ff080, t32_emulate_rd8rn16rm0_rwflags,
REGS(0, 0, NOSPPC, 0, NOSPPC)),
/* ??? 1111 1010 1xxx xxxx 1111 xxxx 0x11 xxxx */
DECODE_REJECT (0xff80f0b0, 0xfa80f030),
/* ??? 1111 1010 1x11 xxxx 1111 xxxx 0xxx xxxx */
DECODE_REJECT (0xffb0f080, 0xfab0f000),
/* SADD16 1111 1010 1001 xxxx 1111 xxxx 0000 xxxx */
/* SASX 1111 1010 1010 xxxx 1111 xxxx 0000 xxxx */
/* SSAX 1111 1010 1110 xxxx 1111 xxxx 0000 xxxx */
/* SSUB16 1111 1010 1101 xxxx 1111 xxxx 0000 xxxx */
/* SADD8 1111 1010 1000 xxxx 1111 xxxx 0000 xxxx */
/* SSUB8 1111 1010 1100 xxxx 1111 xxxx 0000 xxxx */
/* QADD16 1111 1010 1001 xxxx 1111 xxxx 0001 xxxx */
/* QASX 1111 1010 1010 xxxx 1111 xxxx 0001 xxxx */
/* QSAX 1111 1010 1110 xxxx 1111 xxxx 0001 xxxx */
/* QSUB16 1111 1010 1101 xxxx 1111 xxxx 0001 xxxx */
/* QADD8 1111 1010 1000 xxxx 1111 xxxx 0001 xxxx */
/* QSUB8 1111 1010 1100 xxxx 1111 xxxx 0001 xxxx */
/* SHADD16 1111 1010 1001 xxxx 1111 xxxx 0010 xxxx */
/* SHASX 1111 1010 1010 xxxx 1111 xxxx 0010 xxxx */
/* SHSAX 1111 1010 1110 xxxx 1111 xxxx 0010 xxxx */
/* SHSUB16 1111 1010 1101 xxxx 1111 xxxx 0010 xxxx */
/* SHADD8 1111 1010 1000 xxxx 1111 xxxx 0010 xxxx */
/* SHSUB8 1111 1010 1100 xxxx 1111 xxxx 0010 xxxx */
/* UADD16 1111 1010 1001 xxxx 1111 xxxx 0100 xxxx */
/* UASX 1111 1010 1010 xxxx 1111 xxxx 0100 xxxx */
/* USAX 1111 1010 1110 xxxx 1111 xxxx 0100 xxxx */
/* USUB16 1111 1010 1101 xxxx 1111 xxxx 0100 xxxx */
/* UADD8 1111 1010 1000 xxxx 1111 xxxx 0100 xxxx */
/* USUB8 1111 1010 1100 xxxx 1111 xxxx 0100 xxxx */
/* UQADD16 1111 1010 1001 xxxx 1111 xxxx 0101 xxxx */
/* UQASX 1111 1010 1010 xxxx 1111 xxxx 0101 xxxx */
/* UQSAX 1111 1010 1110 xxxx 1111 xxxx 0101 xxxx */
/* UQSUB16 1111 1010 1101 xxxx 1111 xxxx 0101 xxxx */
/* UQADD8 1111 1010 1000 xxxx 1111 xxxx 0101 xxxx */
/* UQSUB8 1111 1010 1100 xxxx 1111 xxxx 0101 xxxx */
/* UHADD16 1111 1010 1001 xxxx 1111 xxxx 0110 xxxx */
/* UHASX 1111 1010 1010 xxxx 1111 xxxx 0110 xxxx */
/* UHSAX 1111 1010 1110 xxxx 1111 xxxx 0110 xxxx */
/* UHSUB16 1111 1010 1101 xxxx 1111 xxxx 0110 xxxx */
/* UHADD8 1111 1010 1000 xxxx 1111 xxxx 0110 xxxx */
/* UHSUB8 1111 1010 1100 xxxx 1111 xxxx 0110 xxxx */
DECODE_OR (0xff80f080, 0xfa80f000),
/* SXTAH 1111 1010 0000 xxxx 1111 xxxx 1xxx xxxx */
/* UXTAH 1111 1010 0001 xxxx 1111 xxxx 1xxx xxxx */
/* SXTAB16 1111 1010 0010 xxxx 1111 xxxx 1xxx xxxx */
/* UXTAB16 1111 1010 0011 xxxx 1111 xxxx 1xxx xxxx */
/* SXTAB 1111 1010 0100 xxxx 1111 xxxx 1xxx xxxx */
/* UXTAB 1111 1010 0101 xxxx 1111 xxxx 1xxx xxxx */
DECODE_OR (0xff80f080, 0xfa00f080),
/* QADD 1111 1010 1000 xxxx 1111 xxxx 1000 xxxx */
/* QDADD 1111 1010 1000 xxxx 1111 xxxx 1001 xxxx */
/* QSUB 1111 1010 1000 xxxx 1111 xxxx 1010 xxxx */
/* QDSUB 1111 1010 1000 xxxx 1111 xxxx 1011 xxxx */
DECODE_OR (0xfff0f0c0, 0xfa80f080),
/* SEL 1111 1010 1010 xxxx 1111 xxxx 1000 xxxx */
DECODE_OR (0xfff0f0f0, 0xfaa0f080),
/* LSL 1111 1010 000x xxxx 1111 xxxx 0000 xxxx */
/* LSR 1111 1010 001x xxxx 1111 xxxx 0000 xxxx */
/* ASR 1111 1010 010x xxxx 1111 xxxx 0000 xxxx */
/* ROR 1111 1010 011x xxxx 1111 xxxx 0000 xxxx */
DECODE_EMULATEX (0xff80f0f0, 0xfa00f000, t32_emulate_rd8rn16rm0_rwflags,
REGS(NOSPPC, 0, NOSPPC, 0, NOSPPC)),
/* CLZ 1111 1010 1010 xxxx 1111 xxxx 1000 xxxx */
DECODE_OR (0xfff0f0f0, 0xfab0f080),
/* REV 1111 1010 1001 xxxx 1111 xxxx 1000 xxxx */
/* REV16 1111 1010 1001 xxxx 1111 xxxx 1001 xxxx */
/* RBIT 1111 1010 1001 xxxx 1111 xxxx 1010 xxxx */
/* REVSH 1111 1010 1001 xxxx 1111 xxxx 1011 xxxx */
DECODE_EMULATEX (0xfff0f0c0, 0xfa90f080, t32_emulate_rd8rn16_noflags,
REGS(NOSPPC, 0, NOSPPC, 0, SAMEAS16)),
/* Other unallocated instructions... */
DECODE_END
};
static const union decode_item t32_table_1111_1011_0[] = {
/* Multiply, multiply accumulate, and absolute difference */
/* ??? 1111 1011 0000 xxxx 1111 xxxx 0001 xxxx */
DECODE_REJECT (0xfff0f0f0, 0xfb00f010),
/* ??? 1111 1011 0111 xxxx 1111 xxxx 0001 xxxx */
DECODE_REJECT (0xfff0f0f0, 0xfb70f010),
/* SMULxy 1111 1011 0001 xxxx 1111 xxxx 00xx xxxx */
DECODE_OR (0xfff0f0c0, 0xfb10f000),
/* MUL 1111 1011 0000 xxxx 1111 xxxx 0000 xxxx */
/* SMUAD{X} 1111 1011 0010 xxxx 1111 xxxx 000x xxxx */
/* SMULWy 1111 1011 0011 xxxx 1111 xxxx 000x xxxx */
/* SMUSD{X} 1111 1011 0100 xxxx 1111 xxxx 000x xxxx */
/* SMMUL{R} 1111 1011 0101 xxxx 1111 xxxx 000x xxxx */
/* USAD8 1111 1011 0111 xxxx 1111 xxxx 0000 xxxx */
DECODE_EMULATEX (0xff80f0e0, 0xfb00f000, t32_emulate_rd8rn16rm0_rwflags,
REGS(NOSPPC, 0, NOSPPC, 0, NOSPPC)),
/* ??? 1111 1011 0111 xxxx xxxx xxxx 0001 xxxx */
DECODE_REJECT (0xfff000f0, 0xfb700010),
/* SMLAxy 1111 1011 0001 xxxx xxxx xxxx 00xx xxxx */
DECODE_OR (0xfff000c0, 0xfb100000),
/* MLA 1111 1011 0000 xxxx xxxx xxxx 0000 xxxx */
/* MLS 1111 1011 0000 xxxx xxxx xxxx 0001 xxxx */
/* SMLAD{X} 1111 1011 0010 xxxx xxxx xxxx 000x xxxx */
/* SMLAWy 1111 1011 0011 xxxx xxxx xxxx 000x xxxx */
/* SMLSD{X} 1111 1011 0100 xxxx xxxx xxxx 000x xxxx */
/* SMMLA{R} 1111 1011 0101 xxxx xxxx xxxx 000x xxxx */
/* SMMLS{R} 1111 1011 0110 xxxx xxxx xxxx 000x xxxx */
/* USADA8 1111 1011 0111 xxxx xxxx xxxx 0000 xxxx */
DECODE_EMULATEX (0xff8000c0, 0xfb000000, t32_emulate_rd8rn16rm0ra12_noflags,
REGS(NOSPPC, NOSPPCX, NOSPPC, 0, NOSPPC)),
/* Other unallocated instructions... */
DECODE_END
};
static const union decode_item t32_table_1111_1011_1[] = {
/* Long multiply, long multiply accumulate, and divide */
/* UMAAL 1111 1011 1110 xxxx xxxx xxxx 0110 xxxx */
DECODE_OR (0xfff000f0, 0xfbe00060),
/* SMLALxy 1111 1011 1100 xxxx xxxx xxxx 10xx xxxx */
DECODE_OR (0xfff000c0, 0xfbc00080),
/* SMLALD{X} 1111 1011 1100 xxxx xxxx xxxx 110x xxxx */
/* SMLSLD{X} 1111 1011 1101 xxxx xxxx xxxx 110x xxxx */
DECODE_OR (0xffe000e0, 0xfbc000c0),
/* SMULL 1111 1011 1000 xxxx xxxx xxxx 0000 xxxx */
/* UMULL 1111 1011 1010 xxxx xxxx xxxx 0000 xxxx */
/* SMLAL 1111 1011 1100 xxxx xxxx xxxx 0000 xxxx */
/* UMLAL 1111 1011 1110 xxxx xxxx xxxx 0000 xxxx */
DECODE_EMULATEX (0xff9000f0, 0xfb800000, t32_emulate_rdlo12rdhi8rn16rm0_noflags,
REGS(NOSPPC, NOSPPC, NOSPPC, 0, NOSPPC)),
/* SDIV 1111 1011 1001 xxxx xxxx xxxx 1111 xxxx */
/* UDIV 1111 1011 1011 xxxx xxxx xxxx 1111 xxxx */
/* Other unallocated instructions... */
DECODE_END
};
const union decode_item kprobe_decode_thumb32_table[] = {
/*
* Load/store multiple instructions
* 1110 100x x0xx xxxx xxxx xxxx xxxx xxxx
*/
DECODE_TABLE (0xfe400000, 0xe8000000, t32_table_1110_100x_x0xx),
/*
* Load/store dual, load/store exclusive, table branch
* 1110 100x x1xx xxxx xxxx xxxx xxxx xxxx
*/
DECODE_TABLE (0xfe400000, 0xe8400000, t32_table_1110_100x_x1xx),
/*
* Data-processing (shifted register)
* 1110 101x xxxx xxxx xxxx xxxx xxxx xxxx
*/
DECODE_TABLE (0xfe000000, 0xea000000, t32_table_1110_101x),
/*
* Coprocessor instructions
* 1110 11xx xxxx xxxx xxxx xxxx xxxx xxxx
*/
DECODE_REJECT (0xfc000000, 0xec000000),
/*
* Data-processing (modified immediate)
* 1111 0x0x xxxx xxxx 0xxx xxxx xxxx xxxx
*/
DECODE_TABLE (0xfa008000, 0xf0000000, t32_table_1111_0x0x___0),
/*
* Data-processing (plain binary immediate)
* 1111 0x1x xxxx xxxx 0xxx xxxx xxxx xxxx
*/
DECODE_TABLE (0xfa008000, 0xf2000000, t32_table_1111_0x1x___0),
/*
* Branches and miscellaneous control
* 1111 0xxx xxxx xxxx 1xxx xxxx xxxx xxxx
*/
DECODE_TABLE (0xf8008000, 0xf0008000, t32_table_1111_0xxx___1),
/*
* Advanced SIMD element or structure load/store instructions
* 1111 1001 xxx0 xxxx xxxx xxxx xxxx xxxx
*/
DECODE_REJECT (0xff100000, 0xf9000000),
/*
* Memory hints
* 1111 100x x0x1 xxxx 1111 xxxx xxxx xxxx
*/
DECODE_TABLE (0xfe50f000, 0xf810f000, t32_table_1111_100x_x0x1__1111),
/*
* Store single data item
* 1111 1000 xxx0 xxxx xxxx xxxx xxxx xxxx
* Load single data items
* 1111 100x xxx1 xxxx xxxx xxxx xxxx xxxx
*/
DECODE_TABLE (0xfe000000, 0xf8000000, t32_table_1111_100x),
/*
* Data-processing (register)
* 1111 1010 xxxx xxxx 1111 xxxx xxxx xxxx
*/
DECODE_TABLE (0xff00f000, 0xfa00f000, t32_table_1111_1010___1111),
/*
* Multiply, multiply accumulate, and absolute difference
* 1111 1011 0xxx xxxx xxxx xxxx xxxx xxxx
*/
DECODE_TABLE (0xff800000, 0xfb000000, t32_table_1111_1011_0),
/*
* Long multiply, long multiply accumulate, and divide
* 1111 1011 1xxx xxxx xxxx xxxx xxxx xxxx
*/
DECODE_TABLE (0xff800000, 0xfb800000, t32_table_1111_1011_1),
/*
* Coprocessor instructions
* 1111 11xx xxxx xxxx xxxx xxxx xxxx xxxx
*/
DECODE_END
};
#ifdef CONFIG_ARM_KPROBES_TEST_MODULE
EXPORT_SYMBOL_GPL(kprobe_decode_thumb32_table);
#endif
static void __kprobes
t16_simulate_bxblx(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long pc = thumb_probe_pc(p);
int rm = (insn >> 3) & 0xf;
unsigned long rmv = (rm == 15) ? pc : regs->uregs[rm];
if (insn & (1 << 7)) /* BLX ? */
regs->ARM_lr = (unsigned long)p->addr + 2;
bx_write_pc(rmv, regs);
}
static void __kprobes
t16_simulate_ldr_literal(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long* base = (unsigned long *)(thumb_probe_pc(p) & ~3);
long index = insn & 0xff;
int rt = (insn >> 8) & 0x7;
regs->uregs[rt] = base[index];
}
static void __kprobes
t16_simulate_ldrstr_sp_relative(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long* base = (unsigned long *)regs->ARM_sp;
long index = insn & 0xff;
int rt = (insn >> 8) & 0x7;
if (insn & 0x800) /* LDR */
regs->uregs[rt] = base[index];
else /* STR */
base[index] = regs->uregs[rt];
}
static void __kprobes
t16_simulate_reladr(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long base = (insn & 0x800) ? regs->ARM_sp
: (thumb_probe_pc(p) & ~3);
long offset = insn & 0xff;
int rt = (insn >> 8) & 0x7;
regs->uregs[rt] = base + offset * 4;
}
static void __kprobes
t16_simulate_add_sp_imm(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
long imm = insn & 0x7f;
if (insn & 0x80) /* SUB */
regs->ARM_sp -= imm * 4;
else /* ADD */
regs->ARM_sp += imm * 4;
}
static void __kprobes
t16_simulate_cbz(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
int rn = insn & 0x7;
kprobe_opcode_t nonzero = regs->uregs[rn] ? insn : ~insn;
if (nonzero & 0x800) {
long i = insn & 0x200;
long imm5 = insn & 0xf8;
unsigned long pc = thumb_probe_pc(p);
regs->ARM_pc = pc + (i >> 3) + (imm5 >> 2);
}
}
static void __kprobes
t16_simulate_it(struct kprobe *p, struct pt_regs *regs)
{
/*
* The 8 IT state bits are split into two parts in CPSR:
* ITSTATE<1:0> are in CPSR<26:25>
* ITSTATE<7:2> are in CPSR<15:10>
* The new IT state is in the lower byte of insn.
*/
kprobe_opcode_t insn = p->opcode;
unsigned long cpsr = regs->ARM_cpsr;
cpsr &= ~PSR_IT_MASK;
cpsr |= (insn & 0xfc) << 8;
cpsr |= (insn & 0x03) << 25;
regs->ARM_cpsr = cpsr;
}
static void __kprobes
t16_singlestep_it(struct kprobe *p, struct pt_regs *regs)
{
regs->ARM_pc += 2;
t16_simulate_it(p, regs);
}
static enum kprobe_insn __kprobes
t16_decode_it(kprobe_opcode_t insn, struct arch_specific_insn *asi)
{
asi->insn_singlestep = t16_singlestep_it;
return INSN_GOOD_NO_SLOT;
}
static void __kprobes
t16_simulate_cond_branch(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long pc = thumb_probe_pc(p);
long offset = insn & 0x7f;
offset -= insn & 0x80; /* Apply sign bit */
regs->ARM_pc = pc + (offset * 2);
}
static enum kprobe_insn __kprobes
t16_decode_cond_branch(kprobe_opcode_t insn, struct arch_specific_insn *asi)
{
int cc = (insn >> 8) & 0xf;
asi->insn_check_cc = kprobe_condition_checks[cc];
asi->insn_handler = t16_simulate_cond_branch;
return INSN_GOOD_NO_SLOT;
}
static void __kprobes
t16_simulate_branch(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long pc = thumb_probe_pc(p);
long offset = insn & 0x3ff;
offset -= insn & 0x400; /* Apply sign bit */
regs->ARM_pc = pc + (offset * 2);
}
static unsigned long __kprobes
t16_emulate_loregs(struct kprobe *p, struct pt_regs *regs)
{
unsigned long oldcpsr = regs->ARM_cpsr;
unsigned long newcpsr;
__asm__ __volatile__ (
"msr cpsr_fs, %[oldcpsr] \n\t"
"ldmia %[regs], {r0-r7} \n\t"
"blx %[fn] \n\t"
"stmia %[regs], {r0-r7} \n\t"
"mrs %[newcpsr], cpsr \n\t"
: [newcpsr] "=r" (newcpsr)
: [oldcpsr] "r" (oldcpsr), [regs] "r" (regs),
[fn] "r" (p->ainsn.insn_fn)
: "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
"lr", "memory", "cc"
);
return (oldcpsr & ~APSR_MASK) | (newcpsr & APSR_MASK);
}
static void __kprobes
t16_emulate_loregs_rwflags(struct kprobe *p, struct pt_regs *regs)
{
regs->ARM_cpsr = t16_emulate_loregs(p, regs);
}
static void __kprobes
t16_emulate_loregs_noitrwflags(struct kprobe *p, struct pt_regs *regs)
{
unsigned long cpsr = t16_emulate_loregs(p, regs);
if (!in_it_block(cpsr))
regs->ARM_cpsr = cpsr;
}
static void __kprobes
t16_emulate_hiregs(struct kprobe *p, struct pt_regs *regs)
{
kprobe_opcode_t insn = p->opcode;
unsigned long pc = thumb_probe_pc(p);
int rdn = (insn & 0x7) | ((insn & 0x80) >> 4);
int rm = (insn >> 3) & 0xf;
register unsigned long rdnv asm("r1");
register unsigned long rmv asm("r0");
unsigned long cpsr = regs->ARM_cpsr;
rdnv = (rdn == 15) ? pc : regs->uregs[rdn];
rmv = (rm == 15) ? pc : regs->uregs[rm];
__asm__ __volatile__ (
"msr cpsr_fs, %[cpsr] \n\t"
"blx %[fn] \n\t"
"mrs %[cpsr], cpsr \n\t"
: "=r" (rdnv), [cpsr] "=r" (cpsr)
: "0" (rdnv), "r" (rmv), "1" (cpsr), [fn] "r" (p->ainsn.insn_fn)
: "lr", "memory", "cc"
);
if (rdn == 15)
rdnv &= ~1;
regs->uregs[rdn] = rdnv;
regs->ARM_cpsr = (regs->ARM_cpsr & ~APSR_MASK) | (cpsr & APSR_MASK);
}
static enum kprobe_insn __kprobes
t16_decode_hiregs(kprobe_opcode_t insn, struct arch_specific_insn *asi)
{
insn &= ~0x00ff;
insn |= 0x001; /* Set Rdn = R1 and Rm = R0 */
((u16 *)asi->insn)[0] = insn;
asi->insn_handler = t16_emulate_hiregs;
return INSN_GOOD;
}
static void __kprobes
t16_emulate_push(struct kprobe *p, struct pt_regs *regs)
{
__asm__ __volatile__ (
"ldr r9, [%[regs], #13*4] \n\t"
"ldr r8, [%[regs], #14*4] \n\t"
"ldmia %[regs], {r0-r7} \n\t"
"blx %[fn] \n\t"
"str r9, [%[regs], #13*4] \n\t"
:
: [regs] "r" (regs), [fn] "r" (p->ainsn.insn_fn)
: "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9",
"lr", "memory", "cc"
);
}
static enum kprobe_insn __kprobes
t16_decode_push(kprobe_opcode_t insn, struct arch_specific_insn *asi)
{
/*
* To simulate a PUSH we use a Thumb-2 "STMDB R9!, {registers}"
* and call it with R9=SP and LR in the register list represented
* by R8.
*/
((u16 *)asi->insn)[0] = 0xe929; /* 1st half STMDB R9!,{} */
((u16 *)asi->insn)[1] = insn & 0x1ff; /* 2nd half (register list) */
asi->insn_handler = t16_emulate_push;
return INSN_GOOD;
}
static void __kprobes
t16_emulate_pop_nopc(struct kprobe *p, struct pt_regs *regs)
{
__asm__ __volatile__ (
"ldr r9, [%[regs], #13*4] \n\t"
"ldmia %[regs], {r0-r7} \n\t"
"blx %[fn] \n\t"
"stmia %[regs], {r0-r7} \n\t"
"str r9, [%[regs], #13*4] \n\t"
:
: [regs] "r" (regs), [fn] "r" (p->ainsn.insn_fn)
: "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r9",
"lr", "memory", "cc"
);
}
static void __kprobes
t16_emulate_pop_pc(struct kprobe *p, struct pt_regs *regs)
{
register unsigned long pc asm("r8");
__asm__ __volatile__ (
"ldr r9, [%[regs], #13*4] \n\t"
"ldmia %[regs], {r0-r7} \n\t"
"blx %[fn] \n\t"
"stmia %[regs], {r0-r7} \n\t"
"str r9, [%[regs], #13*4] \n\t"
: "=r" (pc)
: [regs] "r" (regs), [fn] "r" (p->ainsn.insn_fn)
: "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r9",
"lr", "memory", "cc"
);
bx_write_pc(pc, regs);
}
static enum kprobe_insn __kprobes
t16_decode_pop(kprobe_opcode_t insn, struct arch_specific_insn *asi)
{
/*
* To simulate a POP we use a Thumb-2 "LDMDB R9!, {registers}"
* and call it with R9=SP and PC in the register list represented
* by R8.
*/
((u16 *)asi->insn)[0] = 0xe8b9; /* 1st half LDMIA R9!,{} */
((u16 *)asi->insn)[1] = insn & 0x1ff; /* 2nd half (register list) */
asi->insn_handler = insn & 0x100 ? t16_emulate_pop_pc
: t16_emulate_pop_nopc;
return INSN_GOOD;
}
static const union decode_item t16_table_1011[] = {
/* Miscellaneous 16-bit instructions */
/* ADD (SP plus immediate) 1011 0000 0xxx xxxx */
/* SUB (SP minus immediate) 1011 0000 1xxx xxxx */
DECODE_SIMULATE (0xff00, 0xb000, t16_simulate_add_sp_imm),
/* CBZ 1011 00x1 xxxx xxxx */
/* CBNZ 1011 10x1 xxxx xxxx */
DECODE_SIMULATE (0xf500, 0xb100, t16_simulate_cbz),
/* SXTH 1011 0010 00xx xxxx */
/* SXTB 1011 0010 01xx xxxx */
/* UXTH 1011 0010 10xx xxxx */
/* UXTB 1011 0010 11xx xxxx */
/* REV 1011 1010 00xx xxxx */
/* REV16 1011 1010 01xx xxxx */
/* ??? 1011 1010 10xx xxxx */
/* REVSH 1011 1010 11xx xxxx */
DECODE_REJECT (0xffc0, 0xba80),
DECODE_EMULATE (0xf500, 0xb000, t16_emulate_loregs_rwflags),
/* PUSH 1011 010x xxxx xxxx */
DECODE_CUSTOM (0xfe00, 0xb400, t16_decode_push),
/* POP 1011 110x xxxx xxxx */
DECODE_CUSTOM (0xfe00, 0xbc00, t16_decode_pop),
/*
* If-Then, and hints
* 1011 1111 xxxx xxxx
*/
/* YIELD 1011 1111 0001 0000 */
DECODE_OR (0xffff, 0xbf10),
/* SEV 1011 1111 0100 0000 */
DECODE_EMULATE (0xffff, 0xbf40, kprobe_emulate_none),
/* NOP 1011 1111 0000 0000 */
/* WFE 1011 1111 0010 0000 */
/* WFI 1011 1111 0011 0000 */
DECODE_SIMULATE (0xffcf, 0xbf00, kprobe_simulate_nop),
/* Unassigned hints 1011 1111 xxxx 0000 */
DECODE_REJECT (0xff0f, 0xbf00),
/* IT 1011 1111 xxxx xxxx */
DECODE_CUSTOM (0xff00, 0xbf00, t16_decode_it),
/* SETEND 1011 0110 010x xxxx */
/* CPS 1011 0110 011x xxxx */
/* BKPT 1011 1110 xxxx xxxx */
/* And unallocated instructions... */
DECODE_END
};
const union decode_item kprobe_decode_thumb16_table[] = {
/*
* Shift (immediate), add, subtract, move, and compare
* 00xx xxxx xxxx xxxx
*/
/* CMP (immediate) 0010 1xxx xxxx xxxx */
DECODE_EMULATE (0xf800, 0x2800, t16_emulate_loregs_rwflags),
/* ADD (register) 0001 100x xxxx xxxx */
/* SUB (register) 0001 101x xxxx xxxx */
/* LSL (immediate) 0000 0xxx xxxx xxxx */
/* LSR (immediate) 0000 1xxx xxxx xxxx */
/* ASR (immediate) 0001 0xxx xxxx xxxx */
/* ADD (immediate, Thumb) 0001 110x xxxx xxxx */
/* SUB (immediate, Thumb) 0001 111x xxxx xxxx */
/* MOV (immediate) 0010 0xxx xxxx xxxx */
/* ADD (immediate, Thumb) 0011 0xxx xxxx xxxx */
/* SUB (immediate, Thumb) 0011 1xxx xxxx xxxx */
DECODE_EMULATE (0xc000, 0x0000, t16_emulate_loregs_noitrwflags),
/*
* 16-bit Thumb data-processing instructions
* 0100 00xx xxxx xxxx
*/
/* TST (register) 0100 0010 00xx xxxx */
DECODE_EMULATE (0xffc0, 0x4200, t16_emulate_loregs_rwflags),
/* CMP (register) 0100 0010 10xx xxxx */
/* CMN (register) 0100 0010 11xx xxxx */
DECODE_EMULATE (0xff80, 0x4280, t16_emulate_loregs_rwflags),
/* AND (register) 0100 0000 00xx xxxx */
/* EOR (register) 0100 0000 01xx xxxx */
/* LSL (register) 0100 0000 10xx xxxx */
/* LSR (register) 0100 0000 11xx xxxx */
/* ASR (register) 0100 0001 00xx xxxx */
/* ADC (register) 0100 0001 01xx xxxx */
/* SBC (register) 0100 0001 10xx xxxx */
/* ROR (register) 0100 0001 11xx xxxx */
/* RSB (immediate) 0100 0010 01xx xxxx */
/* ORR (register) 0100 0011 00xx xxxx */
/* MUL 0100 0011 00xx xxxx */
/* BIC (register) 0100 0011 10xx xxxx */
/* MVN (register) 0100 0011 10xx xxxx */
DECODE_EMULATE (0xfc00, 0x4000, t16_emulate_loregs_noitrwflags),
/*
* Special data instructions and branch and exchange
* 0100 01xx xxxx xxxx
*/
/* BLX pc 0100 0111 1111 1xxx */
DECODE_REJECT (0xfff8, 0x47f8),
/* BX (register) 0100 0111 0xxx xxxx */
/* BLX (register) 0100 0111 1xxx xxxx */
DECODE_SIMULATE (0xff00, 0x4700, t16_simulate_bxblx),
/* ADD pc, pc 0100 0100 1111 1111 */
DECODE_REJECT (0xffff, 0x44ff),
/* ADD (register) 0100 0100 xxxx xxxx */
/* CMP (register) 0100 0101 xxxx xxxx */
/* MOV (register) 0100 0110 xxxx xxxx */
DECODE_CUSTOM (0xfc00, 0x4400, t16_decode_hiregs),
/*
* Load from Literal Pool
* LDR (literal) 0100 1xxx xxxx xxxx
*/
DECODE_SIMULATE (0xf800, 0x4800, t16_simulate_ldr_literal),
/*
* 16-bit Thumb Load/store instructions
* 0101 xxxx xxxx xxxx
* 011x xxxx xxxx xxxx
* 100x xxxx xxxx xxxx
*/
/* STR (register) 0101 000x xxxx xxxx */
/* STRH (register) 0101 001x xxxx xxxx */
/* STRB (register) 0101 010x xxxx xxxx */
/* LDRSB (register) 0101 011x xxxx xxxx */
/* LDR (register) 0101 100x xxxx xxxx */
/* LDRH (register) 0101 101x xxxx xxxx */
/* LDRB (register) 0101 110x xxxx xxxx */
/* LDRSH (register) 0101 111x xxxx xxxx */
/* STR (immediate, Thumb) 0110 0xxx xxxx xxxx */
/* LDR (immediate, Thumb) 0110 1xxx xxxx xxxx */
/* STRB (immediate, Thumb) 0111 0xxx xxxx xxxx */
/* LDRB (immediate, Thumb) 0111 1xxx xxxx xxxx */
DECODE_EMULATE (0xc000, 0x4000, t16_emulate_loregs_rwflags),
/* STRH (immediate, Thumb) 1000 0xxx xxxx xxxx */
/* LDRH (immediate, Thumb) 1000 1xxx xxxx xxxx */
DECODE_EMULATE (0xf000, 0x8000, t16_emulate_loregs_rwflags),
/* STR (immediate, Thumb) 1001 0xxx xxxx xxxx */
/* LDR (immediate, Thumb) 1001 1xxx xxxx xxxx */
DECODE_SIMULATE (0xf000, 0x9000, t16_simulate_ldrstr_sp_relative),
/*
* Generate PC-/SP-relative address
* ADR (literal) 1010 0xxx xxxx xxxx
* ADD (SP plus immediate) 1010 1xxx xxxx xxxx
*/
DECODE_SIMULATE (0xf000, 0xa000, t16_simulate_reladr),
/*
* Miscellaneous 16-bit instructions
* 1011 xxxx xxxx xxxx
*/
DECODE_TABLE (0xf000, 0xb000, t16_table_1011),
/* STM 1100 0xxx xxxx xxxx */
/* LDM 1100 1xxx xxxx xxxx */
DECODE_EMULATE (0xf000, 0xc000, t16_emulate_loregs_rwflags),
/*
* Conditional branch, and Supervisor Call
*/
/* Permanently UNDEFINED 1101 1110 xxxx xxxx */
/* SVC 1101 1111 xxxx xxxx */
DECODE_REJECT (0xfe00, 0xde00),
/* Conditional branch 1101 xxxx xxxx xxxx */
DECODE_CUSTOM (0xf000, 0xd000, t16_decode_cond_branch),
/*
* Unconditional branch
* B 1110 0xxx xxxx xxxx
*/
DECODE_SIMULATE (0xf800, 0xe000, t16_simulate_branch),
DECODE_END
};
#ifdef CONFIG_ARM_KPROBES_TEST_MODULE
EXPORT_SYMBOL_GPL(kprobe_decode_thumb16_table);
#endif
static unsigned long __kprobes thumb_check_cc(unsigned long cpsr)
{
if (unlikely(in_it_block(cpsr)))
return kprobe_condition_checks[current_cond(cpsr)](cpsr);
return true;
}
static void __kprobes thumb16_singlestep(struct kprobe *p, struct pt_regs *regs)
{
regs->ARM_pc += 2;
p->ainsn.insn_handler(p, regs);
regs->ARM_cpsr = it_advance(regs->ARM_cpsr);
}
static void __kprobes thumb32_singlestep(struct kprobe *p, struct pt_regs *regs)
{
regs->ARM_pc += 4;
p->ainsn.insn_handler(p, regs);
regs->ARM_cpsr = it_advance(regs->ARM_cpsr);
}
enum kprobe_insn __kprobes
thumb16_kprobe_decode_insn(kprobe_opcode_t insn, struct arch_specific_insn *asi)
{
asi->insn_singlestep = thumb16_singlestep;
asi->insn_check_cc = thumb_check_cc;
return kprobe_decode_insn(insn, asi, kprobe_decode_thumb16_table, true);
}
enum kprobe_insn __kprobes
thumb32_kprobe_decode_insn(kprobe_opcode_t insn, struct arch_specific_insn *asi)
{
asi->insn_singlestep = thumb32_singlestep;
asi->insn_check_cc = thumb_check_cc;
return kprobe_decode_insn(insn, asi, kprobe_decode_thumb32_table, true);
}
| gpl-2.0 |
Shelnutt2/android_kernel_lge_geehrc | net/ax25/ax25_std_timer.c | 5086 | 4335 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Copyright (C) Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk)
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
* Copyright (C) Joerg Reuter DL1BKE (jreuter@yaina.de)
* Copyright (C) Frederic Rible F1OAT (frible@teaser.fr)
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
void ax25_std_heartbeat_expiry(ax25_cb *ax25)
{
struct sock *sk = ax25->sk;
if (sk)
bh_lock_sock(sk);
switch (ax25->state) {
case AX25_STATE_0:
/* Magic here: If we listen() and a new link dies before it
is accepted() it isn't 'dead' so doesn't get removed. */
if (!sk || sock_flag(sk, SOCK_DESTROY) ||
(sk->sk_state == TCP_LISTEN &&
sock_flag(sk, SOCK_DEAD))) {
if (sk) {
sock_hold(sk);
ax25_destroy_socket(ax25);
bh_unlock_sock(sk);
sock_put(sk);
} else
ax25_destroy_socket(ax25);
return;
}
break;
case AX25_STATE_3:
case AX25_STATE_4:
/*
* Check the state of the receive buffer.
*/
if (sk != NULL) {
if (atomic_read(&sk->sk_rmem_alloc) <
(sk->sk_rcvbuf >> 1) &&
(ax25->condition & AX25_COND_OWN_RX_BUSY)) {
ax25->condition &= ~AX25_COND_OWN_RX_BUSY;
ax25->condition &= ~AX25_COND_ACK_PENDING;
ax25_send_control(ax25, AX25_RR, AX25_POLLOFF, AX25_RESPONSE);
break;
}
}
}
if (sk)
bh_unlock_sock(sk);
ax25_start_heartbeat(ax25);
}
void ax25_std_t2timer_expiry(ax25_cb *ax25)
{
if (ax25->condition & AX25_COND_ACK_PENDING) {
ax25->condition &= ~AX25_COND_ACK_PENDING;
ax25_std_timeout_response(ax25);
}
}
void ax25_std_t3timer_expiry(ax25_cb *ax25)
{
ax25->n2count = 0;
ax25_std_transmit_enquiry(ax25);
ax25->state = AX25_STATE_4;
}
void ax25_std_idletimer_expiry(ax25_cb *ax25)
{
ax25_clear_queues(ax25);
ax25->n2count = 0;
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
ax25->state = AX25_STATE_2;
ax25_calculate_t1(ax25);
ax25_start_t1timer(ax25);
ax25_stop_t2timer(ax25);
ax25_stop_t3timer(ax25);
if (ax25->sk != NULL) {
bh_lock_sock(ax25->sk);
ax25->sk->sk_state = TCP_CLOSE;
ax25->sk->sk_err = 0;
ax25->sk->sk_shutdown |= SEND_SHUTDOWN;
if (!sock_flag(ax25->sk, SOCK_DEAD)) {
ax25->sk->sk_state_change(ax25->sk);
sock_set_flag(ax25->sk, SOCK_DEAD);
}
bh_unlock_sock(ax25->sk);
}
}
void ax25_std_t1timer_expiry(ax25_cb *ax25)
{
switch (ax25->state) {
case AX25_STATE_1:
if (ax25->n2count == ax25->n2) {
if (ax25->modulus == AX25_MODULUS) {
ax25_disconnect(ax25, ETIMEDOUT);
return;
} else {
ax25->modulus = AX25_MODULUS;
ax25->window = ax25->ax25_dev->values[AX25_VALUES_WINDOW];
ax25->n2count = 0;
ax25_send_control(ax25, AX25_SABM, AX25_POLLON, AX25_COMMAND);
}
} else {
ax25->n2count++;
if (ax25->modulus == AX25_MODULUS)
ax25_send_control(ax25, AX25_SABM, AX25_POLLON, AX25_COMMAND);
else
ax25_send_control(ax25, AX25_SABME, AX25_POLLON, AX25_COMMAND);
}
break;
case AX25_STATE_2:
if (ax25->n2count == ax25->n2) {
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
ax25_disconnect(ax25, ETIMEDOUT);
return;
} else {
ax25->n2count++;
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
}
break;
case AX25_STATE_3:
ax25->n2count = 1;
ax25_std_transmit_enquiry(ax25);
ax25->state = AX25_STATE_4;
break;
case AX25_STATE_4:
if (ax25->n2count == ax25->n2) {
ax25_send_control(ax25, AX25_DM, AX25_POLLON, AX25_RESPONSE);
ax25_disconnect(ax25, ETIMEDOUT);
return;
} else {
ax25->n2count++;
ax25_std_transmit_enquiry(ax25);
}
break;
}
ax25_calculate_t1(ax25);
ax25_start_t1timer(ax25);
}
| gpl-2.0 |
Flemmard/android_kernel_msm | arch/arm/mach-omap2/omap_l3_noc.c | 5086 | 6910 | /*
* OMAP4XXX L3 Interconnect error handling driver
*
* Copyright (C) 2011 Texas Corporation
* Santosh Shilimkar <santosh.shilimkar@ti.com>
* Sricharan <r.sricharan@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include "omap_l3_noc.h"
/*
* Interrupt Handler for L3 error detection.
* 1) Identify the L3 clockdomain partition to which the error belongs to.
* 2) Identify the slave where the error information is logged
* 3) Print the logged information.
* 4) Add dump stack to provide kernel trace.
*
* Two Types of errors :
* 1) Custom errors in L3 :
* Target like DMM/FW/EMIF generates SRESP=ERR error
* 2) Standard L3 error:
* - Unsupported CMD.
* L3 tries to access target while it is idle
* - OCP disconnect.
* - Address hole error:
* If DSS/ISS/FDIF/USBHOSTFS access a target where they
* do not have connectivity, the error is logged in
* their default target which is DMM2.
*
* On High Secure devices, firewall errors are possible and those
* can be trapped as well. But the trapping is implemented as part
* secure software and hence need not be implemented here.
*/
static irqreturn_t l3_interrupt_handler(int irq, void *_l3)
{
struct omap4_l3 *l3 = _l3;
int inttype, i, k;
int err_src = 0;
u32 std_err_main, err_reg, clear, masterid;
void __iomem *base, *l3_targ_base;
char *target_name, *master_name = "UN IDENTIFIED";
/* Get the Type of interrupt */
inttype = irq == l3->app_irq ? L3_APPLICATION_ERROR : L3_DEBUG_ERROR;
for (i = 0; i < L3_MODULES; i++) {
/*
* Read the regerr register of the clock domain
* to determine the source
*/
base = l3->l3_base[i];
err_reg = __raw_readl(base + l3_flagmux[i] +
+ L3_FLAGMUX_REGERR0 + (inttype << 3));
/* Get the corresponding error and analyse */
if (err_reg) {
/* Identify the source from control status register */
err_src = __ffs(err_reg);
/* Read the stderrlog_main_source from clk domain */
l3_targ_base = base + *(l3_targ[i] + err_src);
std_err_main = __raw_readl(l3_targ_base +
L3_TARG_STDERRLOG_MAIN);
masterid = __raw_readl(l3_targ_base +
L3_TARG_STDERRLOG_MSTADDR);
switch (std_err_main & CUSTOM_ERROR) {
case STANDARD_ERROR:
target_name =
l3_targ_inst_name[i][err_src];
WARN(true, "L3 standard error: TARGET:%s at address 0x%x\n",
target_name,
__raw_readl(l3_targ_base +
L3_TARG_STDERRLOG_SLVOFSLSB));
/* clear the std error log*/
clear = std_err_main | CLEAR_STDERR_LOG;
writel(clear, l3_targ_base +
L3_TARG_STDERRLOG_MAIN);
break;
case CUSTOM_ERROR:
target_name =
l3_targ_inst_name[i][err_src];
for (k = 0; k < NUM_OF_L3_MASTERS; k++) {
if (masterid == l3_masters[k].id)
master_name =
l3_masters[k].name;
}
WARN(true, "L3 custom error: MASTER:%s TARGET:%s\n",
master_name, target_name);
/* clear the std error log*/
clear = std_err_main | CLEAR_STDERR_LOG;
writel(clear, l3_targ_base +
L3_TARG_STDERRLOG_MAIN);
break;
default:
/* Nothing to be handled here as of now */
break;
}
/* Error found so break the for loop */
break;
}
}
return IRQ_HANDLED;
}
static int __devinit omap4_l3_probe(struct platform_device *pdev)
{
static struct omap4_l3 *l3;
struct resource *res;
int ret;
l3 = kzalloc(sizeof(*l3), GFP_KERNEL);
if (!l3)
return -ENOMEM;
platform_set_drvdata(pdev, l3);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "couldn't find resource 0\n");
ret = -ENODEV;
goto err0;
}
l3->l3_base[0] = ioremap(res->start, resource_size(res));
if (!l3->l3_base[0]) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err0;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!res) {
dev_err(&pdev->dev, "couldn't find resource 1\n");
ret = -ENODEV;
goto err1;
}
l3->l3_base[1] = ioremap(res->start, resource_size(res));
if (!l3->l3_base[1]) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err1;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 2);
if (!res) {
dev_err(&pdev->dev, "couldn't find resource 2\n");
ret = -ENODEV;
goto err2;
}
l3->l3_base[2] = ioremap(res->start, resource_size(res));
if (!l3->l3_base[2]) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err2;
}
/*
* Setup interrupt Handlers
*/
l3->debug_irq = platform_get_irq(pdev, 0);
ret = request_irq(l3->debug_irq,
l3_interrupt_handler,
IRQF_DISABLED, "l3-dbg-irq", l3);
if (ret) {
pr_crit("L3: request_irq failed to register for 0x%x\n",
OMAP44XX_IRQ_L3_DBG);
goto err3;
}
l3->app_irq = platform_get_irq(pdev, 1);
ret = request_irq(l3->app_irq,
l3_interrupt_handler,
IRQF_DISABLED, "l3-app-irq", l3);
if (ret) {
pr_crit("L3: request_irq failed to register for 0x%x\n",
OMAP44XX_IRQ_L3_APP);
goto err4;
}
return 0;
err4:
free_irq(l3->debug_irq, l3);
err3:
iounmap(l3->l3_base[2]);
err2:
iounmap(l3->l3_base[1]);
err1:
iounmap(l3->l3_base[0]);
err0:
kfree(l3);
return ret;
}
static int __devexit omap4_l3_remove(struct platform_device *pdev)
{
struct omap4_l3 *l3 = platform_get_drvdata(pdev);
free_irq(l3->app_irq, l3);
free_irq(l3->debug_irq, l3);
iounmap(l3->l3_base[0]);
iounmap(l3->l3_base[1]);
iounmap(l3->l3_base[2]);
kfree(l3);
return 0;
}
#if defined(CONFIG_OF)
static const struct of_device_id l3_noc_match[] = {
{.compatible = "ti,omap4-l3-noc", },
{},
};
MODULE_DEVICE_TABLE(of, l3_noc_match);
#else
#define l3_noc_match NULL
#endif
static struct platform_driver omap4_l3_driver = {
.probe = omap4_l3_probe,
.remove = __devexit_p(omap4_l3_remove),
.driver = {
.name = "omap_l3_noc",
.owner = THIS_MODULE,
.of_match_table = l3_noc_match,
},
};
static int __init omap4_l3_init(void)
{
return platform_driver_register(&omap4_l3_driver);
}
postcore_initcall_sync(omap4_l3_init);
static void __exit omap4_l3_exit(void)
{
platform_driver_unregister(&omap4_l3_driver);
}
module_exit(omap4_l3_exit);
| gpl-2.0 |
Abhinav1997/android_kernel_lge_msm8226 | drivers/media/video/saa7164/saa7164-core.c | 7134 | 42124 | /*
* Driver for the NXP SAA7164 PCIe bridge
*
* Copyright (c) 2010 Steven Toth <stoth@kernellabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kmod.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <asm/div64.h>
#ifdef CONFIG_PROC_FS
#include <linux/proc_fs.h>
#endif
#include "saa7164.h"
MODULE_DESCRIPTION("Driver for NXP SAA7164 based TV cards");
MODULE_AUTHOR("Steven Toth <stoth@kernellabs.com>");
MODULE_LICENSE("GPL");
/*
* 1 Basic
* 2
* 4 i2c
* 8 api
* 16 cmd
* 32 bus
*/
unsigned int saa_debug;
module_param_named(debug, saa_debug, int, 0644);
MODULE_PARM_DESC(debug, "enable debug messages");
unsigned int fw_debug;
module_param(fw_debug, int, 0644);
MODULE_PARM_DESC(fw_debug, "Firware debug level def:2");
unsigned int encoder_buffers = SAA7164_MAX_ENCODER_BUFFERS;
module_param(encoder_buffers, int, 0644);
MODULE_PARM_DESC(encoder_buffers, "Total buffers in read queue 16-512 def:64");
unsigned int vbi_buffers = SAA7164_MAX_VBI_BUFFERS;
module_param(vbi_buffers, int, 0644);
MODULE_PARM_DESC(vbi_buffers, "Total buffers in read queue 16-512 def:64");
unsigned int waitsecs = 10;
module_param(waitsecs, int, 0644);
MODULE_PARM_DESC(waitsecs, "timeout on firmware messages");
static unsigned int card[] = {[0 ... (SAA7164_MAXBOARDS - 1)] = UNSET };
module_param_array(card, int, NULL, 0444);
MODULE_PARM_DESC(card, "card type");
unsigned int print_histogram = 64;
module_param(print_histogram, int, 0644);
MODULE_PARM_DESC(print_histogram, "print histogram values once");
unsigned int crc_checking = 1;
module_param(crc_checking, int, 0644);
MODULE_PARM_DESC(crc_checking, "enable crc sanity checking on buffers");
unsigned int guard_checking = 1;
module_param(guard_checking, int, 0644);
MODULE_PARM_DESC(guard_checking,
"enable dma sanity checking for buffer overruns");
static unsigned int saa7164_devcount;
static DEFINE_MUTEX(devlist);
LIST_HEAD(saa7164_devlist);
#define INT_SIZE 16
void saa7164_dumphex16FF(struct saa7164_dev *dev, u8 *buf, int len)
{
int i;
u8 tmp[16];
memset(&tmp[0], 0xff, sizeof(tmp));
printk(KERN_INFO "--------------------> "
"00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n");
for (i = 0; i < len; i += 16) {
if (memcmp(&tmp, buf + i, sizeof(tmp)) != 0) {
printk(KERN_INFO " [0x%08x] "
"%02x %02x %02x %02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x %02x %02x %02x\n", i,
*(buf+i+0), *(buf+i+1), *(buf+i+2), *(buf+i+3),
*(buf+i+4), *(buf+i+5), *(buf+i+6), *(buf+i+7),
*(buf+i+8), *(buf+i+9), *(buf+i+10), *(buf+i+11),
*(buf+i+12), *(buf+i+13), *(buf+i+14), *(buf+i+15));
}
}
}
static void saa7164_pack_verifier(struct saa7164_buffer *buf)
{
u8 *p = (u8 *)buf->cpu;
int i;
for (i = 0; i < buf->actual_size; i += 2048) {
if ((*(p + i + 0) != 0x00) || (*(p + i + 1) != 0x00) ||
(*(p + i + 2) != 0x01) || (*(p + i + 3) != 0xBA)) {
printk(KERN_ERR "No pack at 0x%x\n", i);
#if 0
saa7164_dumphex16FF(buf->port->dev, (p + i), 32);
#endif
}
}
}
#define FIXED_VIDEO_PID 0xf1
#define FIXED_AUDIO_PID 0xf2
static void saa7164_ts_verifier(struct saa7164_buffer *buf)
{
struct saa7164_port *port = buf->port;
u32 i;
u8 cc, a;
u16 pid;
u8 __iomem *bufcpu = (u8 *)buf->cpu;
port->sync_errors = 0;
port->v_cc_errors = 0;
port->a_cc_errors = 0;
for (i = 0; i < buf->actual_size; i += 188) {
if (*(bufcpu + i) != 0x47)
port->sync_errors++;
/* TODO: Query pid lower 8 bits, ignoring upper bits intensionally */
pid = ((*(bufcpu + i + 1) & 0x1f) << 8) | *(bufcpu + i + 2);
cc = *(bufcpu + i + 3) & 0x0f;
if (pid == FIXED_VIDEO_PID) {
a = ((port->last_v_cc + 1) & 0x0f);
if (a != cc) {
printk(KERN_ERR "video cc last = %x current = %x i = %d\n",
port->last_v_cc, cc, i);
port->v_cc_errors++;
}
port->last_v_cc = cc;
} else
if (pid == FIXED_AUDIO_PID) {
a = ((port->last_a_cc + 1) & 0x0f);
if (a != cc) {
printk(KERN_ERR "audio cc last = %x current = %x i = %d\n",
port->last_a_cc, cc, i);
port->a_cc_errors++;
}
port->last_a_cc = cc;
}
}
/* Only report errors if we've been through this function atleast
* once already and the cached cc values are primed. First time through
* always generates errors.
*/
if (port->v_cc_errors && (port->done_first_interrupt > 1))
printk(KERN_ERR "video pid cc, %d errors\n", port->v_cc_errors);
if (port->a_cc_errors && (port->done_first_interrupt > 1))
printk(KERN_ERR "audio pid cc, %d errors\n", port->a_cc_errors);
if (port->sync_errors && (port->done_first_interrupt > 1))
printk(KERN_ERR "sync_errors = %d\n", port->sync_errors);
if (port->done_first_interrupt == 1)
port->done_first_interrupt++;
}
static void saa7164_histogram_reset(struct saa7164_histogram *hg, char *name)
{
int i;
memset(hg, 0, sizeof(struct saa7164_histogram));
strcpy(hg->name, name);
/* First 30ms x 1ms */
for (i = 0; i < 30; i++)
hg->counter1[0 + i].val = i;
/* 30 - 200ms x 10ms */
for (i = 0; i < 18; i++)
hg->counter1[30 + i].val = 30 + (i * 10);
/* 200 - 2000ms x 100ms */
for (i = 0; i < 15; i++)
hg->counter1[48 + i].val = 200 + (i * 200);
/* Catch all massive value (2secs) */
hg->counter1[55].val = 2000;
/* Catch all massive value (4secs) */
hg->counter1[56].val = 4000;
/* Catch all massive value (8secs) */
hg->counter1[57].val = 8000;
/* Catch all massive value (15secs) */
hg->counter1[58].val = 15000;
/* Catch all massive value (30secs) */
hg->counter1[59].val = 30000;
/* Catch all massive value (60secs) */
hg->counter1[60].val = 60000;
/* Catch all massive value (5mins) */
hg->counter1[61].val = 300000;
/* Catch all massive value (15mins) */
hg->counter1[62].val = 900000;
/* Catch all massive values (1hr) */
hg->counter1[63].val = 3600000;
}
void saa7164_histogram_update(struct saa7164_histogram *hg, u32 val)
{
int i;
for (i = 0; i < 64; i++) {
if (val <= hg->counter1[i].val) {
hg->counter1[i].count++;
hg->counter1[i].update_time = jiffies;
break;
}
}
}
static void saa7164_histogram_print(struct saa7164_port *port,
struct saa7164_histogram *hg)
{
u32 entries = 0;
int i;
printk(KERN_ERR "Histogram named %s (ms, count, last_update_jiffy)\n", hg->name);
for (i = 0; i < 64; i++) {
if (hg->counter1[i].count == 0)
continue;
printk(KERN_ERR " %4d %12d %Ld\n",
hg->counter1[i].val,
hg->counter1[i].count,
hg->counter1[i].update_time);
entries++;
}
printk(KERN_ERR "Total: %d\n", entries);
}
static void saa7164_work_enchandler_helper(struct saa7164_port *port, int bufnr)
{
struct saa7164_dev *dev = port->dev;
struct saa7164_buffer *buf = NULL;
struct saa7164_user_buffer *ubuf = NULL;
struct list_head *c, *n;
int i = 0;
u8 __iomem *p;
mutex_lock(&port->dmaqueue_lock);
list_for_each_safe(c, n, &port->dmaqueue.list) {
buf = list_entry(c, struct saa7164_buffer, list);
if (i++ > port->hwcfg.buffercount) {
printk(KERN_ERR "%s() illegal i count %d\n",
__func__, i);
break;
}
if (buf->idx == bufnr) {
/* Found the buffer, deal with it */
dprintk(DBGLVL_IRQ, "%s() bufnr: %d\n", __func__, bufnr);
if (crc_checking) {
/* Throw a new checksum on the dma buffer */
buf->crc = crc32(0, buf->cpu, buf->actual_size);
}
if (guard_checking) {
p = (u8 *)buf->cpu;
if ((*(p + buf->actual_size + 0) != 0xff) ||
(*(p + buf->actual_size + 1) != 0xff) ||
(*(p + buf->actual_size + 2) != 0xff) ||
(*(p + buf->actual_size + 3) != 0xff) ||
(*(p + buf->actual_size + 0x10) != 0xff) ||
(*(p + buf->actual_size + 0x11) != 0xff) ||
(*(p + buf->actual_size + 0x12) != 0xff) ||
(*(p + buf->actual_size + 0x13) != 0xff)) {
printk(KERN_ERR "%s() buf %p guard buffer breach\n",
__func__, buf);
#if 0
saa7164_dumphex16FF(dev, (p + buf->actual_size) - 32 , 64);
#endif
}
}
if ((port->nr != SAA7164_PORT_VBI1) && (port->nr != SAA7164_PORT_VBI2)) {
/* Validate the incoming buffer content */
if (port->encoder_params.stream_type == V4L2_MPEG_STREAM_TYPE_MPEG2_TS)
saa7164_ts_verifier(buf);
else if (port->encoder_params.stream_type == V4L2_MPEG_STREAM_TYPE_MPEG2_PS)
saa7164_pack_verifier(buf);
}
/* find a free user buffer and clone to it */
if (!list_empty(&port->list_buf_free.list)) {
/* Pull the first buffer from the used list */
ubuf = list_first_entry(&port->list_buf_free.list,
struct saa7164_user_buffer, list);
if (buf->actual_size <= ubuf->actual_size) {
memcpy_fromio(ubuf->data, buf->cpu,
ubuf->actual_size);
if (crc_checking) {
/* Throw a new checksum on the read buffer */
ubuf->crc = crc32(0, ubuf->data, ubuf->actual_size);
}
/* Requeue the buffer on the free list */
ubuf->pos = 0;
list_move_tail(&ubuf->list,
&port->list_buf_used.list);
/* Flag any userland waiters */
wake_up_interruptible(&port->wait_read);
} else {
printk(KERN_ERR "buf %p bufsize fails match\n", buf);
}
} else
printk(KERN_ERR "encirq no free buffers, increase param encoder_buffers\n");
/* Ensure offset into buffer remains 0, fill buffer
* with known bad data. We check for this data at a later point
* in time. */
saa7164_buffer_zero_offsets(port, bufnr);
memset_io(buf->cpu, 0xff, buf->pci_size);
if (crc_checking) {
/* Throw yet aanother new checksum on the dma buffer */
buf->crc = crc32(0, buf->cpu, buf->actual_size);
}
break;
}
}
mutex_unlock(&port->dmaqueue_lock);
}
static void saa7164_work_enchandler(struct work_struct *w)
{
struct saa7164_port *port =
container_of(w, struct saa7164_port, workenc);
struct saa7164_dev *dev = port->dev;
u32 wp, mcb, rp, cnt = 0;
port->last_svc_msecs_diff = port->last_svc_msecs;
port->last_svc_msecs = jiffies_to_msecs(jiffies);
port->last_svc_msecs_diff = port->last_svc_msecs -
port->last_svc_msecs_diff;
saa7164_histogram_update(&port->svc_interval,
port->last_svc_msecs_diff);
port->last_irq_svc_msecs_diff = port->last_svc_msecs -
port->last_irq_msecs;
saa7164_histogram_update(&port->irq_svc_interval,
port->last_irq_svc_msecs_diff);
dprintk(DBGLVL_IRQ,
"%s() %Ldms elapsed irq->deferred %Ldms wp: %d rp: %d\n",
__func__,
port->last_svc_msecs_diff,
port->last_irq_svc_msecs_diff,
port->last_svc_wp,
port->last_svc_rp
);
/* Current write position */
wp = saa7164_readl(port->bufcounter);
if (wp > (port->hwcfg.buffercount - 1)) {
printk(KERN_ERR "%s() illegal buf count %d\n", __func__, wp);
return;
}
/* Most current complete buffer */
if (wp == 0)
mcb = (port->hwcfg.buffercount - 1);
else
mcb = wp - 1;
while (1) {
if (port->done_first_interrupt == 0) {
port->done_first_interrupt++;
rp = mcb;
} else
rp = (port->last_svc_rp + 1) % 8;
if ((rp < 0) || (rp > (port->hwcfg.buffercount - 1))) {
printk(KERN_ERR "%s() illegal rp count %d\n", __func__, rp);
break;
}
saa7164_work_enchandler_helper(port, rp);
port->last_svc_rp = rp;
cnt++;
if (rp == mcb)
break;
}
/* TODO: Convert this into a /proc/saa7164 style readable file */
if (print_histogram == port->nr) {
saa7164_histogram_print(port, &port->irq_interval);
saa7164_histogram_print(port, &port->svc_interval);
saa7164_histogram_print(port, &port->irq_svc_interval);
saa7164_histogram_print(port, &port->read_interval);
saa7164_histogram_print(port, &port->poll_interval);
/* TODO: fix this to preserve any previous state */
print_histogram = 64 + port->nr;
}
}
static void saa7164_work_vbihandler(struct work_struct *w)
{
struct saa7164_port *port =
container_of(w, struct saa7164_port, workenc);
struct saa7164_dev *dev = port->dev;
u32 wp, mcb, rp, cnt = 0;
port->last_svc_msecs_diff = port->last_svc_msecs;
port->last_svc_msecs = jiffies_to_msecs(jiffies);
port->last_svc_msecs_diff = port->last_svc_msecs -
port->last_svc_msecs_diff;
saa7164_histogram_update(&port->svc_interval,
port->last_svc_msecs_diff);
port->last_irq_svc_msecs_diff = port->last_svc_msecs -
port->last_irq_msecs;
saa7164_histogram_update(&port->irq_svc_interval,
port->last_irq_svc_msecs_diff);
dprintk(DBGLVL_IRQ,
"%s() %Ldms elapsed irq->deferred %Ldms wp: %d rp: %d\n",
__func__,
port->last_svc_msecs_diff,
port->last_irq_svc_msecs_diff,
port->last_svc_wp,
port->last_svc_rp
);
/* Current write position */
wp = saa7164_readl(port->bufcounter);
if (wp > (port->hwcfg.buffercount - 1)) {
printk(KERN_ERR "%s() illegal buf count %d\n", __func__, wp);
return;
}
/* Most current complete buffer */
if (wp == 0)
mcb = (port->hwcfg.buffercount - 1);
else
mcb = wp - 1;
while (1) {
if (port->done_first_interrupt == 0) {
port->done_first_interrupt++;
rp = mcb;
} else
rp = (port->last_svc_rp + 1) % 8;
if ((rp < 0) || (rp > (port->hwcfg.buffercount - 1))) {
printk(KERN_ERR "%s() illegal rp count %d\n", __func__, rp);
break;
}
saa7164_work_enchandler_helper(port, rp);
port->last_svc_rp = rp;
cnt++;
if (rp == mcb)
break;
}
/* TODO: Convert this into a /proc/saa7164 style readable file */
if (print_histogram == port->nr) {
saa7164_histogram_print(port, &port->irq_interval);
saa7164_histogram_print(port, &port->svc_interval);
saa7164_histogram_print(port, &port->irq_svc_interval);
saa7164_histogram_print(port, &port->read_interval);
saa7164_histogram_print(port, &port->poll_interval);
/* TODO: fix this to preserve any previous state */
print_histogram = 64 + port->nr;
}
}
static void saa7164_work_cmdhandler(struct work_struct *w)
{
struct saa7164_dev *dev = container_of(w, struct saa7164_dev, workcmd);
/* Wake up any complete commands */
saa7164_irq_dequeue(dev);
}
static void saa7164_buffer_deliver(struct saa7164_buffer *buf)
{
struct saa7164_port *port = buf->port;
/* Feed the transport payload into the kernel demux */
dvb_dmx_swfilter_packets(&port->dvb.demux, (u8 *)buf->cpu,
SAA7164_TS_NUMBER_OF_LINES);
}
static irqreturn_t saa7164_irq_vbi(struct saa7164_port *port)
{
struct saa7164_dev *dev = port->dev;
/* Store old time */
port->last_irq_msecs_diff = port->last_irq_msecs;
/* Collect new stats */
port->last_irq_msecs = jiffies_to_msecs(jiffies);
/* Calculate stats */
port->last_irq_msecs_diff = port->last_irq_msecs -
port->last_irq_msecs_diff;
saa7164_histogram_update(&port->irq_interval,
port->last_irq_msecs_diff);
dprintk(DBGLVL_IRQ, "%s() %Ldms elapsed\n", __func__,
port->last_irq_msecs_diff);
/* Tis calls the vbi irq handler */
schedule_work(&port->workenc);
return 0;
}
static irqreturn_t saa7164_irq_encoder(struct saa7164_port *port)
{
struct saa7164_dev *dev = port->dev;
/* Store old time */
port->last_irq_msecs_diff = port->last_irq_msecs;
/* Collect new stats */
port->last_irq_msecs = jiffies_to_msecs(jiffies);
/* Calculate stats */
port->last_irq_msecs_diff = port->last_irq_msecs -
port->last_irq_msecs_diff;
saa7164_histogram_update(&port->irq_interval,
port->last_irq_msecs_diff);
dprintk(DBGLVL_IRQ, "%s() %Ldms elapsed\n", __func__,
port->last_irq_msecs_diff);
schedule_work(&port->workenc);
return 0;
}
static irqreturn_t saa7164_irq_ts(struct saa7164_port *port)
{
struct saa7164_dev *dev = port->dev;
struct saa7164_buffer *buf;
struct list_head *c, *n;
int wp, i = 0, rp;
/* Find the current write point from the hardware */
wp = saa7164_readl(port->bufcounter);
if (wp > (port->hwcfg.buffercount - 1))
BUG();
/* Find the previous buffer to the current write point */
if (wp == 0)
rp = (port->hwcfg.buffercount - 1);
else
rp = wp - 1;
/* Lookup the WP in the buffer list */
/* TODO: turn this into a worker thread */
list_for_each_safe(c, n, &port->dmaqueue.list) {
buf = list_entry(c, struct saa7164_buffer, list);
if (i++ > port->hwcfg.buffercount)
BUG();
if (buf->idx == rp) {
/* Found the buffer, deal with it */
dprintk(DBGLVL_IRQ, "%s() wp: %d processing: %d\n",
__func__, wp, rp);
saa7164_buffer_deliver(buf);
break;
}
}
return 0;
}
/* Primary IRQ handler and dispatch mechanism */
static irqreturn_t saa7164_irq(int irq, void *dev_id)
{
struct saa7164_dev *dev = dev_id;
struct saa7164_port *porta = &dev->ports[SAA7164_PORT_TS1];
struct saa7164_port *portb = &dev->ports[SAA7164_PORT_TS2];
struct saa7164_port *portc = &dev->ports[SAA7164_PORT_ENC1];
struct saa7164_port *portd = &dev->ports[SAA7164_PORT_ENC2];
struct saa7164_port *porte = &dev->ports[SAA7164_PORT_VBI1];
struct saa7164_port *portf = &dev->ports[SAA7164_PORT_VBI2];
u32 intid, intstat[INT_SIZE/4];
int i, handled = 0, bit;
if (dev == NULL) {
printk(KERN_ERR "%s() No device specified\n", __func__);
handled = 0;
goto out;
}
/* Check that the hardware is accessible. If the status bytes are
* 0xFF then the device is not accessible, the the IRQ belongs
* to another driver.
* 4 x u32 interrupt registers.
*/
for (i = 0; i < INT_SIZE/4; i++) {
/* TODO: Convert into saa7164_readl() */
/* Read the 4 hardware interrupt registers */
intstat[i] = saa7164_readl(dev->int_status + (i * 4));
if (intstat[i])
handled = 1;
}
if (handled == 0)
goto out;
/* For each of the HW interrupt registers */
for (i = 0; i < INT_SIZE/4; i++) {
if (intstat[i]) {
/* Each function of the board has it's own interruptid.
* Find the function that triggered then call
* it's handler.
*/
for (bit = 0; bit < 32; bit++) {
if (((intstat[i] >> bit) & 0x00000001) == 0)
continue;
/* Calculate the interrupt id (0x00 to 0x7f) */
intid = (i * 32) + bit;
if (intid == dev->intfdesc.bInterruptId) {
/* A response to an cmd/api call */
schedule_work(&dev->workcmd);
} else if (intid == porta->hwcfg.interruptid) {
/* Transport path 1 */
saa7164_irq_ts(porta);
} else if (intid == portb->hwcfg.interruptid) {
/* Transport path 2 */
saa7164_irq_ts(portb);
} else if (intid == portc->hwcfg.interruptid) {
/* Encoder path 1 */
saa7164_irq_encoder(portc);
} else if (intid == portd->hwcfg.interruptid) {
/* Encoder path 2 */
saa7164_irq_encoder(portd);
} else if (intid == porte->hwcfg.interruptid) {
/* VBI path 1 */
saa7164_irq_vbi(porte);
} else if (intid == portf->hwcfg.interruptid) {
/* VBI path 2 */
saa7164_irq_vbi(portf);
} else {
/* Find the function */
dprintk(DBGLVL_IRQ,
"%s() unhandled interrupt "
"reg 0x%x bit 0x%x "
"intid = 0x%x\n",
__func__, i, bit, intid);
}
}
/* Ack it */
saa7164_writel(dev->int_ack + (i * 4), intstat[i]);
}
}
out:
return IRQ_RETVAL(handled);
}
void saa7164_getfirmwarestatus(struct saa7164_dev *dev)
{
struct saa7164_fw_status *s = &dev->fw_status;
dev->fw_status.status = saa7164_readl(SAA_DEVICE_SYSINIT_STATUS);
dev->fw_status.mode = saa7164_readl(SAA_DEVICE_SYSINIT_MODE);
dev->fw_status.spec = saa7164_readl(SAA_DEVICE_SYSINIT_SPEC);
dev->fw_status.inst = saa7164_readl(SAA_DEVICE_SYSINIT_INST);
dev->fw_status.cpuload = saa7164_readl(SAA_DEVICE_SYSINIT_CPULOAD);
dev->fw_status.remainheap =
saa7164_readl(SAA_DEVICE_SYSINIT_REMAINHEAP);
dprintk(1, "Firmware status:\n");
dprintk(1, " .status = 0x%08x\n", s->status);
dprintk(1, " .mode = 0x%08x\n", s->mode);
dprintk(1, " .spec = 0x%08x\n", s->spec);
dprintk(1, " .inst = 0x%08x\n", s->inst);
dprintk(1, " .cpuload = 0x%08x\n", s->cpuload);
dprintk(1, " .remainheap = 0x%08x\n", s->remainheap);
}
u32 saa7164_getcurrentfirmwareversion(struct saa7164_dev *dev)
{
u32 reg;
reg = saa7164_readl(SAA_DEVICE_VERSION);
dprintk(1, "Device running firmware version %d.%d.%d.%d (0x%x)\n",
(reg & 0x0000fc00) >> 10,
(reg & 0x000003e0) >> 5,
(reg & 0x0000001f),
(reg & 0xffff0000) >> 16,
reg);
return reg;
}
/* TODO: Debugging func, remove */
void saa7164_dumphex16(struct saa7164_dev *dev, u8 *buf, int len)
{
int i;
printk(KERN_INFO "--------------------> "
"00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n");
for (i = 0; i < len; i += 16)
printk(KERN_INFO " [0x%08x] "
"%02x %02x %02x %02x %02x %02x %02x %02x "
"%02x %02x %02x %02x %02x %02x %02x %02x\n", i,
*(buf+i+0), *(buf+i+1), *(buf+i+2), *(buf+i+3),
*(buf+i+4), *(buf+i+5), *(buf+i+6), *(buf+i+7),
*(buf+i+8), *(buf+i+9), *(buf+i+10), *(buf+i+11),
*(buf+i+12), *(buf+i+13), *(buf+i+14), *(buf+i+15));
}
/* TODO: Debugging func, remove */
void saa7164_dumpregs(struct saa7164_dev *dev, u32 addr)
{
int i;
dprintk(1, "--------------------> "
"00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n");
for (i = 0; i < 0x100; i += 16)
dprintk(1, "region0[0x%08x] = "
"%02x %02x %02x %02x %02x %02x %02x %02x"
" %02x %02x %02x %02x %02x %02x %02x %02x\n", i,
(u8)saa7164_readb(addr + i + 0),
(u8)saa7164_readb(addr + i + 1),
(u8)saa7164_readb(addr + i + 2),
(u8)saa7164_readb(addr + i + 3),
(u8)saa7164_readb(addr + i + 4),
(u8)saa7164_readb(addr + i + 5),
(u8)saa7164_readb(addr + i + 6),
(u8)saa7164_readb(addr + i + 7),
(u8)saa7164_readb(addr + i + 8),
(u8)saa7164_readb(addr + i + 9),
(u8)saa7164_readb(addr + i + 10),
(u8)saa7164_readb(addr + i + 11),
(u8)saa7164_readb(addr + i + 12),
(u8)saa7164_readb(addr + i + 13),
(u8)saa7164_readb(addr + i + 14),
(u8)saa7164_readb(addr + i + 15)
);
}
static void saa7164_dump_hwdesc(struct saa7164_dev *dev)
{
dprintk(1, "@0x%p hwdesc sizeof(struct tmComResHWDescr) = %d bytes\n",
&dev->hwdesc, (u32)sizeof(struct tmComResHWDescr));
dprintk(1, " .bLength = 0x%x\n", dev->hwdesc.bLength);
dprintk(1, " .bDescriptorType = 0x%x\n", dev->hwdesc.bDescriptorType);
dprintk(1, " .bDescriptorSubtype = 0x%x\n",
dev->hwdesc.bDescriptorSubtype);
dprintk(1, " .bcdSpecVersion = 0x%x\n", dev->hwdesc.bcdSpecVersion);
dprintk(1, " .dwClockFrequency = 0x%x\n", dev->hwdesc.dwClockFrequency);
dprintk(1, " .dwClockUpdateRes = 0x%x\n", dev->hwdesc.dwClockUpdateRes);
dprintk(1, " .bCapabilities = 0x%x\n", dev->hwdesc.bCapabilities);
dprintk(1, " .dwDeviceRegistersLocation = 0x%x\n",
dev->hwdesc.dwDeviceRegistersLocation);
dprintk(1, " .dwHostMemoryRegion = 0x%x\n",
dev->hwdesc.dwHostMemoryRegion);
dprintk(1, " .dwHostMemoryRegionSize = 0x%x\n",
dev->hwdesc.dwHostMemoryRegionSize);
dprintk(1, " .dwHostHibernatMemRegion = 0x%x\n",
dev->hwdesc.dwHostHibernatMemRegion);
dprintk(1, " .dwHostHibernatMemRegionSize = 0x%x\n",
dev->hwdesc.dwHostHibernatMemRegionSize);
}
static void saa7164_dump_intfdesc(struct saa7164_dev *dev)
{
dprintk(1, "@0x%p intfdesc "
"sizeof(struct tmComResInterfaceDescr) = %d bytes\n",
&dev->intfdesc, (u32)sizeof(struct tmComResInterfaceDescr));
dprintk(1, " .bLength = 0x%x\n", dev->intfdesc.bLength);
dprintk(1, " .bDescriptorType = 0x%x\n", dev->intfdesc.bDescriptorType);
dprintk(1, " .bDescriptorSubtype = 0x%x\n",
dev->intfdesc.bDescriptorSubtype);
dprintk(1, " .bFlags = 0x%x\n", dev->intfdesc.bFlags);
dprintk(1, " .bInterfaceType = 0x%x\n", dev->intfdesc.bInterfaceType);
dprintk(1, " .bInterfaceId = 0x%x\n", dev->intfdesc.bInterfaceId);
dprintk(1, " .bBaseInterface = 0x%x\n", dev->intfdesc.bBaseInterface);
dprintk(1, " .bInterruptId = 0x%x\n", dev->intfdesc.bInterruptId);
dprintk(1, " .bDebugInterruptId = 0x%x\n",
dev->intfdesc.bDebugInterruptId);
dprintk(1, " .BARLocation = 0x%x\n", dev->intfdesc.BARLocation);
}
static void saa7164_dump_busdesc(struct saa7164_dev *dev)
{
dprintk(1, "@0x%p busdesc sizeof(struct tmComResBusDescr) = %d bytes\n",
&dev->busdesc, (u32)sizeof(struct tmComResBusDescr));
dprintk(1, " .CommandRing = 0x%016Lx\n", dev->busdesc.CommandRing);
dprintk(1, " .ResponseRing = 0x%016Lx\n", dev->busdesc.ResponseRing);
dprintk(1, " .CommandWrite = 0x%x\n", dev->busdesc.CommandWrite);
dprintk(1, " .CommandRead = 0x%x\n", dev->busdesc.CommandRead);
dprintk(1, " .ResponseWrite = 0x%x\n", dev->busdesc.ResponseWrite);
dprintk(1, " .ResponseRead = 0x%x\n", dev->busdesc.ResponseRead);
}
/* Much of the hardware configuration and PCI registers are configured
* dynamically depending on firmware. We have to cache some initial
* structures then use these to locate other important structures
* from PCI space.
*/
static void saa7164_get_descriptors(struct saa7164_dev *dev)
{
memcpy_fromio(&dev->hwdesc, dev->bmmio, sizeof(struct tmComResHWDescr));
memcpy_fromio(&dev->intfdesc, dev->bmmio + sizeof(struct tmComResHWDescr),
sizeof(struct tmComResInterfaceDescr));
memcpy_fromio(&dev->busdesc, dev->bmmio + dev->intfdesc.BARLocation,
sizeof(struct tmComResBusDescr));
if (dev->hwdesc.bLength != sizeof(struct tmComResHWDescr)) {
printk(KERN_ERR "Structure struct tmComResHWDescr is mangled\n");
printk(KERN_ERR "Need %x got %d\n", dev->hwdesc.bLength,
(u32)sizeof(struct tmComResHWDescr));
} else
saa7164_dump_hwdesc(dev);
if (dev->intfdesc.bLength != sizeof(struct tmComResInterfaceDescr)) {
printk(KERN_ERR "struct struct tmComResInterfaceDescr is mangled\n");
printk(KERN_ERR "Need %x got %d\n", dev->intfdesc.bLength,
(u32)sizeof(struct tmComResInterfaceDescr));
} else
saa7164_dump_intfdesc(dev);
saa7164_dump_busdesc(dev);
}
static int saa7164_pci_quirks(struct saa7164_dev *dev)
{
return 0;
}
static int get_resources(struct saa7164_dev *dev)
{
if (request_mem_region(pci_resource_start(dev->pci, 0),
pci_resource_len(dev->pci, 0), dev->name)) {
if (request_mem_region(pci_resource_start(dev->pci, 2),
pci_resource_len(dev->pci, 2), dev->name))
return 0;
}
printk(KERN_ERR "%s: can't get MMIO memory @ 0x%llx or 0x%llx\n",
dev->name,
(u64)pci_resource_start(dev->pci, 0),
(u64)pci_resource_start(dev->pci, 2));
return -EBUSY;
}
static int saa7164_port_init(struct saa7164_dev *dev, int portnr)
{
struct saa7164_port *port = NULL;
if ((portnr < 0) || (portnr >= SAA7164_MAX_PORTS))
BUG();
port = &dev->ports[portnr];
port->dev = dev;
port->nr = portnr;
if ((portnr == SAA7164_PORT_TS1) || (portnr == SAA7164_PORT_TS2))
port->type = SAA7164_MPEG_DVB;
else
if ((portnr == SAA7164_PORT_ENC1) || (portnr == SAA7164_PORT_ENC2)) {
port->type = SAA7164_MPEG_ENCODER;
/* We need a deferred interrupt handler for cmd handling */
INIT_WORK(&port->workenc, saa7164_work_enchandler);
} else if ((portnr == SAA7164_PORT_VBI1) || (portnr == SAA7164_PORT_VBI2)) {
port->type = SAA7164_MPEG_VBI;
/* We need a deferred interrupt handler for cmd handling */
INIT_WORK(&port->workenc, saa7164_work_vbihandler);
} else
BUG();
/* Init all the critical resources */
mutex_init(&port->dvb.lock);
INIT_LIST_HEAD(&port->dmaqueue.list);
mutex_init(&port->dmaqueue_lock);
INIT_LIST_HEAD(&port->list_buf_used.list);
INIT_LIST_HEAD(&port->list_buf_free.list);
init_waitqueue_head(&port->wait_read);
saa7164_histogram_reset(&port->irq_interval, "irq intervals");
saa7164_histogram_reset(&port->svc_interval, "deferred intervals");
saa7164_histogram_reset(&port->irq_svc_interval,
"irq to deferred intervals");
saa7164_histogram_reset(&port->read_interval,
"encoder/vbi read() intervals");
saa7164_histogram_reset(&port->poll_interval,
"encoder/vbi poll() intervals");
return 0;
}
static int saa7164_dev_setup(struct saa7164_dev *dev)
{
int i;
mutex_init(&dev->lock);
atomic_inc(&dev->refcount);
dev->nr = saa7164_devcount++;
snprintf(dev->name, sizeof(dev->name), "saa7164[%d]", dev->nr);
mutex_lock(&devlist);
list_add_tail(&dev->devlist, &saa7164_devlist);
mutex_unlock(&devlist);
/* board config */
dev->board = UNSET;
if (card[dev->nr] < saa7164_bcount)
dev->board = card[dev->nr];
for (i = 0; UNSET == dev->board && i < saa7164_idcount; i++)
if (dev->pci->subsystem_vendor == saa7164_subids[i].subvendor &&
dev->pci->subsystem_device ==
saa7164_subids[i].subdevice)
dev->board = saa7164_subids[i].card;
if (UNSET == dev->board) {
dev->board = SAA7164_BOARD_UNKNOWN;
saa7164_card_list(dev);
}
dev->pci_bus = dev->pci->bus->number;
dev->pci_slot = PCI_SLOT(dev->pci->devfn);
/* I2C Defaults / setup */
dev->i2c_bus[0].dev = dev;
dev->i2c_bus[0].nr = 0;
dev->i2c_bus[1].dev = dev;
dev->i2c_bus[1].nr = 1;
dev->i2c_bus[2].dev = dev;
dev->i2c_bus[2].nr = 2;
/* Transport + Encoder ports 1, 2, 3, 4 - Defaults / setup */
saa7164_port_init(dev, SAA7164_PORT_TS1);
saa7164_port_init(dev, SAA7164_PORT_TS2);
saa7164_port_init(dev, SAA7164_PORT_ENC1);
saa7164_port_init(dev, SAA7164_PORT_ENC2);
saa7164_port_init(dev, SAA7164_PORT_VBI1);
saa7164_port_init(dev, SAA7164_PORT_VBI2);
if (get_resources(dev) < 0) {
printk(KERN_ERR "CORE %s No more PCIe resources for "
"subsystem: %04x:%04x\n",
dev->name, dev->pci->subsystem_vendor,
dev->pci->subsystem_device);
saa7164_devcount--;
return -ENODEV;
}
/* PCI/e allocations */
dev->lmmio = ioremap(pci_resource_start(dev->pci, 0),
pci_resource_len(dev->pci, 0));
dev->lmmio2 = ioremap(pci_resource_start(dev->pci, 2),
pci_resource_len(dev->pci, 2));
dev->bmmio = (u8 __iomem *)dev->lmmio;
dev->bmmio2 = (u8 __iomem *)dev->lmmio2;
/* Inerrupt and ack register locations offset of bmmio */
dev->int_status = 0x183000 + 0xf80;
dev->int_ack = 0x183000 + 0xf90;
printk(KERN_INFO
"CORE %s: subsystem: %04x:%04x, board: %s [card=%d,%s]\n",
dev->name, dev->pci->subsystem_vendor,
dev->pci->subsystem_device, saa7164_boards[dev->board].name,
dev->board, card[dev->nr] == dev->board ?
"insmod option" : "autodetected");
saa7164_pci_quirks(dev);
return 0;
}
static void saa7164_dev_unregister(struct saa7164_dev *dev)
{
dprintk(1, "%s()\n", __func__);
release_mem_region(pci_resource_start(dev->pci, 0),
pci_resource_len(dev->pci, 0));
release_mem_region(pci_resource_start(dev->pci, 2),
pci_resource_len(dev->pci, 2));
if (!atomic_dec_and_test(&dev->refcount))
return;
iounmap(dev->lmmio);
iounmap(dev->lmmio2);
return;
}
#ifdef CONFIG_PROC_FS
static int saa7164_proc_show(struct seq_file *m, void *v)
{
struct saa7164_dev *dev;
struct tmComResBusInfo *b;
struct list_head *list;
int i, c;
if (saa7164_devcount == 0)
return 0;
list_for_each(list, &saa7164_devlist) {
dev = list_entry(list, struct saa7164_dev, devlist);
seq_printf(m, "%s = %p\n", dev->name, dev);
/* Lock the bus from any other access */
b = &dev->bus;
mutex_lock(&b->lock);
seq_printf(m, " .m_pdwSetWritePos = 0x%x (0x%08x)\n",
b->m_dwSetReadPos, saa7164_readl(b->m_dwSetReadPos));
seq_printf(m, " .m_pdwSetReadPos = 0x%x (0x%08x)\n",
b->m_dwSetWritePos, saa7164_readl(b->m_dwSetWritePos));
seq_printf(m, " .m_pdwGetWritePos = 0x%x (0x%08x)\n",
b->m_dwGetReadPos, saa7164_readl(b->m_dwGetReadPos));
seq_printf(m, " .m_pdwGetReadPos = 0x%x (0x%08x)\n",
b->m_dwGetWritePos, saa7164_readl(b->m_dwGetWritePos));
c = 0;
seq_printf(m, "\n Set Ring:\n");
seq_printf(m, "\n addr 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n");
for (i = 0; i < b->m_dwSizeSetRing; i++) {
if (c == 0)
seq_printf(m, " %04x:", i);
seq_printf(m, " %02x", *(b->m_pdwSetRing + i));
if (++c == 16) {
seq_printf(m, "\n");
c = 0;
}
}
c = 0;
seq_printf(m, "\n Get Ring:\n");
seq_printf(m, "\n addr 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f\n");
for (i = 0; i < b->m_dwSizeGetRing; i++) {
if (c == 0)
seq_printf(m, " %04x:", i);
seq_printf(m, " %02x", *(b->m_pdwGetRing + i));
if (++c == 16) {
seq_printf(m, "\n");
c = 0;
}
}
mutex_unlock(&b->lock);
}
return 0;
}
static int saa7164_proc_open(struct inode *inode, struct file *filp)
{
return single_open(filp, saa7164_proc_show, NULL);
}
static const struct file_operations saa7164_proc_fops = {
.open = saa7164_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int saa7164_proc_create(void)
{
struct proc_dir_entry *pe;
pe = proc_create("saa7164", S_IRUGO, NULL, &saa7164_proc_fops);
if (!pe)
return -ENOMEM;
return 0;
}
#endif
static int saa7164_thread_function(void *data)
{
struct saa7164_dev *dev = data;
struct tmFwInfoStruct fwinfo;
u64 last_poll_time = 0;
dprintk(DBGLVL_THR, "thread started\n");
set_freezable();
while (1) {
msleep_interruptible(100);
if (kthread_should_stop())
break;
try_to_freeze();
dprintk(DBGLVL_THR, "thread running\n");
/* Dump the firmware debug message to console */
/* Polling this costs us 1-2% of the arm CPU */
/* convert this into a respnde to interrupt 0x7a */
saa7164_api_collect_debug(dev);
/* Monitor CPU load every 1 second */
if ((last_poll_time + 1000 /* ms */) < jiffies_to_msecs(jiffies)) {
saa7164_api_get_load_info(dev, &fwinfo);
last_poll_time = jiffies_to_msecs(jiffies);
}
}
dprintk(DBGLVL_THR, "thread exiting\n");
return 0;
}
static int __devinit saa7164_initdev(struct pci_dev *pci_dev,
const struct pci_device_id *pci_id)
{
struct saa7164_dev *dev;
int err, i;
u32 version;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (NULL == dev)
return -ENOMEM;
/* pci init */
dev->pci = pci_dev;
if (pci_enable_device(pci_dev)) {
err = -EIO;
goto fail_free;
}
if (saa7164_dev_setup(dev) < 0) {
err = -EINVAL;
goto fail_free;
}
/* print pci info */
dev->pci_rev = pci_dev->revision;
pci_read_config_byte(pci_dev, PCI_LATENCY_TIMER, &dev->pci_lat);
printk(KERN_INFO "%s/0: found at %s, rev: %d, irq: %d, "
"latency: %d, mmio: 0x%llx\n", dev->name,
pci_name(pci_dev), dev->pci_rev, pci_dev->irq,
dev->pci_lat,
(unsigned long long)pci_resource_start(pci_dev, 0));
pci_set_master(pci_dev);
/* TODO */
if (!pci_dma_supported(pci_dev, 0xffffffff)) {
printk("%s/0: Oops: no 32bit PCI DMA ???\n", dev->name);
err = -EIO;
goto fail_irq;
}
err = request_irq(pci_dev->irq, saa7164_irq,
IRQF_SHARED | IRQF_DISABLED, dev->name, dev);
if (err < 0) {
printk(KERN_ERR "%s: can't get IRQ %d\n", dev->name,
pci_dev->irq);
err = -EIO;
goto fail_irq;
}
pci_set_drvdata(pci_dev, dev);
/* Init the internal command list */
for (i = 0; i < SAA_CMD_MAX_MSG_UNITS; i++) {
dev->cmds[i].seqno = i;
dev->cmds[i].inuse = 0;
mutex_init(&dev->cmds[i].lock);
init_waitqueue_head(&dev->cmds[i].wait);
}
/* We need a deferred interrupt handler for cmd handling */
INIT_WORK(&dev->workcmd, saa7164_work_cmdhandler);
/* Only load the firmware if we know the board */
if (dev->board != SAA7164_BOARD_UNKNOWN) {
err = saa7164_downloadfirmware(dev);
if (err < 0) {
printk(KERN_ERR
"Failed to boot firmware, no features "
"registered\n");
goto fail_fw;
}
saa7164_get_descriptors(dev);
saa7164_dumpregs(dev, 0);
saa7164_getcurrentfirmwareversion(dev);
saa7164_getfirmwarestatus(dev);
err = saa7164_bus_setup(dev);
if (err < 0)
printk(KERN_ERR
"Failed to setup the bus, will continue\n");
saa7164_bus_dump(dev);
/* Ping the running firmware via the command bus and get the
* firmware version, this checks the bus is running OK.
*/
version = 0;
if (saa7164_api_get_fw_version(dev, &version) == SAA_OK)
dprintk(1, "Bus is operating correctly using "
"version %d.%d.%d.%d (0x%x)\n",
(version & 0x0000fc00) >> 10,
(version & 0x000003e0) >> 5,
(version & 0x0000001f),
(version & 0xffff0000) >> 16,
version);
else
printk(KERN_ERR
"Failed to communicate with the firmware\n");
/* Bring up the I2C buses */
saa7164_i2c_register(&dev->i2c_bus[0]);
saa7164_i2c_register(&dev->i2c_bus[1]);
saa7164_i2c_register(&dev->i2c_bus[2]);
saa7164_gpio_setup(dev);
saa7164_card_setup(dev);
/* Parse the dynamic device configuration, find various
* media endpoints (MPEG, WMV, PS, TS) and cache their
* configuration details into the driver, so we can
* reference them later during simething_register() func,
* interrupt handlers, deferred work handlers etc.
*/
saa7164_api_enum_subdevs(dev);
/* Begin to create the video sub-systems and register funcs */
if (saa7164_boards[dev->board].porta == SAA7164_MPEG_DVB) {
if (saa7164_dvb_register(&dev->ports[SAA7164_PORT_TS1]) < 0) {
printk(KERN_ERR "%s() Failed to register "
"dvb adapters on porta\n",
__func__);
}
}
if (saa7164_boards[dev->board].portb == SAA7164_MPEG_DVB) {
if (saa7164_dvb_register(&dev->ports[SAA7164_PORT_TS2]) < 0) {
printk(KERN_ERR"%s() Failed to register "
"dvb adapters on portb\n",
__func__);
}
}
if (saa7164_boards[dev->board].portc == SAA7164_MPEG_ENCODER) {
if (saa7164_encoder_register(&dev->ports[SAA7164_PORT_ENC1]) < 0) {
printk(KERN_ERR"%s() Failed to register "
"mpeg encoder\n", __func__);
}
}
if (saa7164_boards[dev->board].portd == SAA7164_MPEG_ENCODER) {
if (saa7164_encoder_register(&dev->ports[SAA7164_PORT_ENC2]) < 0) {
printk(KERN_ERR"%s() Failed to register "
"mpeg encoder\n", __func__);
}
}
if (saa7164_boards[dev->board].porte == SAA7164_MPEG_VBI) {
if (saa7164_vbi_register(&dev->ports[SAA7164_PORT_VBI1]) < 0) {
printk(KERN_ERR"%s() Failed to register "
"vbi device\n", __func__);
}
}
if (saa7164_boards[dev->board].portf == SAA7164_MPEG_VBI) {
if (saa7164_vbi_register(&dev->ports[SAA7164_PORT_VBI2]) < 0) {
printk(KERN_ERR"%s() Failed to register "
"vbi device\n", __func__);
}
}
saa7164_api_set_debug(dev, fw_debug);
if (fw_debug) {
dev->kthread = kthread_run(saa7164_thread_function, dev,
"saa7164 debug");
if (!dev->kthread)
printk(KERN_ERR "%s() Failed to create "
"debug kernel thread\n", __func__);
}
} /* != BOARD_UNKNOWN */
else
printk(KERN_ERR "%s() Unsupported board detected, "
"registering without firmware\n", __func__);
dprintk(1, "%s() parameter debug = %d\n", __func__, saa_debug);
dprintk(1, "%s() parameter waitsecs = %d\n", __func__, waitsecs);
fail_fw:
return 0;
fail_irq:
saa7164_dev_unregister(dev);
fail_free:
kfree(dev);
return err;
}
static void saa7164_shutdown(struct saa7164_dev *dev)
{
dprintk(1, "%s()\n", __func__);
}
static void __devexit saa7164_finidev(struct pci_dev *pci_dev)
{
struct saa7164_dev *dev = pci_get_drvdata(pci_dev);
if (dev->board != SAA7164_BOARD_UNKNOWN) {
if (fw_debug && dev->kthread) {
kthread_stop(dev->kthread);
dev->kthread = NULL;
}
if (dev->firmwareloaded)
saa7164_api_set_debug(dev, 0x00);
}
saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
&dev->ports[SAA7164_PORT_ENC1].irq_interval);
saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
&dev->ports[SAA7164_PORT_ENC1].svc_interval);
saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
&dev->ports[SAA7164_PORT_ENC1].irq_svc_interval);
saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
&dev->ports[SAA7164_PORT_ENC1].read_interval);
saa7164_histogram_print(&dev->ports[SAA7164_PORT_ENC1],
&dev->ports[SAA7164_PORT_ENC1].poll_interval);
saa7164_histogram_print(&dev->ports[SAA7164_PORT_VBI1],
&dev->ports[SAA7164_PORT_VBI1].read_interval);
saa7164_histogram_print(&dev->ports[SAA7164_PORT_VBI2],
&dev->ports[SAA7164_PORT_VBI2].poll_interval);
saa7164_shutdown(dev);
if (saa7164_boards[dev->board].porta == SAA7164_MPEG_DVB)
saa7164_dvb_unregister(&dev->ports[SAA7164_PORT_TS1]);
if (saa7164_boards[dev->board].portb == SAA7164_MPEG_DVB)
saa7164_dvb_unregister(&dev->ports[SAA7164_PORT_TS2]);
if (saa7164_boards[dev->board].portc == SAA7164_MPEG_ENCODER)
saa7164_encoder_unregister(&dev->ports[SAA7164_PORT_ENC1]);
if (saa7164_boards[dev->board].portd == SAA7164_MPEG_ENCODER)
saa7164_encoder_unregister(&dev->ports[SAA7164_PORT_ENC2]);
if (saa7164_boards[dev->board].porte == SAA7164_MPEG_VBI)
saa7164_vbi_unregister(&dev->ports[SAA7164_PORT_VBI1]);
if (saa7164_boards[dev->board].portf == SAA7164_MPEG_VBI)
saa7164_vbi_unregister(&dev->ports[SAA7164_PORT_VBI2]);
saa7164_i2c_unregister(&dev->i2c_bus[0]);
saa7164_i2c_unregister(&dev->i2c_bus[1]);
saa7164_i2c_unregister(&dev->i2c_bus[2]);
pci_disable_device(pci_dev);
/* unregister stuff */
free_irq(pci_dev->irq, dev);
pci_set_drvdata(pci_dev, NULL);
mutex_lock(&devlist);
list_del(&dev->devlist);
mutex_unlock(&devlist);
saa7164_dev_unregister(dev);
kfree(dev);
}
static struct pci_device_id saa7164_pci_tbl[] = {
{
/* SAA7164 */
.vendor = 0x1131,
.device = 0x7164,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
}, {
/* --- end of list --- */
}
};
MODULE_DEVICE_TABLE(pci, saa7164_pci_tbl);
static struct pci_driver saa7164_pci_driver = {
.name = "saa7164",
.id_table = saa7164_pci_tbl,
.probe = saa7164_initdev,
.remove = __devexit_p(saa7164_finidev),
/* TODO */
.suspend = NULL,
.resume = NULL,
};
static int __init saa7164_init(void)
{
printk(KERN_INFO "saa7164 driver loaded\n");
#ifdef CONFIG_PROC_FS
saa7164_proc_create();
#endif
return pci_register_driver(&saa7164_pci_driver);
}
static void __exit saa7164_fini(void)
{
#ifdef CONFIG_PROC_FS
remove_proc_entry("saa7164", NULL);
#endif
pci_unregister_driver(&saa7164_pci_driver);
}
module_init(saa7164_init);
module_exit(saa7164_fini);
| gpl-2.0 |
fus1on/3.4.xx_LG_kernel | fs/xfs/xfs_message.c | 7902 | 2600 | /*
* Copyright (c) 2011 Red Hat, Inc. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
/*
* XFS logging functions
*/
static void
__xfs_printk(
const char *level,
const struct xfs_mount *mp,
struct va_format *vaf)
{
if (mp && mp->m_fsname) {
printk("%sXFS (%s): %pV\n", level, mp->m_fsname, vaf);
return;
}
printk("%sXFS: %pV\n", level, vaf);
}
#define define_xfs_printk_level(func, kern_level) \
void func(const struct xfs_mount *mp, const char *fmt, ...) \
{ \
struct va_format vaf; \
va_list args; \
\
va_start(args, fmt); \
\
vaf.fmt = fmt; \
vaf.va = &args; \
\
__xfs_printk(kern_level, mp, &vaf); \
va_end(args); \
} \
define_xfs_printk_level(xfs_emerg, KERN_EMERG);
define_xfs_printk_level(xfs_alert, KERN_ALERT);
define_xfs_printk_level(xfs_crit, KERN_CRIT);
define_xfs_printk_level(xfs_err, KERN_ERR);
define_xfs_printk_level(xfs_warn, KERN_WARNING);
define_xfs_printk_level(xfs_notice, KERN_NOTICE);
define_xfs_printk_level(xfs_info, KERN_INFO);
#ifdef DEBUG
define_xfs_printk_level(xfs_debug, KERN_DEBUG);
#endif
void
xfs_alert_tag(
const struct xfs_mount *mp,
int panic_tag,
const char *fmt, ...)
{
struct va_format vaf;
va_list args;
int do_panic = 0;
if (xfs_panic_mask && (xfs_panic_mask & panic_tag)) {
xfs_alert(mp, "Transforming an alert into a BUG.");
do_panic = 1;
}
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
__xfs_printk(KERN_ALERT, mp, &vaf);
va_end(args);
BUG_ON(do_panic);
}
void
assfail(char *expr, char *file, int line)
{
xfs_emerg(NULL, "Assertion failed: %s, file: %s, line: %d",
expr, file, line);
BUG();
}
void
xfs_hex_dump(void *p, int length)
{
print_hex_dump(KERN_ALERT, "", DUMP_PREFIX_ADDRESS, 16, 1, p, length, 1);
}
| gpl-2.0 |
Evervolv/android_kernel_samsung_msm8660 | drivers/gpu/drm/r128/r128_state.c | 8414 | 41298 | /* r128_state.c -- State support for r128 -*- linux-c -*-
* Created: Thu Jan 27 02:53:43 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.
*
* Authors:
* Gareth Hughes <gareth@valinux.com>
*/
#include "drmP.h"
#include "drm.h"
#include "r128_drm.h"
#include "r128_drv.h"
/* ================================================================
* CCE hardware state programming functions
*/
static void r128_emit_clip_rects(drm_r128_private_t *dev_priv,
struct drm_clip_rect *boxes, int count)
{
u32 aux_sc_cntl = 0x00000000;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING((count < 3 ? count : 3) * 5 + 2);
if (count >= 1) {
OUT_RING(CCE_PACKET0(R128_AUX1_SC_LEFT, 3));
OUT_RING(boxes[0].x1);
OUT_RING(boxes[0].x2 - 1);
OUT_RING(boxes[0].y1);
OUT_RING(boxes[0].y2 - 1);
aux_sc_cntl |= (R128_AUX1_SC_EN | R128_AUX1_SC_MODE_OR);
}
if (count >= 2) {
OUT_RING(CCE_PACKET0(R128_AUX2_SC_LEFT, 3));
OUT_RING(boxes[1].x1);
OUT_RING(boxes[1].x2 - 1);
OUT_RING(boxes[1].y1);
OUT_RING(boxes[1].y2 - 1);
aux_sc_cntl |= (R128_AUX2_SC_EN | R128_AUX2_SC_MODE_OR);
}
if (count >= 3) {
OUT_RING(CCE_PACKET0(R128_AUX3_SC_LEFT, 3));
OUT_RING(boxes[2].x1);
OUT_RING(boxes[2].x2 - 1);
OUT_RING(boxes[2].y1);
OUT_RING(boxes[2].y2 - 1);
aux_sc_cntl |= (R128_AUX3_SC_EN | R128_AUX3_SC_MODE_OR);
}
OUT_RING(CCE_PACKET0(R128_AUX_SC_CNTL, 0));
OUT_RING(aux_sc_cntl);
ADVANCE_RING();
}
static __inline__ void r128_emit_core(drm_r128_private_t *dev_priv)
{
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
drm_r128_context_regs_t *ctx = &sarea_priv->context_state;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_SCALE_3D_CNTL, 0));
OUT_RING(ctx->scale_3d_cntl);
ADVANCE_RING();
}
static __inline__ void r128_emit_context(drm_r128_private_t *dev_priv)
{
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
drm_r128_context_regs_t *ctx = &sarea_priv->context_state;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(13);
OUT_RING(CCE_PACKET0(R128_DST_PITCH_OFFSET_C, 11));
OUT_RING(ctx->dst_pitch_offset_c);
OUT_RING(ctx->dp_gui_master_cntl_c);
OUT_RING(ctx->sc_top_left_c);
OUT_RING(ctx->sc_bottom_right_c);
OUT_RING(ctx->z_offset_c);
OUT_RING(ctx->z_pitch_c);
OUT_RING(ctx->z_sten_cntl_c);
OUT_RING(ctx->tex_cntl_c);
OUT_RING(ctx->misc_3d_state_cntl_reg);
OUT_RING(ctx->texture_clr_cmp_clr_c);
OUT_RING(ctx->texture_clr_cmp_msk_c);
OUT_RING(ctx->fog_color_c);
ADVANCE_RING();
}
static __inline__ void r128_emit_setup(drm_r128_private_t *dev_priv)
{
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
drm_r128_context_regs_t *ctx = &sarea_priv->context_state;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(3);
OUT_RING(CCE_PACKET1(R128_SETUP_CNTL, R128_PM4_VC_FPU_SETUP));
OUT_RING(ctx->setup_cntl);
OUT_RING(ctx->pm4_vc_fpu_setup);
ADVANCE_RING();
}
static __inline__ void r128_emit_masks(drm_r128_private_t *dev_priv)
{
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
drm_r128_context_regs_t *ctx = &sarea_priv->context_state;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(5);
OUT_RING(CCE_PACKET0(R128_DP_WRITE_MASK, 0));
OUT_RING(ctx->dp_write_mask);
OUT_RING(CCE_PACKET0(R128_STEN_REF_MASK_C, 1));
OUT_RING(ctx->sten_ref_mask_c);
OUT_RING(ctx->plane_3d_mask_c);
ADVANCE_RING();
}
static __inline__ void r128_emit_window(drm_r128_private_t *dev_priv)
{
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
drm_r128_context_regs_t *ctx = &sarea_priv->context_state;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_WINDOW_XY_OFFSET, 0));
OUT_RING(ctx->window_xy_offset);
ADVANCE_RING();
}
static __inline__ void r128_emit_tex0(drm_r128_private_t *dev_priv)
{
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
drm_r128_context_regs_t *ctx = &sarea_priv->context_state;
drm_r128_texture_regs_t *tex = &sarea_priv->tex_state[0];
int i;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(7 + R128_MAX_TEXTURE_LEVELS);
OUT_RING(CCE_PACKET0(R128_PRIM_TEX_CNTL_C,
2 + R128_MAX_TEXTURE_LEVELS));
OUT_RING(tex->tex_cntl);
OUT_RING(tex->tex_combine_cntl);
OUT_RING(ctx->tex_size_pitch_c);
for (i = 0; i < R128_MAX_TEXTURE_LEVELS; i++)
OUT_RING(tex->tex_offset[i]);
OUT_RING(CCE_PACKET0(R128_CONSTANT_COLOR_C, 1));
OUT_RING(ctx->constant_color_c);
OUT_RING(tex->tex_border_color);
ADVANCE_RING();
}
static __inline__ void r128_emit_tex1(drm_r128_private_t *dev_priv)
{
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
drm_r128_texture_regs_t *tex = &sarea_priv->tex_state[1];
int i;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(5 + R128_MAX_TEXTURE_LEVELS);
OUT_RING(CCE_PACKET0(R128_SEC_TEX_CNTL_C, 1 + R128_MAX_TEXTURE_LEVELS));
OUT_RING(tex->tex_cntl);
OUT_RING(tex->tex_combine_cntl);
for (i = 0; i < R128_MAX_TEXTURE_LEVELS; i++)
OUT_RING(tex->tex_offset[i]);
OUT_RING(CCE_PACKET0(R128_SEC_TEXTURE_BORDER_COLOR_C, 0));
OUT_RING(tex->tex_border_color);
ADVANCE_RING();
}
static void r128_emit_state(drm_r128_private_t *dev_priv)
{
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
unsigned int dirty = sarea_priv->dirty;
DRM_DEBUG("dirty=0x%08x\n", dirty);
if (dirty & R128_UPLOAD_CORE) {
r128_emit_core(dev_priv);
sarea_priv->dirty &= ~R128_UPLOAD_CORE;
}
if (dirty & R128_UPLOAD_CONTEXT) {
r128_emit_context(dev_priv);
sarea_priv->dirty &= ~R128_UPLOAD_CONTEXT;
}
if (dirty & R128_UPLOAD_SETUP) {
r128_emit_setup(dev_priv);
sarea_priv->dirty &= ~R128_UPLOAD_SETUP;
}
if (dirty & R128_UPLOAD_MASKS) {
r128_emit_masks(dev_priv);
sarea_priv->dirty &= ~R128_UPLOAD_MASKS;
}
if (dirty & R128_UPLOAD_WINDOW) {
r128_emit_window(dev_priv);
sarea_priv->dirty &= ~R128_UPLOAD_WINDOW;
}
if (dirty & R128_UPLOAD_TEX0) {
r128_emit_tex0(dev_priv);
sarea_priv->dirty &= ~R128_UPLOAD_TEX0;
}
if (dirty & R128_UPLOAD_TEX1) {
r128_emit_tex1(dev_priv);
sarea_priv->dirty &= ~R128_UPLOAD_TEX1;
}
/* Turn off the texture cache flushing */
sarea_priv->context_state.tex_cntl_c &= ~R128_TEX_CACHE_FLUSH;
sarea_priv->dirty &= ~R128_REQUIRE_QUIESCENCE;
}
#if R128_PERFORMANCE_BOXES
/* ================================================================
* Performance monitoring functions
*/
static void r128_clear_box(drm_r128_private_t *dev_priv,
int x, int y, int w, int h, int r, int g, int b)
{
u32 pitch, offset;
u32 fb_bpp, color;
RING_LOCALS;
switch (dev_priv->fb_bpp) {
case 16:
fb_bpp = R128_GMC_DST_16BPP;
color = (((r & 0xf8) << 8) |
((g & 0xfc) << 3) | ((b & 0xf8) >> 3));
break;
case 24:
fb_bpp = R128_GMC_DST_24BPP;
color = ((r << 16) | (g << 8) | b);
break;
case 32:
fb_bpp = R128_GMC_DST_32BPP;
color = (((0xff) << 24) | (r << 16) | (g << 8) | b);
break;
default:
return;
}
offset = dev_priv->back_offset;
pitch = dev_priv->back_pitch >> 3;
BEGIN_RING(6);
OUT_RING(CCE_PACKET3(R128_CNTL_PAINT_MULTI, 4));
OUT_RING(R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_SOLID_COLOR |
fb_bpp |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_P |
R128_GMC_CLR_CMP_CNTL_DIS | R128_GMC_AUX_CLIP_DIS);
OUT_RING((pitch << 21) | (offset >> 5));
OUT_RING(color);
OUT_RING((x << 16) | y);
OUT_RING((w << 16) | h);
ADVANCE_RING();
}
static void r128_cce_performance_boxes(drm_r128_private_t *dev_priv)
{
if (atomic_read(&dev_priv->idle_count) == 0)
r128_clear_box(dev_priv, 64, 4, 8, 8, 0, 255, 0);
else
atomic_set(&dev_priv->idle_count, 0);
}
#endif
/* ================================================================
* CCE command dispatch functions
*/
static void r128_print_dirty(const char *msg, unsigned int flags)
{
DRM_INFO("%s: (0x%x) %s%s%s%s%s%s%s%s%s\n",
msg,
flags,
(flags & R128_UPLOAD_CORE) ? "core, " : "",
(flags & R128_UPLOAD_CONTEXT) ? "context, " : "",
(flags & R128_UPLOAD_SETUP) ? "setup, " : "",
(flags & R128_UPLOAD_TEX0) ? "tex0, " : "",
(flags & R128_UPLOAD_TEX1) ? "tex1, " : "",
(flags & R128_UPLOAD_MASKS) ? "masks, " : "",
(flags & R128_UPLOAD_WINDOW) ? "window, " : "",
(flags & R128_UPLOAD_CLIPRECTS) ? "cliprects, " : "",
(flags & R128_REQUIRE_QUIESCENCE) ? "quiescence, " : "");
}
static void r128_cce_dispatch_clear(struct drm_device *dev,
drm_r128_clear_t *clear)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
int nbox = sarea_priv->nbox;
struct drm_clip_rect *pbox = sarea_priv->boxes;
unsigned int flags = clear->flags;
int i;
RING_LOCALS;
DRM_DEBUG("\n");
if (dev_priv->page_flipping && dev_priv->current_page == 1) {
unsigned int tmp = flags;
flags &= ~(R128_FRONT | R128_BACK);
if (tmp & R128_FRONT)
flags |= R128_BACK;
if (tmp & R128_BACK)
flags |= R128_FRONT;
}
for (i = 0; i < nbox; i++) {
int x = pbox[i].x1;
int y = pbox[i].y1;
int w = pbox[i].x2 - x;
int h = pbox[i].y2 - y;
DRM_DEBUG("dispatch clear %d,%d-%d,%d flags 0x%x\n",
pbox[i].x1, pbox[i].y1, pbox[i].x2,
pbox[i].y2, flags);
if (flags & (R128_FRONT | R128_BACK)) {
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_DP_WRITE_MASK, 0));
OUT_RING(clear->color_mask);
ADVANCE_RING();
}
if (flags & R128_FRONT) {
BEGIN_RING(6);
OUT_RING(CCE_PACKET3(R128_CNTL_PAINT_MULTI, 4));
OUT_RING(R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_SOLID_COLOR |
(dev_priv->color_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_P |
R128_GMC_CLR_CMP_CNTL_DIS |
R128_GMC_AUX_CLIP_DIS);
OUT_RING(dev_priv->front_pitch_offset_c);
OUT_RING(clear->clear_color);
OUT_RING((x << 16) | y);
OUT_RING((w << 16) | h);
ADVANCE_RING();
}
if (flags & R128_BACK) {
BEGIN_RING(6);
OUT_RING(CCE_PACKET3(R128_CNTL_PAINT_MULTI, 4));
OUT_RING(R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_SOLID_COLOR |
(dev_priv->color_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_P |
R128_GMC_CLR_CMP_CNTL_DIS |
R128_GMC_AUX_CLIP_DIS);
OUT_RING(dev_priv->back_pitch_offset_c);
OUT_RING(clear->clear_color);
OUT_RING((x << 16) | y);
OUT_RING((w << 16) | h);
ADVANCE_RING();
}
if (flags & R128_DEPTH) {
BEGIN_RING(6);
OUT_RING(CCE_PACKET3(R128_CNTL_PAINT_MULTI, 4));
OUT_RING(R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_SOLID_COLOR |
(dev_priv->depth_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_P |
R128_GMC_CLR_CMP_CNTL_DIS |
R128_GMC_AUX_CLIP_DIS | R128_GMC_WR_MSK_DIS);
OUT_RING(dev_priv->depth_pitch_offset_c);
OUT_RING(clear->clear_depth);
OUT_RING((x << 16) | y);
OUT_RING((w << 16) | h);
ADVANCE_RING();
}
}
}
static void r128_cce_dispatch_swap(struct drm_device *dev)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
int nbox = sarea_priv->nbox;
struct drm_clip_rect *pbox = sarea_priv->boxes;
int i;
RING_LOCALS;
DRM_DEBUG("\n");
#if R128_PERFORMANCE_BOXES
/* Do some trivial performance monitoring...
*/
r128_cce_performance_boxes(dev_priv);
#endif
for (i = 0; i < nbox; i++) {
int x = pbox[i].x1;
int y = pbox[i].y1;
int w = pbox[i].x2 - x;
int h = pbox[i].y2 - y;
BEGIN_RING(7);
OUT_RING(CCE_PACKET3(R128_CNTL_BITBLT_MULTI, 5));
OUT_RING(R128_GMC_SRC_PITCH_OFFSET_CNTL |
R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_NONE |
(dev_priv->color_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_S |
R128_DP_SRC_SOURCE_MEMORY |
R128_GMC_CLR_CMP_CNTL_DIS |
R128_GMC_AUX_CLIP_DIS | R128_GMC_WR_MSK_DIS);
/* Make this work even if front & back are flipped:
*/
if (dev_priv->current_page == 0) {
OUT_RING(dev_priv->back_pitch_offset_c);
OUT_RING(dev_priv->front_pitch_offset_c);
} else {
OUT_RING(dev_priv->front_pitch_offset_c);
OUT_RING(dev_priv->back_pitch_offset_c);
}
OUT_RING((x << 16) | y);
OUT_RING((x << 16) | y);
OUT_RING((w << 16) | h);
ADVANCE_RING();
}
/* Increment the frame counter. The client-side 3D driver must
* throttle the framerate by waiting for this value before
* performing the swapbuffer ioctl.
*/
dev_priv->sarea_priv->last_frame++;
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_LAST_FRAME_REG, 0));
OUT_RING(dev_priv->sarea_priv->last_frame);
ADVANCE_RING();
}
static void r128_cce_dispatch_flip(struct drm_device *dev)
{
drm_r128_private_t *dev_priv = dev->dev_private;
RING_LOCALS;
DRM_DEBUG("page=%d pfCurrentPage=%d\n",
dev_priv->current_page, dev_priv->sarea_priv->pfCurrentPage);
#if R128_PERFORMANCE_BOXES
/* Do some trivial performance monitoring...
*/
r128_cce_performance_boxes(dev_priv);
#endif
BEGIN_RING(4);
R128_WAIT_UNTIL_PAGE_FLIPPED();
OUT_RING(CCE_PACKET0(R128_CRTC_OFFSET, 0));
if (dev_priv->current_page == 0)
OUT_RING(dev_priv->back_offset);
else
OUT_RING(dev_priv->front_offset);
ADVANCE_RING();
/* Increment the frame counter. The client-side 3D driver must
* throttle the framerate by waiting for this value before
* performing the swapbuffer ioctl.
*/
dev_priv->sarea_priv->last_frame++;
dev_priv->sarea_priv->pfCurrentPage = dev_priv->current_page =
1 - dev_priv->current_page;
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_LAST_FRAME_REG, 0));
OUT_RING(dev_priv->sarea_priv->last_frame);
ADVANCE_RING();
}
static void r128_cce_dispatch_vertex(struct drm_device *dev, struct drm_buf *buf)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_buf_priv_t *buf_priv = buf->dev_private;
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
int format = sarea_priv->vc_format;
int offset = buf->bus_address;
int size = buf->used;
int prim = buf_priv->prim;
int i = 0;
RING_LOCALS;
DRM_DEBUG("buf=%d nbox=%d\n", buf->idx, sarea_priv->nbox);
if (0)
r128_print_dirty("dispatch_vertex", sarea_priv->dirty);
if (buf->used) {
buf_priv->dispatched = 1;
if (sarea_priv->dirty & ~R128_UPLOAD_CLIPRECTS)
r128_emit_state(dev_priv);
do {
/* Emit the next set of up to three cliprects */
if (i < sarea_priv->nbox) {
r128_emit_clip_rects(dev_priv,
&sarea_priv->boxes[i],
sarea_priv->nbox - i);
}
/* Emit the vertex buffer rendering commands */
BEGIN_RING(5);
OUT_RING(CCE_PACKET3(R128_3D_RNDR_GEN_INDX_PRIM, 3));
OUT_RING(offset);
OUT_RING(size);
OUT_RING(format);
OUT_RING(prim | R128_CCE_VC_CNTL_PRIM_WALK_LIST |
(size << R128_CCE_VC_CNTL_NUM_SHIFT));
ADVANCE_RING();
i += 3;
} while (i < sarea_priv->nbox);
}
if (buf_priv->discard) {
buf_priv->age = dev_priv->sarea_priv->last_dispatch;
/* Emit the vertex buffer age */
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_LAST_DISPATCH_REG, 0));
OUT_RING(buf_priv->age);
ADVANCE_RING();
buf->pending = 1;
buf->used = 0;
/* FIXME: Check dispatched field */
buf_priv->dispatched = 0;
}
dev_priv->sarea_priv->last_dispatch++;
sarea_priv->dirty &= ~R128_UPLOAD_CLIPRECTS;
sarea_priv->nbox = 0;
}
static void r128_cce_dispatch_indirect(struct drm_device *dev,
struct drm_buf *buf, int start, int end)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_buf_priv_t *buf_priv = buf->dev_private;
RING_LOCALS;
DRM_DEBUG("indirect: buf=%d s=0x%x e=0x%x\n", buf->idx, start, end);
if (start != end) {
int offset = buf->bus_address + start;
int dwords = (end - start + 3) / sizeof(u32);
/* Indirect buffer data must be an even number of
* dwords, so if we've been given an odd number we must
* pad the data with a Type-2 CCE packet.
*/
if (dwords & 1) {
u32 *data = (u32 *)
((char *)dev->agp_buffer_map->handle
+ buf->offset + start);
data[dwords++] = cpu_to_le32(R128_CCE_PACKET2);
}
buf_priv->dispatched = 1;
/* Fire off the indirect buffer */
BEGIN_RING(3);
OUT_RING(CCE_PACKET0(R128_PM4_IW_INDOFF, 1));
OUT_RING(offset);
OUT_RING(dwords);
ADVANCE_RING();
}
if (buf_priv->discard) {
buf_priv->age = dev_priv->sarea_priv->last_dispatch;
/* Emit the indirect buffer age */
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_LAST_DISPATCH_REG, 0));
OUT_RING(buf_priv->age);
ADVANCE_RING();
buf->pending = 1;
buf->used = 0;
/* FIXME: Check dispatched field */
buf_priv->dispatched = 0;
}
dev_priv->sarea_priv->last_dispatch++;
}
static void r128_cce_dispatch_indices(struct drm_device *dev,
struct drm_buf *buf,
int start, int end, int count)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_buf_priv_t *buf_priv = buf->dev_private;
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
int format = sarea_priv->vc_format;
int offset = dev->agp_buffer_map->offset - dev_priv->cce_buffers_offset;
int prim = buf_priv->prim;
u32 *data;
int dwords;
int i = 0;
RING_LOCALS;
DRM_DEBUG("indices: s=%d e=%d c=%d\n", start, end, count);
if (0)
r128_print_dirty("dispatch_indices", sarea_priv->dirty);
if (start != end) {
buf_priv->dispatched = 1;
if (sarea_priv->dirty & ~R128_UPLOAD_CLIPRECTS)
r128_emit_state(dev_priv);
dwords = (end - start + 3) / sizeof(u32);
data = (u32 *) ((char *)dev->agp_buffer_map->handle
+ buf->offset + start);
data[0] = cpu_to_le32(CCE_PACKET3(R128_3D_RNDR_GEN_INDX_PRIM,
dwords - 2));
data[1] = cpu_to_le32(offset);
data[2] = cpu_to_le32(R128_MAX_VB_VERTS);
data[3] = cpu_to_le32(format);
data[4] = cpu_to_le32((prim | R128_CCE_VC_CNTL_PRIM_WALK_IND |
(count << 16)));
if (count & 0x1) {
#ifdef __LITTLE_ENDIAN
data[dwords - 1] &= 0x0000ffff;
#else
data[dwords - 1] &= 0xffff0000;
#endif
}
do {
/* Emit the next set of up to three cliprects */
if (i < sarea_priv->nbox) {
r128_emit_clip_rects(dev_priv,
&sarea_priv->boxes[i],
sarea_priv->nbox - i);
}
r128_cce_dispatch_indirect(dev, buf, start, end);
i += 3;
} while (i < sarea_priv->nbox);
}
if (buf_priv->discard) {
buf_priv->age = dev_priv->sarea_priv->last_dispatch;
/* Emit the vertex buffer age */
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_LAST_DISPATCH_REG, 0));
OUT_RING(buf_priv->age);
ADVANCE_RING();
buf->pending = 1;
/* FIXME: Check dispatched field */
buf_priv->dispatched = 0;
}
dev_priv->sarea_priv->last_dispatch++;
sarea_priv->dirty &= ~R128_UPLOAD_CLIPRECTS;
sarea_priv->nbox = 0;
}
static int r128_cce_dispatch_blit(struct drm_device *dev,
struct drm_file *file_priv,
drm_r128_blit_t *blit)
{
drm_r128_private_t *dev_priv = dev->dev_private;
struct drm_device_dma *dma = dev->dma;
struct drm_buf *buf;
drm_r128_buf_priv_t *buf_priv;
u32 *data;
int dword_shift, dwords;
RING_LOCALS;
DRM_DEBUG("\n");
/* The compiler won't optimize away a division by a variable,
* even if the only legal values are powers of two. Thus, we'll
* use a shift instead.
*/
switch (blit->format) {
case R128_DATATYPE_ARGB8888:
dword_shift = 0;
break;
case R128_DATATYPE_ARGB1555:
case R128_DATATYPE_RGB565:
case R128_DATATYPE_ARGB4444:
case R128_DATATYPE_YVYU422:
case R128_DATATYPE_VYUY422:
dword_shift = 1;
break;
case R128_DATATYPE_CI8:
case R128_DATATYPE_RGB8:
dword_shift = 2;
break;
default:
DRM_ERROR("invalid blit format %d\n", blit->format);
return -EINVAL;
}
/* Flush the pixel cache, and mark the contents as Read Invalid.
* This ensures no pixel data gets mixed up with the texture
* data from the host data blit, otherwise part of the texture
* image may be corrupted.
*/
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_PC_GUI_CTLSTAT, 0));
OUT_RING(R128_PC_RI_GUI | R128_PC_FLUSH_GUI);
ADVANCE_RING();
/* Dispatch the indirect buffer.
*/
buf = dma->buflist[blit->idx];
buf_priv = buf->dev_private;
if (buf->file_priv != file_priv) {
DRM_ERROR("process %d using buffer owned by %p\n",
DRM_CURRENTPID, buf->file_priv);
return -EINVAL;
}
if (buf->pending) {
DRM_ERROR("sending pending buffer %d\n", blit->idx);
return -EINVAL;
}
buf_priv->discard = 1;
dwords = (blit->width * blit->height) >> dword_shift;
data = (u32 *) ((char *)dev->agp_buffer_map->handle + buf->offset);
data[0] = cpu_to_le32(CCE_PACKET3(R128_CNTL_HOSTDATA_BLT, dwords + 6));
data[1] = cpu_to_le32((R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_NONE |
(blit->format << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_S |
R128_DP_SRC_SOURCE_HOST_DATA |
R128_GMC_CLR_CMP_CNTL_DIS |
R128_GMC_AUX_CLIP_DIS | R128_GMC_WR_MSK_DIS));
data[2] = cpu_to_le32((blit->pitch << 21) | (blit->offset >> 5));
data[3] = cpu_to_le32(0xffffffff);
data[4] = cpu_to_le32(0xffffffff);
data[5] = cpu_to_le32((blit->y << 16) | blit->x);
data[6] = cpu_to_le32((blit->height << 16) | blit->width);
data[7] = cpu_to_le32(dwords);
buf->used = (dwords + 8) * sizeof(u32);
r128_cce_dispatch_indirect(dev, buf, 0, buf->used);
/* Flush the pixel cache after the blit completes. This ensures
* the texture data is written out to memory before rendering
* continues.
*/
BEGIN_RING(2);
OUT_RING(CCE_PACKET0(R128_PC_GUI_CTLSTAT, 0));
OUT_RING(R128_PC_FLUSH_GUI);
ADVANCE_RING();
return 0;
}
/* ================================================================
* Tiled depth buffer management
*
* FIXME: These should all set the destination write mask for when we
* have hardware stencil support.
*/
static int r128_cce_dispatch_write_span(struct drm_device *dev,
drm_r128_depth_t *depth)
{
drm_r128_private_t *dev_priv = dev->dev_private;
int count, x, y;
u32 *buffer;
u8 *mask;
int i, buffer_size, mask_size;
RING_LOCALS;
DRM_DEBUG("\n");
count = depth->n;
if (count > 4096 || count <= 0)
return -EMSGSIZE;
if (DRM_COPY_FROM_USER(&x, depth->x, sizeof(x)))
return -EFAULT;
if (DRM_COPY_FROM_USER(&y, depth->y, sizeof(y)))
return -EFAULT;
buffer_size = depth->n * sizeof(u32);
buffer = kmalloc(buffer_size, GFP_KERNEL);
if (buffer == NULL)
return -ENOMEM;
if (DRM_COPY_FROM_USER(buffer, depth->buffer, buffer_size)) {
kfree(buffer);
return -EFAULT;
}
mask_size = depth->n * sizeof(u8);
if (depth->mask) {
mask = kmalloc(mask_size, GFP_KERNEL);
if (mask == NULL) {
kfree(buffer);
return -ENOMEM;
}
if (DRM_COPY_FROM_USER(mask, depth->mask, mask_size)) {
kfree(buffer);
kfree(mask);
return -EFAULT;
}
for (i = 0; i < count; i++, x++) {
if (mask[i]) {
BEGIN_RING(6);
OUT_RING(CCE_PACKET3(R128_CNTL_PAINT_MULTI, 4));
OUT_RING(R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_SOLID_COLOR |
(dev_priv->depth_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_P |
R128_GMC_CLR_CMP_CNTL_DIS |
R128_GMC_WR_MSK_DIS);
OUT_RING(dev_priv->depth_pitch_offset_c);
OUT_RING(buffer[i]);
OUT_RING((x << 16) | y);
OUT_RING((1 << 16) | 1);
ADVANCE_RING();
}
}
kfree(mask);
} else {
for (i = 0; i < count; i++, x++) {
BEGIN_RING(6);
OUT_RING(CCE_PACKET3(R128_CNTL_PAINT_MULTI, 4));
OUT_RING(R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_SOLID_COLOR |
(dev_priv->depth_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_P |
R128_GMC_CLR_CMP_CNTL_DIS |
R128_GMC_WR_MSK_DIS);
OUT_RING(dev_priv->depth_pitch_offset_c);
OUT_RING(buffer[i]);
OUT_RING((x << 16) | y);
OUT_RING((1 << 16) | 1);
ADVANCE_RING();
}
}
kfree(buffer);
return 0;
}
static int r128_cce_dispatch_write_pixels(struct drm_device *dev,
drm_r128_depth_t *depth)
{
drm_r128_private_t *dev_priv = dev->dev_private;
int count, *x, *y;
u32 *buffer;
u8 *mask;
int i, xbuf_size, ybuf_size, buffer_size, mask_size;
RING_LOCALS;
DRM_DEBUG("\n");
count = depth->n;
if (count > 4096 || count <= 0)
return -EMSGSIZE;
xbuf_size = count * sizeof(*x);
ybuf_size = count * sizeof(*y);
x = kmalloc(xbuf_size, GFP_KERNEL);
if (x == NULL)
return -ENOMEM;
y = kmalloc(ybuf_size, GFP_KERNEL);
if (y == NULL) {
kfree(x);
return -ENOMEM;
}
if (DRM_COPY_FROM_USER(x, depth->x, xbuf_size)) {
kfree(x);
kfree(y);
return -EFAULT;
}
if (DRM_COPY_FROM_USER(y, depth->y, xbuf_size)) {
kfree(x);
kfree(y);
return -EFAULT;
}
buffer_size = depth->n * sizeof(u32);
buffer = kmalloc(buffer_size, GFP_KERNEL);
if (buffer == NULL) {
kfree(x);
kfree(y);
return -ENOMEM;
}
if (DRM_COPY_FROM_USER(buffer, depth->buffer, buffer_size)) {
kfree(x);
kfree(y);
kfree(buffer);
return -EFAULT;
}
if (depth->mask) {
mask_size = depth->n * sizeof(u8);
mask = kmalloc(mask_size, GFP_KERNEL);
if (mask == NULL) {
kfree(x);
kfree(y);
kfree(buffer);
return -ENOMEM;
}
if (DRM_COPY_FROM_USER(mask, depth->mask, mask_size)) {
kfree(x);
kfree(y);
kfree(buffer);
kfree(mask);
return -EFAULT;
}
for (i = 0; i < count; i++) {
if (mask[i]) {
BEGIN_RING(6);
OUT_RING(CCE_PACKET3(R128_CNTL_PAINT_MULTI, 4));
OUT_RING(R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_SOLID_COLOR |
(dev_priv->depth_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_P |
R128_GMC_CLR_CMP_CNTL_DIS |
R128_GMC_WR_MSK_DIS);
OUT_RING(dev_priv->depth_pitch_offset_c);
OUT_RING(buffer[i]);
OUT_RING((x[i] << 16) | y[i]);
OUT_RING((1 << 16) | 1);
ADVANCE_RING();
}
}
kfree(mask);
} else {
for (i = 0; i < count; i++) {
BEGIN_RING(6);
OUT_RING(CCE_PACKET3(R128_CNTL_PAINT_MULTI, 4));
OUT_RING(R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_SOLID_COLOR |
(dev_priv->depth_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_P |
R128_GMC_CLR_CMP_CNTL_DIS |
R128_GMC_WR_MSK_DIS);
OUT_RING(dev_priv->depth_pitch_offset_c);
OUT_RING(buffer[i]);
OUT_RING((x[i] << 16) | y[i]);
OUT_RING((1 << 16) | 1);
ADVANCE_RING();
}
}
kfree(x);
kfree(y);
kfree(buffer);
return 0;
}
static int r128_cce_dispatch_read_span(struct drm_device *dev,
drm_r128_depth_t *depth)
{
drm_r128_private_t *dev_priv = dev->dev_private;
int count, x, y;
RING_LOCALS;
DRM_DEBUG("\n");
count = depth->n;
if (count > 4096 || count <= 0)
return -EMSGSIZE;
if (DRM_COPY_FROM_USER(&x, depth->x, sizeof(x)))
return -EFAULT;
if (DRM_COPY_FROM_USER(&y, depth->y, sizeof(y)))
return -EFAULT;
BEGIN_RING(7);
OUT_RING(CCE_PACKET3(R128_CNTL_BITBLT_MULTI, 5));
OUT_RING(R128_GMC_SRC_PITCH_OFFSET_CNTL |
R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_NONE |
(dev_priv->depth_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_S |
R128_DP_SRC_SOURCE_MEMORY |
R128_GMC_CLR_CMP_CNTL_DIS | R128_GMC_WR_MSK_DIS);
OUT_RING(dev_priv->depth_pitch_offset_c);
OUT_RING(dev_priv->span_pitch_offset_c);
OUT_RING((x << 16) | y);
OUT_RING((0 << 16) | 0);
OUT_RING((count << 16) | 1);
ADVANCE_RING();
return 0;
}
static int r128_cce_dispatch_read_pixels(struct drm_device *dev,
drm_r128_depth_t *depth)
{
drm_r128_private_t *dev_priv = dev->dev_private;
int count, *x, *y;
int i, xbuf_size, ybuf_size;
RING_LOCALS;
DRM_DEBUG("\n");
count = depth->n;
if (count > 4096 || count <= 0)
return -EMSGSIZE;
if (count > dev_priv->depth_pitch)
count = dev_priv->depth_pitch;
xbuf_size = count * sizeof(*x);
ybuf_size = count * sizeof(*y);
x = kmalloc(xbuf_size, GFP_KERNEL);
if (x == NULL)
return -ENOMEM;
y = kmalloc(ybuf_size, GFP_KERNEL);
if (y == NULL) {
kfree(x);
return -ENOMEM;
}
if (DRM_COPY_FROM_USER(x, depth->x, xbuf_size)) {
kfree(x);
kfree(y);
return -EFAULT;
}
if (DRM_COPY_FROM_USER(y, depth->y, ybuf_size)) {
kfree(x);
kfree(y);
return -EFAULT;
}
for (i = 0; i < count; i++) {
BEGIN_RING(7);
OUT_RING(CCE_PACKET3(R128_CNTL_BITBLT_MULTI, 5));
OUT_RING(R128_GMC_SRC_PITCH_OFFSET_CNTL |
R128_GMC_DST_PITCH_OFFSET_CNTL |
R128_GMC_BRUSH_NONE |
(dev_priv->depth_fmt << 8) |
R128_GMC_SRC_DATATYPE_COLOR |
R128_ROP3_S |
R128_DP_SRC_SOURCE_MEMORY |
R128_GMC_CLR_CMP_CNTL_DIS | R128_GMC_WR_MSK_DIS);
OUT_RING(dev_priv->depth_pitch_offset_c);
OUT_RING(dev_priv->span_pitch_offset_c);
OUT_RING((x[i] << 16) | y[i]);
OUT_RING((i << 16) | 0);
OUT_RING((1 << 16) | 1);
ADVANCE_RING();
}
kfree(x);
kfree(y);
return 0;
}
/* ================================================================
* Polygon stipple
*/
static void r128_cce_dispatch_stipple(struct drm_device *dev, u32 *stipple)
{
drm_r128_private_t *dev_priv = dev->dev_private;
int i;
RING_LOCALS;
DRM_DEBUG("\n");
BEGIN_RING(33);
OUT_RING(CCE_PACKET0(R128_BRUSH_DATA0, 31));
for (i = 0; i < 32; i++)
OUT_RING(stipple[i]);
ADVANCE_RING();
}
/* ================================================================
* IOCTL functions
*/
static int r128_cce_clear(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_sarea_t *sarea_priv;
drm_r128_clear_t *clear = data;
DRM_DEBUG("\n");
LOCK_TEST_WITH_RETURN(dev, file_priv);
DEV_INIT_TEST_WITH_RETURN(dev_priv);
RING_SPACE_TEST_WITH_RETURN(dev_priv);
sarea_priv = dev_priv->sarea_priv;
if (sarea_priv->nbox > R128_NR_SAREA_CLIPRECTS)
sarea_priv->nbox = R128_NR_SAREA_CLIPRECTS;
r128_cce_dispatch_clear(dev, clear);
COMMIT_RING();
/* Make sure we restore the 3D state next time.
*/
dev_priv->sarea_priv->dirty |= R128_UPLOAD_CONTEXT | R128_UPLOAD_MASKS;
return 0;
}
static int r128_do_init_pageflip(struct drm_device *dev)
{
drm_r128_private_t *dev_priv = dev->dev_private;
DRM_DEBUG("\n");
dev_priv->crtc_offset = R128_READ(R128_CRTC_OFFSET);
dev_priv->crtc_offset_cntl = R128_READ(R128_CRTC_OFFSET_CNTL);
R128_WRITE(R128_CRTC_OFFSET, dev_priv->front_offset);
R128_WRITE(R128_CRTC_OFFSET_CNTL,
dev_priv->crtc_offset_cntl | R128_CRTC_OFFSET_FLIP_CNTL);
dev_priv->page_flipping = 1;
dev_priv->current_page = 0;
dev_priv->sarea_priv->pfCurrentPage = dev_priv->current_page;
return 0;
}
static int r128_do_cleanup_pageflip(struct drm_device *dev)
{
drm_r128_private_t *dev_priv = dev->dev_private;
DRM_DEBUG("\n");
R128_WRITE(R128_CRTC_OFFSET, dev_priv->crtc_offset);
R128_WRITE(R128_CRTC_OFFSET_CNTL, dev_priv->crtc_offset_cntl);
if (dev_priv->current_page != 0) {
r128_cce_dispatch_flip(dev);
COMMIT_RING();
}
dev_priv->page_flipping = 0;
return 0;
}
/* Swapping and flipping are different operations, need different ioctls.
* They can & should be intermixed to support multiple 3d windows.
*/
static int r128_cce_flip(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_r128_private_t *dev_priv = dev->dev_private;
DRM_DEBUG("\n");
LOCK_TEST_WITH_RETURN(dev, file_priv);
DEV_INIT_TEST_WITH_RETURN(dev_priv);
RING_SPACE_TEST_WITH_RETURN(dev_priv);
if (!dev_priv->page_flipping)
r128_do_init_pageflip(dev);
r128_cce_dispatch_flip(dev);
COMMIT_RING();
return 0;
}
static int r128_cce_swap(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_sarea_t *sarea_priv = dev_priv->sarea_priv;
DRM_DEBUG("\n");
LOCK_TEST_WITH_RETURN(dev, file_priv);
DEV_INIT_TEST_WITH_RETURN(dev_priv);
RING_SPACE_TEST_WITH_RETURN(dev_priv);
if (sarea_priv->nbox > R128_NR_SAREA_CLIPRECTS)
sarea_priv->nbox = R128_NR_SAREA_CLIPRECTS;
r128_cce_dispatch_swap(dev);
dev_priv->sarea_priv->dirty |= (R128_UPLOAD_CONTEXT |
R128_UPLOAD_MASKS);
COMMIT_RING();
return 0;
}
static int r128_cce_vertex(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_r128_private_t *dev_priv = dev->dev_private;
struct drm_device_dma *dma = dev->dma;
struct drm_buf *buf;
drm_r128_buf_priv_t *buf_priv;
drm_r128_vertex_t *vertex = data;
LOCK_TEST_WITH_RETURN(dev, file_priv);
DEV_INIT_TEST_WITH_RETURN(dev_priv);
DRM_DEBUG("pid=%d index=%d count=%d discard=%d\n",
DRM_CURRENTPID, vertex->idx, vertex->count, vertex->discard);
if (vertex->idx < 0 || vertex->idx >= dma->buf_count) {
DRM_ERROR("buffer index %d (of %d max)\n",
vertex->idx, dma->buf_count - 1);
return -EINVAL;
}
if (vertex->prim < 0 ||
vertex->prim > R128_CCE_VC_CNTL_PRIM_TYPE_TRI_TYPE2) {
DRM_ERROR("buffer prim %d\n", vertex->prim);
return -EINVAL;
}
RING_SPACE_TEST_WITH_RETURN(dev_priv);
VB_AGE_TEST_WITH_RETURN(dev_priv);
buf = dma->buflist[vertex->idx];
buf_priv = buf->dev_private;
if (buf->file_priv != file_priv) {
DRM_ERROR("process %d using buffer owned by %p\n",
DRM_CURRENTPID, buf->file_priv);
return -EINVAL;
}
if (buf->pending) {
DRM_ERROR("sending pending buffer %d\n", vertex->idx);
return -EINVAL;
}
buf->used = vertex->count;
buf_priv->prim = vertex->prim;
buf_priv->discard = vertex->discard;
r128_cce_dispatch_vertex(dev, buf);
COMMIT_RING();
return 0;
}
static int r128_cce_indices(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_r128_private_t *dev_priv = dev->dev_private;
struct drm_device_dma *dma = dev->dma;
struct drm_buf *buf;
drm_r128_buf_priv_t *buf_priv;
drm_r128_indices_t *elts = data;
int count;
LOCK_TEST_WITH_RETURN(dev, file_priv);
DEV_INIT_TEST_WITH_RETURN(dev_priv);
DRM_DEBUG("pid=%d buf=%d s=%d e=%d d=%d\n", DRM_CURRENTPID,
elts->idx, elts->start, elts->end, elts->discard);
if (elts->idx < 0 || elts->idx >= dma->buf_count) {
DRM_ERROR("buffer index %d (of %d max)\n",
elts->idx, dma->buf_count - 1);
return -EINVAL;
}
if (elts->prim < 0 ||
elts->prim > R128_CCE_VC_CNTL_PRIM_TYPE_TRI_TYPE2) {
DRM_ERROR("buffer prim %d\n", elts->prim);
return -EINVAL;
}
RING_SPACE_TEST_WITH_RETURN(dev_priv);
VB_AGE_TEST_WITH_RETURN(dev_priv);
buf = dma->buflist[elts->idx];
buf_priv = buf->dev_private;
if (buf->file_priv != file_priv) {
DRM_ERROR("process %d using buffer owned by %p\n",
DRM_CURRENTPID, buf->file_priv);
return -EINVAL;
}
if (buf->pending) {
DRM_ERROR("sending pending buffer %d\n", elts->idx);
return -EINVAL;
}
count = (elts->end - elts->start) / sizeof(u16);
elts->start -= R128_INDEX_PRIM_OFFSET;
if (elts->start & 0x7) {
DRM_ERROR("misaligned buffer 0x%x\n", elts->start);
return -EINVAL;
}
if (elts->start < buf->used) {
DRM_ERROR("no header 0x%x - 0x%x\n", elts->start, buf->used);
return -EINVAL;
}
buf->used = elts->end;
buf_priv->prim = elts->prim;
buf_priv->discard = elts->discard;
r128_cce_dispatch_indices(dev, buf, elts->start, elts->end, count);
COMMIT_RING();
return 0;
}
static int r128_cce_blit(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
struct drm_device_dma *dma = dev->dma;
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_blit_t *blit = data;
int ret;
LOCK_TEST_WITH_RETURN(dev, file_priv);
DEV_INIT_TEST_WITH_RETURN(dev_priv);
DRM_DEBUG("pid=%d index=%d\n", DRM_CURRENTPID, blit->idx);
if (blit->idx < 0 || blit->idx >= dma->buf_count) {
DRM_ERROR("buffer index %d (of %d max)\n",
blit->idx, dma->buf_count - 1);
return -EINVAL;
}
RING_SPACE_TEST_WITH_RETURN(dev_priv);
VB_AGE_TEST_WITH_RETURN(dev_priv);
ret = r128_cce_dispatch_blit(dev, file_priv, blit);
COMMIT_RING();
return ret;
}
static int r128_cce_depth(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_depth_t *depth = data;
int ret;
LOCK_TEST_WITH_RETURN(dev, file_priv);
DEV_INIT_TEST_WITH_RETURN(dev_priv);
RING_SPACE_TEST_WITH_RETURN(dev_priv);
ret = -EINVAL;
switch (depth->func) {
case R128_WRITE_SPAN:
ret = r128_cce_dispatch_write_span(dev, depth);
break;
case R128_WRITE_PIXELS:
ret = r128_cce_dispatch_write_pixels(dev, depth);
break;
case R128_READ_SPAN:
ret = r128_cce_dispatch_read_span(dev, depth);
break;
case R128_READ_PIXELS:
ret = r128_cce_dispatch_read_pixels(dev, depth);
break;
}
COMMIT_RING();
return ret;
}
static int r128_cce_stipple(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_stipple_t *stipple = data;
u32 mask[32];
LOCK_TEST_WITH_RETURN(dev, file_priv);
DEV_INIT_TEST_WITH_RETURN(dev_priv);
if (DRM_COPY_FROM_USER(&mask, stipple->mask, 32 * sizeof(u32)))
return -EFAULT;
RING_SPACE_TEST_WITH_RETURN(dev_priv);
r128_cce_dispatch_stipple(dev, mask);
COMMIT_RING();
return 0;
}
static int r128_cce_indirect(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_r128_private_t *dev_priv = dev->dev_private;
struct drm_device_dma *dma = dev->dma;
struct drm_buf *buf;
drm_r128_buf_priv_t *buf_priv;
drm_r128_indirect_t *indirect = data;
#if 0
RING_LOCALS;
#endif
LOCK_TEST_WITH_RETURN(dev, file_priv);
DEV_INIT_TEST_WITH_RETURN(dev_priv);
DRM_DEBUG("idx=%d s=%d e=%d d=%d\n",
indirect->idx, indirect->start, indirect->end,
indirect->discard);
if (indirect->idx < 0 || indirect->idx >= dma->buf_count) {
DRM_ERROR("buffer index %d (of %d max)\n",
indirect->idx, dma->buf_count - 1);
return -EINVAL;
}
buf = dma->buflist[indirect->idx];
buf_priv = buf->dev_private;
if (buf->file_priv != file_priv) {
DRM_ERROR("process %d using buffer owned by %p\n",
DRM_CURRENTPID, buf->file_priv);
return -EINVAL;
}
if (buf->pending) {
DRM_ERROR("sending pending buffer %d\n", indirect->idx);
return -EINVAL;
}
if (indirect->start < buf->used) {
DRM_ERROR("reusing indirect: start=0x%x actual=0x%x\n",
indirect->start, buf->used);
return -EINVAL;
}
RING_SPACE_TEST_WITH_RETURN(dev_priv);
VB_AGE_TEST_WITH_RETURN(dev_priv);
buf->used = indirect->end;
buf_priv->discard = indirect->discard;
#if 0
/* Wait for the 3D stream to idle before the indirect buffer
* containing 2D acceleration commands is processed.
*/
BEGIN_RING(2);
RADEON_WAIT_UNTIL_3D_IDLE();
ADVANCE_RING();
#endif
/* Dispatch the indirect buffer full of commands from the
* X server. This is insecure and is thus only available to
* privileged clients.
*/
r128_cce_dispatch_indirect(dev, buf, indirect->start, indirect->end);
COMMIT_RING();
return 0;
}
static int r128_getparam(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
drm_r128_private_t *dev_priv = dev->dev_private;
drm_r128_getparam_t *param = data;
int value;
DEV_INIT_TEST_WITH_RETURN(dev_priv);
DRM_DEBUG("pid=%d\n", DRM_CURRENTPID);
switch (param->param) {
case R128_PARAM_IRQ_NR:
value = drm_dev_to_irq(dev);
break;
default:
return -EINVAL;
}
if (DRM_COPY_TO_USER(param->value, &value, sizeof(int))) {
DRM_ERROR("copy_to_user\n");
return -EFAULT;
}
return 0;
}
void r128_driver_preclose(struct drm_device *dev, struct drm_file *file_priv)
{
if (dev->dev_private) {
drm_r128_private_t *dev_priv = dev->dev_private;
if (dev_priv->page_flipping)
r128_do_cleanup_pageflip(dev);
}
}
void r128_driver_lastclose(struct drm_device *dev)
{
r128_do_cleanup_cce(dev);
}
struct drm_ioctl_desc r128_ioctls[] = {
DRM_IOCTL_DEF_DRV(R128_INIT, r128_cce_init, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(R128_CCE_START, r128_cce_start, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(R128_CCE_STOP, r128_cce_stop, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(R128_CCE_RESET, r128_cce_reset, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(R128_CCE_IDLE, r128_cce_idle, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_RESET, r128_engine_reset, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_FULLSCREEN, r128_fullscreen, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_SWAP, r128_cce_swap, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_FLIP, r128_cce_flip, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_CLEAR, r128_cce_clear, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_VERTEX, r128_cce_vertex, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_INDICES, r128_cce_indices, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_BLIT, r128_cce_blit, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_DEPTH, r128_cce_depth, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_STIPPLE, r128_cce_stipple, DRM_AUTH),
DRM_IOCTL_DEF_DRV(R128_INDIRECT, r128_cce_indirect, DRM_AUTH|DRM_MASTER|DRM_ROOT_ONLY),
DRM_IOCTL_DEF_DRV(R128_GETPARAM, r128_getparam, DRM_AUTH),
};
int r128_max_ioctl = DRM_ARRAY_SIZE(r128_ioctls);
| gpl-2.0 |
BPI-SINOVOIP/BPI-Mainline-kernel | linux-4.19/drivers/cpufreq/kirkwood-cpufreq.c | 223 | 5116 | /*
* kirkwood_freq.c: cpufreq driver for the Marvell kirkwood
*
* Copyright (C) 2013 Andrew Lunn <andrew@lunn.ch>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/clk.h>
#include <linux/cpufreq.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <asm/proc-fns.h>
#define CPU_SW_INT_BLK BIT(28)
static struct priv
{
struct clk *cpu_clk;
struct clk *ddr_clk;
struct clk *powersave_clk;
struct device *dev;
void __iomem *base;
} priv;
#define STATE_CPU_FREQ 0x01
#define STATE_DDR_FREQ 0x02
/*
* Kirkwood can swap the clock to the CPU between two clocks:
*
* - cpu clk
* - ddr clk
*
* The frequencies are set at runtime before registering this table.
*/
static struct cpufreq_frequency_table kirkwood_freq_table[] = {
{0, STATE_CPU_FREQ, 0}, /* CPU uses cpuclk */
{0, STATE_DDR_FREQ, 0}, /* CPU uses ddrclk */
{0, 0, CPUFREQ_TABLE_END},
};
static unsigned int kirkwood_cpufreq_get_cpu_frequency(unsigned int cpu)
{
return clk_get_rate(priv.powersave_clk) / 1000;
}
static int kirkwood_cpufreq_target(struct cpufreq_policy *policy,
unsigned int index)
{
unsigned int state = kirkwood_freq_table[index].driver_data;
unsigned long reg;
local_irq_disable();
/* Disable interrupts to the CPU */
reg = readl_relaxed(priv.base);
reg |= CPU_SW_INT_BLK;
writel_relaxed(reg, priv.base);
switch (state) {
case STATE_CPU_FREQ:
clk_set_parent(priv.powersave_clk, priv.cpu_clk);
break;
case STATE_DDR_FREQ:
clk_set_parent(priv.powersave_clk, priv.ddr_clk);
break;
}
/* Wait-for-Interrupt, while the hardware changes frequency */
cpu_do_idle();
/* Enable interrupts to the CPU */
reg = readl_relaxed(priv.base);
reg &= ~CPU_SW_INT_BLK;
writel_relaxed(reg, priv.base);
local_irq_enable();
return 0;
}
/* Module init and exit code */
static int kirkwood_cpufreq_cpu_init(struct cpufreq_policy *policy)
{
return cpufreq_generic_init(policy, kirkwood_freq_table, 5000);
}
static struct cpufreq_driver kirkwood_cpufreq_driver = {
.flags = CPUFREQ_NEED_INITIAL_FREQ_CHECK,
.get = kirkwood_cpufreq_get_cpu_frequency,
.verify = cpufreq_generic_frequency_table_verify,
.target_index = kirkwood_cpufreq_target,
.init = kirkwood_cpufreq_cpu_init,
.name = "kirkwood-cpufreq",
.attr = cpufreq_generic_attr,
};
static int kirkwood_cpufreq_probe(struct platform_device *pdev)
{
struct device_node *np;
struct resource *res;
int err;
priv.dev = &pdev->dev;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
priv.base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(priv.base))
return PTR_ERR(priv.base);
np = of_cpu_device_node_get(0);
if (!np) {
dev_err(&pdev->dev, "failed to get cpu device node\n");
return -ENODEV;
}
priv.cpu_clk = of_clk_get_by_name(np, "cpu_clk");
if (IS_ERR(priv.cpu_clk)) {
dev_err(priv.dev, "Unable to get cpuclk\n");
return PTR_ERR(priv.cpu_clk);
}
err = clk_prepare_enable(priv.cpu_clk);
if (err) {
dev_err(priv.dev, "Unable to prepare cpuclk\n");
return err;
}
kirkwood_freq_table[0].frequency = clk_get_rate(priv.cpu_clk) / 1000;
priv.ddr_clk = of_clk_get_by_name(np, "ddrclk");
if (IS_ERR(priv.ddr_clk)) {
dev_err(priv.dev, "Unable to get ddrclk\n");
err = PTR_ERR(priv.ddr_clk);
goto out_cpu;
}
err = clk_prepare_enable(priv.ddr_clk);
if (err) {
dev_err(priv.dev, "Unable to prepare ddrclk\n");
goto out_cpu;
}
kirkwood_freq_table[1].frequency = clk_get_rate(priv.ddr_clk) / 1000;
priv.powersave_clk = of_clk_get_by_name(np, "powersave");
if (IS_ERR(priv.powersave_clk)) {
dev_err(priv.dev, "Unable to get powersave\n");
err = PTR_ERR(priv.powersave_clk);
goto out_ddr;
}
err = clk_prepare_enable(priv.powersave_clk);
if (err) {
dev_err(priv.dev, "Unable to prepare powersave clk\n");
goto out_ddr;
}
of_node_put(np);
np = NULL;
err = cpufreq_register_driver(&kirkwood_cpufreq_driver);
if (!err)
return 0;
dev_err(priv.dev, "Failed to register cpufreq driver\n");
clk_disable_unprepare(priv.powersave_clk);
out_ddr:
clk_disable_unprepare(priv.ddr_clk);
out_cpu:
clk_disable_unprepare(priv.cpu_clk);
of_node_put(np);
return err;
}
static int kirkwood_cpufreq_remove(struct platform_device *pdev)
{
cpufreq_unregister_driver(&kirkwood_cpufreq_driver);
clk_disable_unprepare(priv.powersave_clk);
clk_disable_unprepare(priv.ddr_clk);
clk_disable_unprepare(priv.cpu_clk);
return 0;
}
static struct platform_driver kirkwood_cpufreq_platform_driver = {
.probe = kirkwood_cpufreq_probe,
.remove = kirkwood_cpufreq_remove,
.driver = {
.name = "kirkwood-cpufreq",
},
};
module_platform_driver(kirkwood_cpufreq_platform_driver);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Andrew Lunn <andrew@lunn.ch");
MODULE_DESCRIPTION("cpufreq driver for Marvell's kirkwood CPU");
MODULE_ALIAS("platform:kirkwood-cpufreq");
| gpl-2.0 |
sdfd/FPGA_Linux | arch/x86/xen/time.c | 223 | 14015 | /*
* Xen time implementation.
*
* This is implemented in terms of a clocksource driver which uses
* the hypervisor clock as a nanosecond timebase, and a clockevent
* driver which uses the hypervisor's timer mechanism.
*
* Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007
*/
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/clocksource.h>
#include <linux/clockchips.h>
#include <linux/kernel_stat.h>
#include <linux/math64.h>
#include <linux/gfp.h>
#include <linux/slab.h>
#include <linux/pvclock_gtod.h>
#include <asm/pvclock.h>
#include <asm/xen/hypervisor.h>
#include <asm/xen/hypercall.h>
#include <xen/events.h>
#include <xen/features.h>
#include <xen/interface/xen.h>
#include <xen/interface/vcpu.h>
#include "xen-ops.h"
/* Xen may fire a timer up to this many ns early */
#define TIMER_SLOP 100000
#define NS_PER_TICK (1000000000LL / HZ)
/* runstate info updated by Xen */
static DEFINE_PER_CPU(struct vcpu_runstate_info, xen_runstate);
/* snapshots of runstate info */
static DEFINE_PER_CPU(struct vcpu_runstate_info, xen_runstate_snapshot);
/* unused ns of stolen time */
static DEFINE_PER_CPU(u64, xen_residual_stolen);
/* return an consistent snapshot of 64-bit time/counter value */
static u64 get64(const u64 *p)
{
u64 ret;
if (BITS_PER_LONG < 64) {
u32 *p32 = (u32 *)p;
u32 h, l;
/*
* Read high then low, and then make sure high is
* still the same; this will only loop if low wraps
* and carries into high.
* XXX some clean way to make this endian-proof?
*/
do {
h = p32[1];
barrier();
l = p32[0];
barrier();
} while (p32[1] != h);
ret = (((u64)h) << 32) | l;
} else
ret = *p;
return ret;
}
/*
* Runstate accounting
*/
static void get_runstate_snapshot(struct vcpu_runstate_info *res)
{
u64 state_time;
struct vcpu_runstate_info *state;
BUG_ON(preemptible());
state = &__get_cpu_var(xen_runstate);
/*
* The runstate info is always updated by the hypervisor on
* the current CPU, so there's no need to use anything
* stronger than a compiler barrier when fetching it.
*/
do {
state_time = get64(&state->state_entry_time);
barrier();
*res = *state;
barrier();
} while (get64(&state->state_entry_time) != state_time);
}
/* return true when a vcpu could run but has no real cpu to run on */
bool xen_vcpu_stolen(int vcpu)
{
return per_cpu(xen_runstate, vcpu).state == RUNSTATE_runnable;
}
void xen_setup_runstate_info(int cpu)
{
struct vcpu_register_runstate_memory_area area;
area.addr.v = &per_cpu(xen_runstate, cpu);
if (HYPERVISOR_vcpu_op(VCPUOP_register_runstate_memory_area,
cpu, &area))
BUG();
}
static void do_stolen_accounting(void)
{
struct vcpu_runstate_info state;
struct vcpu_runstate_info *snap;
s64 runnable, offline, stolen;
cputime_t ticks;
get_runstate_snapshot(&state);
WARN_ON(state.state != RUNSTATE_running);
snap = &__get_cpu_var(xen_runstate_snapshot);
/* work out how much time the VCPU has not been runn*ing* */
runnable = state.time[RUNSTATE_runnable] - snap->time[RUNSTATE_runnable];
offline = state.time[RUNSTATE_offline] - snap->time[RUNSTATE_offline];
*snap = state;
/* Add the appropriate number of ticks of stolen time,
including any left-overs from last time. */
stolen = runnable + offline + __this_cpu_read(xen_residual_stolen);
if (stolen < 0)
stolen = 0;
ticks = iter_div_u64_rem(stolen, NS_PER_TICK, &stolen);
__this_cpu_write(xen_residual_stolen, stolen);
account_steal_ticks(ticks);
}
/* Get the TSC speed from Xen */
static unsigned long xen_tsc_khz(void)
{
struct pvclock_vcpu_time_info *info =
&HYPERVISOR_shared_info->vcpu_info[0].time;
return pvclock_tsc_khz(info);
}
cycle_t xen_clocksource_read(void)
{
struct pvclock_vcpu_time_info *src;
cycle_t ret;
preempt_disable_notrace();
src = &__get_cpu_var(xen_vcpu)->time;
ret = pvclock_clocksource_read(src);
preempt_enable_notrace();
return ret;
}
static cycle_t xen_clocksource_get_cycles(struct clocksource *cs)
{
return xen_clocksource_read();
}
static void xen_read_wallclock(struct timespec *ts)
{
struct shared_info *s = HYPERVISOR_shared_info;
struct pvclock_wall_clock *wall_clock = &(s->wc);
struct pvclock_vcpu_time_info *vcpu_time;
vcpu_time = &get_cpu_var(xen_vcpu)->time;
pvclock_read_wallclock(wall_clock, vcpu_time, ts);
put_cpu_var(xen_vcpu);
}
static void xen_get_wallclock(struct timespec *now)
{
xen_read_wallclock(now);
}
static int xen_set_wallclock(const struct timespec *now)
{
return -1;
}
static int xen_pvclock_gtod_notify(struct notifier_block *nb,
unsigned long was_set, void *priv)
{
/* Protected by the calling core code serialization */
static struct timespec next_sync;
struct xen_platform_op op;
struct timespec now;
now = __current_kernel_time();
/*
* We only take the expensive HV call when the clock was set
* or when the 11 minutes RTC synchronization time elapsed.
*/
if (!was_set && timespec_compare(&now, &next_sync) < 0)
return NOTIFY_OK;
op.cmd = XENPF_settime;
op.u.settime.secs = now.tv_sec;
op.u.settime.nsecs = now.tv_nsec;
op.u.settime.system_time = xen_clocksource_read();
(void)HYPERVISOR_dom0_op(&op);
/*
* Move the next drift compensation time 11 minutes
* ahead. That's emulating the sync_cmos_clock() update for
* the hardware RTC.
*/
next_sync = now;
next_sync.tv_sec += 11 * 60;
return NOTIFY_OK;
}
static struct notifier_block xen_pvclock_gtod_notifier = {
.notifier_call = xen_pvclock_gtod_notify,
};
static struct clocksource xen_clocksource __read_mostly = {
.name = "xen",
.rating = 400,
.read = xen_clocksource_get_cycles,
.mask = ~0,
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
/*
Xen clockevent implementation
Xen has two clockevent implementations:
The old timer_op one works with all released versions of Xen prior
to version 3.0.4. This version of the hypervisor provides a
single-shot timer with nanosecond resolution. However, sharing the
same event channel is a 100Hz tick which is delivered while the
vcpu is running. We don't care about or use this tick, but it will
cause the core time code to think the timer fired too soon, and
will end up resetting it each time. It could be filtered, but
doing so has complications when the ktime clocksource is not yet
the xen clocksource (ie, at boot time).
The new vcpu_op-based timer interface allows the tick timer period
to be changed or turned off. The tick timer is not useful as a
periodic timer because events are only delivered to running vcpus.
The one-shot timer can report when a timeout is in the past, so
set_next_event is capable of returning -ETIME when appropriate.
This interface is used when available.
*/
/*
Get a hypervisor absolute time. In theory we could maintain an
offset between the kernel's time and the hypervisor's time, and
apply that to a kernel's absolute timeout. Unfortunately the
hypervisor and kernel times can drift even if the kernel is using
the Xen clocksource, because ntp can warp the kernel's clocksource.
*/
static s64 get_abs_timeout(unsigned long delta)
{
return xen_clocksource_read() + delta;
}
static void xen_timerop_set_mode(enum clock_event_mode mode,
struct clock_event_device *evt)
{
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
/* unsupported */
WARN_ON(1);
break;
case CLOCK_EVT_MODE_ONESHOT:
case CLOCK_EVT_MODE_RESUME:
break;
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
HYPERVISOR_set_timer_op(0); /* cancel timeout */
break;
}
}
static int xen_timerop_set_next_event(unsigned long delta,
struct clock_event_device *evt)
{
WARN_ON(evt->mode != CLOCK_EVT_MODE_ONESHOT);
if (HYPERVISOR_set_timer_op(get_abs_timeout(delta)) < 0)
BUG();
/* We may have missed the deadline, but there's no real way of
knowing for sure. If the event was in the past, then we'll
get an immediate interrupt. */
return 0;
}
static const struct clock_event_device xen_timerop_clockevent = {
.name = "xen",
.features = CLOCK_EVT_FEAT_ONESHOT,
.max_delta_ns = 0xffffffff,
.min_delta_ns = TIMER_SLOP,
.mult = 1,
.shift = 0,
.rating = 500,
.set_mode = xen_timerop_set_mode,
.set_next_event = xen_timerop_set_next_event,
};
static void xen_vcpuop_set_mode(enum clock_event_mode mode,
struct clock_event_device *evt)
{
int cpu = smp_processor_id();
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
WARN_ON(1); /* unsupported */
break;
case CLOCK_EVT_MODE_ONESHOT:
if (HYPERVISOR_vcpu_op(VCPUOP_stop_periodic_timer, cpu, NULL))
BUG();
break;
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
if (HYPERVISOR_vcpu_op(VCPUOP_stop_singleshot_timer, cpu, NULL) ||
HYPERVISOR_vcpu_op(VCPUOP_stop_periodic_timer, cpu, NULL))
BUG();
break;
case CLOCK_EVT_MODE_RESUME:
break;
}
}
static int xen_vcpuop_set_next_event(unsigned long delta,
struct clock_event_device *evt)
{
int cpu = smp_processor_id();
struct vcpu_set_singleshot_timer single;
int ret;
WARN_ON(evt->mode != CLOCK_EVT_MODE_ONESHOT);
single.timeout_abs_ns = get_abs_timeout(delta);
single.flags = VCPU_SSHOTTMR_future;
ret = HYPERVISOR_vcpu_op(VCPUOP_set_singleshot_timer, cpu, &single);
BUG_ON(ret != 0 && ret != -ETIME);
return ret;
}
static const struct clock_event_device xen_vcpuop_clockevent = {
.name = "xen",
.features = CLOCK_EVT_FEAT_ONESHOT,
.max_delta_ns = 0xffffffff,
.min_delta_ns = TIMER_SLOP,
.mult = 1,
.shift = 0,
.rating = 500,
.set_mode = xen_vcpuop_set_mode,
.set_next_event = xen_vcpuop_set_next_event,
};
static const struct clock_event_device *xen_clockevent =
&xen_timerop_clockevent;
struct xen_clock_event_device {
struct clock_event_device evt;
char *name;
};
static DEFINE_PER_CPU(struct xen_clock_event_device, xen_clock_events) = { .evt.irq = -1 };
static irqreturn_t xen_timer_interrupt(int irq, void *dev_id)
{
struct clock_event_device *evt = &__get_cpu_var(xen_clock_events).evt;
irqreturn_t ret;
ret = IRQ_NONE;
if (evt->event_handler) {
evt->event_handler(evt);
ret = IRQ_HANDLED;
}
do_stolen_accounting();
return ret;
}
void xen_teardown_timer(int cpu)
{
struct clock_event_device *evt;
BUG_ON(cpu == 0);
evt = &per_cpu(xen_clock_events, cpu).evt;
if (evt->irq >= 0) {
unbind_from_irqhandler(evt->irq, NULL);
evt->irq = -1;
kfree(per_cpu(xen_clock_events, cpu).name);
per_cpu(xen_clock_events, cpu).name = NULL;
}
}
void xen_setup_timer(int cpu)
{
char *name;
struct clock_event_device *evt;
int irq;
evt = &per_cpu(xen_clock_events, cpu).evt;
WARN(evt->irq >= 0, "IRQ%d for CPU%d is already allocated\n", evt->irq, cpu);
if (evt->irq >= 0)
xen_teardown_timer(cpu);
printk(KERN_INFO "installing Xen timer for CPU %d\n", cpu);
name = kasprintf(GFP_KERNEL, "timer%d", cpu);
if (!name)
name = "<timer kasprintf failed>";
irq = bind_virq_to_irqhandler(VIRQ_TIMER, cpu, xen_timer_interrupt,
IRQF_PERCPU|IRQF_NOBALANCING|IRQF_TIMER|
IRQF_FORCE_RESUME,
name, NULL);
(void)xen_set_irq_priority(irq, XEN_IRQ_PRIORITY_MAX);
memcpy(evt, xen_clockevent, sizeof(*evt));
evt->cpumask = cpumask_of(cpu);
evt->irq = irq;
per_cpu(xen_clock_events, cpu).name = name;
}
void xen_setup_cpu_clockevents(void)
{
BUG_ON(preemptible());
clockevents_register_device(&__get_cpu_var(xen_clock_events).evt);
}
void xen_timer_resume(void)
{
int cpu;
pvclock_resume();
if (xen_clockevent != &xen_vcpuop_clockevent)
return;
for_each_online_cpu(cpu) {
if (HYPERVISOR_vcpu_op(VCPUOP_stop_periodic_timer, cpu, NULL))
BUG();
}
}
static const struct pv_time_ops xen_time_ops __initconst = {
.sched_clock = xen_clocksource_read,
};
static void __init xen_time_init(void)
{
int cpu = smp_processor_id();
struct timespec tp;
clocksource_register_hz(&xen_clocksource, NSEC_PER_SEC);
if (HYPERVISOR_vcpu_op(VCPUOP_stop_periodic_timer, cpu, NULL) == 0) {
/* Successfully turned off 100Hz tick, so we have the
vcpuop-based timer interface */
printk(KERN_DEBUG "Xen: using vcpuop timer interface\n");
xen_clockevent = &xen_vcpuop_clockevent;
}
/* Set initial system time with full resolution */
xen_read_wallclock(&tp);
do_settimeofday(&tp);
setup_force_cpu_cap(X86_FEATURE_TSC);
xen_setup_runstate_info(cpu);
xen_setup_timer(cpu);
xen_setup_cpu_clockevents();
if (xen_initial_domain())
pvclock_gtod_register_notifier(&xen_pvclock_gtod_notifier);
}
void __init xen_init_time_ops(void)
{
pv_time_ops = xen_time_ops;
x86_init.timers.timer_init = xen_time_init;
x86_init.timers.setup_percpu_clockev = x86_init_noop;
x86_cpuinit.setup_percpu_clockev = x86_init_noop;
x86_platform.calibrate_tsc = xen_tsc_khz;
x86_platform.get_wallclock = xen_get_wallclock;
/* Dom0 uses the native method to set the hardware RTC. */
if (!xen_initial_domain())
x86_platform.set_wallclock = xen_set_wallclock;
}
#ifdef CONFIG_XEN_PVHVM
static void xen_hvm_setup_cpu_clockevents(void)
{
int cpu = smp_processor_id();
xen_setup_runstate_info(cpu);
/*
* xen_setup_timer(cpu) - snprintf is bad in atomic context. Hence
* doing it xen_hvm_cpu_notify (which gets called by smp_init during
* early bootup and also during CPU hotplug events).
*/
xen_setup_cpu_clockevents();
}
void __init xen_hvm_init_time_ops(void)
{
/* vector callback is needed otherwise we cannot receive interrupts
* on cpu > 0 and at this point we don't know how many cpus are
* available */
if (!xen_have_vector_callback)
return;
if (!xen_feature(XENFEAT_hvm_safe_pvclock)) {
printk(KERN_INFO "Xen doesn't support pvclock on HVM,"
"disable pv timer\n");
return;
}
pv_time_ops = xen_time_ops;
x86_init.timers.setup_percpu_clockev = xen_time_init;
x86_cpuinit.setup_percpu_clockev = xen_hvm_setup_cpu_clockevents;
x86_platform.calibrate_tsc = xen_tsc_khz;
x86_platform.get_wallclock = xen_get_wallclock;
x86_platform.set_wallclock = xen_set_wallclock;
}
#endif
| gpl-2.0 |
androidbftab1/bf-kernel-3.18 | net/mac80211/iface.c | 223 | 49193 | /*
* Interface handling
*
* Copyright 2002-2005, Instant802 Networks, Inc.
* Copyright 2005-2006, Devicescape Software, Inc.
* Copyright (c) 2006 Jiri Benc <jbenc@suse.cz>
* Copyright 2008, Johannes Berg <johannes@sipsolutions.net>
* Copyright 2013-2014 Intel Mobile Communications GmbH
*
* 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/slab.h>
#include <linux/kernel.h>
#include <linux/if_arp.h>
#include <linux/netdevice.h>
#include <linux/rtnetlink.h>
#include <net/mac80211.h>
#include <net/ieee80211_radiotap.h>
#include "ieee80211_i.h"
#include "sta_info.h"
#include "debugfs_netdev.h"
#include "mesh.h"
#include "led.h"
#include "driver-ops.h"
#include "wme.h"
#include "rate.h"
/**
* DOC: Interface list locking
*
* The interface list in each struct ieee80211_local is protected
* three-fold:
*
* (1) modifications may only be done under the RTNL
* (2) modifications and readers are protected against each other by
* the iflist_mtx.
* (3) modifications are done in an RCU manner so atomic readers
* can traverse the list in RCU-safe blocks.
*
* As a consequence, reads (traversals) of the list can be protected
* by either the RTNL, the iflist_mtx or RCU.
*/
bool __ieee80211_recalc_txpower(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_chanctx_conf *chanctx_conf;
int power;
rcu_read_lock();
chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf);
if (!chanctx_conf) {
rcu_read_unlock();
return false;
}
power = ieee80211_chandef_max_power(&chanctx_conf->def);
rcu_read_unlock();
if (sdata->user_power_level != IEEE80211_UNSET_POWER_LEVEL)
power = min(power, sdata->user_power_level);
if (sdata->ap_power_level != IEEE80211_UNSET_POWER_LEVEL)
power = min(power, sdata->ap_power_level);
if (power != sdata->vif.bss_conf.txpower) {
sdata->vif.bss_conf.txpower = power;
ieee80211_hw_config(sdata->local, 0);
return true;
}
return false;
}
void ieee80211_recalc_txpower(struct ieee80211_sub_if_data *sdata)
{
if (__ieee80211_recalc_txpower(sdata))
ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_TXPOWER);
}
static u32 __ieee80211_idle_off(struct ieee80211_local *local)
{
if (!(local->hw.conf.flags & IEEE80211_CONF_IDLE))
return 0;
local->hw.conf.flags &= ~IEEE80211_CONF_IDLE;
return IEEE80211_CONF_CHANGE_IDLE;
}
static u32 __ieee80211_idle_on(struct ieee80211_local *local)
{
if (local->hw.conf.flags & IEEE80211_CONF_IDLE)
return 0;
ieee80211_flush_queues(local, NULL);
local->hw.conf.flags |= IEEE80211_CONF_IDLE;
return IEEE80211_CONF_CHANGE_IDLE;
}
static u32 __ieee80211_recalc_idle(struct ieee80211_local *local,
bool force_active)
{
bool working, scanning, active;
unsigned int led_trig_start = 0, led_trig_stop = 0;
lockdep_assert_held(&local->mtx);
active = force_active ||
!list_empty(&local->chanctx_list) ||
local->monitors;
working = !local->ops->remain_on_channel &&
!list_empty(&local->roc_list);
scanning = test_bit(SCAN_SW_SCANNING, &local->scanning) ||
test_bit(SCAN_ONCHANNEL_SCANNING, &local->scanning);
if (working || scanning)
led_trig_start |= IEEE80211_TPT_LEDTRIG_FL_WORK;
else
led_trig_stop |= IEEE80211_TPT_LEDTRIG_FL_WORK;
if (active)
led_trig_start |= IEEE80211_TPT_LEDTRIG_FL_CONNECTED;
else
led_trig_stop |= IEEE80211_TPT_LEDTRIG_FL_CONNECTED;
ieee80211_mod_tpt_led_trig(local, led_trig_start, led_trig_stop);
if (working || scanning || active)
return __ieee80211_idle_off(local);
return __ieee80211_idle_on(local);
}
u32 ieee80211_idle_off(struct ieee80211_local *local)
{
return __ieee80211_recalc_idle(local, true);
}
void ieee80211_recalc_idle(struct ieee80211_local *local)
{
u32 change = __ieee80211_recalc_idle(local, false);
if (change)
ieee80211_hw_config(local, change);
}
static int ieee80211_change_mtu(struct net_device *dev, int new_mtu)
{
if (new_mtu < 256 || new_mtu > IEEE80211_MAX_DATA_LEN)
return -EINVAL;
dev->mtu = new_mtu;
return 0;
}
static int ieee80211_verify_mac(struct ieee80211_sub_if_data *sdata, u8 *addr,
bool check_dup)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_sub_if_data *iter;
u64 new, mask, tmp;
u8 *m;
int ret = 0;
if (is_zero_ether_addr(local->hw.wiphy->addr_mask))
return 0;
m = addr;
new = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) |
((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) |
((u64)m[4] << 1*8) | ((u64)m[5] << 0*8);
m = local->hw.wiphy->addr_mask;
mask = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) |
((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) |
((u64)m[4] << 1*8) | ((u64)m[5] << 0*8);
if (!check_dup)
return ret;
mutex_lock(&local->iflist_mtx);
list_for_each_entry(iter, &local->interfaces, list) {
if (iter == sdata)
continue;
if (iter->vif.type == NL80211_IFTYPE_MONITOR &&
!(iter->u.mntr_flags & MONITOR_FLAG_ACTIVE))
continue;
m = iter->vif.addr;
tmp = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) |
((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) |
((u64)m[4] << 1*8) | ((u64)m[5] << 0*8);
if ((new & ~mask) != (tmp & ~mask)) {
ret = -EINVAL;
break;
}
}
mutex_unlock(&local->iflist_mtx);
return ret;
}
static int ieee80211_change_mac(struct net_device *dev, void *addr)
{
struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev);
struct sockaddr *sa = addr;
bool check_dup = true;
int ret;
if (ieee80211_sdata_running(sdata))
return -EBUSY;
if (sdata->vif.type == NL80211_IFTYPE_MONITOR &&
!(sdata->u.mntr_flags & MONITOR_FLAG_ACTIVE))
check_dup = false;
ret = ieee80211_verify_mac(sdata, sa->sa_data, check_dup);
if (ret)
return ret;
ret = eth_mac_addr(dev, sa);
if (ret == 0)
memcpy(sdata->vif.addr, sa->sa_data, ETH_ALEN);
return ret;
}
static inline int identical_mac_addr_allowed(int type1, int type2)
{
return type1 == NL80211_IFTYPE_MONITOR ||
type2 == NL80211_IFTYPE_MONITOR ||
type1 == NL80211_IFTYPE_P2P_DEVICE ||
type2 == NL80211_IFTYPE_P2P_DEVICE ||
(type1 == NL80211_IFTYPE_AP && type2 == NL80211_IFTYPE_WDS) ||
(type1 == NL80211_IFTYPE_WDS &&
(type2 == NL80211_IFTYPE_WDS ||
type2 == NL80211_IFTYPE_AP)) ||
(type1 == NL80211_IFTYPE_AP && type2 == NL80211_IFTYPE_AP_VLAN) ||
(type1 == NL80211_IFTYPE_AP_VLAN &&
(type2 == NL80211_IFTYPE_AP ||
type2 == NL80211_IFTYPE_AP_VLAN));
}
static int ieee80211_check_concurrent_iface(struct ieee80211_sub_if_data *sdata,
enum nl80211_iftype iftype)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_sub_if_data *nsdata;
int ret;
ASSERT_RTNL();
/* we hold the RTNL here so can safely walk the list */
list_for_each_entry(nsdata, &local->interfaces, list) {
if (nsdata != sdata && ieee80211_sdata_running(nsdata)) {
/*
* Allow only a single IBSS interface to be up at any
* time. This is restricted because beacon distribution
* cannot work properly if both are in the same IBSS.
*
* To remove this restriction we'd have to disallow them
* from setting the same SSID on different IBSS interfaces
* belonging to the same hardware. Then, however, we're
* faced with having to adopt two different TSF timers...
*/
if (iftype == NL80211_IFTYPE_ADHOC &&
nsdata->vif.type == NL80211_IFTYPE_ADHOC)
return -EBUSY;
/*
* will not add another interface while any channel
* switch is active.
*/
if (nsdata->vif.csa_active)
return -EBUSY;
/*
* The remaining checks are only performed for interfaces
* with the same MAC address.
*/
if (!ether_addr_equal(sdata->vif.addr,
nsdata->vif.addr))
continue;
/*
* check whether it may have the same address
*/
if (!identical_mac_addr_allowed(iftype,
nsdata->vif.type))
return -ENOTUNIQ;
/*
* can only add VLANs to enabled APs
*/
if (iftype == NL80211_IFTYPE_AP_VLAN &&
nsdata->vif.type == NL80211_IFTYPE_AP)
sdata->bss = &nsdata->u.ap;
}
}
mutex_lock(&local->chanctx_mtx);
ret = ieee80211_check_combinations(sdata, NULL, 0, 0);
mutex_unlock(&local->chanctx_mtx);
return ret;
}
static int ieee80211_check_queues(struct ieee80211_sub_if_data *sdata,
enum nl80211_iftype iftype)
{
int n_queues = sdata->local->hw.queues;
int i;
if (iftype != NL80211_IFTYPE_P2P_DEVICE) {
for (i = 0; i < IEEE80211_NUM_ACS; i++) {
if (WARN_ON_ONCE(sdata->vif.hw_queue[i] ==
IEEE80211_INVAL_HW_QUEUE))
return -EINVAL;
if (WARN_ON_ONCE(sdata->vif.hw_queue[i] >=
n_queues))
return -EINVAL;
}
}
if ((iftype != NL80211_IFTYPE_AP &&
iftype != NL80211_IFTYPE_P2P_GO &&
iftype != NL80211_IFTYPE_MESH_POINT) ||
!(sdata->local->hw.flags & IEEE80211_HW_QUEUE_CONTROL)) {
sdata->vif.cab_queue = IEEE80211_INVAL_HW_QUEUE;
return 0;
}
if (WARN_ON_ONCE(sdata->vif.cab_queue == IEEE80211_INVAL_HW_QUEUE))
return -EINVAL;
if (WARN_ON_ONCE(sdata->vif.cab_queue >= n_queues))
return -EINVAL;
return 0;
}
void ieee80211_adjust_monitor_flags(struct ieee80211_sub_if_data *sdata,
const int offset)
{
struct ieee80211_local *local = sdata->local;
u32 flags = sdata->u.mntr_flags;
#define ADJUST(_f, _s) do { \
if (flags & MONITOR_FLAG_##_f) \
local->fif_##_s += offset; \
} while (0)
ADJUST(FCSFAIL, fcsfail);
ADJUST(PLCPFAIL, plcpfail);
ADJUST(CONTROL, control);
ADJUST(CONTROL, pspoll);
ADJUST(OTHER_BSS, other_bss);
#undef ADJUST
}
static void ieee80211_set_default_queues(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_local *local = sdata->local;
int i;
for (i = 0; i < IEEE80211_NUM_ACS; i++) {
if (local->hw.flags & IEEE80211_HW_QUEUE_CONTROL)
sdata->vif.hw_queue[i] = IEEE80211_INVAL_HW_QUEUE;
else if (local->hw.queues >= IEEE80211_NUM_ACS)
sdata->vif.hw_queue[i] = i;
else
sdata->vif.hw_queue[i] = 0;
}
sdata->vif.cab_queue = IEEE80211_INVAL_HW_QUEUE;
}
int ieee80211_add_virtual_monitor(struct ieee80211_local *local)
{
struct ieee80211_sub_if_data *sdata;
int ret;
if (!(local->hw.flags & IEEE80211_HW_WANT_MONITOR_VIF))
return 0;
ASSERT_RTNL();
if (local->monitor_sdata)
return 0;
sdata = kzalloc(sizeof(*sdata) + local->hw.vif_data_size, GFP_KERNEL);
if (!sdata)
return -ENOMEM;
/* set up data */
sdata->local = local;
sdata->vif.type = NL80211_IFTYPE_MONITOR;
snprintf(sdata->name, IFNAMSIZ, "%s-monitor",
wiphy_name(local->hw.wiphy));
sdata->wdev.iftype = NL80211_IFTYPE_MONITOR;
sdata->encrypt_headroom = IEEE80211_ENCRYPT_HEADROOM;
ieee80211_set_default_queues(sdata);
ret = drv_add_interface(local, sdata);
if (WARN_ON(ret)) {
/* ok .. stupid driver, it asked for this! */
kfree(sdata);
return ret;
}
ret = ieee80211_check_queues(sdata, NL80211_IFTYPE_MONITOR);
if (ret) {
kfree(sdata);
return ret;
}
mutex_lock(&local->iflist_mtx);
rcu_assign_pointer(local->monitor_sdata, sdata);
mutex_unlock(&local->iflist_mtx);
mutex_lock(&local->mtx);
ret = ieee80211_vif_use_channel(sdata, &local->monitor_chandef,
IEEE80211_CHANCTX_EXCLUSIVE);
mutex_unlock(&local->mtx);
if (ret) {
mutex_lock(&local->iflist_mtx);
RCU_INIT_POINTER(local->monitor_sdata, NULL);
mutex_unlock(&local->iflist_mtx);
synchronize_net();
drv_remove_interface(local, sdata);
kfree(sdata);
return ret;
}
return 0;
}
void ieee80211_del_virtual_monitor(struct ieee80211_local *local)
{
struct ieee80211_sub_if_data *sdata;
if (!(local->hw.flags & IEEE80211_HW_WANT_MONITOR_VIF))
return;
ASSERT_RTNL();
mutex_lock(&local->iflist_mtx);
sdata = rcu_dereference_protected(local->monitor_sdata,
lockdep_is_held(&local->iflist_mtx));
if (!sdata) {
mutex_unlock(&local->iflist_mtx);
return;
}
RCU_INIT_POINTER(local->monitor_sdata, NULL);
mutex_unlock(&local->iflist_mtx);
synchronize_net();
mutex_lock(&local->mtx);
ieee80211_vif_release_channel(sdata);
mutex_unlock(&local->mtx);
drv_remove_interface(local, sdata);
kfree(sdata);
}
/*
* NOTE: Be very careful when changing this function, it must NOT return
* an error on interface type changes that have been pre-checked, so most
* checks should be in ieee80211_check_concurrent_iface.
*/
int ieee80211_do_open(struct wireless_dev *wdev, bool coming_up)
{
struct ieee80211_sub_if_data *sdata = IEEE80211_WDEV_TO_SUB_IF(wdev);
struct net_device *dev = wdev->netdev;
struct ieee80211_local *local = sdata->local;
struct sta_info *sta;
u32 changed = 0;
int res;
u32 hw_reconf_flags = 0;
switch (sdata->vif.type) {
case NL80211_IFTYPE_WDS:
if (!is_valid_ether_addr(sdata->u.wds.remote_addr))
return -ENOLINK;
break;
case NL80211_IFTYPE_AP_VLAN: {
struct ieee80211_sub_if_data *master;
if (!sdata->bss)
return -ENOLINK;
mutex_lock(&local->mtx);
list_add(&sdata->u.vlan.list, &sdata->bss->vlans);
mutex_unlock(&local->mtx);
master = container_of(sdata->bss,
struct ieee80211_sub_if_data, u.ap);
sdata->control_port_protocol =
master->control_port_protocol;
sdata->control_port_no_encrypt =
master->control_port_no_encrypt;
sdata->vif.cab_queue = master->vif.cab_queue;
memcpy(sdata->vif.hw_queue, master->vif.hw_queue,
sizeof(sdata->vif.hw_queue));
sdata->vif.bss_conf.chandef = master->vif.bss_conf.chandef;
break;
}
case NL80211_IFTYPE_AP:
sdata->bss = &sdata->u.ap;
break;
case NL80211_IFTYPE_MESH_POINT:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_P2P_DEVICE:
/* no special treatment */
break;
case NL80211_IFTYPE_UNSPECIFIED:
case NUM_NL80211_IFTYPES:
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_P2P_GO:
/* cannot happen */
WARN_ON(1);
break;
}
if (local->open_count == 0) {
res = drv_start(local);
if (res)
goto err_del_bss;
/* we're brought up, everything changes */
hw_reconf_flags = ~0;
ieee80211_led_radio(local, true);
ieee80211_mod_tpt_led_trig(local,
IEEE80211_TPT_LEDTRIG_FL_RADIO, 0);
}
/*
* Copy the hopefully now-present MAC address to
* this interface, if it has the special null one.
*/
if (dev && is_zero_ether_addr(dev->dev_addr)) {
memcpy(dev->dev_addr,
local->hw.wiphy->perm_addr,
ETH_ALEN);
memcpy(dev->perm_addr, dev->dev_addr, ETH_ALEN);
if (!is_valid_ether_addr(dev->dev_addr)) {
res = -EADDRNOTAVAIL;
goto err_stop;
}
}
switch (sdata->vif.type) {
case NL80211_IFTYPE_AP_VLAN:
/* no need to tell driver, but set carrier and chanctx */
if (rtnl_dereference(sdata->bss->beacon)) {
ieee80211_vif_vlan_copy_chanctx(sdata);
netif_carrier_on(dev);
} else {
netif_carrier_off(dev);
}
break;
case NL80211_IFTYPE_MONITOR:
if (sdata->u.mntr_flags & MONITOR_FLAG_COOK_FRAMES) {
local->cooked_mntrs++;
break;
}
if (sdata->u.mntr_flags & MONITOR_FLAG_ACTIVE) {
res = drv_add_interface(local, sdata);
if (res)
goto err_stop;
} else if (local->monitors == 0 && local->open_count == 0) {
res = ieee80211_add_virtual_monitor(local);
if (res)
goto err_stop;
}
/* must be before the call to ieee80211_configure_filter */
local->monitors++;
if (local->monitors == 1) {
local->hw.conf.flags |= IEEE80211_CONF_MONITOR;
hw_reconf_flags |= IEEE80211_CONF_CHANGE_MONITOR;
}
ieee80211_adjust_monitor_flags(sdata, 1);
ieee80211_configure_filter(local);
mutex_lock(&local->mtx);
ieee80211_recalc_idle(local);
mutex_unlock(&local->mtx);
netif_carrier_on(dev);
break;
default:
if (coming_up) {
ieee80211_del_virtual_monitor(local);
res = drv_add_interface(local, sdata);
if (res)
goto err_stop;
res = ieee80211_check_queues(sdata,
ieee80211_vif_type_p2p(&sdata->vif));
if (res)
goto err_del_interface;
}
if (sdata->vif.type == NL80211_IFTYPE_AP) {
local->fif_pspoll++;
local->fif_probe_req++;
ieee80211_configure_filter(local);
} else if (sdata->vif.type == NL80211_IFTYPE_ADHOC) {
local->fif_probe_req++;
}
if (sdata->vif.type != NL80211_IFTYPE_P2P_DEVICE)
changed |= ieee80211_reset_erp_info(sdata);
ieee80211_bss_info_change_notify(sdata, changed);
switch (sdata->vif.type) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_MESH_POINT:
netif_carrier_off(dev);
break;
case NL80211_IFTYPE_WDS:
case NL80211_IFTYPE_P2P_DEVICE:
break;
default:
/* not reached */
WARN_ON(1);
}
/*
* set default queue parameters so drivers don't
* need to initialise the hardware if the hardware
* doesn't start up with sane defaults
*/
ieee80211_set_wmm_default(sdata, true);
}
set_bit(SDATA_STATE_RUNNING, &sdata->state);
if (sdata->vif.type == NL80211_IFTYPE_WDS) {
/* Create STA entry for the WDS peer */
sta = sta_info_alloc(sdata, sdata->u.wds.remote_addr,
GFP_KERNEL);
if (!sta) {
res = -ENOMEM;
goto err_del_interface;
}
sta_info_pre_move_state(sta, IEEE80211_STA_AUTH);
sta_info_pre_move_state(sta, IEEE80211_STA_ASSOC);
sta_info_pre_move_state(sta, IEEE80211_STA_AUTHORIZED);
res = sta_info_insert(sta);
if (res) {
/* STA has been freed */
goto err_del_interface;
}
rate_control_rate_init(sta);
netif_carrier_on(dev);
} else if (sdata->vif.type == NL80211_IFTYPE_P2P_DEVICE) {
rcu_assign_pointer(local->p2p_sdata, sdata);
}
/*
* set_multicast_list will be invoked by the networking core
* which will check whether any increments here were done in
* error and sync them down to the hardware as filter flags.
*/
if (sdata->flags & IEEE80211_SDATA_ALLMULTI)
atomic_inc(&local->iff_allmultis);
if (sdata->flags & IEEE80211_SDATA_PROMISC)
atomic_inc(&local->iff_promiscs);
if (coming_up)
local->open_count++;
if (hw_reconf_flags)
ieee80211_hw_config(local, hw_reconf_flags);
ieee80211_recalc_ps(local, -1);
if (sdata->vif.type == NL80211_IFTYPE_MONITOR ||
sdata->vif.type == NL80211_IFTYPE_AP_VLAN) {
/* XXX: for AP_VLAN, actually track AP queues */
netif_tx_start_all_queues(dev);
} else if (dev) {
unsigned long flags;
int n_acs = IEEE80211_NUM_ACS;
int ac;
if (local->hw.queues < IEEE80211_NUM_ACS)
n_acs = 1;
spin_lock_irqsave(&local->queue_stop_reason_lock, flags);
if (sdata->vif.cab_queue == IEEE80211_INVAL_HW_QUEUE ||
(local->queue_stop_reasons[sdata->vif.cab_queue] == 0 &&
skb_queue_empty(&local->pending[sdata->vif.cab_queue]))) {
for (ac = 0; ac < n_acs; ac++) {
int ac_queue = sdata->vif.hw_queue[ac];
if (local->queue_stop_reasons[ac_queue] == 0 &&
skb_queue_empty(&local->pending[ac_queue]))
netif_start_subqueue(dev, ac);
}
}
spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags);
}
return 0;
err_del_interface:
drv_remove_interface(local, sdata);
err_stop:
if (!local->open_count)
drv_stop(local);
err_del_bss:
sdata->bss = NULL;
if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) {
mutex_lock(&local->mtx);
list_del(&sdata->u.vlan.list);
mutex_unlock(&local->mtx);
}
/* might already be clear but that doesn't matter */
clear_bit(SDATA_STATE_RUNNING, &sdata->state);
return res;
}
static int ieee80211_open(struct net_device *dev)
{
struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev);
int err;
/* fail early if user set an invalid address */
if (!is_valid_ether_addr(dev->dev_addr))
return -EADDRNOTAVAIL;
err = ieee80211_check_concurrent_iface(sdata, sdata->vif.type);
if (err)
return err;
return ieee80211_do_open(&sdata->wdev, true);
}
static void ieee80211_do_stop(struct ieee80211_sub_if_data *sdata,
bool going_down)
{
struct ieee80211_local *local = sdata->local;
unsigned long flags;
struct sk_buff *skb, *tmp;
u32 hw_reconf_flags = 0;
int i, flushed;
struct ps_data *ps;
struct cfg80211_chan_def chandef;
bool cancel_scan;
clear_bit(SDATA_STATE_RUNNING, &sdata->state);
cancel_scan = rcu_access_pointer(local->scan_sdata) == sdata;
if (cancel_scan)
ieee80211_scan_cancel(local);
/*
* Stop TX on this interface first.
*/
if (sdata->dev)
netif_tx_stop_all_queues(sdata->dev);
ieee80211_roc_purge(local, sdata);
switch (sdata->vif.type) {
case NL80211_IFTYPE_STATION:
ieee80211_mgd_stop(sdata);
break;
case NL80211_IFTYPE_ADHOC:
ieee80211_ibss_stop(sdata);
break;
case NL80211_IFTYPE_AP:
cancel_work_sync(&sdata->u.ap.request_smps_work);
break;
default:
break;
}
/*
* Remove all stations associated with this interface.
*
* This must be done before calling ops->remove_interface()
* because otherwise we can later invoke ops->sta_notify()
* whenever the STAs are removed, and that invalidates driver
* assumptions about always getting a vif pointer that is valid
* (because if we remove a STA after ops->remove_interface()
* the driver will have removed the vif info already!)
*
* This is relevant only in WDS mode, in all other modes we've
* already removed all stations when disconnecting or similar,
* so warn otherwise.
*/
flushed = sta_info_flush(sdata);
WARN_ON_ONCE((sdata->vif.type != NL80211_IFTYPE_WDS && flushed > 0) ||
(sdata->vif.type == NL80211_IFTYPE_WDS && flushed != 1));
/* don't count this interface for promisc/allmulti while it is down */
if (sdata->flags & IEEE80211_SDATA_ALLMULTI)
atomic_dec(&local->iff_allmultis);
if (sdata->flags & IEEE80211_SDATA_PROMISC)
atomic_dec(&local->iff_promiscs);
if (sdata->vif.type == NL80211_IFTYPE_AP) {
local->fif_pspoll--;
local->fif_probe_req--;
} else if (sdata->vif.type == NL80211_IFTYPE_ADHOC) {
local->fif_probe_req--;
}
if (sdata->dev) {
netif_addr_lock_bh(sdata->dev);
spin_lock_bh(&local->filter_lock);
__hw_addr_unsync(&local->mc_list, &sdata->dev->mc,
sdata->dev->addr_len);
spin_unlock_bh(&local->filter_lock);
netif_addr_unlock_bh(sdata->dev);
}
del_timer_sync(&local->dynamic_ps_timer);
cancel_work_sync(&local->dynamic_ps_enable_work);
cancel_work_sync(&sdata->recalc_smps);
sdata_lock(sdata);
mutex_lock(&local->mtx);
sdata->vif.csa_active = false;
if (sdata->csa_block_tx) {
ieee80211_wake_vif_queues(local, sdata,
IEEE80211_QUEUE_STOP_REASON_CSA);
sdata->csa_block_tx = false;
}
mutex_unlock(&local->mtx);
sdata_unlock(sdata);
cancel_work_sync(&sdata->csa_finalize_work);
cancel_delayed_work_sync(&sdata->dfs_cac_timer_work);
if (sdata->wdev.cac_started) {
chandef = sdata->vif.bss_conf.chandef;
WARN_ON(local->suspended);
mutex_lock(&local->mtx);
ieee80211_vif_release_channel(sdata);
mutex_unlock(&local->mtx);
cfg80211_cac_event(sdata->dev, &chandef,
NL80211_RADAR_CAC_ABORTED,
GFP_KERNEL);
}
/* APs need special treatment */
if (sdata->vif.type == NL80211_IFTYPE_AP) {
struct ieee80211_sub_if_data *vlan, *tmpsdata;
/* down all dependent devices, that is VLANs */
list_for_each_entry_safe(vlan, tmpsdata, &sdata->u.ap.vlans,
u.vlan.list)
dev_close(vlan->dev);
WARN_ON(!list_empty(&sdata->u.ap.vlans));
} else if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) {
/* remove all packets in parent bc_buf pointing to this dev */
ps = &sdata->bss->ps;
spin_lock_irqsave(&ps->bc_buf.lock, flags);
skb_queue_walk_safe(&ps->bc_buf, skb, tmp) {
if (skb->dev == sdata->dev) {
__skb_unlink(skb, &ps->bc_buf);
local->total_ps_buffered--;
ieee80211_free_txskb(&local->hw, skb);
}
}
spin_unlock_irqrestore(&ps->bc_buf.lock, flags);
}
if (going_down)
local->open_count--;
switch (sdata->vif.type) {
case NL80211_IFTYPE_AP_VLAN:
mutex_lock(&local->mtx);
list_del(&sdata->u.vlan.list);
mutex_unlock(&local->mtx);
RCU_INIT_POINTER(sdata->vif.chanctx_conf, NULL);
/* see comment in the default case below */
ieee80211_free_keys(sdata, true);
/* no need to tell driver */
break;
case NL80211_IFTYPE_MONITOR:
if (sdata->u.mntr_flags & MONITOR_FLAG_COOK_FRAMES) {
local->cooked_mntrs--;
break;
}
local->monitors--;
if (local->monitors == 0) {
local->hw.conf.flags &= ~IEEE80211_CONF_MONITOR;
hw_reconf_flags |= IEEE80211_CONF_CHANGE_MONITOR;
}
ieee80211_adjust_monitor_flags(sdata, -1);
break;
case NL80211_IFTYPE_P2P_DEVICE:
/* relies on synchronize_rcu() below */
RCU_INIT_POINTER(local->p2p_sdata, NULL);
/* fall through */
default:
cancel_work_sync(&sdata->work);
/*
* When we get here, the interface is marked down.
* Free the remaining keys, if there are any
* (which can happen in AP mode if userspace sets
* keys before the interface is operating, and maybe
* also in WDS mode)
*
* Force the key freeing to always synchronize_net()
* to wait for the RX path in case it is using this
* interface enqueuing frames at this very time on
* another CPU.
*/
ieee80211_free_keys(sdata, true);
skb_queue_purge(&sdata->skb_queue);
}
sdata->bss = NULL;
spin_lock_irqsave(&local->queue_stop_reason_lock, flags);
for (i = 0; i < IEEE80211_MAX_QUEUES; i++) {
skb_queue_walk_safe(&local->pending[i], skb, tmp) {
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
if (info->control.vif == &sdata->vif) {
__skb_unlink(skb, &local->pending[i]);
ieee80211_free_txskb(&local->hw, skb);
}
}
}
spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags);
if (local->open_count == 0)
ieee80211_clear_tx_pending(local);
/*
* If the interface goes down while suspended, presumably because
* the device was unplugged and that happens before our resume,
* then the driver is already unconfigured and the remainder of
* this function isn't needed.
* XXX: what about WoWLAN? If the device has software state, e.g.
* memory allocated, it might expect teardown commands from
* mac80211 here?
*/
if (local->suspended) {
WARN_ON(local->wowlan);
WARN_ON(rtnl_dereference(local->monitor_sdata));
return;
}
switch (sdata->vif.type) {
case NL80211_IFTYPE_AP_VLAN:
break;
case NL80211_IFTYPE_MONITOR:
if (local->monitors == 0)
ieee80211_del_virtual_monitor(local);
mutex_lock(&local->mtx);
ieee80211_recalc_idle(local);
mutex_unlock(&local->mtx);
if (!(sdata->u.mntr_flags & MONITOR_FLAG_ACTIVE))
break;
/* fall through */
default:
if (going_down)
drv_remove_interface(local, sdata);
}
ieee80211_recalc_ps(local, -1);
if (cancel_scan)
flush_delayed_work(&local->scan_work);
if (local->open_count == 0) {
ieee80211_stop_device(local);
/* no reconfiguring after stop! */
return;
}
/* do after stop to avoid reconfiguring when we stop anyway */
ieee80211_configure_filter(local);
ieee80211_hw_config(local, hw_reconf_flags);
if (local->monitors == local->open_count)
ieee80211_add_virtual_monitor(local);
}
static int ieee80211_stop(struct net_device *dev)
{
struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev);
ieee80211_do_stop(sdata, true);
return 0;
}
static void ieee80211_set_multicast_list(struct net_device *dev)
{
struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev);
struct ieee80211_local *local = sdata->local;
int allmulti, promisc, sdata_allmulti, sdata_promisc;
allmulti = !!(dev->flags & IFF_ALLMULTI);
promisc = !!(dev->flags & IFF_PROMISC);
sdata_allmulti = !!(sdata->flags & IEEE80211_SDATA_ALLMULTI);
sdata_promisc = !!(sdata->flags & IEEE80211_SDATA_PROMISC);
if (allmulti != sdata_allmulti) {
if (dev->flags & IFF_ALLMULTI)
atomic_inc(&local->iff_allmultis);
else
atomic_dec(&local->iff_allmultis);
sdata->flags ^= IEEE80211_SDATA_ALLMULTI;
}
if (promisc != sdata_promisc) {
if (dev->flags & IFF_PROMISC)
atomic_inc(&local->iff_promiscs);
else
atomic_dec(&local->iff_promiscs);
sdata->flags ^= IEEE80211_SDATA_PROMISC;
}
spin_lock_bh(&local->filter_lock);
__hw_addr_sync(&local->mc_list, &dev->mc, dev->addr_len);
spin_unlock_bh(&local->filter_lock);
ieee80211_queue_work(&local->hw, &local->reconfig_filter);
}
/*
* Called when the netdev is removed or, by the code below, before
* the interface type changes.
*/
static void ieee80211_teardown_sdata(struct ieee80211_sub_if_data *sdata)
{
int i;
/* free extra data */
ieee80211_free_keys(sdata, false);
ieee80211_debugfs_remove_netdev(sdata);
for (i = 0; i < IEEE80211_FRAGMENT_MAX; i++)
__skb_queue_purge(&sdata->fragments[i].skb_list);
sdata->fragment_next = 0;
if (ieee80211_vif_is_mesh(&sdata->vif))
mesh_rmc_free(sdata);
}
static void ieee80211_uninit(struct net_device *dev)
{
ieee80211_teardown_sdata(IEEE80211_DEV_TO_SUB_IF(dev));
}
static u16 ieee80211_netdev_select_queue(struct net_device *dev,
struct sk_buff *skb,
void *accel_priv,
select_queue_fallback_t fallback)
{
return ieee80211_select_queue(IEEE80211_DEV_TO_SUB_IF(dev), skb);
}
static const struct net_device_ops ieee80211_dataif_ops = {
.ndo_open = ieee80211_open,
.ndo_stop = ieee80211_stop,
.ndo_uninit = ieee80211_uninit,
.ndo_start_xmit = ieee80211_subif_start_xmit,
.ndo_set_rx_mode = ieee80211_set_multicast_list,
.ndo_change_mtu = ieee80211_change_mtu,
.ndo_set_mac_address = ieee80211_change_mac,
.ndo_select_queue = ieee80211_netdev_select_queue,
};
static u16 ieee80211_monitor_select_queue(struct net_device *dev,
struct sk_buff *skb,
void *accel_priv,
select_queue_fallback_t fallback)
{
struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev);
struct ieee80211_local *local = sdata->local;
struct ieee80211_hdr *hdr;
struct ieee80211_radiotap_header *rtap = (void *)skb->data;
if (local->hw.queues < IEEE80211_NUM_ACS)
return 0;
if (skb->len < 4 ||
skb->len < le16_to_cpu(rtap->it_len) + 2 /* frame control */)
return 0; /* doesn't matter, frame will be dropped */
hdr = (void *)((u8 *)skb->data + le16_to_cpu(rtap->it_len));
return ieee80211_select_queue_80211(sdata, skb, hdr);
}
static const struct net_device_ops ieee80211_monitorif_ops = {
.ndo_open = ieee80211_open,
.ndo_stop = ieee80211_stop,
.ndo_uninit = ieee80211_uninit,
.ndo_start_xmit = ieee80211_monitor_start_xmit,
.ndo_set_rx_mode = ieee80211_set_multicast_list,
.ndo_change_mtu = ieee80211_change_mtu,
.ndo_set_mac_address = ieee80211_change_mac,
.ndo_select_queue = ieee80211_monitor_select_queue,
};
static void ieee80211_if_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->netdev_ops = &ieee80211_dataif_ops;
dev->destructor = free_netdev;
}
static void ieee80211_iface_work(struct work_struct *work)
{
struct ieee80211_sub_if_data *sdata =
container_of(work, struct ieee80211_sub_if_data, work);
struct ieee80211_local *local = sdata->local;
struct sk_buff *skb;
struct sta_info *sta;
struct ieee80211_ra_tid *ra_tid;
struct ieee80211_rx_agg *rx_agg;
if (!ieee80211_sdata_running(sdata))
return;
if (local->scanning)
return;
/*
* ieee80211_queue_work() should have picked up most cases,
* here we'll pick the rest.
*/
if (WARN(local->suspended,
"interface work scheduled while going to suspend\n"))
return;
/* first process frames */
while ((skb = skb_dequeue(&sdata->skb_queue))) {
struct ieee80211_mgmt *mgmt = (void *)skb->data;
if (skb->pkt_type == IEEE80211_SDATA_QUEUE_AGG_START) {
ra_tid = (void *)&skb->cb;
ieee80211_start_tx_ba_cb(&sdata->vif, ra_tid->ra,
ra_tid->tid);
} else if (skb->pkt_type == IEEE80211_SDATA_QUEUE_AGG_STOP) {
ra_tid = (void *)&skb->cb;
ieee80211_stop_tx_ba_cb(&sdata->vif, ra_tid->ra,
ra_tid->tid);
} else if (skb->pkt_type == IEEE80211_SDATA_QUEUE_RX_AGG_START) {
rx_agg = (void *)&skb->cb;
mutex_lock(&local->sta_mtx);
sta = sta_info_get_bss(sdata, rx_agg->addr);
if (sta)
__ieee80211_start_rx_ba_session(sta,
0, 0, 0, 1, rx_agg->tid,
IEEE80211_MAX_AMPDU_BUF,
false, true);
mutex_unlock(&local->sta_mtx);
} else if (skb->pkt_type == IEEE80211_SDATA_QUEUE_RX_AGG_STOP) {
rx_agg = (void *)&skb->cb;
mutex_lock(&local->sta_mtx);
sta = sta_info_get_bss(sdata, rx_agg->addr);
if (sta)
__ieee80211_stop_rx_ba_session(sta,
rx_agg->tid,
WLAN_BACK_RECIPIENT, 0,
false);
mutex_unlock(&local->sta_mtx);
} else if (ieee80211_is_action(mgmt->frame_control) &&
mgmt->u.action.category == WLAN_CATEGORY_BACK) {
int len = skb->len;
mutex_lock(&local->sta_mtx);
sta = sta_info_get_bss(sdata, mgmt->sa);
if (sta) {
switch (mgmt->u.action.u.addba_req.action_code) {
case WLAN_ACTION_ADDBA_REQ:
ieee80211_process_addba_request(
local, sta, mgmt, len);
break;
case WLAN_ACTION_ADDBA_RESP:
ieee80211_process_addba_resp(local, sta,
mgmt, len);
break;
case WLAN_ACTION_DELBA:
ieee80211_process_delba(sdata, sta,
mgmt, len);
break;
default:
WARN_ON(1);
break;
}
}
mutex_unlock(&local->sta_mtx);
} else if (ieee80211_is_data_qos(mgmt->frame_control)) {
struct ieee80211_hdr *hdr = (void *)mgmt;
/*
* So the frame isn't mgmt, but frame_control
* is at the right place anyway, of course, so
* the if statement is correct.
*
* Warn if we have other data frame types here,
* they must not get here.
*/
WARN_ON(hdr->frame_control &
cpu_to_le16(IEEE80211_STYPE_NULLFUNC));
WARN_ON(!(hdr->seq_ctrl &
cpu_to_le16(IEEE80211_SCTL_FRAG)));
/*
* This was a fragment of a frame, received while
* a block-ack session was active. That cannot be
* right, so terminate the session.
*/
mutex_lock(&local->sta_mtx);
sta = sta_info_get_bss(sdata, mgmt->sa);
if (sta) {
u16 tid = *ieee80211_get_qos_ctl(hdr) &
IEEE80211_QOS_CTL_TID_MASK;
__ieee80211_stop_rx_ba_session(
sta, tid, WLAN_BACK_RECIPIENT,
WLAN_REASON_QSTA_REQUIRE_SETUP,
true);
}
mutex_unlock(&local->sta_mtx);
} else switch (sdata->vif.type) {
case NL80211_IFTYPE_STATION:
ieee80211_sta_rx_queued_mgmt(sdata, skb);
break;
case NL80211_IFTYPE_ADHOC:
ieee80211_ibss_rx_queued_mgmt(sdata, skb);
break;
case NL80211_IFTYPE_MESH_POINT:
if (!ieee80211_vif_is_mesh(&sdata->vif))
break;
ieee80211_mesh_rx_queued_mgmt(sdata, skb);
break;
default:
WARN(1, "frame for unexpected interface type");
break;
}
kfree_skb(skb);
}
/* then other type-dependent work */
switch (sdata->vif.type) {
case NL80211_IFTYPE_STATION:
ieee80211_sta_work(sdata);
break;
case NL80211_IFTYPE_ADHOC:
ieee80211_ibss_work(sdata);
break;
case NL80211_IFTYPE_MESH_POINT:
if (!ieee80211_vif_is_mesh(&sdata->vif))
break;
ieee80211_mesh_work(sdata);
break;
default:
break;
}
}
static void ieee80211_recalc_smps_work(struct work_struct *work)
{
struct ieee80211_sub_if_data *sdata =
container_of(work, struct ieee80211_sub_if_data, recalc_smps);
ieee80211_recalc_smps(sdata);
}
/*
* Helper function to initialise an interface to a specific type.
*/
static void ieee80211_setup_sdata(struct ieee80211_sub_if_data *sdata,
enum nl80211_iftype type)
{
/* clear type-dependent union */
memset(&sdata->u, 0, sizeof(sdata->u));
/* and set some type-dependent values */
sdata->vif.type = type;
sdata->vif.p2p = false;
sdata->wdev.iftype = type;
sdata->control_port_protocol = cpu_to_be16(ETH_P_PAE);
sdata->control_port_no_encrypt = false;
sdata->encrypt_headroom = IEEE80211_ENCRYPT_HEADROOM;
sdata->vif.bss_conf.idle = true;
sdata->noack_map = 0;
/* only monitor/p2p-device differ */
if (sdata->dev) {
sdata->dev->netdev_ops = &ieee80211_dataif_ops;
sdata->dev->type = ARPHRD_ETHER;
}
skb_queue_head_init(&sdata->skb_queue);
INIT_WORK(&sdata->work, ieee80211_iface_work);
INIT_WORK(&sdata->recalc_smps, ieee80211_recalc_smps_work);
INIT_WORK(&sdata->csa_finalize_work, ieee80211_csa_finalize_work);
INIT_LIST_HEAD(&sdata->assigned_chanctx_list);
INIT_LIST_HEAD(&sdata->reserved_chanctx_list);
switch (type) {
case NL80211_IFTYPE_P2P_GO:
type = NL80211_IFTYPE_AP;
sdata->vif.type = type;
sdata->vif.p2p = true;
/* fall through */
case NL80211_IFTYPE_AP:
skb_queue_head_init(&sdata->u.ap.ps.bc_buf);
INIT_LIST_HEAD(&sdata->u.ap.vlans);
INIT_WORK(&sdata->u.ap.request_smps_work,
ieee80211_request_smps_ap_work);
sdata->vif.bss_conf.bssid = sdata->vif.addr;
sdata->u.ap.req_smps = IEEE80211_SMPS_OFF;
break;
case NL80211_IFTYPE_P2P_CLIENT:
type = NL80211_IFTYPE_STATION;
sdata->vif.type = type;
sdata->vif.p2p = true;
/* fall through */
case NL80211_IFTYPE_STATION:
sdata->vif.bss_conf.bssid = sdata->u.mgd.bssid;
ieee80211_sta_setup_sdata(sdata);
break;
case NL80211_IFTYPE_ADHOC:
sdata->vif.bss_conf.bssid = sdata->u.ibss.bssid;
ieee80211_ibss_setup_sdata(sdata);
break;
case NL80211_IFTYPE_MESH_POINT:
if (ieee80211_vif_is_mesh(&sdata->vif))
ieee80211_mesh_init_sdata(sdata);
break;
case NL80211_IFTYPE_MONITOR:
sdata->dev->type = ARPHRD_IEEE80211_RADIOTAP;
sdata->dev->netdev_ops = &ieee80211_monitorif_ops;
sdata->u.mntr_flags = MONITOR_FLAG_CONTROL |
MONITOR_FLAG_OTHER_BSS;
break;
case NL80211_IFTYPE_WDS:
sdata->vif.bss_conf.bssid = NULL;
break;
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_P2P_DEVICE:
sdata->vif.bss_conf.bssid = sdata->vif.addr;
break;
case NL80211_IFTYPE_UNSPECIFIED:
case NUM_NL80211_IFTYPES:
BUG();
break;
}
ieee80211_debugfs_add_netdev(sdata);
}
static int ieee80211_runtime_change_iftype(struct ieee80211_sub_if_data *sdata,
enum nl80211_iftype type)
{
struct ieee80211_local *local = sdata->local;
int ret, err;
enum nl80211_iftype internal_type = type;
bool p2p = false;
ASSERT_RTNL();
if (!local->ops->change_interface)
return -EBUSY;
switch (sdata->vif.type) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
/*
* Could maybe also all others here?
* Just not sure how that interacts
* with the RX/config path e.g. for
* mesh.
*/
break;
default:
return -EBUSY;
}
switch (type) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
/*
* Could probably support everything
* but WDS here (WDS do_open can fail
* under memory pressure, which this
* code isn't prepared to handle).
*/
break;
case NL80211_IFTYPE_P2P_CLIENT:
p2p = true;
internal_type = NL80211_IFTYPE_STATION;
break;
case NL80211_IFTYPE_P2P_GO:
p2p = true;
internal_type = NL80211_IFTYPE_AP;
break;
default:
return -EBUSY;
}
ret = ieee80211_check_concurrent_iface(sdata, internal_type);
if (ret)
return ret;
ieee80211_do_stop(sdata, false);
ieee80211_teardown_sdata(sdata);
ret = drv_change_interface(local, sdata, internal_type, p2p);
if (ret)
type = ieee80211_vif_type_p2p(&sdata->vif);
/*
* Ignore return value here, there's not much we can do since
* the driver changed the interface type internally already.
* The warnings will hopefully make driver authors fix it :-)
*/
ieee80211_check_queues(sdata, type);
ieee80211_setup_sdata(sdata, type);
err = ieee80211_do_open(&sdata->wdev, false);
WARN(err, "type change: do_open returned %d", err);
return ret;
}
int ieee80211_if_change_type(struct ieee80211_sub_if_data *sdata,
enum nl80211_iftype type)
{
int ret;
ASSERT_RTNL();
if (type == ieee80211_vif_type_p2p(&sdata->vif))
return 0;
if (ieee80211_sdata_running(sdata)) {
ret = ieee80211_runtime_change_iftype(sdata, type);
if (ret)
return ret;
} else {
/* Purge and reset type-dependent state. */
ieee80211_teardown_sdata(sdata);
ieee80211_setup_sdata(sdata, type);
}
/* reset some values that shouldn't be kept across type changes */
sdata->drop_unencrypted = 0;
if (type == NL80211_IFTYPE_STATION)
sdata->u.mgd.use_4addr = false;
return 0;
}
static void ieee80211_assign_perm_addr(struct ieee80211_local *local,
u8 *perm_addr, enum nl80211_iftype type)
{
struct ieee80211_sub_if_data *sdata;
u64 mask, start, addr, val, inc;
u8 *m;
u8 tmp_addr[ETH_ALEN];
int i;
/* default ... something at least */
memcpy(perm_addr, local->hw.wiphy->perm_addr, ETH_ALEN);
if (is_zero_ether_addr(local->hw.wiphy->addr_mask) &&
local->hw.wiphy->n_addresses <= 1)
return;
mutex_lock(&local->iflist_mtx);
switch (type) {
case NL80211_IFTYPE_MONITOR:
/* doesn't matter */
break;
case NL80211_IFTYPE_WDS:
case NL80211_IFTYPE_AP_VLAN:
/* match up with an AP interface */
list_for_each_entry(sdata, &local->interfaces, list) {
if (sdata->vif.type != NL80211_IFTYPE_AP)
continue;
memcpy(perm_addr, sdata->vif.addr, ETH_ALEN);
break;
}
/* keep default if no AP interface present */
break;
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_P2P_GO:
if (local->hw.flags & IEEE80211_HW_P2P_DEV_ADDR_FOR_INTF) {
list_for_each_entry(sdata, &local->interfaces, list) {
if (sdata->vif.type != NL80211_IFTYPE_P2P_DEVICE)
continue;
if (!ieee80211_sdata_running(sdata))
continue;
memcpy(perm_addr, sdata->vif.addr, ETH_ALEN);
goto out_unlock;
}
}
/* otherwise fall through */
default:
/* assign a new address if possible -- try n_addresses first */
for (i = 0; i < local->hw.wiphy->n_addresses; i++) {
bool used = false;
list_for_each_entry(sdata, &local->interfaces, list) {
if (ether_addr_equal(local->hw.wiphy->addresses[i].addr,
sdata->vif.addr)) {
used = true;
break;
}
}
if (!used) {
memcpy(perm_addr,
local->hw.wiphy->addresses[i].addr,
ETH_ALEN);
break;
}
}
/* try mask if available */
if (is_zero_ether_addr(local->hw.wiphy->addr_mask))
break;
m = local->hw.wiphy->addr_mask;
mask = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) |
((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) |
((u64)m[4] << 1*8) | ((u64)m[5] << 0*8);
if (__ffs64(mask) + hweight64(mask) != fls64(mask)) {
/* not a contiguous mask ... not handled now! */
pr_info("not contiguous\n");
break;
}
/*
* Pick address of existing interface in case user changed
* MAC address manually, default to perm_addr.
*/
m = local->hw.wiphy->perm_addr;
list_for_each_entry(sdata, &local->interfaces, list) {
if (sdata->vif.type == NL80211_IFTYPE_MONITOR)
continue;
m = sdata->vif.addr;
break;
}
start = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) |
((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) |
((u64)m[4] << 1*8) | ((u64)m[5] << 0*8);
inc = 1ULL<<__ffs64(mask);
val = (start & mask);
addr = (start & ~mask) | (val & mask);
do {
bool used = false;
tmp_addr[5] = addr >> 0*8;
tmp_addr[4] = addr >> 1*8;
tmp_addr[3] = addr >> 2*8;
tmp_addr[2] = addr >> 3*8;
tmp_addr[1] = addr >> 4*8;
tmp_addr[0] = addr >> 5*8;
val += inc;
list_for_each_entry(sdata, &local->interfaces, list) {
if (ether_addr_equal(tmp_addr, sdata->vif.addr)) {
used = true;
break;
}
}
if (!used) {
memcpy(perm_addr, tmp_addr, ETH_ALEN);
break;
}
addr = (start & ~mask) | (val & mask);
} while (addr != start);
break;
}
out_unlock:
mutex_unlock(&local->iflist_mtx);
}
int ieee80211_if_add(struct ieee80211_local *local, const char *name,
struct wireless_dev **new_wdev, enum nl80211_iftype type,
struct vif_params *params)
{
struct net_device *ndev = NULL;
struct ieee80211_sub_if_data *sdata = NULL;
int ret, i;
int txqs = 1;
ASSERT_RTNL();
if (type == NL80211_IFTYPE_P2P_DEVICE) {
struct wireless_dev *wdev;
sdata = kzalloc(sizeof(*sdata) + local->hw.vif_data_size,
GFP_KERNEL);
if (!sdata)
return -ENOMEM;
wdev = &sdata->wdev;
sdata->dev = NULL;
strlcpy(sdata->name, name, IFNAMSIZ);
ieee80211_assign_perm_addr(local, wdev->address, type);
memcpy(sdata->vif.addr, wdev->address, ETH_ALEN);
} else {
if (local->hw.queues >= IEEE80211_NUM_ACS)
txqs = IEEE80211_NUM_ACS;
ndev = alloc_netdev_mqs(sizeof(*sdata) + local->hw.vif_data_size,
name, NET_NAME_UNKNOWN,
ieee80211_if_setup, txqs, 1);
if (!ndev)
return -ENOMEM;
dev_net_set(ndev, wiphy_net(local->hw.wiphy));
ndev->needed_headroom = local->tx_headroom +
4*6 /* four MAC addresses */
+ 2 + 2 + 2 + 2 /* ctl, dur, seq, qos */
+ 6 /* mesh */
+ 8 /* rfc1042/bridge tunnel */
- ETH_HLEN /* ethernet hard_header_len */
+ IEEE80211_ENCRYPT_HEADROOM;
ndev->needed_tailroom = IEEE80211_ENCRYPT_TAILROOM;
ret = dev_alloc_name(ndev, ndev->name);
if (ret < 0) {
free_netdev(ndev);
return ret;
}
ieee80211_assign_perm_addr(local, ndev->perm_addr, type);
memcpy(ndev->dev_addr, ndev->perm_addr, ETH_ALEN);
SET_NETDEV_DEV(ndev, wiphy_dev(local->hw.wiphy));
/* don't use IEEE80211_DEV_TO_SUB_IF -- it checks too much */
sdata = netdev_priv(ndev);
ndev->ieee80211_ptr = &sdata->wdev;
memcpy(sdata->vif.addr, ndev->dev_addr, ETH_ALEN);
memcpy(sdata->name, ndev->name, IFNAMSIZ);
sdata->dev = ndev;
}
/* initialise type-independent data */
sdata->wdev.wiphy = local->hw.wiphy;
sdata->local = local;
for (i = 0; i < IEEE80211_FRAGMENT_MAX; i++)
skb_queue_head_init(&sdata->fragments[i].skb_list);
INIT_LIST_HEAD(&sdata->key_list);
INIT_DELAYED_WORK(&sdata->dfs_cac_timer_work,
ieee80211_dfs_cac_timer_work);
INIT_DELAYED_WORK(&sdata->dec_tailroom_needed_wk,
ieee80211_delayed_tailroom_dec);
for (i = 0; i < IEEE80211_NUM_BANDS; i++) {
struct ieee80211_supported_band *sband;
sband = local->hw.wiphy->bands[i];
sdata->rc_rateidx_mask[i] =
sband ? (1 << sband->n_bitrates) - 1 : 0;
if (sband)
memcpy(sdata->rc_rateidx_mcs_mask[i],
sband->ht_cap.mcs.rx_mask,
sizeof(sdata->rc_rateidx_mcs_mask[i]));
else
memset(sdata->rc_rateidx_mcs_mask[i], 0,
sizeof(sdata->rc_rateidx_mcs_mask[i]));
}
ieee80211_set_default_queues(sdata);
sdata->ap_power_level = IEEE80211_UNSET_POWER_LEVEL;
sdata->user_power_level = local->user_power_level;
sdata->encrypt_headroom = IEEE80211_ENCRYPT_HEADROOM;
/* setup type-dependent data */
ieee80211_setup_sdata(sdata, type);
if (ndev) {
if (params) {
ndev->ieee80211_ptr->use_4addr = params->use_4addr;
if (type == NL80211_IFTYPE_STATION)
sdata->u.mgd.use_4addr = params->use_4addr;
}
ndev->features |= local->hw.netdev_features;
netdev_set_default_ethtool_ops(ndev, &ieee80211_ethtool_ops);
ret = register_netdevice(ndev);
if (ret) {
free_netdev(ndev);
return ret;
}
}
mutex_lock(&local->iflist_mtx);
list_add_tail_rcu(&sdata->list, &local->interfaces);
mutex_unlock(&local->iflist_mtx);
if (new_wdev)
*new_wdev = &sdata->wdev;
return 0;
}
void ieee80211_if_remove(struct ieee80211_sub_if_data *sdata)
{
ASSERT_RTNL();
mutex_lock(&sdata->local->iflist_mtx);
list_del_rcu(&sdata->list);
mutex_unlock(&sdata->local->iflist_mtx);
synchronize_rcu();
if (sdata->dev) {
unregister_netdevice(sdata->dev);
} else {
cfg80211_unregister_wdev(&sdata->wdev);
kfree(sdata);
}
}
void ieee80211_sdata_stop(struct ieee80211_sub_if_data *sdata)
{
if (WARN_ON_ONCE(!test_bit(SDATA_STATE_RUNNING, &sdata->state)))
return;
ieee80211_do_stop(sdata, true);
ieee80211_teardown_sdata(sdata);
}
/*
* Remove all interfaces, may only be called at hardware unregistration
* time because it doesn't do RCU-safe list removals.
*/
void ieee80211_remove_interfaces(struct ieee80211_local *local)
{
struct ieee80211_sub_if_data *sdata, *tmp;
LIST_HEAD(unreg_list);
LIST_HEAD(wdev_list);
ASSERT_RTNL();
/*
* Close all AP_VLAN interfaces first, as otherwise they
* might be closed while the AP interface they belong to
* is closed, causing unregister_netdevice_many() to crash.
*/
list_for_each_entry(sdata, &local->interfaces, list)
if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
dev_close(sdata->dev);
mutex_lock(&local->iflist_mtx);
list_for_each_entry_safe(sdata, tmp, &local->interfaces, list) {
list_del(&sdata->list);
if (sdata->dev)
unregister_netdevice_queue(sdata->dev, &unreg_list);
else
list_add(&sdata->list, &wdev_list);
}
mutex_unlock(&local->iflist_mtx);
unregister_netdevice_many(&unreg_list);
list_for_each_entry_safe(sdata, tmp, &wdev_list, list) {
list_del(&sdata->list);
cfg80211_unregister_wdev(&sdata->wdev);
kfree(sdata);
}
}
static int netdev_notify(struct notifier_block *nb,
unsigned long state, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct ieee80211_sub_if_data *sdata;
if (state != NETDEV_CHANGENAME)
return NOTIFY_DONE;
if (!dev->ieee80211_ptr || !dev->ieee80211_ptr->wiphy)
return NOTIFY_DONE;
if (dev->ieee80211_ptr->wiphy->privid != mac80211_wiphy_privid)
return NOTIFY_DONE;
sdata = IEEE80211_DEV_TO_SUB_IF(dev);
memcpy(sdata->name, dev->name, IFNAMSIZ);
ieee80211_debugfs_rename_netdev(sdata);
return NOTIFY_OK;
}
static struct notifier_block mac80211_netdev_notifier = {
.notifier_call = netdev_notify,
};
int ieee80211_iface_init(void)
{
return register_netdevice_notifier(&mac80211_netdev_notifier);
}
void ieee80211_iface_exit(void)
{
unregister_netdevice_notifier(&mac80211_netdev_notifier);
}
| gpl-2.0 |
TeamTwisted/hells-Core-N6 | drivers/net/wireless/bcmdhd/dhd_cfg80211.c | 223 | 8269 | /*
* Linux cfg80211 driver - Dongle Host Driver (DHD) related
*
* Copyright (C) 1999-2014, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: wl_cfg80211.c,v 1.1.4.1.2.14 2011/02/09 01:40:07 Exp $
*/
#include <linux/vmalloc.h>
#include <net/rtnetlink.h>
#include <bcmutils.h>
#include <wldev_common.h>
#include <wl_cfg80211.h>
#include <dhd_cfg80211.h>
#ifdef PKT_FILTER_SUPPORT
#include <dngl_stats.h>
#include <dhd.h>
#endif
extern struct bcm_cfg80211 *g_bcm_cfg;
#ifdef PKT_FILTER_SUPPORT
extern uint dhd_pkt_filter_enable;
extern uint dhd_master_mode;
extern void dhd_pktfilter_offload_enable(dhd_pub_t * dhd, char *arg, int enable, int master_mode);
#endif
static int dhd_dongle_up = FALSE;
#include <dngl_stats.h>
#include <dhd.h>
#include <dhdioctl.h>
#include <wlioctl.h>
#include <brcm_nl80211.h>
#include <dhd_cfg80211.h>
#ifdef PCIE_FULL_DONGLE
#include <dhd_flowring.h>
#endif
static s32 wl_dongle_up(struct net_device *ndev);
static s32 wl_dongle_down(struct net_device *ndev);
/**
* Function implementations
*/
s32 dhd_cfg80211_init(struct bcm_cfg80211 *cfg)
{
dhd_dongle_up = FALSE;
return 0;
}
s32 dhd_cfg80211_deinit(struct bcm_cfg80211 *cfg)
{
dhd_dongle_up = FALSE;
return 0;
}
s32 dhd_cfg80211_down(struct bcm_cfg80211 *cfg)
{
struct net_device *ndev;
s32 err = 0;
WL_TRACE(("In\n"));
if (!dhd_dongle_up) {
WL_ERR(("Dongle is already down\n"));
return err;
}
ndev = bcmcfg_to_prmry_ndev(cfg);
wl_dongle_down(ndev);
dhd_dongle_up = FALSE;
return 0;
}
s32 dhd_cfg80211_set_p2p_info(struct bcm_cfg80211 *cfg, int val)
{
dhd_pub_t *dhd = (dhd_pub_t *)(cfg->pub);
dhd->op_mode |= val;
WL_ERR(("Set : op_mode=0x%04x\n", dhd->op_mode));
#ifdef ARP_OFFLOAD_SUPPORT
if (dhd->arp_version == 1) {
/* IF P2P is enabled, disable arpoe */
dhd_arp_offload_set(dhd, 0);
dhd_arp_offload_enable(dhd, false);
}
#endif /* ARP_OFFLOAD_SUPPORT */
return 0;
}
s32 dhd_cfg80211_clean_p2p_info(struct bcm_cfg80211 *cfg)
{
dhd_pub_t *dhd = (dhd_pub_t *)(cfg->pub);
dhd->op_mode &= ~(DHD_FLAG_P2P_GC_MODE | DHD_FLAG_P2P_GO_MODE);
WL_ERR(("Clean : op_mode=0x%04x\n", dhd->op_mode));
#ifdef ARP_OFFLOAD_SUPPORT
if (dhd->arp_version == 1) {
/* IF P2P is disabled, enable arpoe back for STA mode. */
dhd_arp_offload_set(dhd, dhd_arp_mode);
dhd_arp_offload_enable(dhd, true);
}
#endif /* ARP_OFFLOAD_SUPPORT */
return 0;
}
struct net_device* wl_cfg80211_allocate_if(struct bcm_cfg80211 *cfg, int ifidx, char *name,
uint8 *mac, uint8 bssidx)
{
return dhd_allocate_if(cfg->pub, ifidx, name, mac, bssidx, FALSE);
}
int wl_cfg80211_register_if(struct bcm_cfg80211 *cfg, int ifidx, struct net_device* ndev)
{
return dhd_register_if(cfg->pub, ifidx, FALSE);
}
int wl_cfg80211_remove_if(struct bcm_cfg80211 *cfg, int ifidx, struct net_device* ndev)
{
return dhd_remove_if(cfg->pub, ifidx, FALSE);
}
struct net_device * dhd_cfg80211_netdev_free(struct net_device *ndev)
{
if (ndev) {
if (ndev->ieee80211_ptr) {
kfree(ndev->ieee80211_ptr);
ndev->ieee80211_ptr = NULL;
}
free_netdev(ndev);
return NULL;
}
return ndev;
}
void dhd_netdev_free(struct net_device *ndev)
{
#ifdef WL_CFG80211
ndev = dhd_cfg80211_netdev_free(ndev);
#endif
if (ndev)
free_netdev(ndev);
}
static s32
wl_dongle_up(struct net_device *ndev)
{
s32 err = 0;
u32 up = 0;
err = wldev_ioctl(ndev, WLC_UP, &up, sizeof(up), true);
if (unlikely(err)) {
WL_ERR(("WLC_UP error (%d)\n", err));
}
return err;
}
static s32
wl_dongle_down(struct net_device *ndev)
{
s32 err = 0;
u32 down = 0;
err = wldev_ioctl(ndev, WLC_DOWN, &down, sizeof(down), true);
if (unlikely(err)) {
WL_ERR(("WLC_DOWN error (%d)\n", err));
}
return err;
}
s32 dhd_config_dongle(struct bcm_cfg80211 *cfg)
{
#ifndef DHD_SDALIGN
#define DHD_SDALIGN 32
#endif
struct net_device *ndev;
s32 err = 0;
WL_TRACE(("In\n"));
if (dhd_dongle_up) {
WL_ERR(("Dongle is already up\n"));
return err;
}
ndev = bcmcfg_to_prmry_ndev(cfg);
err = wl_dongle_up(ndev);
if (unlikely(err)) {
WL_ERR(("wl_dongle_up failed\n"));
goto default_conf_out;
}
dhd_dongle_up = true;
default_conf_out:
return err;
}
#ifdef PCIE_FULL_DONGLE
void wl_roam_flowring_cleanup(struct bcm_cfg80211 *cfg)
{
int hostidx = 0;
dhd_pub_t *dhd_pub = (dhd_pub_t *)(cfg->pub);
hostidx = dhd_ifidx2hostidx(dhd_pub->info, hostidx);
dhd_flow_rings_delete(dhd_pub, hostidx);
}
#endif
#ifdef CONFIG_NL80211_TESTMODE
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0))
int dhd_cfg80211_testmode_cmd(struct wiphy *wiphy, struct wireless_dev *wdev, void *data, int len)
#else
int dhd_cfg80211_testmode_cmd(struct wiphy *wiphy, void *data, int len)
#endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0) */
{
struct sk_buff *reply;
struct bcm_cfg80211 *cfg;
dhd_pub_t *dhd;
struct bcm_nlmsg_hdr *nlioc = data;
dhd_ioctl_t ioc = { 0 };
int err = 0;
void *buf = NULL, *cur;
u16 buflen;
u16 maxmsglen = PAGE_SIZE - 0x100;
bool newbuf = false;
int8 index = 0;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0))
struct net_device *ndev = NULL;
#endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0) */
WL_TRACE(("entry: cmd = %d\n", nlioc->cmd));
cfg = wiphy_priv(wiphy);
dhd = cfg->pub;
DHD_OS_WAKE_LOCK(dhd);
/* send to dongle only if we are not waiting for reload already */
if (dhd->hang_was_sent) {
WL_ERR(("HANG was sent up earlier\n"));
DHD_OS_WAKE_LOCK_CTRL_TIMEOUT_ENABLE(dhd, DHD_EVENT_TIMEOUT_MS);
DHD_OS_WAKE_UNLOCK(dhd);
return OSL_ERROR(BCME_DONGLE_DOWN);
}
len -= sizeof(struct bcm_nlmsg_hdr);
if (nlioc->len > 0) {
if (nlioc->len <= len) {
buf = (void *)nlioc + nlioc->offset;
*(char *)(buf + nlioc->len) = '\0';
} else {
if (nlioc->len > DHD_IOCTL_MAXLEN)
nlioc->len = DHD_IOCTL_MAXLEN;
buf = vzalloc(nlioc->len);
if (!buf)
return -ENOMEM;
newbuf = true;
memcpy(buf, (void *)nlioc + nlioc->offset, len);
*(char *)(buf + len) = '\0';
}
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0))
ndev = wdev_to_wlc_ndev(wdev, cfg);
index = dhd_net2idx(dhd->info, ndev);
if (index == DHD_BAD_IF) {
WL_ERR(("Bad ifidx from wdev:%p\n", wdev));
return BCME_ERROR;
}
#endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(3, 11, 0) */
ioc.cmd = nlioc->cmd;
ioc.len = nlioc->len;
ioc.set = nlioc->set;
ioc.driver = nlioc->magic;
err = dhd_ioctl_process(dhd, index, &ioc, buf);
if (err) {
WL_TRACE(("dhd_ioctl_process return err %d\n", err));
err = OSL_ERROR(err);
goto done;
}
cur = buf;
while (nlioc->len > 0) {
buflen = nlioc->len > maxmsglen ? maxmsglen : nlioc->len;
nlioc->len -= buflen;
reply = cfg80211_testmode_alloc_reply_skb(wiphy, buflen+4);
if (!reply) {
WL_ERR(("Failed to allocate reply msg\n"));
err = -ENOMEM;
break;
}
if (nla_put(reply, BCM_NLATTR_DATA, buflen, cur) ||
nla_put_u16(reply, BCM_NLATTR_LEN, buflen)) {
kfree_skb(reply);
err = -ENOBUFS;
break;
}
do {
err = cfg80211_testmode_reply(reply);
} while (err == -EAGAIN);
if (err) {
WL_ERR(("testmode reply failed:%d\n", err));
break;
}
cur += buflen;
}
done:
if (newbuf)
vfree(buf);
DHD_OS_WAKE_UNLOCK(dhd);
return err;
}
#endif /* CONFIG_NL80211_TESTMODE */
| gpl-2.0 |
openwrt-es/linux | drivers/thermal/spear_thermal.c | 479 | 4905 | // SPDX-License-Identifier: GPL-2.0-only
/*
* SPEAr thermal driver.
*
* Copyright (C) 2011-2012 ST Microelectronics
* Author: Vincenzo Frascino <vincenzo.frascino@st.com>
*/
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/of.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/thermal.h>
#define MD_FACTOR 1000
/* SPEAr Thermal Sensor Dev Structure */
struct spear_thermal_dev {
/* pointer to base address of the thermal sensor */
void __iomem *thermal_base;
/* clk structure */
struct clk *clk;
/* pointer to thermal flags */
unsigned int flags;
};
static inline int thermal_get_temp(struct thermal_zone_device *thermal,
int *temp)
{
struct spear_thermal_dev *stdev = thermal->devdata;
/*
* Data are ready to be read after 628 usec from POWERDOWN signal
* (PDN) = 1
*/
*temp = (readl_relaxed(stdev->thermal_base) & 0x7F) * MD_FACTOR;
return 0;
}
static struct thermal_zone_device_ops ops = {
.get_temp = thermal_get_temp,
};
static int __maybe_unused spear_thermal_suspend(struct device *dev)
{
struct thermal_zone_device *spear_thermal = dev_get_drvdata(dev);
struct spear_thermal_dev *stdev = spear_thermal->devdata;
unsigned int actual_mask = 0;
/* Disable SPEAr Thermal Sensor */
actual_mask = readl_relaxed(stdev->thermal_base);
writel_relaxed(actual_mask & ~stdev->flags, stdev->thermal_base);
clk_disable(stdev->clk);
dev_info(dev, "Suspended.\n");
return 0;
}
static int __maybe_unused spear_thermal_resume(struct device *dev)
{
struct thermal_zone_device *spear_thermal = dev_get_drvdata(dev);
struct spear_thermal_dev *stdev = spear_thermal->devdata;
unsigned int actual_mask = 0;
int ret = 0;
ret = clk_enable(stdev->clk);
if (ret) {
dev_err(dev, "Can't enable clock\n");
return ret;
}
/* Enable SPEAr Thermal Sensor */
actual_mask = readl_relaxed(stdev->thermal_base);
writel_relaxed(actual_mask | stdev->flags, stdev->thermal_base);
dev_info(dev, "Resumed.\n");
return 0;
}
static SIMPLE_DEV_PM_OPS(spear_thermal_pm_ops, spear_thermal_suspend,
spear_thermal_resume);
static int spear_thermal_probe(struct platform_device *pdev)
{
struct thermal_zone_device *spear_thermal = NULL;
struct spear_thermal_dev *stdev;
struct device_node *np = pdev->dev.of_node;
struct resource *res;
int ret = 0, val;
if (!np || !of_property_read_u32(np, "st,thermal-flags", &val)) {
dev_err(&pdev->dev, "Failed: DT Pdata not passed\n");
return -EINVAL;
}
stdev = devm_kzalloc(&pdev->dev, sizeof(*stdev), GFP_KERNEL);
if (!stdev)
return -ENOMEM;
/* Enable thermal sensor */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
stdev->thermal_base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(stdev->thermal_base))
return PTR_ERR(stdev->thermal_base);
stdev->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(stdev->clk)) {
dev_err(&pdev->dev, "Can't get clock\n");
return PTR_ERR(stdev->clk);
}
ret = clk_enable(stdev->clk);
if (ret) {
dev_err(&pdev->dev, "Can't enable clock\n");
return ret;
}
stdev->flags = val;
writel_relaxed(stdev->flags, stdev->thermal_base);
spear_thermal = thermal_zone_device_register("spear_thermal", 0, 0,
stdev, &ops, NULL, 0, 0);
if (IS_ERR(spear_thermal)) {
dev_err(&pdev->dev, "thermal zone device is NULL\n");
ret = PTR_ERR(spear_thermal);
goto disable_clk;
}
ret = thermal_zone_device_enable(spear_thermal);
if (ret) {
dev_err(&pdev->dev, "Cannot enable thermal zone\n");
goto unregister_tzd;
}
platform_set_drvdata(pdev, spear_thermal);
dev_info(&spear_thermal->device, "Thermal Sensor Loaded at: 0x%p.\n",
stdev->thermal_base);
return 0;
unregister_tzd:
thermal_zone_device_unregister(spear_thermal);
disable_clk:
clk_disable(stdev->clk);
return ret;
}
static int spear_thermal_exit(struct platform_device *pdev)
{
unsigned int actual_mask = 0;
struct thermal_zone_device *spear_thermal = platform_get_drvdata(pdev);
struct spear_thermal_dev *stdev = spear_thermal->devdata;
thermal_zone_device_unregister(spear_thermal);
/* Disable SPEAr Thermal Sensor */
actual_mask = readl_relaxed(stdev->thermal_base);
writel_relaxed(actual_mask & ~stdev->flags, stdev->thermal_base);
clk_disable(stdev->clk);
return 0;
}
static const struct of_device_id spear_thermal_id_table[] = {
{ .compatible = "st,thermal-spear1340" },
{}
};
MODULE_DEVICE_TABLE(of, spear_thermal_id_table);
static struct platform_driver spear_thermal_driver = {
.probe = spear_thermal_probe,
.remove = spear_thermal_exit,
.driver = {
.name = "spear_thermal",
.pm = &spear_thermal_pm_ops,
.of_match_table = spear_thermal_id_table,
},
};
module_platform_driver(spear_thermal_driver);
MODULE_AUTHOR("Vincenzo Frascino <vincenzo.frascino@st.com>");
MODULE_DESCRIPTION("SPEAr thermal driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ruffy91/u0lte_kernel | net/ipv4/tcp_ipv4.c | 479 | 68228 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Implementation of the Transmission Control Protocol(TCP).
*
* IPv4 specific functions
*
*
* code split from:
* linux/ipv4/tcp.c
* linux/ipv4/tcp_input.c
* linux/ipv4/tcp_output.c
*
* See tcp.c for author information
*
* 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.
*/
/*
* Changes:
* David S. Miller : New socket lookup architecture.
* This code is dedicated to John Dyson.
* David S. Miller : Change semantics of established hash,
* half is devoted to TIME_WAIT sockets
* and the rest go in the other half.
* Andi Kleen : Add support for syncookies and fixed
* some bugs: ip options weren't passed to
* the TCP layer, missed a check for an
* ACK bit.
* Andi Kleen : Implemented fast path mtu discovery.
* Fixed many serious bugs in the
* request_sock handling and moved
* most of it into the af independent code.
* Added tail drop and some other bugfixes.
* Added new listen semantics.
* Mike McLagan : Routing by source
* Juan Jose Ciarlante: ip_dynaddr bits
* Andi Kleen: various fixes.
* Vitaly E. Lavrov : Transparent proxy revived after year
* coma.
* Andi Kleen : Fix new listen.
* Andi Kleen : Fix accept error reporting.
* YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which
* Alexey Kuznetsov allow both IPv4 and IPv6 sockets to bind
* a single port at the same time.
*/
#include <linux/bottom_half.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/module.h>
#include <linux/random.h>
#include <linux/cache.h>
#include <linux/jhash.h>
#include <linux/init.h>
#include <linux/times.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/icmp.h>
#include <net/inet_hashtables.h>
#include <net/tcp.h>
#include <net/transp_v6.h>
#include <net/ipv6.h>
#include <net/inet_common.h>
#include <net/timewait_sock.h>
#include <net/xfrm.h>
#include <net/netdma.h>
#include <net/secure_seq.h>
#include <linux/inet.h>
#include <linux/ipv6.h>
#include <linux/stddef.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/crypto.h>
#include <linux/scatterlist.h>
int sysctl_tcp_tw_reuse __read_mostly;
int sysctl_tcp_low_latency __read_mostly;
EXPORT_SYMBOL(sysctl_tcp_low_latency);
#ifdef CONFIG_TCP_MD5SIG
static struct tcp_md5sig_key *tcp_v4_md5_do_lookup(struct sock *sk,
__be32 addr);
static int tcp_v4_md5_hash_hdr(char *md5_hash, struct tcp_md5sig_key *key,
__be32 daddr, __be32 saddr, struct tcphdr *th);
#else
static inline
struct tcp_md5sig_key *tcp_v4_md5_do_lookup(struct sock *sk, __be32 addr)
{
return NULL;
}
#endif
struct inet_hashinfo tcp_hashinfo;
EXPORT_SYMBOL(tcp_hashinfo);
static inline __u32 tcp_v4_init_sequence(struct sk_buff *skb)
{
return secure_tcp_sequence_number(ip_hdr(skb)->daddr,
ip_hdr(skb)->saddr,
tcp_hdr(skb)->dest,
tcp_hdr(skb)->source);
}
int tcp_twsk_unique(struct sock *sk, struct sock *sktw, void *twp)
{
const struct tcp_timewait_sock *tcptw = tcp_twsk(sktw);
struct tcp_sock *tp = tcp_sk(sk);
/* With PAWS, it is safe from the viewpoint
of data integrity. Even without PAWS it is safe provided sequence
spaces do not overlap i.e. at data rates <= 80Mbit/sec.
Actually, the idea is close to VJ's one, only timestamp cache is
held not per host, but per port pair and TW bucket is used as state
holder.
If TW bucket has been already destroyed we fall back to VJ's scheme
and use initial timestamp retrieved from peer table.
*/
if (tcptw->tw_ts_recent_stamp &&
(twp == NULL || (sysctl_tcp_tw_reuse &&
get_seconds() - tcptw->tw_ts_recent_stamp > 1))) {
tp->write_seq = tcptw->tw_snd_nxt + 65535 + 2;
if (tp->write_seq == 0)
tp->write_seq = 1;
tp->rx_opt.ts_recent = tcptw->tw_ts_recent;
tp->rx_opt.ts_recent_stamp = tcptw->tw_ts_recent_stamp;
sock_hold(sktw);
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(tcp_twsk_unique);
/* This will initiate an outgoing connection. */
int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
struct inet_sock *inet = inet_sk(sk);
struct tcp_sock *tp = tcp_sk(sk);
__be16 orig_sport, orig_dport;
__be32 daddr, nexthop;
struct flowi4 *fl4;
struct rtable *rt;
int err;
struct ip_options_rcu *inet_opt;
if (addr_len < sizeof(struct sockaddr_in))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
nexthop = daddr = usin->sin_addr.s_addr;
inet_opt = rcu_dereference_protected(inet->inet_opt,
sock_owned_by_user(sk));
if (inet_opt && inet_opt->opt.srr) {
if (!daddr)
return -EINVAL;
nexthop = inet_opt->opt.faddr;
}
orig_sport = inet->inet_sport;
orig_dport = usin->sin_port;
fl4 = &inet->cork.fl.u.ip4;
rt = ip_route_connect(fl4, nexthop, inet->inet_saddr,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
IPPROTO_TCP,
orig_sport, orig_dport, sk, true);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
if (err == -ENETUNREACH)
IP_INC_STATS_BH(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
return err;
}
if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
ip_rt_put(rt);
return -ENETUNREACH;
}
if (!inet_opt || !inet_opt->opt.srr)
daddr = fl4->daddr;
if (!inet->inet_saddr)
inet->inet_saddr = fl4->saddr;
inet->inet_rcv_saddr = inet->inet_saddr;
if (tp->rx_opt.ts_recent_stamp && inet->inet_daddr != daddr) {
/* Reset inherited state */
tp->rx_opt.ts_recent = 0;
tp->rx_opt.ts_recent_stamp = 0;
tp->write_seq = 0;
}
if (tcp_death_row.sysctl_tw_recycle &&
!tp->rx_opt.ts_recent_stamp && fl4->daddr == daddr) {
struct inet_peer *peer = rt_get_peer(rt, fl4->daddr);
/*
* VJ's idea. We save last timestamp seen from
* the destination in peer table, when entering state
* TIME-WAIT * and initialize rx_opt.ts_recent from it,
* when trying new connection.
*/
if (peer) {
inet_peer_refcheck(peer);
if ((u32)get_seconds() - peer->tcp_ts_stamp <= TCP_PAWS_MSL) {
tp->rx_opt.ts_recent_stamp = peer->tcp_ts_stamp;
tp->rx_opt.ts_recent = peer->tcp_ts;
}
}
}
inet->inet_dport = usin->sin_port;
inet->inet_daddr = daddr;
inet_csk(sk)->icsk_ext_hdr_len = 0;
if (inet_opt)
inet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
tp->rx_opt.mss_clamp = TCP_MSS_DEFAULT;
/* Socket identity is still unknown (sport may be zero).
* However we set state to SYN-SENT and not releasing socket
* lock select source port, enter ourselves into the hash tables and
* complete initialization after this.
*/
tcp_set_state(sk, TCP_SYN_SENT);
err = inet_hash_connect(&tcp_death_row, sk);
if (err)
goto failure;
rt = ip_route_newports(fl4, rt, orig_sport, orig_dport,
inet->inet_sport, inet->inet_dport, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
goto failure;
}
/* OK, now commit destination to socket. */
sk->sk_gso_type = SKB_GSO_TCPV4;
sk_setup_caps(sk, &rt->dst);
if (!tp->write_seq)
tp->write_seq = secure_tcp_sequence_number(inet->inet_saddr,
inet->inet_daddr,
inet->inet_sport,
usin->sin_port);
inet->inet_id = tp->write_seq ^ jiffies;
err = tcp_connect(sk);
rt = NULL;
if (err)
goto failure;
return 0;
failure:
/*
* This unhashes the socket and releases the local port,
* if necessary.
*/
tcp_set_state(sk, TCP_CLOSE);
ip_rt_put(rt);
sk->sk_route_caps = 0;
inet->inet_dport = 0;
return err;
}
EXPORT_SYMBOL(tcp_v4_connect);
/*
* This routine does path mtu discovery as defined in RFC1191.
*/
static void do_pmtu_discovery(struct sock *sk, const struct iphdr *iph, u32 mtu)
{
struct dst_entry *dst;
struct inet_sock *inet = inet_sk(sk);
/* We are not interested in TCP_LISTEN and open_requests (SYN-ACKs
* send out by Linux are always <576bytes so they should go through
* unfragmented).
*/
if (sk->sk_state == TCP_LISTEN)
return;
/* We don't check in the destentry if pmtu discovery is forbidden
* on this route. We just assume that no packet_to_big packets
* are send back when pmtu discovery is not active.
* There is a small race when the user changes this flag in the
* route, but I think that's acceptable.
*/
if ((dst = __sk_dst_check(sk, 0)) == NULL)
return;
dst->ops->update_pmtu(dst, mtu);
/* Something is about to be wrong... Remember soft error
* for the case, if this connection will not able to recover.
*/
if (mtu < dst_mtu(dst) && ip_dont_fragment(sk, dst))
sk->sk_err_soft = EMSGSIZE;
mtu = dst_mtu(dst);
if (inet->pmtudisc != IP_PMTUDISC_DONT &&
inet_csk(sk)->icsk_pmtu_cookie > mtu) {
tcp_sync_mss(sk, mtu);
/* Resend the TCP packet because it's
* clear that the old packet has been
* dropped. This is the new "fast" path mtu
* discovery.
*/
tcp_simple_retransmit(sk);
} /* else let the usual retransmit timer handle it */
}
/*
* This routine is called by the ICMP module when it gets some
* sort of error condition. If err < 0 then the socket should
* be closed and the error returned to the user. If err > 0
* it's just the icmp type << 8 | icmp code. After adjustment
* header points to the first 8 bytes of the tcp header. We need
* to find the appropriate port.
*
* The locking strategy used here is very "optimistic". When
* someone else accesses the socket the ICMP is just dropped
* and for some paths there is no check at all.
* A more general error queue to queue errors for later handling
* is probably better.
*
*/
void tcp_v4_err(struct sk_buff *icmp_skb, u32 info)
{
const struct iphdr *iph = (const struct iphdr *)icmp_skb->data;
struct tcphdr *th = (struct tcphdr *)(icmp_skb->data + (iph->ihl << 2));
struct inet_connection_sock *icsk;
struct tcp_sock *tp;
struct inet_sock *inet;
const int type = icmp_hdr(icmp_skb)->type;
const int code = icmp_hdr(icmp_skb)->code;
struct sock *sk;
struct sk_buff *skb;
__u32 seq;
__u32 remaining;
int err;
struct net *net = dev_net(icmp_skb->dev);
if (icmp_skb->len < (iph->ihl << 2) + 8) {
ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS);
return;
}
sk = inet_lookup(net, &tcp_hashinfo, iph->daddr, th->dest,
iph->saddr, th->source, inet_iif(icmp_skb));
if (!sk) {
ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS);
return;
}
if (sk->sk_state == TCP_TIME_WAIT) {
inet_twsk_put(inet_twsk(sk));
return;
}
bh_lock_sock(sk);
/* If too many ICMPs get dropped on busy
* servers this needs to be solved differently.
*/
if (sock_owned_by_user(sk))
NET_INC_STATS_BH(net, LINUX_MIB_LOCKDROPPEDICMPS);
if (sk->sk_state == TCP_CLOSE)
goto out;
if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) {
NET_INC_STATS_BH(net, LINUX_MIB_TCPMINTTLDROP);
goto out;
}
icsk = inet_csk(sk);
tp = tcp_sk(sk);
seq = ntohl(th->seq);
if (sk->sk_state != TCP_LISTEN &&
!between(seq, tp->snd_una, tp->snd_nxt)) {
NET_INC_STATS_BH(net, LINUX_MIB_OUTOFWINDOWICMPS);
goto out;
}
switch (type) {
case ICMP_SOURCE_QUENCH:
/* Just silently ignore these. */
goto out;
case ICMP_PARAMETERPROB:
err = EPROTO;
break;
case ICMP_DEST_UNREACH:
if (code > NR_ICMP_UNREACH)
goto out;
if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */
if (!sock_owned_by_user(sk))
do_pmtu_discovery(sk, iph, info);
goto out;
}
err = icmp_err_convert[code].errno;
/* check if icmp_skb allows revert of backoff
* (see draft-zimmermann-tcp-lcd) */
if (code != ICMP_NET_UNREACH && code != ICMP_HOST_UNREACH)
break;
if (seq != tp->snd_una || !icsk->icsk_retransmits ||
!icsk->icsk_backoff)
break;
if (sock_owned_by_user(sk))
break;
icsk->icsk_backoff--;
inet_csk(sk)->icsk_rto = __tcp_set_rto(tp) <<
icsk->icsk_backoff;
tcp_bound_rto(sk);
skb = tcp_write_queue_head(sk);
BUG_ON(!skb);
remaining = icsk->icsk_rto - min(icsk->icsk_rto,
tcp_time_stamp - TCP_SKB_CB(skb)->when);
if (remaining) {
inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
remaining, TCP_RTO_MAX);
} else {
/* RTO revert clocked out retransmission.
* Will retransmit now */
tcp_retransmit_timer(sk);
}
break;
case ICMP_TIME_EXCEEDED:
err = EHOSTUNREACH;
break;
default:
goto out;
}
switch (sk->sk_state) {
struct request_sock *req, **prev;
case TCP_LISTEN:
if (sock_owned_by_user(sk))
goto out;
req = inet_csk_search_req(sk, &prev, th->dest,
iph->daddr, iph->saddr);
if (!req)
goto out;
/* ICMPs are not backlogged, hence we cannot get
an established socket here.
*/
WARN_ON(req->sk);
if (seq != tcp_rsk(req)->snt_isn) {
NET_INC_STATS_BH(net, LINUX_MIB_OUTOFWINDOWICMPS);
goto out;
}
/*
* Still in SYN_RECV, just remove it silently.
* There is no good way to pass the error to the newly
* created socket, and POSIX does not want network
* errors returned from accept().
*/
inet_csk_reqsk_queue_drop(sk, req, prev);
goto out;
case TCP_SYN_SENT:
case TCP_SYN_RECV: /* Cannot happen.
It can f.e. if SYNs crossed.
*/
if (!sock_owned_by_user(sk)) {
sk->sk_err = err;
sk->sk_error_report(sk);
tcp_done(sk);
} else {
sk->sk_err_soft = err;
}
goto out;
}
/* If we've already connected we will keep trying
* until we time out, or the user gives up.
*
* rfc1122 4.2.3.9 allows to consider as hard errors
* only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too,
* but it is obsoleted by pmtu discovery).
*
* Note, that in modern internet, where routing is unreliable
* and in each dark corner broken firewalls sit, sending random
* errors ordered by their masters even this two messages finally lose
* their original sense (even Linux sends invalid PORT_UNREACHs)
*
* Now we are in compliance with RFCs.
* --ANK (980905)
*/
inet = inet_sk(sk);
if (!sock_owned_by_user(sk) && inet->recverr) {
sk->sk_err = err;
sk->sk_error_report(sk);
} else { /* Only an error on timeout */
sk->sk_err_soft = err;
}
out:
bh_unlock_sock(sk);
sock_put(sk);
}
static void __tcp_v4_send_check(struct sk_buff *skb,
__be32 saddr, __be32 daddr)
{
struct tcphdr *th = tcp_hdr(skb);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
th->check = ~tcp_v4_check(skb->len, saddr, daddr, 0);
skb->csum_start = skb_transport_header(skb) - skb->head;
skb->csum_offset = offsetof(struct tcphdr, check);
} else {
th->check = tcp_v4_check(skb->len, saddr, daddr,
csum_partial(th,
th->doff << 2,
skb->csum));
}
}
/* This routine computes an IPv4 TCP checksum. */
void tcp_v4_send_check(struct sock *sk, struct sk_buff *skb)
{
struct inet_sock *inet = inet_sk(sk);
__tcp_v4_send_check(skb, inet->inet_saddr, inet->inet_daddr);
}
EXPORT_SYMBOL(tcp_v4_send_check);
int tcp_v4_gso_send_check(struct sk_buff *skb)
{
const struct iphdr *iph;
struct tcphdr *th;
if (!pskb_may_pull(skb, sizeof(*th)))
return -EINVAL;
iph = ip_hdr(skb);
th = tcp_hdr(skb);
th->check = 0;
skb->ip_summed = CHECKSUM_PARTIAL;
__tcp_v4_send_check(skb, iph->saddr, iph->daddr);
return 0;
}
/*
* This routine will send an RST to the other tcp.
*
* Someone asks: why I NEVER use socket parameters (TOS, TTL etc.)
* for reset.
* Answer: if a packet caused RST, it is not for a socket
* existing in our system, if it is matched to a socket,
* it is just duplicate segment or bug in other side's TCP.
* So that we build reply only basing on parameters
* arrived with segment.
* Exception: precedence violation. We do not implement it in any case.
*/
static void tcp_v4_send_reset(struct sock *sk, struct sk_buff *skb)
{
struct tcphdr *th = tcp_hdr(skb);
struct {
struct tcphdr th;
#ifdef CONFIG_TCP_MD5SIG
__be32 opt[(TCPOLEN_MD5SIG_ALIGNED >> 2)];
#endif
} rep;
struct ip_reply_arg arg;
#ifdef CONFIG_TCP_MD5SIG
struct tcp_md5sig_key *key;
#endif
struct net *net;
/* Never send a reset in response to a reset. */
if (th->rst)
return;
if (skb_rtable(skb)->rt_type != RTN_LOCAL)
return;
/* Swap the send and the receive. */
memset(&rep, 0, sizeof(rep));
rep.th.dest = th->source;
rep.th.source = th->dest;
rep.th.doff = sizeof(struct tcphdr) / 4;
rep.th.rst = 1;
if (th->ack) {
rep.th.seq = th->ack_seq;
} else {
rep.th.ack = 1;
rep.th.ack_seq = htonl(ntohl(th->seq) + th->syn + th->fin +
skb->len - (th->doff << 2));
}
memset(&arg, 0, sizeof(arg));
arg.iov[0].iov_base = (unsigned char *)&rep;
arg.iov[0].iov_len = sizeof(rep.th);
#ifdef CONFIG_TCP_MD5SIG
key = sk ? tcp_v4_md5_do_lookup(sk, ip_hdr(skb)->saddr) : NULL;
if (key) {
rep.opt[0] = htonl((TCPOPT_NOP << 24) |
(TCPOPT_NOP << 16) |
(TCPOPT_MD5SIG << 8) |
TCPOLEN_MD5SIG);
/* Update length and the length the header thinks exists */
arg.iov[0].iov_len += TCPOLEN_MD5SIG_ALIGNED;
rep.th.doff = arg.iov[0].iov_len / 4;
tcp_v4_md5_hash_hdr((__u8 *) &rep.opt[1],
key, ip_hdr(skb)->saddr,
ip_hdr(skb)->daddr, &rep.th);
}
#endif
arg.csum = csum_tcpudp_nofold(ip_hdr(skb)->daddr,
ip_hdr(skb)->saddr, /* XXX */
arg.iov[0].iov_len, IPPROTO_TCP, 0);
arg.csumoffset = offsetof(struct tcphdr, check) / 2;
arg.flags = (sk && inet_sk(sk)->transparent) ? IP_REPLY_ARG_NOSRCCHECK : 0;
/* When socket is gone, all binding information is lost.
* routing might fail in this case. No choice here, if we choose to force
* input interface, we will misroute in case of asymmetric route.
*/
if (sk)
arg.bound_dev_if = sk->sk_bound_dev_if;
net = dev_net(skb_dst(skb)->dev);
ip_send_reply(net->ipv4.tcp_sock, skb, ip_hdr(skb)->saddr,
&arg, arg.iov[0].iov_len);
TCP_INC_STATS_BH(net, TCP_MIB_OUTSEGS);
TCP_INC_STATS_BH(net, TCP_MIB_OUTRSTS);
}
/* The code following below sending ACKs in SYN-RECV and TIME-WAIT states
outside socket context is ugly, certainly. What can I do?
*/
static void tcp_v4_send_ack(struct sk_buff *skb, u32 seq, u32 ack,
u32 win, u32 ts, int oif,
struct tcp_md5sig_key *key,
int reply_flags)
{
struct tcphdr *th = tcp_hdr(skb);
struct {
struct tcphdr th;
__be32 opt[(TCPOLEN_TSTAMP_ALIGNED >> 2)
#ifdef CONFIG_TCP_MD5SIG
+ (TCPOLEN_MD5SIG_ALIGNED >> 2)
#endif
];
} rep;
struct ip_reply_arg arg;
struct net *net = dev_net(skb_dst(skb)->dev);
memset(&rep.th, 0, sizeof(struct tcphdr));
memset(&arg, 0, sizeof(arg));
arg.iov[0].iov_base = (unsigned char *)&rep;
arg.iov[0].iov_len = sizeof(rep.th);
if (ts) {
rep.opt[0] = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) |
(TCPOPT_TIMESTAMP << 8) |
TCPOLEN_TIMESTAMP);
rep.opt[1] = htonl(tcp_time_stamp);
rep.opt[2] = htonl(ts);
arg.iov[0].iov_len += TCPOLEN_TSTAMP_ALIGNED;
}
/* Swap the send and the receive. */
rep.th.dest = th->source;
rep.th.source = th->dest;
rep.th.doff = arg.iov[0].iov_len / 4;
rep.th.seq = htonl(seq);
rep.th.ack_seq = htonl(ack);
rep.th.ack = 1;
rep.th.window = htons(win);
#ifdef CONFIG_TCP_MD5SIG
if (key) {
int offset = (ts) ? 3 : 0;
rep.opt[offset++] = htonl((TCPOPT_NOP << 24) |
(TCPOPT_NOP << 16) |
(TCPOPT_MD5SIG << 8) |
TCPOLEN_MD5SIG);
arg.iov[0].iov_len += TCPOLEN_MD5SIG_ALIGNED;
rep.th.doff = arg.iov[0].iov_len/4;
tcp_v4_md5_hash_hdr((__u8 *) &rep.opt[offset],
key, ip_hdr(skb)->saddr,
ip_hdr(skb)->daddr, &rep.th);
}
#endif
arg.flags = reply_flags;
arg.csum = csum_tcpudp_nofold(ip_hdr(skb)->daddr,
ip_hdr(skb)->saddr, /* XXX */
arg.iov[0].iov_len, IPPROTO_TCP, 0);
arg.csumoffset = offsetof(struct tcphdr, check) / 2;
if (oif)
arg.bound_dev_if = oif;
ip_send_reply(net->ipv4.tcp_sock, skb, ip_hdr(skb)->saddr,
&arg, arg.iov[0].iov_len);
TCP_INC_STATS_BH(net, TCP_MIB_OUTSEGS);
}
static void tcp_v4_timewait_ack(struct sock *sk, struct sk_buff *skb)
{
struct inet_timewait_sock *tw = inet_twsk(sk);
struct tcp_timewait_sock *tcptw = tcp_twsk(sk);
tcp_v4_send_ack(skb, tcptw->tw_snd_nxt, tcptw->tw_rcv_nxt,
tcptw->tw_rcv_wnd >> tw->tw_rcv_wscale,
tcptw->tw_ts_recent,
tw->tw_bound_dev_if,
tcp_twsk_md5_key(tcptw),
tw->tw_transparent ? IP_REPLY_ARG_NOSRCCHECK : 0
);
inet_twsk_put(tw);
}
static void tcp_v4_reqsk_send_ack(struct sock *sk, struct sk_buff *skb,
struct request_sock *req)
{
tcp_v4_send_ack(skb, tcp_rsk(req)->snt_isn + 1,
tcp_rsk(req)->rcv_isn + 1, req->rcv_wnd,
req->ts_recent,
0,
tcp_v4_md5_do_lookup(sk, ip_hdr(skb)->daddr),
inet_rsk(req)->no_srccheck ? IP_REPLY_ARG_NOSRCCHECK : 0);
}
/*
* Send a SYN-ACK after having received a SYN.
* This still operates on a request_sock only, not on a big
* socket.
*/
static int tcp_v4_send_synack(struct sock *sk, struct dst_entry *dst,
struct request_sock *req,
struct request_values *rvp)
{
const struct inet_request_sock *ireq = inet_rsk(req);
struct flowi4 fl4;
int err = -1;
struct sk_buff * skb;
/* First, grab a route. */
if (!dst && (dst = inet_csk_route_req(sk, &fl4, req)) == NULL)
return -1;
skb = tcp_make_synack(sk, dst, req, rvp);
if (skb) {
__tcp_v4_send_check(skb, ireq->loc_addr, ireq->rmt_addr);
err = ip_build_and_send_pkt(skb, sk, ireq->loc_addr,
ireq->rmt_addr,
ireq->opt);
err = net_xmit_eval(err);
}
dst_release(dst);
return err;
}
static int tcp_v4_rtx_synack(struct sock *sk, struct request_sock *req,
struct request_values *rvp)
{
TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_RETRANSSEGS);
return tcp_v4_send_synack(sk, NULL, req, rvp);
}
/*
* IPv4 request_sock destructor.
*/
static void tcp_v4_reqsk_destructor(struct request_sock *req)
{
kfree(inet_rsk(req)->opt);
}
static void syn_flood_warning(const struct sk_buff *skb)
{
const char *msg;
#ifdef CONFIG_SYN_COOKIES
if (sysctl_tcp_syncookies)
msg = "Sending cookies";
else
#endif
msg = "Dropping request";
pr_info("TCP: Possible SYN flooding on port %d. %s.\n",
ntohs(tcp_hdr(skb)->dest), msg);
}
/*
* Save and compile IPv4 options into the request_sock if needed.
*/
static struct ip_options_rcu *tcp_v4_save_options(struct sock *sk,
struct sk_buff *skb)
{
const struct ip_options *opt = &(IPCB(skb)->opt);
struct ip_options_rcu *dopt = NULL;
if (opt && opt->optlen) {
int opt_size = sizeof(*dopt) + opt->optlen;
dopt = kmalloc(opt_size, GFP_ATOMIC);
if (dopt) {
if (ip_options_echo(&dopt->opt, skb)) {
kfree(dopt);
dopt = NULL;
}
}
}
return dopt;
}
#ifdef CONFIG_TCP_MD5SIG
/*
* RFC2385 MD5 checksumming requires a mapping of
* IP address->MD5 Key.
* We need to maintain these in the sk structure.
*/
/* Find the Key structure for an address. */
static struct tcp_md5sig_key *
tcp_v4_md5_do_lookup(struct sock *sk, __be32 addr)
{
struct tcp_sock *tp = tcp_sk(sk);
int i;
if (!tp->md5sig_info || !tp->md5sig_info->entries4)
return NULL;
for (i = 0; i < tp->md5sig_info->entries4; i++) {
if (tp->md5sig_info->keys4[i].addr == addr)
return &tp->md5sig_info->keys4[i].base;
}
return NULL;
}
struct tcp_md5sig_key *tcp_v4_md5_lookup(struct sock *sk,
struct sock *addr_sk)
{
return tcp_v4_md5_do_lookup(sk, inet_sk(addr_sk)->inet_daddr);
}
EXPORT_SYMBOL(tcp_v4_md5_lookup);
static struct tcp_md5sig_key *tcp_v4_reqsk_md5_lookup(struct sock *sk,
struct request_sock *req)
{
return tcp_v4_md5_do_lookup(sk, inet_rsk(req)->rmt_addr);
}
/* This can be called on a newly created socket, from other files */
int tcp_v4_md5_do_add(struct sock *sk, __be32 addr,
u8 *newkey, u8 newkeylen)
{
/* Add Key to the list */
struct tcp_md5sig_key *key;
struct tcp_sock *tp = tcp_sk(sk);
struct tcp4_md5sig_key *keys;
key = tcp_v4_md5_do_lookup(sk, addr);
if (key) {
/* Pre-existing entry - just update that one. */
kfree(key->key);
key->key = newkey;
key->keylen = newkeylen;
} else {
struct tcp_md5sig_info *md5sig;
if (!tp->md5sig_info) {
tp->md5sig_info = kzalloc(sizeof(*tp->md5sig_info),
GFP_ATOMIC);
if (!tp->md5sig_info) {
kfree(newkey);
return -ENOMEM;
}
sk_nocaps_add(sk, NETIF_F_GSO_MASK);
}
md5sig = tp->md5sig_info;
if (md5sig->entries4 == 0 &&
tcp_alloc_md5sig_pool(sk) == NULL) {
kfree(newkey);
return -ENOMEM;
}
if (md5sig->alloced4 == md5sig->entries4) {
keys = kmalloc((sizeof(*keys) *
(md5sig->entries4 + 1)), GFP_ATOMIC);
if (!keys) {
kfree(newkey);
if (md5sig->entries4 == 0)
tcp_free_md5sig_pool();
return -ENOMEM;
}
if (md5sig->entries4)
memcpy(keys, md5sig->keys4,
sizeof(*keys) * md5sig->entries4);
/* Free old key list, and reference new one */
kfree(md5sig->keys4);
md5sig->keys4 = keys;
md5sig->alloced4++;
}
md5sig->entries4++;
md5sig->keys4[md5sig->entries4 - 1].addr = addr;
md5sig->keys4[md5sig->entries4 - 1].base.key = newkey;
md5sig->keys4[md5sig->entries4 - 1].base.keylen = newkeylen;
}
return 0;
}
EXPORT_SYMBOL(tcp_v4_md5_do_add);
static int tcp_v4_md5_add_func(struct sock *sk, struct sock *addr_sk,
u8 *newkey, u8 newkeylen)
{
return tcp_v4_md5_do_add(sk, inet_sk(addr_sk)->inet_daddr,
newkey, newkeylen);
}
int tcp_v4_md5_do_del(struct sock *sk, __be32 addr)
{
struct tcp_sock *tp = tcp_sk(sk);
int i;
for (i = 0; i < tp->md5sig_info->entries4; i++) {
if (tp->md5sig_info->keys4[i].addr == addr) {
/* Free the key */
kfree(tp->md5sig_info->keys4[i].base.key);
tp->md5sig_info->entries4--;
if (tp->md5sig_info->entries4 == 0) {
kfree(tp->md5sig_info->keys4);
tp->md5sig_info->keys4 = NULL;
tp->md5sig_info->alloced4 = 0;
tcp_free_md5sig_pool();
} else if (tp->md5sig_info->entries4 != i) {
/* Need to do some manipulation */
memmove(&tp->md5sig_info->keys4[i],
&tp->md5sig_info->keys4[i+1],
(tp->md5sig_info->entries4 - i) *
sizeof(struct tcp4_md5sig_key));
}
return 0;
}
}
return -ENOENT;
}
EXPORT_SYMBOL(tcp_v4_md5_do_del);
static void tcp_v4_clear_md5_list(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
/* Free each key, then the set of key keys,
* the crypto element, and then decrement our
* hold on the last resort crypto.
*/
if (tp->md5sig_info->entries4) {
int i;
for (i = 0; i < tp->md5sig_info->entries4; i++)
kfree(tp->md5sig_info->keys4[i].base.key);
tp->md5sig_info->entries4 = 0;
tcp_free_md5sig_pool();
}
if (tp->md5sig_info->keys4) {
kfree(tp->md5sig_info->keys4);
tp->md5sig_info->keys4 = NULL;
tp->md5sig_info->alloced4 = 0;
}
}
static int tcp_v4_parse_md5_keys(struct sock *sk, char __user *optval,
int optlen)
{
struct tcp_md5sig cmd;
struct sockaddr_in *sin = (struct sockaddr_in *)&cmd.tcpm_addr;
u8 *newkey;
if (optlen < sizeof(cmd))
return -EINVAL;
if (copy_from_user(&cmd, optval, sizeof(cmd)))
return -EFAULT;
if (sin->sin_family != AF_INET)
return -EINVAL;
if (!cmd.tcpm_key || !cmd.tcpm_keylen) {
if (!tcp_sk(sk)->md5sig_info)
return -ENOENT;
return tcp_v4_md5_do_del(sk, sin->sin_addr.s_addr);
}
if (cmd.tcpm_keylen > TCP_MD5SIG_MAXKEYLEN)
return -EINVAL;
if (!tcp_sk(sk)->md5sig_info) {
struct tcp_sock *tp = tcp_sk(sk);
struct tcp_md5sig_info *p;
p = kzalloc(sizeof(*p), sk->sk_allocation);
if (!p)
return -EINVAL;
tp->md5sig_info = p;
sk_nocaps_add(sk, NETIF_F_GSO_MASK);
}
newkey = kmemdup(cmd.tcpm_key, cmd.tcpm_keylen, sk->sk_allocation);
if (!newkey)
return -ENOMEM;
return tcp_v4_md5_do_add(sk, sin->sin_addr.s_addr,
newkey, cmd.tcpm_keylen);
}
static int tcp_v4_md5_hash_pseudoheader(struct tcp_md5sig_pool *hp,
__be32 daddr, __be32 saddr, int nbytes)
{
struct tcp4_pseudohdr *bp;
struct scatterlist sg;
bp = &hp->md5_blk.ip4;
/*
* 1. the TCP pseudo-header (in the order: source IP address,
* destination IP address, zero-padded protocol number, and
* segment length)
*/
bp->saddr = saddr;
bp->daddr = daddr;
bp->pad = 0;
bp->protocol = IPPROTO_TCP;
bp->len = cpu_to_be16(nbytes);
sg_init_one(&sg, bp, sizeof(*bp));
return crypto_hash_update(&hp->md5_desc, &sg, sizeof(*bp));
}
static int tcp_v4_md5_hash_hdr(char *md5_hash, struct tcp_md5sig_key *key,
__be32 daddr, __be32 saddr, struct tcphdr *th)
{
struct tcp_md5sig_pool *hp;
struct hash_desc *desc;
hp = tcp_get_md5sig_pool();
if (!hp)
goto clear_hash_noput;
desc = &hp->md5_desc;
if (crypto_hash_init(desc))
goto clear_hash;
if (tcp_v4_md5_hash_pseudoheader(hp, daddr, saddr, th->doff << 2))
goto clear_hash;
if (tcp_md5_hash_header(hp, th))
goto clear_hash;
if (tcp_md5_hash_key(hp, key))
goto clear_hash;
if (crypto_hash_final(desc, md5_hash))
goto clear_hash;
tcp_put_md5sig_pool();
return 0;
clear_hash:
tcp_put_md5sig_pool();
clear_hash_noput:
memset(md5_hash, 0, 16);
return 1;
}
int tcp_v4_md5_hash_skb(char *md5_hash, struct tcp_md5sig_key *key,
struct sock *sk, struct request_sock *req,
struct sk_buff *skb)
{
struct tcp_md5sig_pool *hp;
struct hash_desc *desc;
struct tcphdr *th = tcp_hdr(skb);
__be32 saddr, daddr;
if (sk) {
saddr = inet_sk(sk)->inet_saddr;
daddr = inet_sk(sk)->inet_daddr;
} else if (req) {
saddr = inet_rsk(req)->loc_addr;
daddr = inet_rsk(req)->rmt_addr;
} else {
const struct iphdr *iph = ip_hdr(skb);
saddr = iph->saddr;
daddr = iph->daddr;
}
hp = tcp_get_md5sig_pool();
if (!hp)
goto clear_hash_noput;
desc = &hp->md5_desc;
if (crypto_hash_init(desc))
goto clear_hash;
if (tcp_v4_md5_hash_pseudoheader(hp, daddr, saddr, skb->len))
goto clear_hash;
if (tcp_md5_hash_header(hp, th))
goto clear_hash;
if (tcp_md5_hash_skb_data(hp, skb, th->doff << 2))
goto clear_hash;
if (tcp_md5_hash_key(hp, key))
goto clear_hash;
if (crypto_hash_final(desc, md5_hash))
goto clear_hash;
tcp_put_md5sig_pool();
return 0;
clear_hash:
tcp_put_md5sig_pool();
clear_hash_noput:
memset(md5_hash, 0, 16);
return 1;
}
EXPORT_SYMBOL(tcp_v4_md5_hash_skb);
static int tcp_v4_inbound_md5_hash(struct sock *sk, struct sk_buff *skb)
{
/*
* This gets called for each TCP segment that arrives
* so we want to be efficient.
* We have 3 drop cases:
* o No MD5 hash and one expected.
* o MD5 hash and we're not expecting one.
* o MD5 hash and its wrong.
*/
__u8 *hash_location = NULL;
struct tcp_md5sig_key *hash_expected;
const struct iphdr *iph = ip_hdr(skb);
struct tcphdr *th = tcp_hdr(skb);
int genhash;
unsigned char newhash[16];
hash_expected = tcp_v4_md5_do_lookup(sk, iph->saddr);
hash_location = tcp_parse_md5sig_option(th);
/* We've parsed the options - do we have a hash? */
if (!hash_expected && !hash_location)
return 0;
if (hash_expected && !hash_location) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPMD5NOTFOUND);
return 1;
}
if (!hash_expected && hash_location) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED);
return 1;
}
/* Okay, so this is hash_expected and hash_location -
* so we need to calculate the checksum.
*/
genhash = tcp_v4_md5_hash_skb(newhash,
hash_expected,
NULL, NULL, skb);
if (genhash || memcmp(hash_location, newhash, 16) != 0) {
if (net_ratelimit()) {
printk(KERN_INFO "MD5 Hash failed for (%pI4, %d)->(%pI4, %d)%s\n",
&iph->saddr, ntohs(th->source),
&iph->daddr, ntohs(th->dest),
genhash ? " tcp_v4_calc_md5_hash failed" : "");
}
return 1;
}
return 0;
}
#endif
struct request_sock_ops tcp_request_sock_ops __read_mostly = {
.family = PF_INET,
.obj_size = sizeof(struct tcp_request_sock),
.rtx_syn_ack = tcp_v4_rtx_synack,
.send_ack = tcp_v4_reqsk_send_ack,
.destructor = tcp_v4_reqsk_destructor,
.send_reset = tcp_v4_send_reset,
.syn_ack_timeout = tcp_syn_ack_timeout,
};
#ifdef CONFIG_TCP_MD5SIG
static const struct tcp_request_sock_ops tcp_request_sock_ipv4_ops = {
.md5_lookup = tcp_v4_reqsk_md5_lookup,
.calc_md5_hash = tcp_v4_md5_hash_skb,
};
#endif
int tcp_v4_conn_request(struct sock *sk, struct sk_buff *skb)
{
struct tcp_extend_values tmp_ext;
struct tcp_options_received tmp_opt;
u8 *hash_location;
struct request_sock *req;
struct inet_request_sock *ireq;
struct tcp_sock *tp = tcp_sk(sk);
struct dst_entry *dst = NULL;
__be32 saddr = ip_hdr(skb)->saddr;
__be32 daddr = ip_hdr(skb)->daddr;
__u32 isn = TCP_SKB_CB(skb)->when;
#ifdef CONFIG_SYN_COOKIES
int want_cookie = 0;
#else
#define want_cookie 0 /* Argh, why doesn't gcc optimize this :( */
#endif
/* Never answer to SYNs send to broadcast or multicast */
if (skb_rtable(skb)->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
goto drop;
/* TW buckets are converted to open requests without
* limitations, they conserve resources and peer is
* evidently real one.
*/
if (inet_csk_reqsk_queue_is_full(sk) && !isn) {
if (net_ratelimit())
syn_flood_warning(skb);
#ifdef CONFIG_SYN_COOKIES
if (sysctl_tcp_syncookies) {
want_cookie = 1;
} else
#endif
goto drop;
}
/* Accept backlog is full. If we have already queued enough
* of warm entries in syn queue, drop request. It is better than
* clogging syn queue with openreqs with exponentially increasing
* timeout.
*/
if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1)
goto drop;
req = inet_reqsk_alloc(&tcp_request_sock_ops);
if (!req)
goto drop;
#ifdef CONFIG_TCP_MD5SIG
tcp_rsk(req)->af_specific = &tcp_request_sock_ipv4_ops;
#endif
tcp_clear_options(&tmp_opt);
tmp_opt.mss_clamp = TCP_MSS_DEFAULT;
tmp_opt.user_mss = tp->rx_opt.user_mss;
tcp_parse_options(skb, &tmp_opt, &hash_location, 0);
if (tmp_opt.cookie_plus > 0 &&
tmp_opt.saw_tstamp &&
!tp->rx_opt.cookie_out_never &&
(sysctl_tcp_cookie_size > 0 ||
(tp->cookie_values != NULL &&
tp->cookie_values->cookie_desired > 0))) {
u8 *c;
u32 *mess = &tmp_ext.cookie_bakery[COOKIE_DIGEST_WORDS];
int l = tmp_opt.cookie_plus - TCPOLEN_COOKIE_BASE;
if (tcp_cookie_generator(&tmp_ext.cookie_bakery[0]) != 0)
goto drop_and_release;
/* Secret recipe starts with IP addresses */
*mess++ ^= (__force u32)daddr;
*mess++ ^= (__force u32)saddr;
/* plus variable length Initiator Cookie */
c = (u8 *)mess;
while (l-- > 0)
*c++ ^= *hash_location++;
#ifdef CONFIG_SYN_COOKIES
want_cookie = 0; /* not our kind of cookie */
#endif
tmp_ext.cookie_out_never = 0; /* false */
tmp_ext.cookie_plus = tmp_opt.cookie_plus;
} else if (!tp->rx_opt.cookie_in_always) {
/* redundant indications, but ensure initialization. */
tmp_ext.cookie_out_never = 1; /* true */
tmp_ext.cookie_plus = 0;
} else {
goto drop_and_release;
}
tmp_ext.cookie_in_always = tp->rx_opt.cookie_in_always;
if (want_cookie && !tmp_opt.saw_tstamp)
tcp_clear_options(&tmp_opt);
tmp_opt.tstamp_ok = tmp_opt.saw_tstamp;
tcp_openreq_init(req, &tmp_opt, skb);
ireq = inet_rsk(req);
ireq->loc_addr = daddr;
ireq->rmt_addr = saddr;
ireq->no_srccheck = inet_sk(sk)->transparent;
ireq->opt = tcp_v4_save_options(sk, skb);
if (security_inet_conn_request(sk, skb, req))
goto drop_and_free;
if (!want_cookie || tmp_opt.tstamp_ok)
TCP_ECN_create_request(req, tcp_hdr(skb));
if (want_cookie) {
isn = cookie_v4_init_sequence(sk, skb, &req->mss);
req->cookie_ts = tmp_opt.tstamp_ok;
} else if (!isn) {
struct inet_peer *peer = NULL;
struct flowi4 fl4;
/* VJ's idea. We save last timestamp seen
* from the destination in peer table, when entering
* state TIME-WAIT, and check against it before
* accepting new connection request.
*
* If "isn" is not zero, this request hit alive
* timewait bucket, so that all the necessary checks
* are made in the function processing timewait state.
*/
if (tmp_opt.saw_tstamp &&
tcp_death_row.sysctl_tw_recycle &&
(dst = inet_csk_route_req(sk, &fl4, req)) != NULL &&
fl4.daddr == saddr &&
(peer = rt_get_peer((struct rtable *)dst, fl4.daddr)) != NULL) {
inet_peer_refcheck(peer);
if ((u32)get_seconds() - peer->tcp_ts_stamp < TCP_PAWS_MSL &&
(s32)(peer->tcp_ts - req->ts_recent) >
TCP_PAWS_WINDOW) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSPASSIVEREJECTED);
goto drop_and_release;
}
}
/* Kill the following clause, if you dislike this way. */
else if (!sysctl_tcp_syncookies &&
(sysctl_max_syn_backlog - inet_csk_reqsk_queue_len(sk) <
(sysctl_max_syn_backlog >> 2)) &&
(!peer || !peer->tcp_ts_stamp) &&
(!dst || !dst_metric(dst, RTAX_RTT))) {
/* Without syncookies last quarter of
* backlog is filled with destinations,
* proven to be alive.
* It means that we continue to communicate
* to destinations, already remembered
* to the moment of synflood.
*/
LIMIT_NETDEBUG(KERN_DEBUG "TCP: drop open request from %pI4/%u\n",
&saddr, ntohs(tcp_hdr(skb)->source));
goto drop_and_release;
}
isn = tcp_v4_init_sequence(skb);
}
tcp_rsk(req)->snt_isn = isn;
if (tcp_v4_send_synack(sk, dst, req,
(struct request_values *)&tmp_ext) ||
want_cookie)
goto drop_and_free;
inet_csk_reqsk_queue_hash_add(sk, req, TCP_TIMEOUT_INIT);
return 0;
drop_and_release:
dst_release(dst);
drop_and_free:
reqsk_free(req);
drop:
return 0;
}
EXPORT_SYMBOL(tcp_v4_conn_request);
/*
* The three way handshake has completed - we got a valid synack -
* now create the new socket.
*/
struct sock *tcp_v4_syn_recv_sock(struct sock *sk, struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst)
{
struct inet_request_sock *ireq;
struct inet_sock *newinet;
struct tcp_sock *newtp;
struct sock *newsk;
#ifdef CONFIG_TCP_MD5SIG
struct tcp_md5sig_key *key;
#endif
struct ip_options_rcu *inet_opt;
if (sk_acceptq_is_full(sk))
goto exit_overflow;
newsk = tcp_create_openreq_child(sk, req, skb);
if (!newsk)
goto exit_nonewsk;
newsk->sk_gso_type = SKB_GSO_TCPV4;
newtp = tcp_sk(newsk);
newinet = inet_sk(newsk);
ireq = inet_rsk(req);
newinet->inet_daddr = ireq->rmt_addr;
newinet->inet_rcv_saddr = ireq->loc_addr;
newinet->inet_saddr = ireq->loc_addr;
inet_opt = ireq->opt;
rcu_assign_pointer(newinet->inet_opt, inet_opt);
ireq->opt = NULL;
newinet->mc_index = inet_iif(skb);
newinet->mc_ttl = ip_hdr(skb)->ttl;
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (inet_opt)
inet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
newinet->inet_id = newtp->write_seq ^ jiffies;
if (!dst) {
dst = inet_csk_route_child_sock(sk, newsk, req);
if (!dst)
goto put_and_exit;
} else {
/* syncookie case : see end of cookie_v4_check() */
}
sk_setup_caps(newsk, dst);
tcp_mtup_init(newsk);
tcp_sync_mss(newsk, dst_mtu(dst));
newtp->advmss = dst_metric_advmss(dst);
if (tcp_sk(sk)->rx_opt.user_mss &&
tcp_sk(sk)->rx_opt.user_mss < newtp->advmss)
newtp->advmss = tcp_sk(sk)->rx_opt.user_mss;
tcp_initialize_rcv_mss(newsk);
#ifdef CONFIG_TCP_MD5SIG
/* Copy over the MD5 key from the original socket */
key = tcp_v4_md5_do_lookup(sk, newinet->inet_daddr);
if (key != NULL) {
/*
* We're using one, so create a matching key
* on the newsk structure. If we fail to get
* memory, then we end up not copying the key
* across. Shucks.
*/
char *newkey = kmemdup(key->key, key->keylen, GFP_ATOMIC);
if (newkey != NULL)
tcp_v4_md5_do_add(newsk, newinet->inet_daddr,
newkey, key->keylen);
sk_nocaps_add(newsk, NETIF_F_GSO_MASK);
}
#endif
if (__inet_inherit_port(sk, newsk) < 0)
goto put_and_exit;
__inet_hash_nolisten(newsk, NULL);
return newsk;
exit_overflow:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
exit_nonewsk:
dst_release(dst);
exit:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);
return NULL;
put_and_exit:
sock_put(newsk);
goto exit;
}
EXPORT_SYMBOL(tcp_v4_syn_recv_sock);
static struct sock *tcp_v4_hnd_req(struct sock *sk, struct sk_buff *skb)
{
struct tcphdr *th = tcp_hdr(skb);
const struct iphdr *iph = ip_hdr(skb);
struct sock *nsk;
struct request_sock **prev;
/* Find possible connection requests. */
struct request_sock *req = inet_csk_search_req(sk, &prev, th->source,
iph->saddr, iph->daddr);
if (req)
return tcp_check_req(sk, skb, req, prev);
nsk = inet_lookup_established(sock_net(sk), &tcp_hashinfo, iph->saddr,
th->source, iph->daddr, th->dest, inet_iif(skb));
if (nsk) {
if (nsk->sk_state != TCP_TIME_WAIT) {
bh_lock_sock(nsk);
return nsk;
}
inet_twsk_put(inet_twsk(nsk));
return NULL;
}
#ifdef CONFIG_SYN_COOKIES
if (!th->syn)
sk = cookie_v4_check(sk, skb, &(IPCB(skb)->opt));
#endif
return sk;
}
static __sum16 tcp_v4_checksum_init(struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
if (skb->ip_summed == CHECKSUM_COMPLETE) {
if (!tcp_v4_check(skb->len, iph->saddr,
iph->daddr, skb->csum)) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
return 0;
}
}
skb->csum = csum_tcpudp_nofold(iph->saddr, iph->daddr,
skb->len, IPPROTO_TCP, 0);
if (skb->len <= 76) {
return __skb_checksum_complete(skb);
}
return 0;
}
/* The socket must have it's spinlock held when we get
* here.
*
* We have a potential double-lock case here, so even when
* doing backlog processing we use the BH locking scheme.
* This is because we cannot sleep with the original spinlock
* held.
*/
int tcp_v4_do_rcv(struct sock *sk, struct sk_buff *skb)
{
struct sock *rsk;
#ifdef CONFIG_TCP_MD5SIG
/*
* We really want to reject the packet as early as possible
* if:
* o We're expecting an MD5'd packet and this is no MD5 tcp option
* o There is an MD5 option and we're not expecting one
*/
if (tcp_v4_inbound_md5_hash(sk, skb))
goto discard;
#endif
if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */
sock_rps_save_rxhash(sk, skb->rxhash);
if (tcp_rcv_established(sk, skb, tcp_hdr(skb), skb->len)) {
rsk = sk;
goto reset;
}
return 0;
}
if (skb->len < tcp_hdrlen(skb) || tcp_checksum_complete(skb))
goto csum_err;
if (sk->sk_state == TCP_LISTEN) {
struct sock *nsk = tcp_v4_hnd_req(sk, skb);
if (!nsk)
goto discard;
if (nsk != sk) {
sock_rps_save_rxhash(nsk, skb->rxhash);
if (tcp_child_process(sk, nsk, skb)) {
rsk = nsk;
goto reset;
}
return 0;
}
} else
sock_rps_save_rxhash(sk, skb->rxhash);
if (tcp_rcv_state_process(sk, skb, tcp_hdr(skb), skb->len)) {
rsk = sk;
goto reset;
}
return 0;
reset:
tcp_v4_send_reset(rsk, skb);
discard:
kfree_skb(skb);
/* Be careful here. If this function gets more complicated and
* gcc suffers from register pressure on the x86, sk (in %ebx)
* might be destroyed here. This current version compiles correctly,
* but you have been warned.
*/
return 0;
csum_err:
TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
goto discard;
}
EXPORT_SYMBOL(tcp_v4_do_rcv);
/*
* From tcp_input.c
*/
int tcp_v4_rcv(struct sk_buff *skb)
{
const struct iphdr *iph;
struct tcphdr *th;
struct sock *sk;
int ret;
struct net *net = dev_net(skb->dev);
if (skb->pkt_type != PACKET_HOST)
goto discard_it;
/* Count it even if it's bad */
TCP_INC_STATS_BH(net, TCP_MIB_INSEGS);
if (!pskb_may_pull(skb, sizeof(struct tcphdr)))
goto discard_it;
th = tcp_hdr(skb);
if (th->doff < sizeof(struct tcphdr) / 4)
goto bad_packet;
if (!pskb_may_pull(skb, th->doff * 4))
goto discard_it;
/* An explanation is required here, I think.
* Packet length and doff are validated by header prediction,
* provided case of th->doff==0 is eliminated.
* So, we defer the checks. */
if (!skb_csum_unnecessary(skb) && tcp_v4_checksum_init(skb))
goto bad_packet;
th = tcp_hdr(skb);
iph = ip_hdr(skb);
TCP_SKB_CB(skb)->seq = ntohl(th->seq);
TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +
skb->len - th->doff * 4);
TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);
TCP_SKB_CB(skb)->when = 0;
TCP_SKB_CB(skb)->flags = iph->tos;
TCP_SKB_CB(skb)->sacked = 0;
sk = __inet_lookup_skb(&tcp_hashinfo, skb, th->source, th->dest);
if (!sk)
goto no_tcp_socket;
process:
if (sk->sk_state == TCP_TIME_WAIT)
goto do_time_wait;
if (unlikely(iph->ttl < inet_sk(sk)->min_ttl)) {
NET_INC_STATS_BH(net, LINUX_MIB_TCPMINTTLDROP);
goto discard_and_relse;
}
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
goto discard_and_relse;
nf_reset(skb);
if (sk_filter(sk, skb))
goto discard_and_relse;
skb->dev = NULL;
bh_lock_sock_nested(sk);
ret = 0;
if (!sock_owned_by_user(sk)) {
#ifdef CONFIG_NET_DMA
struct tcp_sock *tp = tcp_sk(sk);
if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list)
tp->ucopy.dma_chan = dma_find_channel(DMA_MEMCPY);
if (tp->ucopy.dma_chan)
ret = tcp_v4_do_rcv(sk, skb);
else
#endif
{
if (!tcp_prequeue(sk, skb))
ret = tcp_v4_do_rcv(sk, skb);
}
} else if (unlikely(sk_add_backlog(sk, skb))) {
bh_unlock_sock(sk);
NET_INC_STATS_BH(net, LINUX_MIB_TCPBACKLOGDROP);
goto discard_and_relse;
}
bh_unlock_sock(sk);
sock_put(sk);
return ret;
no_tcp_socket:
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
goto discard_it;
if (skb->len < (th->doff << 2) || tcp_checksum_complete(skb)) {
bad_packet:
TCP_INC_STATS_BH(net, TCP_MIB_INERRS);
} else {
tcp_v4_send_reset(NULL, skb);
}
discard_it:
/* Discard frame. */
kfree_skb(skb);
return 0;
discard_and_relse:
sock_put(sk);
goto discard_it;
do_time_wait:
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
inet_twsk_put(inet_twsk(sk));
goto discard_it;
}
if (skb->len < (th->doff << 2) || tcp_checksum_complete(skb)) {
TCP_INC_STATS_BH(net, TCP_MIB_INERRS);
inet_twsk_put(inet_twsk(sk));
goto discard_it;
}
switch (tcp_timewait_state_process(inet_twsk(sk), skb, th)) {
case TCP_TW_SYN: {
struct sock *sk2 = inet_lookup_listener(dev_net(skb->dev),
&tcp_hashinfo,
iph->daddr, th->dest,
inet_iif(skb));
if (sk2) {
inet_twsk_deschedule(inet_twsk(sk), &tcp_death_row);
inet_twsk_put(inet_twsk(sk));
sk = sk2;
goto process;
}
/* Fall through to ACK */
}
case TCP_TW_ACK:
tcp_v4_timewait_ack(sk, skb);
break;
case TCP_TW_RST:
goto no_tcp_socket;
case TCP_TW_SUCCESS:;
}
goto discard_it;
}
struct inet_peer *tcp_v4_get_peer(struct sock *sk, bool *release_it)
{
struct rtable *rt = (struct rtable *) __sk_dst_get(sk);
struct inet_sock *inet = inet_sk(sk);
struct inet_peer *peer;
if (!rt ||
inet->cork.fl.u.ip4.daddr != inet->inet_daddr) {
peer = inet_getpeer_v4(inet->inet_daddr, 1);
*release_it = true;
} else {
if (!rt->peer)
rt_bind_peer(rt, inet->inet_daddr, 1);
peer = rt->peer;
*release_it = false;
}
return peer;
}
EXPORT_SYMBOL(tcp_v4_get_peer);
void *tcp_v4_tw_get_peer(struct sock *sk)
{
struct inet_timewait_sock *tw = inet_twsk(sk);
return inet_getpeer_v4(tw->tw_daddr, 1);
}
EXPORT_SYMBOL(tcp_v4_tw_get_peer);
static struct timewait_sock_ops tcp_timewait_sock_ops = {
.twsk_obj_size = sizeof(struct tcp_timewait_sock),
.twsk_unique = tcp_twsk_unique,
.twsk_destructor= tcp_twsk_destructor,
.twsk_getpeer = tcp_v4_tw_get_peer,
};
const struct inet_connection_sock_af_ops ipv4_specific = {
.queue_xmit = ip_queue_xmit,
.send_check = tcp_v4_send_check,
.rebuild_header = inet_sk_rebuild_header,
.conn_request = tcp_v4_conn_request,
.syn_recv_sock = tcp_v4_syn_recv_sock,
.get_peer = tcp_v4_get_peer,
.net_header_len = sizeof(struct iphdr),
.setsockopt = ip_setsockopt,
.getsockopt = ip_getsockopt,
.addr2sockaddr = inet_csk_addr2sockaddr,
.sockaddr_len = sizeof(struct sockaddr_in),
.bind_conflict = inet_csk_bind_conflict,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_ip_setsockopt,
.compat_getsockopt = compat_ip_getsockopt,
#endif
};
EXPORT_SYMBOL(ipv4_specific);
#ifdef CONFIG_TCP_MD5SIG
static const struct tcp_sock_af_ops tcp_sock_ipv4_specific = {
.md5_lookup = tcp_v4_md5_lookup,
.calc_md5_hash = tcp_v4_md5_hash_skb,
.md5_add = tcp_v4_md5_add_func,
.md5_parse = tcp_v4_parse_md5_keys,
};
#endif
/* NOTE: A lot of things set to zero explicitly by call to
* sk_alloc() so need not be done here.
*/
static int tcp_v4_init_sock(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
skb_queue_head_init(&tp->out_of_order_queue);
tcp_init_xmit_timers(sk);
tcp_prequeue_init(tp);
icsk->icsk_rto = TCP_TIMEOUT_INIT;
tp->mdev = TCP_TIMEOUT_INIT;
/* So many TCP implementations out there (incorrectly) count the
* initial SYN frame in their delayed-ACK and congestion control
* algorithms that we must have the following bandaid to talk
* efficiently to them. -DaveM
*/
tp->snd_cwnd = 2;
/* See draft-stevens-tcpca-spec-01 for discussion of the
* initialization of these values.
*/
tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
tp->snd_cwnd_clamp = ~0;
tp->mss_cache = TCP_MSS_DEFAULT;
tp->reordering = sysctl_tcp_reordering;
icsk->icsk_ca_ops = &tcp_init_congestion_ops;
sk->sk_state = TCP_CLOSE;
sk->sk_write_space = sk_stream_write_space;
sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
icsk->icsk_af_ops = &ipv4_specific;
icsk->icsk_sync_mss = tcp_sync_mss;
#ifdef CONFIG_TCP_MD5SIG
tp->af_specific = &tcp_sock_ipv4_specific;
#endif
/* TCP Cookie Transactions */
if (sysctl_tcp_cookie_size > 0) {
/* Default, cookies without s_data_payload. */
tp->cookie_values =
kzalloc(sizeof(*tp->cookie_values),
sk->sk_allocation);
if (tp->cookie_values != NULL)
kref_init(&tp->cookie_values->kref);
}
/* Presumed zeroed, in order of appearance:
* cookie_in_always, cookie_out_never,
* s_data_constant, s_data_in, s_data_out
*/
sk->sk_sndbuf = sysctl_tcp_wmem[1];
sk->sk_rcvbuf = sysctl_tcp_rmem[1];
local_bh_disable();
percpu_counter_inc(&tcp_sockets_allocated);
local_bh_enable();
return 0;
}
void tcp_v4_destroy_sock(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
tcp_clear_xmit_timers(sk);
tcp_cleanup_congestion_control(sk);
/* Cleanup up the write buffer. */
tcp_write_queue_purge(sk);
/* Cleans up our, hopefully empty, out_of_order_queue. */
__skb_queue_purge(&tp->out_of_order_queue);
#ifdef CONFIG_TCP_MD5SIG
/* Clean up the MD5 key list, if any */
if (tp->md5sig_info) {
tcp_v4_clear_md5_list(sk);
kfree(tp->md5sig_info);
tp->md5sig_info = NULL;
}
#endif
#ifdef CONFIG_NET_DMA
/* Cleans up our sk_async_wait_queue */
__skb_queue_purge(&sk->sk_async_wait_queue);
#endif
/* Clean prequeue, it must be empty really */
__skb_queue_purge(&tp->ucopy.prequeue);
/* Clean up a referenced TCP bind bucket. */
if (inet_csk(sk)->icsk_bind_hash)
inet_put_port(sk);
/*
* If sendmsg cached page exists, toss it.
*/
if (sk->sk_sndmsg_page) {
__free_page(sk->sk_sndmsg_page);
sk->sk_sndmsg_page = NULL;
}
/* TCP Cookie Transactions */
if (tp->cookie_values != NULL) {
kref_put(&tp->cookie_values->kref,
tcp_cookie_values_release);
tp->cookie_values = NULL;
}
percpu_counter_dec(&tcp_sockets_allocated);
}
EXPORT_SYMBOL(tcp_v4_destroy_sock);
#ifdef CONFIG_PROC_FS
/* Proc filesystem TCP sock list dumping. */
static inline struct inet_timewait_sock *tw_head(struct hlist_nulls_head *head)
{
return hlist_nulls_empty(head) ? NULL :
list_entry(head->first, struct inet_timewait_sock, tw_node);
}
static inline struct inet_timewait_sock *tw_next(struct inet_timewait_sock *tw)
{
return !is_a_nulls(tw->tw_node.next) ?
hlist_nulls_entry(tw->tw_node.next, typeof(*tw), tw_node) : NULL;
}
/*
* Get next listener socket follow cur. If cur is NULL, get first socket
* starting from bucket given in st->bucket; when st->bucket is zero the
* very first socket in the hash table is returned.
*/
static void *listening_get_next(struct seq_file *seq, void *cur)
{
struct inet_connection_sock *icsk;
struct hlist_nulls_node *node;
struct sock *sk = cur;
struct inet_listen_hashbucket *ilb;
struct tcp_iter_state *st = seq->private;
struct net *net = seq_file_net(seq);
if (!sk) {
ilb = &tcp_hashinfo.listening_hash[st->bucket];
spin_lock_bh(&ilb->lock);
sk = sk_nulls_head(&ilb->head);
st->offset = 0;
goto get_sk;
}
ilb = &tcp_hashinfo.listening_hash[st->bucket];
++st->num;
++st->offset;
if (st->state == TCP_SEQ_STATE_OPENREQ) {
struct request_sock *req = cur;
icsk = inet_csk(st->syn_wait_sk);
req = req->dl_next;
while (1) {
while (req) {
if (req->rsk_ops->family == st->family) {
cur = req;
goto out;
}
req = req->dl_next;
}
if (++st->sbucket >= icsk->icsk_accept_queue.listen_opt->nr_table_entries)
break;
get_req:
req = icsk->icsk_accept_queue.listen_opt->syn_table[st->sbucket];
}
sk = sk_nulls_next(st->syn_wait_sk);
st->state = TCP_SEQ_STATE_LISTENING;
read_unlock_bh(&icsk->icsk_accept_queue.syn_wait_lock);
} else {
icsk = inet_csk(sk);
read_lock_bh(&icsk->icsk_accept_queue.syn_wait_lock);
if (reqsk_queue_len(&icsk->icsk_accept_queue))
goto start_req;
read_unlock_bh(&icsk->icsk_accept_queue.syn_wait_lock);
sk = sk_nulls_next(sk);
}
get_sk:
sk_nulls_for_each_from(sk, node) {
if (!net_eq(sock_net(sk), net))
continue;
if (sk->sk_family == st->family) {
cur = sk;
goto out;
}
icsk = inet_csk(sk);
read_lock_bh(&icsk->icsk_accept_queue.syn_wait_lock);
if (reqsk_queue_len(&icsk->icsk_accept_queue)) {
start_req:
st->uid = sock_i_uid(sk);
st->syn_wait_sk = sk;
st->state = TCP_SEQ_STATE_OPENREQ;
st->sbucket = 0;
goto get_req;
}
read_unlock_bh(&icsk->icsk_accept_queue.syn_wait_lock);
}
spin_unlock_bh(&ilb->lock);
st->offset = 0;
if (++st->bucket < INET_LHTABLE_SIZE) {
ilb = &tcp_hashinfo.listening_hash[st->bucket];
spin_lock_bh(&ilb->lock);
sk = sk_nulls_head(&ilb->head);
goto get_sk;
}
cur = NULL;
out:
return cur;
}
static void *listening_get_idx(struct seq_file *seq, loff_t *pos)
{
struct tcp_iter_state *st = seq->private;
void *rc;
st->bucket = 0;
st->offset = 0;
rc = listening_get_next(seq, NULL);
while (rc && *pos) {
rc = listening_get_next(seq, rc);
--*pos;
}
return rc;
}
static inline int empty_bucket(struct tcp_iter_state *st)
{
return hlist_nulls_empty(&tcp_hashinfo.ehash[st->bucket].chain) &&
hlist_nulls_empty(&tcp_hashinfo.ehash[st->bucket].twchain);
}
/*
* Get first established socket starting from bucket given in st->bucket.
* If st->bucket is zero, the very first socket in the hash is returned.
*/
static void *established_get_first(struct seq_file *seq)
{
struct tcp_iter_state *st = seq->private;
struct net *net = seq_file_net(seq);
void *rc = NULL;
st->offset = 0;
for (; st->bucket <= tcp_hashinfo.ehash_mask; ++st->bucket) {
struct sock *sk;
struct hlist_nulls_node *node;
struct inet_timewait_sock *tw;
spinlock_t *lock = inet_ehash_lockp(&tcp_hashinfo, st->bucket);
/* Lockless fast path for the common case of empty buckets */
if (empty_bucket(st))
continue;
spin_lock_bh(lock);
sk_nulls_for_each(sk, node, &tcp_hashinfo.ehash[st->bucket].chain) {
if (sk->sk_family != st->family ||
!net_eq(sock_net(sk), net)) {
continue;
}
rc = sk;
goto out;
}
st->state = TCP_SEQ_STATE_TIME_WAIT;
inet_twsk_for_each(tw, node,
&tcp_hashinfo.ehash[st->bucket].twchain) {
if (tw->tw_family != st->family ||
!net_eq(twsk_net(tw), net)) {
continue;
}
rc = tw;
goto out;
}
spin_unlock_bh(lock);
st->state = TCP_SEQ_STATE_ESTABLISHED;
}
out:
return rc;
}
static void *established_get_next(struct seq_file *seq, void *cur)
{
struct sock *sk = cur;
struct inet_timewait_sock *tw;
struct hlist_nulls_node *node;
struct tcp_iter_state *st = seq->private;
struct net *net = seq_file_net(seq);
++st->num;
++st->offset;
if (st->state == TCP_SEQ_STATE_TIME_WAIT) {
tw = cur;
tw = tw_next(tw);
get_tw:
while (tw && (tw->tw_family != st->family || !net_eq(twsk_net(tw), net))) {
tw = tw_next(tw);
}
if (tw) {
cur = tw;
goto out;
}
spin_unlock_bh(inet_ehash_lockp(&tcp_hashinfo, st->bucket));
st->state = TCP_SEQ_STATE_ESTABLISHED;
/* Look for next non empty bucket */
st->offset = 0;
while (++st->bucket <= tcp_hashinfo.ehash_mask &&
empty_bucket(st))
;
if (st->bucket > tcp_hashinfo.ehash_mask)
return NULL;
spin_lock_bh(inet_ehash_lockp(&tcp_hashinfo, st->bucket));
sk = sk_nulls_head(&tcp_hashinfo.ehash[st->bucket].chain);
} else
sk = sk_nulls_next(sk);
sk_nulls_for_each_from(sk, node) {
if (sk->sk_family == st->family && net_eq(sock_net(sk), net))
goto found;
}
st->state = TCP_SEQ_STATE_TIME_WAIT;
tw = tw_head(&tcp_hashinfo.ehash[st->bucket].twchain);
goto get_tw;
found:
cur = sk;
out:
return cur;
}
static void *established_get_idx(struct seq_file *seq, loff_t pos)
{
struct tcp_iter_state *st = seq->private;
void *rc;
st->bucket = 0;
rc = established_get_first(seq);
while (rc && pos) {
rc = established_get_next(seq, rc);
--pos;
}
return rc;
}
static void *tcp_get_idx(struct seq_file *seq, loff_t pos)
{
void *rc;
struct tcp_iter_state *st = seq->private;
st->state = TCP_SEQ_STATE_LISTENING;
rc = listening_get_idx(seq, &pos);
if (!rc) {
st->state = TCP_SEQ_STATE_ESTABLISHED;
rc = established_get_idx(seq, pos);
}
return rc;
}
static void *tcp_seek_last_pos(struct seq_file *seq)
{
struct tcp_iter_state *st = seq->private;
int offset = st->offset;
int orig_num = st->num;
void *rc = NULL;
switch (st->state) {
case TCP_SEQ_STATE_OPENREQ:
case TCP_SEQ_STATE_LISTENING:
if (st->bucket >= INET_LHTABLE_SIZE)
break;
st->state = TCP_SEQ_STATE_LISTENING;
rc = listening_get_next(seq, NULL);
while (offset-- && rc)
rc = listening_get_next(seq, rc);
if (rc)
break;
st->bucket = 0;
/* Fallthrough */
case TCP_SEQ_STATE_ESTABLISHED:
case TCP_SEQ_STATE_TIME_WAIT:
st->state = TCP_SEQ_STATE_ESTABLISHED;
if (st->bucket > tcp_hashinfo.ehash_mask)
break;
rc = established_get_first(seq);
while (offset-- && rc)
rc = established_get_next(seq, rc);
}
st->num = orig_num;
return rc;
}
static void *tcp_seq_start(struct seq_file *seq, loff_t *pos)
{
struct tcp_iter_state *st = seq->private;
void *rc;
if (*pos && *pos == st->last_pos) {
rc = tcp_seek_last_pos(seq);
if (rc)
goto out;
}
st->state = TCP_SEQ_STATE_LISTENING;
st->num = 0;
st->bucket = 0;
st->offset = 0;
rc = *pos ? tcp_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
out:
st->last_pos = *pos;
return rc;
}
static void *tcp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct tcp_iter_state *st = seq->private;
void *rc = NULL;
if (v == SEQ_START_TOKEN) {
rc = tcp_get_idx(seq, 0);
goto out;
}
switch (st->state) {
case TCP_SEQ_STATE_OPENREQ:
case TCP_SEQ_STATE_LISTENING:
rc = listening_get_next(seq, v);
if (!rc) {
st->state = TCP_SEQ_STATE_ESTABLISHED;
st->bucket = 0;
st->offset = 0;
rc = established_get_first(seq);
}
break;
case TCP_SEQ_STATE_ESTABLISHED:
case TCP_SEQ_STATE_TIME_WAIT:
rc = established_get_next(seq, v);
break;
}
out:
++*pos;
st->last_pos = *pos;
return rc;
}
static void tcp_seq_stop(struct seq_file *seq, void *v)
{
struct tcp_iter_state *st = seq->private;
switch (st->state) {
case TCP_SEQ_STATE_OPENREQ:
if (v) {
struct inet_connection_sock *icsk = inet_csk(st->syn_wait_sk);
read_unlock_bh(&icsk->icsk_accept_queue.syn_wait_lock);
}
case TCP_SEQ_STATE_LISTENING:
if (v != SEQ_START_TOKEN)
spin_unlock_bh(&tcp_hashinfo.listening_hash[st->bucket].lock);
break;
case TCP_SEQ_STATE_TIME_WAIT:
case TCP_SEQ_STATE_ESTABLISHED:
if (v)
spin_unlock_bh(inet_ehash_lockp(&tcp_hashinfo, st->bucket));
break;
}
}
static int tcp_seq_open(struct inode *inode, struct file *file)
{
struct tcp_seq_afinfo *afinfo = PDE(inode)->data;
struct tcp_iter_state *s;
int err;
err = seq_open_net(inode, file, &afinfo->seq_ops,
sizeof(struct tcp_iter_state));
if (err < 0)
return err;
s = ((struct seq_file *)file->private_data)->private;
s->family = afinfo->family;
s->last_pos = 0;
return 0;
}
int tcp_proc_register(struct net *net, struct tcp_seq_afinfo *afinfo)
{
int rc = 0;
struct proc_dir_entry *p;
afinfo->seq_fops.open = tcp_seq_open;
afinfo->seq_fops.read = seq_read;
afinfo->seq_fops.llseek = seq_lseek;
afinfo->seq_fops.release = seq_release_net;
afinfo->seq_ops.start = tcp_seq_start;
afinfo->seq_ops.next = tcp_seq_next;
afinfo->seq_ops.stop = tcp_seq_stop;
p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net,
&afinfo->seq_fops, afinfo);
if (!p)
rc = -ENOMEM;
return rc;
}
EXPORT_SYMBOL(tcp_proc_register);
void tcp_proc_unregister(struct net *net, struct tcp_seq_afinfo *afinfo)
{
proc_net_remove(net, afinfo->name);
}
EXPORT_SYMBOL(tcp_proc_unregister);
static void get_openreq4(struct sock *sk, struct request_sock *req,
struct seq_file *f, int i, int uid, int *len)
{
const struct inet_request_sock *ireq = inet_rsk(req);
int ttd = req->expires - jiffies;
seq_printf(f, "%4d: %08X:%04X %08X:%04X"
" %02X %08X:%08X %02X:%08lX %08X %5d %8d %u %d %pK%n",
i,
ireq->loc_addr,
ntohs(inet_sk(sk)->inet_sport),
ireq->rmt_addr,
ntohs(ireq->rmt_port),
TCP_SYN_RECV,
0, 0, /* could print option size, but that is af dependent. */
1, /* timers active (only the expire timer) */
jiffies_to_clock_t(ttd),
req->retrans,
uid,
0, /* non standard timer */
0, /* open_requests have no inode */
atomic_read(&sk->sk_refcnt),
req,
len);
}
static void get_tcp4_sock(struct sock *sk, struct seq_file *f, int i, int *len)
{
int timer_active;
unsigned long timer_expires;
struct tcp_sock *tp = tcp_sk(sk);
const struct inet_connection_sock *icsk = inet_csk(sk);
struct inet_sock *inet = inet_sk(sk);
__be32 dest = inet->inet_daddr;
__be32 src = inet->inet_rcv_saddr;
__u16 destp = ntohs(inet->inet_dport);
__u16 srcp = ntohs(inet->inet_sport);
int rx_queue;
if (icsk->icsk_pending == ICSK_TIME_RETRANS) {
timer_active = 1;
timer_expires = icsk->icsk_timeout;
} else if (icsk->icsk_pending == ICSK_TIME_PROBE0) {
timer_active = 4;
timer_expires = icsk->icsk_timeout;
} else if (timer_pending(&sk->sk_timer)) {
timer_active = 2;
timer_expires = sk->sk_timer.expires;
} else {
timer_active = 0;
timer_expires = jiffies;
}
if (sk->sk_state == TCP_LISTEN)
rx_queue = sk->sk_ack_backlog;
else
/*
* because we dont lock socket, we might find a transient negative value
*/
rx_queue = max_t(int, tp->rcv_nxt - tp->copied_seq, 0);
seq_printf(f, "%4d: %08X:%04X %08X:%04X %02X %08X:%08X %02X:%08lX "
"%08X %5d %8d %lu %d %pK %lu %lu %u %u %d%n",
i, src, srcp, dest, destp, sk->sk_state,
tp->write_seq - tp->snd_una,
rx_queue,
timer_active,
jiffies_to_clock_t(timer_expires - jiffies),
icsk->icsk_retransmits,
sock_i_uid(sk),
icsk->icsk_probes_out,
sock_i_ino(sk),
atomic_read(&sk->sk_refcnt), sk,
jiffies_to_clock_t(icsk->icsk_rto),
jiffies_to_clock_t(icsk->icsk_ack.ato),
(icsk->icsk_ack.quick << 1) | icsk->icsk_ack.pingpong,
tp->snd_cwnd,
tcp_in_initial_slowstart(tp) ? -1 : tp->snd_ssthresh,
len);
}
static void get_timewait4_sock(struct inet_timewait_sock *tw,
struct seq_file *f, int i, int *len)
{
__be32 dest, src;
__u16 destp, srcp;
int ttd = tw->tw_ttd - jiffies;
if (ttd < 0)
ttd = 0;
dest = tw->tw_daddr;
src = tw->tw_rcv_saddr;
destp = ntohs(tw->tw_dport);
srcp = ntohs(tw->tw_sport);
seq_printf(f, "%4d: %08X:%04X %08X:%04X"
" %02X %08X:%08X %02X:%08lX %08X %5d %8d %d %d %pK%n",
i, src, srcp, dest, destp, tw->tw_substate, 0, 0,
3, jiffies_to_clock_t(ttd), 0, 0, 0, 0,
atomic_read(&tw->tw_refcnt), tw, len);
}
#define TMPSZ 150
static int tcp4_seq_show(struct seq_file *seq, void *v)
{
struct tcp_iter_state *st;
int len;
if (v == SEQ_START_TOKEN) {
seq_printf(seq, "%-*s\n", TMPSZ - 1,
" sl local_address rem_address st tx_queue "
"rx_queue tr tm->when retrnsmt uid timeout "
"inode");
goto out;
}
st = seq->private;
switch (st->state) {
case TCP_SEQ_STATE_LISTENING:
case TCP_SEQ_STATE_ESTABLISHED:
get_tcp4_sock(v, seq, st->num, &len);
break;
case TCP_SEQ_STATE_OPENREQ:
get_openreq4(st->syn_wait_sk, v, seq, st->num, st->uid, &len);
break;
case TCP_SEQ_STATE_TIME_WAIT:
get_timewait4_sock(v, seq, st->num, &len);
break;
}
seq_printf(seq, "%*s\n", TMPSZ - 1 - len, "");
out:
return 0;
}
static struct tcp_seq_afinfo tcp4_seq_afinfo = {
.name = "tcp",
.family = AF_INET,
.seq_fops = {
.owner = THIS_MODULE,
},
.seq_ops = {
.show = tcp4_seq_show,
},
};
static int __net_init tcp4_proc_init_net(struct net *net)
{
return tcp_proc_register(net, &tcp4_seq_afinfo);
}
static void __net_exit tcp4_proc_exit_net(struct net *net)
{
tcp_proc_unregister(net, &tcp4_seq_afinfo);
}
static struct pernet_operations tcp4_net_ops = {
.init = tcp4_proc_init_net,
.exit = tcp4_proc_exit_net,
};
int __init tcp4_proc_init(void)
{
return register_pernet_subsys(&tcp4_net_ops);
}
void tcp4_proc_exit(void)
{
unregister_pernet_subsys(&tcp4_net_ops);
}
#endif /* CONFIG_PROC_FS */
struct sk_buff **tcp4_gro_receive(struct sk_buff **head, struct sk_buff *skb)
{
const struct iphdr *iph = skb_gro_network_header(skb);
switch (skb->ip_summed) {
case CHECKSUM_COMPLETE:
if (!tcp_v4_check(skb_gro_len(skb), iph->saddr, iph->daddr,
skb->csum)) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
break;
}
/* fall through */
case CHECKSUM_NONE:
NAPI_GRO_CB(skb)->flush = 1;
return NULL;
}
return tcp_gro_receive(head, skb);
}
int tcp4_gro_complete(struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
struct tcphdr *th = tcp_hdr(skb);
th->check = ~tcp_v4_check(skb->len - skb_transport_offset(skb),
iph->saddr, iph->daddr, 0);
skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
return tcp_gro_complete(skb);
}
struct proto tcp_prot = {
.name = "TCP",
.owner = THIS_MODULE,
.close = tcp_close,
.connect = tcp_v4_connect,
.disconnect = tcp_disconnect,
.accept = inet_csk_accept,
.ioctl = tcp_ioctl,
.init = tcp_v4_init_sock,
.destroy = tcp_v4_destroy_sock,
.shutdown = tcp_shutdown,
.setsockopt = tcp_setsockopt,
.getsockopt = tcp_getsockopt,
.recvmsg = tcp_recvmsg,
.sendmsg = tcp_sendmsg,
.sendpage = tcp_sendpage,
.backlog_rcv = tcp_v4_do_rcv,
.hash = inet_hash,
.unhash = inet_unhash,
.get_port = inet_csk_get_port,
.enter_memory_pressure = tcp_enter_memory_pressure,
.sockets_allocated = &tcp_sockets_allocated,
.orphan_count = &tcp_orphan_count,
.memory_allocated = &tcp_memory_allocated,
.memory_pressure = &tcp_memory_pressure,
.sysctl_mem = sysctl_tcp_mem,
.sysctl_wmem = sysctl_tcp_wmem,
.sysctl_rmem = sysctl_tcp_rmem,
.max_header = MAX_TCP_HEADER,
.obj_size = sizeof(struct tcp_sock),
.slab_flags = SLAB_DESTROY_BY_RCU,
.twsk_prot = &tcp_timewait_sock_ops,
.rsk_prot = &tcp_request_sock_ops,
.h.hashinfo = &tcp_hashinfo,
.no_autobind = true,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_tcp_setsockopt,
.compat_getsockopt = compat_tcp_getsockopt,
#endif
};
EXPORT_SYMBOL(tcp_prot);
static int __net_init tcp_sk_init(struct net *net)
{
return inet_ctl_sock_create(&net->ipv4.tcp_sock,
PF_INET, SOCK_RAW, IPPROTO_TCP, net);
}
static void __net_exit tcp_sk_exit(struct net *net)
{
inet_ctl_sock_destroy(net->ipv4.tcp_sock);
}
static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list)
{
inet_twsk_purge(&tcp_hashinfo, &tcp_death_row, AF_INET);
}
static struct pernet_operations __net_initdata tcp_sk_ops = {
.init = tcp_sk_init,
.exit = tcp_sk_exit,
.exit_batch = tcp_sk_exit_batch,
};
void __init tcp_v4_init(void)
{
inet_hashinfo_init(&tcp_hashinfo);
if (register_pernet_subsys(&tcp_sk_ops))
panic("Failed to create the TCP control socket.\n");
}
| gpl-2.0 |
blackb1rd/android_kernel_samsung_d2 | drivers/usb/host/ehci-hcd.c | 479 | 43846 | /*
* Enhanced Host Controller Interface (EHCI) driver for USB.
*
* Maintainer: Alan Stern <stern@rowland.harvard.edu>
*
* Copyright (c) 2000-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.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/dmapool.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/sched.h>
#include <linux/vmalloc.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/ktime.h>
#include <linux/list.h>
#include <linux/interrupt.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include <linux/moduleparam.h>
#include <linux/dma-mapping.h>
#include <linux/debugfs.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <asm/byteorder.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/unaligned.h>
#if defined(CONFIG_PPC_PS3)
#include <asm/firmware.h>
#endif
/*-------------------------------------------------------------------------*/
/*
* EHCI hc_driver implementation ... experimental, incomplete.
* Based on the final 1.0 register interface specification.
*
* USB 2.0 shows up in upcoming www.pcmcia.org technology.
* First was PCMCIA, like ISA; then CardBus, which is PCI.
* Next comes "CardBay", using USB 2.0 signals.
*
* Contains additional contributions by Brad Hards, Rory Bolt, and others.
* Special thanks to Intel and VIA for providing host controllers to
* test this driver on, and Cypress (including In-System Design) for
* providing early devices for those host controllers to talk to!
*/
#define DRIVER_AUTHOR "David Brownell"
#define DRIVER_DESC "USB 2.0 'Enhanced' Host Controller (EHCI) Driver"
static const char hcd_name [] = "ehci_hcd";
#undef VERBOSE_DEBUG
#undef EHCI_URB_TRACE
#ifdef DEBUG
#define EHCI_STATS
#endif
/* magic numbers that can affect system performance */
#define EHCI_TUNE_CERR 3 /* 0-3 qtd retries; 0 == don't stop */
#define EHCI_TUNE_RL_HS 4 /* nak throttle; see 4.9 */
#define EHCI_TUNE_RL_TT 0
#define EHCI_TUNE_MULT_HS 1 /* 1-3 transactions/uframe; 4.10.3 */
#define EHCI_TUNE_MULT_TT 1
/*
* Some drivers think it's safe to schedule isochronous transfers more than
* 256 ms into the future (partly as a result of an old bug in the scheduling
* code). In an attempt to avoid trouble, we will use a minimum scheduling
* length of 512 frames instead of 256.
*/
#define EHCI_TUNE_FLS 1 /* (medium) 512-frame schedule */
#define EHCI_IAA_MSECS 100 /* arbitrary */
#define EHCI_IO_JIFFIES (HZ/10) /* io watchdog > irq_thresh */
#define EHCI_ASYNC_JIFFIES (HZ/20) /* async idle timeout */
#define EHCI_SHRINK_JIFFIES (DIV_ROUND_UP(HZ, 200) + 1)
/* 5-ms async qh unlink delay */
/* Initial IRQ latency: faster than hw default */
static int log2_irq_thresh = 0; // 0 to 6
module_param (log2_irq_thresh, int, S_IRUGO);
MODULE_PARM_DESC (log2_irq_thresh, "log2 IRQ latency, 1-64 microframes");
/* initial park setting: slower than hw default */
static unsigned park = 0;
module_param (park, uint, S_IRUGO);
MODULE_PARM_DESC (park, "park setting; 1-3 back-to-back async packets");
/* for flakey hardware, ignore overcurrent indicators */
static bool ignore_oc = 0;
module_param (ignore_oc, bool, S_IRUGO);
MODULE_PARM_DESC (ignore_oc, "ignore bogus hardware overcurrent indications");
/* for link power management(LPM) feature */
static unsigned int hird;
module_param(hird, int, S_IRUGO);
MODULE_PARM_DESC(hird, "host initiated resume duration, +1 for each 75us");
#define INTR_MASK (STS_IAA | STS_FATAL | STS_PCD | STS_ERR | STS_INT)
/*-------------------------------------------------------------------------*/
#include "ehci.h"
#include "ehci-dbg.c"
#include "pci-quirks.h"
/*-------------------------------------------------------------------------*/
static void
timer_action(struct ehci_hcd *ehci, enum ehci_timer_action action)
{
/* Don't override timeouts which shrink or (later) disable
* the async ring; just the I/O watchdog. Note that if a
* SHRINK were pending, OFF would never be requested.
*/
if (timer_pending(&ehci->watchdog)
&& ((BIT(TIMER_ASYNC_SHRINK) | BIT(TIMER_ASYNC_OFF))
& ehci->actions))
return;
if (!test_and_set_bit(action, &ehci->actions)) {
unsigned long t;
switch (action) {
case TIMER_IO_WATCHDOG:
if (!ehci->need_io_watchdog)
return;
t = EHCI_IO_JIFFIES;
break;
case TIMER_ASYNC_OFF:
t = EHCI_ASYNC_JIFFIES;
break;
/* case TIMER_ASYNC_SHRINK: */
default:
t = EHCI_SHRINK_JIFFIES;
break;
}
mod_timer(&ehci->watchdog, t + jiffies);
}
}
/*-------------------------------------------------------------------------*/
/*
* handshake - spin reading hc until handshake completes or fails
* @ptr: address of hc register to be read
* @mask: bits to look at in result of read
* @done: value of those bits when handshake succeeds
* @usec: timeout in microseconds
*
* Returns negative errno, or zero on success
*
* Success happens when the "mask" bits have the specified value (hardware
* handshake done). There are two failure modes: "usec" have passed (major
* hardware flakeout), or the register reads as all-ones (hardware removed).
*
* That last failure should_only happen in cases like physical cardbus eject
* before driver shutdown. But it also seems to be caused by bugs in cardbus
* bridge shutdown: shutting down the bridge before the devices using it.
*/
static int handshake (struct ehci_hcd *ehci, void __iomem *ptr,
u32 mask, u32 done, int usec)
{
u32 result;
do {
result = ehci_readl(ehci, ptr);
if (result == ~(u32)0) /* card removed */
return -ENODEV;
result &= mask;
if (result == done)
return 0;
udelay (1);
usec--;
} while (usec > 0);
return -ETIMEDOUT;
}
/* check TDI/ARC silicon is in host mode */
static int tdi_in_host_mode (struct ehci_hcd *ehci)
{
u32 __iomem *reg_ptr;
u32 tmp;
reg_ptr = (u32 __iomem *)(((u8 __iomem *)ehci->regs) + USBMODE);
tmp = ehci_readl(ehci, reg_ptr);
return (tmp & 3) == USBMODE_CM_HC;
}
/* force HC to halt state from unknown (EHCI spec section 2.3) */
static int ehci_halt (struct ehci_hcd *ehci)
{
u32 temp = ehci_readl(ehci, &ehci->regs->status);
/* disable any irqs left enabled by previous code */
ehci_writel(ehci, 0, &ehci->regs->intr_enable);
if (ehci_is_TDI(ehci) && tdi_in_host_mode(ehci) == 0) {
return 0;
}
if ((temp & STS_HALT) != 0)
return 0;
temp = ehci_readl(ehci, &ehci->regs->command);
temp &= ~CMD_RUN;
ehci_writel(ehci, temp, &ehci->regs->command);
return handshake (ehci, &ehci->regs->status,
STS_HALT, STS_HALT, 16 * 125);
}
#if defined(CONFIG_USB_SUSPEND) && defined(CONFIG_PPC_PS3)
/*
* The EHCI controller of the Cell Super Companion Chip used in the
* PS3 will stop the root hub after all root hub ports are suspended.
* When in this condition handshake will return -ETIMEDOUT. The
* STS_HLT bit will not be set, so inspection of the frame index is
* used here to test for the condition. If the condition is found
* return success to allow the USB suspend to complete.
*/
static int handshake_for_broken_root_hub(struct ehci_hcd *ehci,
void __iomem *ptr, u32 mask, u32 done,
int usec)
{
unsigned int old_index;
int error;
if (!firmware_has_feature(FW_FEATURE_PS3_LV1))
return -ETIMEDOUT;
old_index = ehci_read_frame_index(ehci);
error = handshake(ehci, ptr, mask, done, usec);
if (error == -ETIMEDOUT && ehci_read_frame_index(ehci) == old_index)
return 0;
return error;
}
#else
static int handshake_for_broken_root_hub(struct ehci_hcd *ehci,
void __iomem *ptr, u32 mask, u32 done,
int usec)
{
return -ETIMEDOUT;
}
#endif
static int handshake_on_error_set_halt(struct ehci_hcd *ehci, void __iomem *ptr,
u32 mask, u32 done, int usec)
{
int error;
error = handshake(ehci, ptr, mask, done, usec);
if (error == -ETIMEDOUT)
error = handshake_for_broken_root_hub(ehci, ptr, mask, done,
usec);
if (error) {
ehci_halt(ehci);
ehci->rh_state = EHCI_RH_HALTED;
ehci_err(ehci, "force halt; handshake %p %08x %08x -> %d\n",
ptr, mask, done, error);
}
return error;
}
/* put TDI/ARC silicon into EHCI mode */
static void tdi_reset (struct ehci_hcd *ehci)
{
u32 __iomem *reg_ptr;
u32 tmp;
reg_ptr = (u32 __iomem *)(((u8 __iomem *)ehci->regs) + USBMODE);
tmp = ehci_readl(ehci, reg_ptr);
tmp |= USBMODE_CM_HC;
/* The default byte access to MMR space is LE after
* controller reset. Set the required endian mode
* for transfer buffers to match the host microprocessor
*/
if (ehci_big_endian_mmio(ehci))
tmp |= USBMODE_BE;
ehci_writel(ehci, tmp, reg_ptr);
}
/* reset a non-running (STS_HALT == 1) controller */
static int ehci_reset (struct ehci_hcd *ehci)
{
int retval;
u32 command = ehci_readl(ehci, &ehci->regs->command);
/* If the EHCI debug controller is active, special care must be
* taken before and after a host controller reset */
if (ehci->debug && !dbgp_reset_prep())
ehci->debug = NULL;
command |= CMD_RESET;
dbg_cmd (ehci, "reset", command);
ehci_writel(ehci, command, &ehci->regs->command);
ehci->rh_state = EHCI_RH_HALTED;
ehci->next_statechange = jiffies;
retval = handshake (ehci, &ehci->regs->command,
CMD_RESET, 0, 250 * 1000);
if (ehci->has_hostpc) {
ehci_writel(ehci, USBMODE_EX_HC | USBMODE_EX_VBPS,
(u32 __iomem *)(((u8 *)ehci->regs) + USBMODE_EX));
ehci_writel(ehci, TXFIFO_DEFAULT,
(u32 __iomem *)(((u8 *)ehci->regs) + TXFILLTUNING));
}
if (retval)
return retval;
if (ehci_is_TDI(ehci))
tdi_reset (ehci);
if (ehci->debug)
dbgp_external_startup();
ehci->port_c_suspend = ehci->suspended_ports =
ehci->resuming_ports = 0;
return retval;
}
/* idle the controller (from running) */
static void ehci_quiesce (struct ehci_hcd *ehci)
{
u32 temp;
#ifdef DEBUG
if (ehci->rh_state != EHCI_RH_RUNNING)
BUG ();
#endif
/* wait for any schedule enables/disables to take effect */
temp = ehci_readl(ehci, &ehci->regs->command) << 10;
temp &= STS_ASS | STS_PSS;
if (handshake_on_error_set_halt(ehci, &ehci->regs->status,
STS_ASS | STS_PSS, temp, 16 * 125))
return;
/* then disable anything that's still active */
temp = ehci_readl(ehci, &ehci->regs->command);
temp &= ~(CMD_ASE | CMD_IAAD | CMD_PSE);
ehci_writel(ehci, temp, &ehci->regs->command);
/* hardware can take 16 microframes to turn off ... */
handshake_on_error_set_halt(ehci, &ehci->regs->status,
STS_ASS | STS_PSS, 0, 16 * 125);
}
/*-------------------------------------------------------------------------*/
static void end_unlink_async(struct ehci_hcd *ehci);
static void ehci_work(struct ehci_hcd *ehci);
#include "ehci-hub.c"
#include "ehci-lpm.c"
#include "ehci-mem.c"
#include "ehci-q.c"
#include "ehci-sched.c"
#include "ehci-sysfs.c"
/*-------------------------------------------------------------------------*/
static void ehci_iaa_watchdog(unsigned long param)
{
struct ehci_hcd *ehci = (struct ehci_hcd *) param;
unsigned long flags;
spin_lock_irqsave (&ehci->lock, flags);
/* Lost IAA irqs wedge things badly; seen first with a vt8235.
* So we need this watchdog, but must protect it against both
* (a) SMP races against real IAA firing and retriggering, and
* (b) clean HC shutdown, when IAA watchdog was pending.
*/
if (ehci->reclaim
&& !timer_pending(&ehci->iaa_watchdog)
&& ehci->rh_state == EHCI_RH_RUNNING) {
u32 cmd, status;
/* If we get here, IAA is *REALLY* late. It's barely
* conceivable that the system is so busy that CMD_IAAD
* is still legitimately set, so let's be sure it's
* clear before we read STS_IAA. (The HC should clear
* CMD_IAAD when it sets STS_IAA.)
*/
cmd = ehci_readl(ehci, &ehci->regs->command);
if (cmd & CMD_IAAD)
ehci_writel(ehci, cmd & ~CMD_IAAD,
&ehci->regs->command);
/* If IAA is set here it either legitimately triggered
* before we cleared IAAD above (but _way_ late, so we'll
* still count it as lost) ... or a silicon erratum:
* - VIA seems to set IAA without triggering the IRQ;
* - IAAD potentially cleared without setting IAA.
*/
status = ehci_readl(ehci, &ehci->regs->status);
if ((status & STS_IAA) || !(cmd & CMD_IAAD)) {
COUNT (ehci->stats.lost_iaa);
ehci_writel(ehci, STS_IAA, &ehci->regs->status);
}
ehci_vdbg(ehci, "IAA watchdog: status %x cmd %x\n",
status, cmd);
end_unlink_async(ehci);
}
spin_unlock_irqrestore(&ehci->lock, flags);
}
static void ehci_watchdog(unsigned long param)
{
struct ehci_hcd *ehci = (struct ehci_hcd *) param;
unsigned long flags;
spin_lock_irqsave(&ehci->lock, flags);
/* stop async processing after it's idled a bit */
if (test_bit (TIMER_ASYNC_OFF, &ehci->actions))
start_unlink_async (ehci, ehci->async);
/* ehci could run by timer, without IRQs ... */
ehci_work (ehci);
spin_unlock_irqrestore (&ehci->lock, flags);
}
/* On some systems, leaving remote wakeup enabled prevents system shutdown.
* The firmware seems to think that powering off is a wakeup event!
* This routine turns off remote wakeup and everything else, on all ports.
*/
static void ehci_turn_off_all_ports(struct ehci_hcd *ehci)
{
int port = HCS_N_PORTS(ehci->hcs_params);
while (port--)
ehci_writel(ehci, PORT_RWC_BITS,
&ehci->regs->port_status[port]);
}
/*
* Halt HC, turn off all ports, and let the BIOS use the companion controllers.
* Should be called with ehci->lock held.
*/
static void ehci_silence_controller(struct ehci_hcd *ehci)
{
ehci_halt(ehci);
ehci_turn_off_all_ports(ehci);
/* make BIOS/etc use companion controller during reboot */
ehci_writel(ehci, 0, &ehci->regs->configured_flag);
/* unblock posted writes */
ehci_readl(ehci, &ehci->regs->configured_flag);
}
/* ehci_shutdown kick in for silicon on any bus (not just pci, etc).
* This forcibly disables dma and IRQs, helping kexec and other cases
* where the next system software may expect clean state.
*/
static void ehci_shutdown(struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
del_timer_sync(&ehci->watchdog);
del_timer_sync(&ehci->iaa_watchdog);
spin_lock_irq(&ehci->lock);
ehci_silence_controller(ehci);
spin_unlock_irq(&ehci->lock);
}
static void __maybe_unused ehci_port_power (struct ehci_hcd *ehci, int is_on)
{
unsigned port;
if (!HCS_PPC (ehci->hcs_params))
return;
ehci_dbg (ehci, "...power%s ports...\n", is_on ? "up" : "down");
for (port = HCS_N_PORTS (ehci->hcs_params); port > 0; )
(void) ehci_hub_control(ehci_to_hcd(ehci),
is_on ? SetPortFeature : ClearPortFeature,
USB_PORT_FEAT_POWER,
port--, NULL, 0);
/* Flush those writes */
ehci_readl(ehci, &ehci->regs->command);
msleep(20);
}
/*-------------------------------------------------------------------------*/
/*
* ehci_work is called from some interrupts, timers, and so on.
* it calls driver completion functions, after dropping ehci->lock.
*/
static void ehci_work (struct ehci_hcd *ehci)
{
timer_action_done (ehci, TIMER_IO_WATCHDOG);
/* another CPU may drop ehci->lock during a schedule scan while
* it reports urb completions. this flag guards against bogus
* attempts at re-entrant schedule scanning.
*/
if (ehci->scanning)
return;
ehci->scanning = 1;
scan_async (ehci);
if (ehci->next_uframe != -1)
scan_periodic (ehci);
ehci->scanning = 0;
/* the IO watchdog guards against hardware or driver bugs that
* misplace IRQs, and should let us run completely without IRQs.
* such lossage has been observed on both VT6202 and VT8235.
*/
if (ehci->rh_state == EHCI_RH_RUNNING &&
(ehci->async->qh_next.ptr != NULL ||
ehci->periodic_sched != 0))
timer_action (ehci, TIMER_IO_WATCHDOG);
}
/*
* Called when the ehci_hcd module is removed.
*/
static void ehci_stop (struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
ehci_dbg (ehci, "stop\n");
/* no more interrupts ... */
del_timer_sync (&ehci->watchdog);
del_timer_sync(&ehci->iaa_watchdog);
spin_lock_irq(&ehci->lock);
if (ehci->rh_state == EHCI_RH_RUNNING)
ehci_quiesce (ehci);
ehci_silence_controller(ehci);
ehci_reset (ehci);
spin_unlock_irq(&ehci->lock);
remove_sysfs_files(ehci);
remove_debug_files (ehci);
/* root hub is shut down separately (first, when possible) */
spin_lock_irq (&ehci->lock);
if (ehci->async) {
/*
* TODO: Observed that ehci->async next ptr is not
* NULL sometimes which leads to crash in mem_cleanup.
* Root cause is not yet known why this messup is
* happenning.
* The follwing workaround fixes the crash caused
* by this temporarily.
* check if async next ptr is not NULL and unlink
* explictly.
*/
if (ehci->async->qh_next.ptr != NULL)
start_unlink_async(ehci, ehci->async->qh_next.qh);
ehci_work (ehci);
}
spin_unlock_irq (&ehci->lock);
ehci_mem_cleanup (ehci);
if (ehci->amd_pll_fix == 1)
usb_amd_dev_put();
#ifdef EHCI_STATS
ehci_dbg (ehci, "irq normal %ld err %ld reclaim %ld (lost %ld)\n",
ehci->stats.normal, ehci->stats.error, ehci->stats.reclaim,
ehci->stats.lost_iaa);
ehci_dbg (ehci, "complete %ld unlink %ld\n",
ehci->stats.complete, ehci->stats.unlink);
#endif
dbg_status (ehci, "ehci_stop completed",
ehci_readl(ehci, &ehci->regs->status));
}
/* one-time init, only for memory state */
static int ehci_init(struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
u32 temp;
int retval;
u32 hcc_params;
struct ehci_qh_hw *hw;
spin_lock_init(&ehci->lock);
/*
* keep io watchdog by default, those good HCDs could turn off it later
*/
ehci->need_io_watchdog = 1;
init_timer(&ehci->watchdog);
ehci->watchdog.function = ehci_watchdog;
ehci->watchdog.data = (unsigned long) ehci;
init_timer(&ehci->iaa_watchdog);
ehci->iaa_watchdog.function = ehci_iaa_watchdog;
ehci->iaa_watchdog.data = (unsigned long) ehci;
hcc_params = ehci_readl(ehci, &ehci->caps->hcc_params);
/*
* by default set standard 80% (== 100 usec/uframe) max periodic
* bandwidth as required by USB 2.0
*/
ehci->uframe_periodic_max = 100;
/*
* hw default: 1K periodic list heads, one per frame.
* periodic_size can shrink by USBCMD update if hcc_params allows.
*/
ehci->periodic_size = DEFAULT_I_TDPS;
INIT_LIST_HEAD(&ehci->cached_itd_list);
INIT_LIST_HEAD(&ehci->cached_sitd_list);
if (HCC_PGM_FRAMELISTLEN(hcc_params)) {
/* periodic schedule size can be smaller than default */
switch (EHCI_TUNE_FLS) {
case 0: ehci->periodic_size = 1024; break;
case 1: ehci->periodic_size = 512; break;
case 2: ehci->periodic_size = 256; break;
default: BUG();
}
}
if ((retval = ehci_mem_init(ehci, GFP_KERNEL)) < 0)
return retval;
/* controllers may cache some of the periodic schedule ... */
if (HCC_ISOC_CACHE(hcc_params)) // full frame cache
ehci->i_thresh = 2 + 8;
else // N microframes cached
ehci->i_thresh = 2 + HCC_ISOC_THRES(hcc_params);
ehci->reclaim = NULL;
ehci->next_uframe = -1;
ehci->clock_frame = -1;
/*
* dedicate a qh for the async ring head, since we couldn't unlink
* a 'real' qh without stopping the async schedule [4.8]. use it
* as the 'reclamation list head' too.
* its dummy is used in hw_alt_next of many tds, to prevent the qh
* from automatically advancing to the next td after short reads.
*/
ehci->async->qh_next.qh = NULL;
hw = ehci->async->hw;
hw->hw_next = QH_NEXT(ehci, ehci->async->qh_dma);
hw->hw_info1 = cpu_to_hc32(ehci, QH_HEAD);
#if defined(CONFIG_PPC_PS3)
hw->hw_info1 |= cpu_to_hc32(ehci, (1 << 7)); /* I = 1 */
#endif
hw->hw_token = cpu_to_hc32(ehci, QTD_STS_HALT);
hw->hw_qtd_next = EHCI_LIST_END(ehci);
ehci->async->qh_state = QH_STATE_LINKED;
hw->hw_alt_next = QTD_NEXT(ehci, ehci->async->dummy->qtd_dma);
/* clear interrupt enables, set irq latency */
log2_irq_thresh = ehci->log2_irq_thresh;
if (log2_irq_thresh < 0 || log2_irq_thresh > 6)
log2_irq_thresh = 0;
temp = 1 << (16 + log2_irq_thresh);
if (HCC_PER_PORT_CHANGE_EVENT(hcc_params)) {
ehci->has_ppcd = 1;
ehci_dbg(ehci, "enable per-port change event\n");
temp |= CMD_PPCEE;
}
if (HCC_CANPARK(hcc_params)) {
/* HW default park == 3, on hardware that supports it (like
* NVidia and ALI silicon), maximizes throughput on the async
* schedule by avoiding QH fetches between transfers.
*
* With fast usb storage devices and NForce2, "park" seems to
* make problems: throughput reduction (!), data errors...
*/
if (park) {
park = min(park, (unsigned) 3);
temp |= CMD_PARK;
temp |= park << 8;
}
ehci_dbg(ehci, "park %d\n", park);
}
if (HCC_PGM_FRAMELISTLEN(hcc_params)) {
/* periodic schedule size can be smaller than default */
temp &= ~(3 << 2);
temp |= (EHCI_TUNE_FLS << 2);
}
if (HCC_LPM(hcc_params)) {
/* support link power management EHCI 1.1 addendum */
ehci_dbg(ehci, "support lpm\n");
ehci->has_lpm = 1;
if (hird > 0xf) {
ehci_dbg(ehci, "hird %d invalid, use default 0",
hird);
hird = 0;
}
temp |= hird << 24;
}
ehci->command = temp;
/* Accept arbitrarily long scatter-gather lists */
if (!(hcd->driver->flags & HCD_LOCAL_MEM))
hcd->self.sg_tablesize = ~0;
return 0;
}
/* start HC running; it's halted, ehci_init() has been run (once) */
static int __maybe_unused ehci_run (struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
u32 temp;
u32 hcc_params;
hcd->uses_new_polling = 1;
/* EHCI spec section 4.1 */
ehci_writel(ehci, ehci->periodic_dma, &ehci->regs->frame_list);
ehci_writel(ehci, (u32)ehci->async->qh_dma, &ehci->regs->async_next);
/*
* hcc_params controls whether ehci->regs->segment must (!!!)
* be used; it constrains QH/ITD/SITD and QTD locations.
* pci_pool consistent memory always uses segment zero.
* streaming mappings for I/O buffers, like pci_map_single(),
* can return segments above 4GB, if the device allows.
*
* NOTE: the dma mask is visible through dma_supported(), so
* drivers can pass this info along ... like NETIF_F_HIGHDMA,
* Scsi_Host.highmem_io, and so forth. It's readonly to all
* host side drivers though.
*/
hcc_params = ehci_readl(ehci, &ehci->caps->hcc_params);
if (HCC_64BIT_ADDR(hcc_params)) {
ehci_writel(ehci, 0, &ehci->regs->segment);
#if 0
// this is deeply broken on almost all architectures
if (!dma_set_mask(hcd->self.controller, DMA_BIT_MASK(64)))
ehci_info(ehci, "enabled 64bit DMA\n");
#endif
}
// Philips, Intel, and maybe others need CMD_RUN before the
// root hub will detect new devices (why?); NEC doesn't
ehci->command &= ~(CMD_LRESET|CMD_IAAD|CMD_PSE|CMD_ASE|CMD_RESET);
ehci->command |= CMD_RUN;
ehci_writel(ehci, ehci->command, &ehci->regs->command);
dbg_cmd (ehci, "init", ehci->command);
/*
* Start, enabling full USB 2.0 functionality ... usb 1.1 devices
* are explicitly handed to companion controller(s), so no TT is
* involved with the root hub. (Except where one is integrated,
* and there's no companion controller unless maybe for USB OTG.)
*
* Turning on the CF flag will transfer ownership of all ports
* from the companions to the EHCI controller. If any of the
* companions are in the middle of a port reset at the time, it
* could cause trouble. Write-locking ehci_cf_port_reset_rwsem
* guarantees that no resets are in progress. After we set CF,
* a short delay lets the hardware catch up; new resets shouldn't
* be started before the port switching actions could complete.
*/
down_write(&ehci_cf_port_reset_rwsem);
ehci->rh_state = EHCI_RH_RUNNING;
ehci_writel(ehci, FLAG_CF, &ehci->regs->configured_flag);
ehci_readl(ehci, &ehci->regs->command); /* unblock posted writes */
msleep(5);
up_write(&ehci_cf_port_reset_rwsem);
ehci->last_periodic_enable = ktime_get_real();
temp = HC_VERSION(ehci, ehci_readl(ehci, &ehci->caps->hc_capbase));
ehci_info (ehci,
"USB %x.%x started, EHCI %x.%02x%s\n",
((ehci->sbrn & 0xf0)>>4), (ehci->sbrn & 0x0f),
temp >> 8, temp & 0xff,
ignore_oc ? ", overcurrent ignored" : "");
ehci_writel(ehci, INTR_MASK,
&ehci->regs->intr_enable); /* Turn On Interrupts */
/* GRR this is run-once init(), being done every time the HC starts.
* So long as they're part of class devices, we can't do it init()
* since the class device isn't created that early.
*/
create_debug_files(ehci);
create_sysfs_files(ehci);
return 0;
}
static int __maybe_unused ehci_setup (struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
int retval;
ehci->regs = (void __iomem *)ehci->caps +
HC_LENGTH(ehci, ehci_readl(ehci, &ehci->caps->hc_capbase));
dbg_hcs_params(ehci, "reset");
dbg_hcc_params(ehci, "reset");
/* cache this readonly data; minimize chip reads */
ehci->hcs_params = ehci_readl(ehci, &ehci->caps->hcs_params);
ehci->sbrn = HCD_USB2;
retval = ehci_halt(ehci);
if (retval)
return retval;
/* data structure init */
retval = ehci_init(hcd);
if (retval)
return retval;
ehci_reset(ehci);
return 0;
}
/*-------------------------------------------------------------------------*/
static irqreturn_t ehci_irq (struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
u32 status, masked_status, pcd_status = 0, cmd;
int bh;
spin_lock (&ehci->lock);
status = ehci_readl(ehci, &ehci->regs->status);
/* e.g. cardbus physical eject */
if (status == ~(u32) 0) {
ehci_dbg (ehci, "device removed\n");
goto dead;
}
/*
* We don't use STS_FLR, but some controllers don't like it to
* remain on, so mask it out along with the other status bits.
*/
masked_status = status & (INTR_MASK | STS_FLR);
/* Shared IRQ? */
if (!masked_status || unlikely(ehci->rh_state == EHCI_RH_HALTED)) {
spin_unlock(&ehci->lock);
return IRQ_NONE;
}
/* clear (just) interrupts */
ehci_writel(ehci, masked_status, &ehci->regs->status);
cmd = ehci_readl(ehci, &ehci->regs->command);
bh = 0;
#ifdef VERBOSE_DEBUG
/* unrequested/ignored: Frame List Rollover */
dbg_status (ehci, "irq", status);
#endif
/* INT, ERR, and IAA interrupt rates can be throttled */
/* normal [4.15.1.2] or error [4.15.1.1] completion */
if (likely ((status & (STS_INT|STS_ERR)) != 0)) {
if (likely ((status & STS_ERR) == 0))
COUNT (ehci->stats.normal);
else
COUNT (ehci->stats.error);
bh = 1;
}
/* complete the unlinking of some qh [4.15.2.3] */
if (status & STS_IAA) {
/* guard against (alleged) silicon errata */
if (cmd & CMD_IAAD) {
ehci_writel(ehci, cmd & ~CMD_IAAD,
&ehci->regs->command);
ehci_dbg(ehci, "IAA with IAAD still set?\n");
}
if (ehci->reclaim) {
COUNT(ehci->stats.reclaim);
end_unlink_async(ehci);
} else
ehci_dbg(ehci, "IAA with nothing to reclaim?\n");
}
/* remote wakeup [4.3.1] */
if (status & STS_PCD) {
unsigned i = HCS_N_PORTS (ehci->hcs_params);
u32 ppcd = 0;
/* kick root hub later */
pcd_status = status;
/* resume root hub? */
if (ehci->rh_state == EHCI_RH_SUSPENDED)
usb_hcd_resume_root_hub(hcd);
/* get per-port change detect bits */
if (ehci->has_ppcd)
ppcd = status >> 16;
while (i--) {
int pstatus;
/* leverage per-port change bits feature */
if (ehci->has_ppcd && !(ppcd & (1 << i)))
continue;
pstatus = ehci_readl(ehci,
&ehci->regs->port_status[i]);
/*set RS bit in case of remote wakeup*/
if (ehci_is_TDI(ehci) && !(cmd & CMD_RUN) &&
(pstatus & PORT_SUSPEND))
ehci_writel(ehci, cmd | CMD_RUN,
&ehci->regs->command);
if (pstatus & PORT_OWNER)
continue;
if (!(test_bit(i, &ehci->suspended_ports) &&
((pstatus & PORT_RESUME) ||
!(pstatus & PORT_SUSPEND)) &&
(pstatus & PORT_PE) &&
ehci->reset_done[i] == 0))
continue;
/* start 20 msec resume signaling from this port,
* and make khubd collect PORT_STAT_C_SUSPEND to
* stop that signaling. Use 5 ms extra for safety,
* like usb_port_resume() does.
*/
ehci->reset_done[i] = jiffies + msecs_to_jiffies(25);
set_bit(i, &ehci->resuming_ports);
ehci_dbg (ehci, "port %d remote wakeup\n", i + 1);
mod_timer(&hcd->rh_timer, ehci->reset_done[i]);
}
}
/* PCI errors [4.15.2.4] */
if (unlikely ((status & STS_FATAL) != 0)) {
ehci_err(ehci, "fatal error\n");
if (hcd->driver->dump_regs)
hcd->driver->dump_regs(hcd);
panic("System error\n");
dbg_cmd(ehci, "fatal", cmd);
dbg_status(ehci, "fatal", status);
ehci_halt(ehci);
dead:
ehci_reset(ehci);
ehci_writel(ehci, 0, &ehci->regs->configured_flag);
usb_hc_died(hcd);
/* generic layer kills/unlinks all urbs, then
* uses ehci_stop to clean up the rest
*/
bh = 1;
}
if (bh)
ehci_work (ehci);
spin_unlock (&ehci->lock);
if (pcd_status)
usb_hcd_poll_rh_status(hcd);
return IRQ_HANDLED;
}
/*-------------------------------------------------------------------------*/
/*
* non-error returns are a promise to giveback() the urb later
* we drop ownership so next owner (or urb unlink) can get it
*
* urb + dev is in hcd.self.controller.urb_list
* we're queueing TDs onto software and hardware lists
*
* hcd-specific init for hcpriv hasn't been done yet
*
* NOTE: control, bulk, and interrupt share the same code to append TDs
* to a (possibly active) QH, and the same QH scanning code.
*/
static int ehci_urb_enqueue (
struct usb_hcd *hcd,
struct urb *urb,
gfp_t mem_flags
) {
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
struct list_head qtd_list;
INIT_LIST_HEAD (&qtd_list);
switch (usb_pipetype (urb->pipe)) {
case PIPE_CONTROL:
/* qh_completions() code doesn't handle all the fault cases
* in multi-TD control transfers. Even 1KB is rare anyway.
*/
if (urb->transfer_buffer_length > (16 * 1024))
return -EMSGSIZE;
/* FALLTHROUGH */
/* case PIPE_BULK: */
default:
if (!qh_urb_transaction (ehci, urb, &qtd_list, mem_flags))
return -ENOMEM;
return submit_async(ehci, urb, &qtd_list, mem_flags);
case PIPE_INTERRUPT:
if (!qh_urb_transaction (ehci, urb, &qtd_list, mem_flags))
return -ENOMEM;
return intr_submit(ehci, urb, &qtd_list, mem_flags);
case PIPE_ISOCHRONOUS:
if (urb->dev->speed == USB_SPEED_HIGH)
return itd_submit (ehci, urb, mem_flags);
else
return sitd_submit (ehci, urb, mem_flags);
}
}
static void unlink_async (struct ehci_hcd *ehci, struct ehci_qh *qh)
{
/* failfast */
if (ehci->rh_state != EHCI_RH_RUNNING && ehci->reclaim)
end_unlink_async(ehci);
/* If the QH isn't linked then there's nothing we can do
* unless we were called during a giveback, in which case
* qh_completions() has to deal with it.
*/
if (qh->qh_state != QH_STATE_LINKED) {
if (qh->qh_state == QH_STATE_COMPLETING)
qh->needs_rescan = 1;
return;
}
/* defer till later if busy */
if (ehci->reclaim) {
struct ehci_qh *last;
for (last = ehci->reclaim;
last->reclaim;
last = last->reclaim)
continue;
qh->qh_state = QH_STATE_UNLINK_WAIT;
last->reclaim = qh;
/* start IAA cycle */
} else
start_unlink_async (ehci, qh);
}
/* remove from hardware lists
* completions normally happen asynchronously
*/
static int ehci_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
{
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
struct ehci_qh *qh;
unsigned long flags;
int rc;
spin_lock_irqsave (&ehci->lock, flags);
rc = usb_hcd_check_unlink_urb(hcd, urb, status);
if (rc)
goto done;
switch (usb_pipetype (urb->pipe)) {
// case PIPE_CONTROL:
// case PIPE_BULK:
default:
qh = (struct ehci_qh *) urb->hcpriv;
if (!qh)
break;
switch (qh->qh_state) {
case QH_STATE_LINKED:
case QH_STATE_COMPLETING:
unlink_async(ehci, qh);
break;
case QH_STATE_UNLINK:
case QH_STATE_UNLINK_WAIT:
/* already started */
break;
case QH_STATE_IDLE:
/* QH might be waiting for a Clear-TT-Buffer */
qh_completions(ehci, qh);
break;
}
break;
case PIPE_INTERRUPT:
qh = (struct ehci_qh *) urb->hcpriv;
if (!qh)
break;
switch (qh->qh_state) {
case QH_STATE_LINKED:
case QH_STATE_COMPLETING:
intr_deschedule (ehci, qh);
break;
case QH_STATE_IDLE:
qh_completions (ehci, qh);
break;
default:
ehci_dbg (ehci, "bogus qh %p state %d\n",
qh, qh->qh_state);
goto done;
}
break;
case PIPE_ISOCHRONOUS:
// itd or sitd ...
// wait till next completion, do it then.
// completion irqs can wait up to 1024 msec,
break;
}
done:
spin_unlock_irqrestore (&ehci->lock, flags);
return rc;
}
/*-------------------------------------------------------------------------*/
// bulk qh holds the data toggle
static void
ehci_endpoint_disable (struct usb_hcd *hcd, struct usb_host_endpoint *ep)
{
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
unsigned long flags;
struct ehci_qh *qh, *tmp;
/* ASSERT: any requests/urbs are being unlinked */
/* ASSERT: nobody can be submitting urbs for this any more */
rescan:
spin_lock_irqsave (&ehci->lock, flags);
qh = ep->hcpriv;
if (!qh)
goto done;
/* endpoints can be iso streams. for now, we don't
* accelerate iso completions ... so spin a while.
*/
if (qh->hw == NULL) {
ehci_vdbg (ehci, "iso delay\n");
goto idle_timeout;
}
if (ehci->rh_state != EHCI_RH_RUNNING)
qh->qh_state = QH_STATE_IDLE;
switch (qh->qh_state) {
case QH_STATE_LINKED:
case QH_STATE_COMPLETING:
for (tmp = ehci->async->qh_next.qh;
tmp && tmp != qh;
tmp = tmp->qh_next.qh)
continue;
/* periodic qh self-unlinks on empty, and a COMPLETING qh
* may already be unlinked.
*/
if (tmp)
unlink_async(ehci, qh);
/* FALL THROUGH */
case QH_STATE_UNLINK: /* wait for hw to finish? */
case QH_STATE_UNLINK_WAIT:
idle_timeout:
spin_unlock_irqrestore (&ehci->lock, flags);
schedule_timeout_uninterruptible(1);
goto rescan;
case QH_STATE_IDLE: /* fully unlinked */
if (qh->clearing_tt)
goto idle_timeout;
if (list_empty (&qh->qtd_list)) {
qh_put (qh);
break;
}
/* else FALL THROUGH */
default:
/* caller was supposed to have unlinked any requests;
* that's not our job. just leak this memory.
*/
ehci_err (ehci, "qh %p (#%02x) state %d%s\n",
qh, ep->desc.bEndpointAddress, qh->qh_state,
list_empty (&qh->qtd_list) ? "" : "(has tds)");
break;
}
ep->hcpriv = NULL;
done:
spin_unlock_irqrestore (&ehci->lock, flags);
}
static void __maybe_unused
ehci_endpoint_reset(struct usb_hcd *hcd, struct usb_host_endpoint *ep)
{
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
struct ehci_qh *qh;
int eptype = usb_endpoint_type(&ep->desc);
int epnum = usb_endpoint_num(&ep->desc);
int is_out = usb_endpoint_dir_out(&ep->desc);
unsigned long flags;
if (eptype != USB_ENDPOINT_XFER_BULK && eptype != USB_ENDPOINT_XFER_INT)
return;
spin_lock_irqsave(&ehci->lock, flags);
qh = ep->hcpriv;
/* For Bulk and Interrupt endpoints we maintain the toggle state
* in the hardware; the toggle bits in udev aren't used at all.
* When an endpoint is reset by usb_clear_halt() we must reset
* the toggle bit in the QH.
*/
if (qh) {
usb_settoggle(qh->dev, epnum, is_out, 0);
if (!list_empty(&qh->qtd_list)) {
WARN_ONCE(1, "clear_halt for a busy endpoint\n");
} else if (qh->qh_state == QH_STATE_LINKED ||
qh->qh_state == QH_STATE_COMPLETING) {
/* The toggle value in the QH can't be updated
* while the QH is active. Unlink it now;
* re-linking will call qh_refresh().
*/
if (eptype == USB_ENDPOINT_XFER_BULK)
unlink_async(ehci, qh);
else
intr_deschedule(ehci, qh);
}
}
spin_unlock_irqrestore(&ehci->lock, flags);
}
static int ehci_get_frame (struct usb_hcd *hcd)
{
struct ehci_hcd *ehci = hcd_to_ehci (hcd);
return (ehci_read_frame_index(ehci) >> 3) % ehci->periodic_size;
}
/*-------------------------------------------------------------------------*/
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_AUTHOR (DRIVER_AUTHOR);
MODULE_LICENSE ("GPL");
#ifdef CONFIG_PCI
#include "ehci-pci.c"
#define PCI_DRIVER ehci_pci_driver
#endif
#ifdef CONFIG_PPC_PS3
#include "ehci-ps3.c"
#define PS3_SYSTEM_BUS_DRIVER ps3_ehci_driver
#endif
#ifdef CONFIG_USB_EHCI_HCD_PPC_OF
#include "ehci-ppc-of.c"
#define OF_PLATFORM_DRIVER ehci_hcd_ppc_of_driver
#endif
#ifdef CONFIG_XPS_USB_HCD_XILINX
#include "ehci-xilinx-of.c"
#define XILINX_OF_PLATFORM_DRIVER ehci_hcd_xilinx_of_driver
#endif
#ifdef CONFIG_USB_EHCI_FSL
#include "ehci-fsl.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_MXC
#include "ehci-mxc.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_SH
#include "ehci-sh.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_MIPS_ALCHEMY
#include "ehci-au1xxx.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_HCD_OMAP
#include "ehci-omap.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_PLAT_ORION
#include "ehci-orion.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_ARCH_IXP4XX
#include "ehci-ixp4xx.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_W90X900_EHCI
#include "ehci-w90x900.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_ARCH_AT91
#include "ehci-atmel.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_OCTEON_EHCI
#include "ehci-octeon.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_CNS3XXX_EHCI
#include "ehci-cns3xxx.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_ARCH_VT8500
#include "ehci-vt8500.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_PLAT_SPEAR
#include "ehci-spear.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_MSM_72K
#include "ehci-msm72k.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_MSM
#include "ehci-msm.c"
#include "ehci-msm2.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_HCD_PMC_MSP
#include "ehci-pmcmsp.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_TEGRA
#include "ehci-tegra.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_S5P
#include "ehci-s5p.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_ATH79
#include "ehci-ath79.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_SPARC_LEON
#include "ehci-grlib.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_MSM_HSIC
#include "ehci-msm-hsic.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_PXA168_EHCI
#include "ehci-pxa168.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_CPU_XLR
#include "ehci-xls.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_MV
#include "ehci-mv.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_MACH_LOONGSON1
#include "ehci-ls1x.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#ifdef CONFIG_USB_EHCI_HCD_PLATFORM
#include "ehci-platform.c"
#define PLATFORM_DRIVER_PRESENT
#endif
#if !defined(PCI_DRIVER) && !defined(PLATFORM_DRIVER_PRESENT) && \
!defined(PS3_SYSTEM_BUS_DRIVER) && !defined(OF_PLATFORM_DRIVER) && \
!defined(XILINX_OF_PLATFORM_DRIVER)
#error "missing bus glue for ehci-hcd"
#endif
static struct platform_driver *plat_drivers[] = {
#ifdef CONFIG_USB_EHCI_FSL
&ehci_fsl_driver,
#endif
#ifdef CONFIG_USB_EHCI_MXC
&ehci_mxc_driver,
#endif
#ifdef CONFIG_CPU_SUBTYPE_SH7786
&ehci_hcd_sh_driver,
#endif
#ifdef CONFIG_SOC_AU1200
&ehci_hcd_au1xxx_driver,
#endif
#ifdef CONFIG_USB_EHCI_HCD_OMAP
&ehci_hcd_omap_driver,
#endif
#ifdef CONFIG_PLAT_ORION
&ehci_orion_driver,
#endif
#ifdef CONFIG_ARCH_IXP4XX
&ixp4xx_ehci_driver,
#endif
#ifdef CONFIG_USB_W90X900_EHCI
&ehci_hcd_w90x900_driver,
#endif
#ifdef CONFIG_ARCH_AT91
&ehci_atmel_driver,
#endif
#ifdef CONFIG_USB_OCTEON_EHCI
&ehci_octeon_driver,
#endif
#ifdef CONFIG_USB_CNS3XXX_EHCI
&cns3xxx_ehci_driver,
#endif
#ifdef CONFIG_ARCH_VT8500
&vt8500_ehci_driver,
#endif
#ifdef CONFIG_PLAT_SPEAR
&spear_ehci_hcd_driver,
#endif
#ifdef CONFIG_USB_EHCI_HCD_PMC_MSP
&ehci_hcd_msp_driver
#endif
#ifdef CONFIG_USB_EHCI_TEGRA
&tegra_ehci_driver
#endif
#ifdef CONFIG_USB_EHCI_S5P
&s5p_ehci_driver
#endif
#ifdef CONFIG_USB_EHCI_ATH79
&ehci_ath79_driver
#endif
#ifdef CONFIG_SPARC_LEON
&ehci_grlib_driver
#endif
#if defined(CONFIG_USB_EHCI_MSM_72K) || defined(CONFIG_USB_EHCI_MSM)
&ehci_msm_driver,
#endif
#ifdef CONFIG_USB_EHCI_MSM_HSIC
&ehci_msm_hsic_driver,
#endif
#ifdef CONFIG_USB_EHCI_MSM
&ehci_msm2_driver,
#endif
#ifdef CONFIG_USB_PXA168_EHCI
&ehci_pxa168_driver,
#endif
#ifdef CONFIG_CPU_XLR
&ehci_xls_driver,
#endif
#ifdef CONFIG_USB_EHCI_MV
&ehci_mv_driver,
#endif
#ifdef CONFIG_MACH_LOONGSON1
&ehci_ls1x_driver,
#endif
#ifdef CONFIG_USB_EHCI_HCD_PLATFORM
&ehci_platform_driver,
#endif
};
static int __init ehci_hcd_init(void)
{
int i, retval = 0;
if (usb_disabled())
return -ENODEV;
printk(KERN_INFO "%s: " DRIVER_DESC "\n", hcd_name);
set_bit(USB_EHCI_LOADED, &usb_hcds_loaded);
if (test_bit(USB_UHCI_LOADED, &usb_hcds_loaded) ||
test_bit(USB_OHCI_LOADED, &usb_hcds_loaded))
printk(KERN_WARNING "Warning! ehci_hcd should always be loaded"
" before uhci_hcd and ohci_hcd, not after\n");
pr_debug("%s: block sizes: qh %Zd qtd %Zd itd %Zd sitd %Zd\n",
hcd_name,
sizeof(struct ehci_qh), sizeof(struct ehci_qtd),
sizeof(struct ehci_itd), sizeof(struct ehci_sitd));
#ifdef DEBUG
ehci_debug_root = debugfs_create_dir("ehci", usb_debug_root);
if (!ehci_debug_root) {
retval = -ENOENT;
goto err_debug;
}
#endif
for (i = 0; i < ARRAY_SIZE(plat_drivers); i++) {
retval = platform_driver_register(plat_drivers[i]);
if (retval) {
while (--i >= 0)
platform_driver_unregister(plat_drivers[i]);
goto clean0;
}
}
#ifdef PCI_DRIVER
retval = pci_register_driver(&PCI_DRIVER);
if (retval < 0)
goto clean1;
#endif
#ifdef PS3_SYSTEM_BUS_DRIVER
retval = ps3_ehci_driver_register(&PS3_SYSTEM_BUS_DRIVER);
if (retval < 0)
goto clean2;
#endif
#ifdef OF_PLATFORM_DRIVER
retval = platform_driver_register(&OF_PLATFORM_DRIVER);
if (retval < 0)
goto clean3;
#endif
#ifdef XILINX_OF_PLATFORM_DRIVER
retval = platform_driver_register(&XILINX_OF_PLATFORM_DRIVER);
if (retval < 0)
goto clean4;
#endif
return retval;
#ifdef XILINX_OF_PLATFORM_DRIVER
/* platform_driver_unregister(&XILINX_OF_PLATFORM_DRIVER); */
clean4:
#endif
#ifdef OF_PLATFORM_DRIVER
platform_driver_unregister(&OF_PLATFORM_DRIVER);
clean3:
#endif
#ifdef PS3_SYSTEM_BUS_DRIVER
ps3_ehci_driver_unregister(&PS3_SYSTEM_BUS_DRIVER);
clean2:
#endif
#ifdef PCI_DRIVER
pci_unregister_driver(&PCI_DRIVER);
clean1:
#endif
for (i = 0; i < ARRAY_SIZE(plat_drivers); i++)
platform_driver_unregister(plat_drivers[i]);
clean0:
#ifdef DEBUG
debugfs_remove(ehci_debug_root);
ehci_debug_root = NULL;
err_debug:
#endif
clear_bit(USB_EHCI_LOADED, &usb_hcds_loaded);
return retval;
}
module_init(ehci_hcd_init);
static void __exit ehci_hcd_cleanup(void)
{
int i;
#ifdef XILINX_OF_PLATFORM_DRIVER
platform_driver_unregister(&XILINX_OF_PLATFORM_DRIVER);
#endif
#ifdef OF_PLATFORM_DRIVER
platform_driver_unregister(&OF_PLATFORM_DRIVER);
#endif
for (i = 0; i < ARRAY_SIZE(plat_drivers); i++)
platform_driver_unregister(plat_drivers[i]);
#ifdef PCI_DRIVER
pci_unregister_driver(&PCI_DRIVER);
#endif
#ifdef PS3_SYSTEM_BUS_DRIVER
ps3_ehci_driver_unregister(&PS3_SYSTEM_BUS_DRIVER);
#endif
#ifdef DEBUG
debugfs_remove(ehci_debug_root);
#endif
clear_bit(USB_EHCI_LOADED, &usb_hcds_loaded);
}
module_exit(ehci_hcd_cleanup);
| gpl-2.0 |
gem5/linux-arm-gem5 | kernel/debug/kdb/kdb_bp.c | 991 | 11230 | /*
* Kernel Debugger Architecture Independent Breakpoint Handler
*
* 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) 1999-2004 Silicon Graphics, Inc. All Rights Reserved.
* Copyright (c) 2009 Wind River Systems, Inc. All Rights Reserved.
*/
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/kdb.h>
#include <linux/kgdb.h>
#include <linux/smp.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include "kdb_private.h"
/*
* Table of kdb_breakpoints
*/
kdb_bp_t kdb_breakpoints[KDB_MAXBPT];
static void kdb_setsinglestep(struct pt_regs *regs)
{
KDB_STATE_SET(DOING_SS);
}
static char *kdb_rwtypes[] = {
"Instruction(i)",
"Instruction(Register)",
"Data Write",
"I/O",
"Data Access"
};
static char *kdb_bptype(kdb_bp_t *bp)
{
if (bp->bp_type < 0 || bp->bp_type > 4)
return "";
return kdb_rwtypes[bp->bp_type];
}
static int kdb_parsebp(int argc, const char **argv, int *nextargp, kdb_bp_t *bp)
{
int nextarg = *nextargp;
int diag;
bp->bph_length = 1;
if ((argc + 1) != nextarg) {
if (strncasecmp(argv[nextarg], "datar", sizeof("datar")) == 0)
bp->bp_type = BP_ACCESS_WATCHPOINT;
else if (strncasecmp(argv[nextarg], "dataw", sizeof("dataw")) == 0)
bp->bp_type = BP_WRITE_WATCHPOINT;
else if (strncasecmp(argv[nextarg], "inst", sizeof("inst")) == 0)
bp->bp_type = BP_HARDWARE_BREAKPOINT;
else
return KDB_ARGCOUNT;
bp->bph_length = 1;
nextarg++;
if ((argc + 1) != nextarg) {
unsigned long len;
diag = kdbgetularg((char *)argv[nextarg],
&len);
if (diag)
return diag;
if (len > 8)
return KDB_BADLENGTH;
bp->bph_length = len;
nextarg++;
}
if ((argc + 1) != nextarg)
return KDB_ARGCOUNT;
}
*nextargp = nextarg;
return 0;
}
static int _kdb_bp_remove(kdb_bp_t *bp)
{
int ret = 1;
if (!bp->bp_installed)
return ret;
if (!bp->bp_type)
ret = dbg_remove_sw_break(bp->bp_addr);
else
ret = arch_kgdb_ops.remove_hw_breakpoint(bp->bp_addr,
bp->bph_length,
bp->bp_type);
if (ret == 0)
bp->bp_installed = 0;
return ret;
}
static void kdb_handle_bp(struct pt_regs *regs, kdb_bp_t *bp)
{
if (KDB_DEBUG(BP))
kdb_printf("regs->ip = 0x%lx\n", instruction_pointer(regs));
/*
* Setup single step
*/
kdb_setsinglestep(regs);
/*
* Reset delay attribute
*/
bp->bp_delay = 0;
bp->bp_delayed = 1;
}
static int _kdb_bp_install(struct pt_regs *regs, kdb_bp_t *bp)
{
int ret;
/*
* Install the breakpoint, if it is not already installed.
*/
if (KDB_DEBUG(BP))
kdb_printf("%s: bp_installed %d\n",
__func__, bp->bp_installed);
if (!KDB_STATE(SSBPT))
bp->bp_delay = 0;
if (bp->bp_installed)
return 1;
if (bp->bp_delay || (bp->bp_delayed && KDB_STATE(DOING_SS))) {
if (KDB_DEBUG(BP))
kdb_printf("%s: delayed bp\n", __func__);
kdb_handle_bp(regs, bp);
return 0;
}
if (!bp->bp_type)
ret = dbg_set_sw_break(bp->bp_addr);
else
ret = arch_kgdb_ops.set_hw_breakpoint(bp->bp_addr,
bp->bph_length,
bp->bp_type);
if (ret == 0) {
bp->bp_installed = 1;
} else {
kdb_printf("%s: failed to set breakpoint at 0x%lx\n",
__func__, bp->bp_addr);
#ifdef CONFIG_DEBUG_RODATA
if (!bp->bp_type) {
kdb_printf("Software breakpoints are unavailable.\n"
" Change the kernel CONFIG_DEBUG_RODATA=n\n"
" OR use hw breaks: help bph\n");
}
#endif
return 1;
}
return 0;
}
/*
* kdb_bp_install
*
* Install kdb_breakpoints prior to returning from the
* kernel debugger. This allows the kdb_breakpoints to be set
* upon functions that are used internally by kdb, such as
* printk(). This function is only called once per kdb session.
*/
void kdb_bp_install(struct pt_regs *regs)
{
int i;
for (i = 0; i < KDB_MAXBPT; i++) {
kdb_bp_t *bp = &kdb_breakpoints[i];
if (KDB_DEBUG(BP)) {
kdb_printf("%s: bp %d bp_enabled %d\n",
__func__, i, bp->bp_enabled);
}
if (bp->bp_enabled)
_kdb_bp_install(regs, bp);
}
}
/*
* kdb_bp_remove
*
* Remove kdb_breakpoints upon entry to the kernel debugger.
*
* Parameters:
* None.
* Outputs:
* None.
* Returns:
* None.
* Locking:
* None.
* Remarks:
*/
void kdb_bp_remove(void)
{
int i;
for (i = KDB_MAXBPT - 1; i >= 0; i--) {
kdb_bp_t *bp = &kdb_breakpoints[i];
if (KDB_DEBUG(BP)) {
kdb_printf("%s: bp %d bp_enabled %d\n",
__func__, i, bp->bp_enabled);
}
if (bp->bp_enabled)
_kdb_bp_remove(bp);
}
}
/*
* kdb_printbp
*
* Internal function to format and print a breakpoint entry.
*
* Parameters:
* None.
* Outputs:
* None.
* Returns:
* None.
* Locking:
* None.
* Remarks:
*/
static void kdb_printbp(kdb_bp_t *bp, int i)
{
kdb_printf("%s ", kdb_bptype(bp));
kdb_printf("BP #%d at ", i);
kdb_symbol_print(bp->bp_addr, NULL, KDB_SP_DEFAULT);
if (bp->bp_enabled)
kdb_printf("\n is enabled");
else
kdb_printf("\n is disabled");
kdb_printf("\taddr at %016lx, hardtype=%d installed=%d\n",
bp->bp_addr, bp->bp_type, bp->bp_installed);
kdb_printf("\n");
}
/*
* kdb_bp
*
* Handle the bp commands.
*
* [bp|bph] <addr-expression> [DATAR|DATAW]
*
* Parameters:
* argc Count of arguments in argv
* argv Space delimited command line arguments
* Outputs:
* None.
* Returns:
* Zero for success, a kdb diagnostic if failure.
* Locking:
* None.
* Remarks:
*
* bp Set breakpoint on all cpus. Only use hardware assist if need.
* bph Set breakpoint on all cpus. Force hardware register
*/
static int kdb_bp(int argc, const char **argv)
{
int i, bpno;
kdb_bp_t *bp, *bp_check;
int diag;
char *symname = NULL;
long offset = 0ul;
int nextarg;
kdb_bp_t template = {0};
if (argc == 0) {
/*
* Display breakpoint table
*/
for (bpno = 0, bp = kdb_breakpoints; bpno < KDB_MAXBPT;
bpno++, bp++) {
if (bp->bp_free)
continue;
kdb_printbp(bp, bpno);
}
return 0;
}
nextarg = 1;
diag = kdbgetaddrarg(argc, argv, &nextarg, &template.bp_addr,
&offset, &symname);
if (diag)
return diag;
if (!template.bp_addr)
return KDB_BADINT;
/*
* Find an empty bp structure to allocate
*/
for (bpno = 0, bp = kdb_breakpoints; bpno < KDB_MAXBPT; bpno++, bp++) {
if (bp->bp_free)
break;
}
if (bpno == KDB_MAXBPT)
return KDB_TOOMANYBPT;
if (strcmp(argv[0], "bph") == 0) {
template.bp_type = BP_HARDWARE_BREAKPOINT;
diag = kdb_parsebp(argc, argv, &nextarg, &template);
if (diag)
return diag;
} else {
template.bp_type = BP_BREAKPOINT;
}
/*
* Check for clashing breakpoints.
*
* Note, in this design we can't have hardware breakpoints
* enabled for both read and write on the same address.
*/
for (i = 0, bp_check = kdb_breakpoints; i < KDB_MAXBPT;
i++, bp_check++) {
if (!bp_check->bp_free &&
bp_check->bp_addr == template.bp_addr) {
kdb_printf("You already have a breakpoint at "
kdb_bfd_vma_fmt0 "\n", template.bp_addr);
return KDB_DUPBPT;
}
}
template.bp_enabled = 1;
/*
* Actually allocate the breakpoint found earlier
*/
*bp = template;
bp->bp_free = 0;
kdb_printbp(bp, bpno);
return 0;
}
/*
* kdb_bc
*
* Handles the 'bc', 'be', and 'bd' commands
*
* [bd|bc|be] <breakpoint-number>
* [bd|bc|be] *
*
* Parameters:
* argc Count of arguments in argv
* argv Space delimited command line arguments
* Outputs:
* None.
* Returns:
* Zero for success, a kdb diagnostic for failure
* Locking:
* None.
* Remarks:
*/
static int kdb_bc(int argc, const char **argv)
{
unsigned long addr;
kdb_bp_t *bp = NULL;
int lowbp = KDB_MAXBPT;
int highbp = 0;
int done = 0;
int i;
int diag = 0;
int cmd; /* KDBCMD_B? */
#define KDBCMD_BC 0
#define KDBCMD_BE 1
#define KDBCMD_BD 2
if (strcmp(argv[0], "be") == 0)
cmd = KDBCMD_BE;
else if (strcmp(argv[0], "bd") == 0)
cmd = KDBCMD_BD;
else
cmd = KDBCMD_BC;
if (argc != 1)
return KDB_ARGCOUNT;
if (strcmp(argv[1], "*") == 0) {
lowbp = 0;
highbp = KDB_MAXBPT;
} else {
diag = kdbgetularg(argv[1], &addr);
if (diag)
return diag;
/*
* For addresses less than the maximum breakpoint number,
* assume that the breakpoint number is desired.
*/
if (addr < KDB_MAXBPT) {
bp = &kdb_breakpoints[addr];
lowbp = highbp = addr;
highbp++;
} else {
for (i = 0, bp = kdb_breakpoints; i < KDB_MAXBPT;
i++, bp++) {
if (bp->bp_addr == addr) {
lowbp = highbp = i;
highbp++;
break;
}
}
}
}
/*
* Now operate on the set of breakpoints matching the input
* criteria (either '*' for all, or an individual breakpoint).
*/
for (bp = &kdb_breakpoints[lowbp], i = lowbp;
i < highbp;
i++, bp++) {
if (bp->bp_free)
continue;
done++;
switch (cmd) {
case KDBCMD_BC:
bp->bp_enabled = 0;
kdb_printf("Breakpoint %d at "
kdb_bfd_vma_fmt " cleared\n",
i, bp->bp_addr);
bp->bp_addr = 0;
bp->bp_free = 1;
break;
case KDBCMD_BE:
bp->bp_enabled = 1;
kdb_printf("Breakpoint %d at "
kdb_bfd_vma_fmt " enabled",
i, bp->bp_addr);
kdb_printf("\n");
break;
case KDBCMD_BD:
if (!bp->bp_enabled)
break;
bp->bp_enabled = 0;
kdb_printf("Breakpoint %d at "
kdb_bfd_vma_fmt " disabled\n",
i, bp->bp_addr);
break;
}
if (bp->bp_delay && (cmd == KDBCMD_BC || cmd == KDBCMD_BD)) {
bp->bp_delay = 0;
KDB_STATE_CLEAR(SSBPT);
}
}
return (!done) ? KDB_BPTNOTFOUND : 0;
}
/*
* kdb_ss
*
* Process the 'ss' (Single Step) command.
*
* ss
*
* Parameters:
* argc Argument count
* argv Argument vector
* Outputs:
* None.
* Returns:
* KDB_CMD_SS for success, a kdb error if failure.
* Locking:
* None.
* Remarks:
*
* Set the arch specific option to trigger a debug trap after the next
* instruction.
*/
static int kdb_ss(int argc, const char **argv)
{
if (argc != 0)
return KDB_ARGCOUNT;
/*
* Set trace flag and go.
*/
KDB_STATE_SET(DOING_SS);
return KDB_CMD_SS;
}
/* Initialize the breakpoint table and register breakpoint commands. */
void __init kdb_initbptab(void)
{
int i;
kdb_bp_t *bp;
/*
* First time initialization.
*/
memset(&kdb_breakpoints, '\0', sizeof(kdb_breakpoints));
for (i = 0, bp = kdb_breakpoints; i < KDB_MAXBPT; i++, bp++)
bp->bp_free = 1;
kdb_register_flags("bp", kdb_bp, "[<vaddr>]",
"Set/Display breakpoints", 0,
KDB_ENABLE_FLOW_CTRL | KDB_REPEAT_NO_ARGS);
kdb_register_flags("bl", kdb_bp, "[<vaddr>]",
"Display breakpoints", 0,
KDB_ENABLE_FLOW_CTRL | KDB_REPEAT_NO_ARGS);
if (arch_kgdb_ops.flags & KGDB_HW_BREAKPOINT)
kdb_register_flags("bph", kdb_bp, "[<vaddr>]",
"[datar [length]|dataw [length]] Set hw brk", 0,
KDB_ENABLE_FLOW_CTRL | KDB_REPEAT_NO_ARGS);
kdb_register_flags("bc", kdb_bc, "<bpnum>",
"Clear Breakpoint", 0,
KDB_ENABLE_FLOW_CTRL);
kdb_register_flags("be", kdb_bc, "<bpnum>",
"Enable Breakpoint", 0,
KDB_ENABLE_FLOW_CTRL);
kdb_register_flags("bd", kdb_bc, "<bpnum>",
"Disable Breakpoint", 0,
KDB_ENABLE_FLOW_CTRL);
kdb_register_flags("ss", kdb_ss, "",
"Single Step", 1,
KDB_ENABLE_FLOW_CTRL | KDB_REPEAT_NO_ARGS);
/*
* Architecture dependent initialization.
*/
}
| gpl-2.0 |
richardtrip/Iconia_a500_3.2 | drivers/char/cs5535_gpio.c | 991 | 5951 | /*
* AMD CS5535/CS5536 GPIO driver.
* Allows a user space process to play with the GPIO pins.
*
* Copyright (c) 2005 Ben Gardner <bgardner@wabtec.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the smems of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*/
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/ioport.h>
#include <linux/pci.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#define NAME "cs5535_gpio"
MODULE_AUTHOR("Ben Gardner <bgardner@wabtec.com>");
MODULE_DESCRIPTION("AMD CS5535/CS5536 GPIO Pin Driver");
MODULE_LICENSE("GPL");
static int major;
module_param(major, int, 0);
MODULE_PARM_DESC(major, "Major device number");
static ulong mask;
module_param(mask, ulong, 0);
MODULE_PARM_DESC(mask, "GPIO channel mask");
#define MSR_LBAR_GPIO 0x5140000C
static u32 gpio_base;
static struct pci_device_id divil_pci[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_CS5535_ISA) },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_ISA) },
{ } /* NULL entry */
};
MODULE_DEVICE_TABLE(pci, divil_pci);
static struct cdev cs5535_gpio_cdev;
/* reserve 32 entries even though some aren't usable */
#define CS5535_GPIO_COUNT 32
/* IO block size */
#define CS5535_GPIO_SIZE 256
struct gpio_regmap {
u32 rd_offset;
u32 wr_offset;
char on;
char off;
};
static struct gpio_regmap rm[] =
{
{ 0x30, 0x00, '1', '0' }, /* GPIOx_READ_BACK / GPIOx_OUT_VAL */
{ 0x20, 0x20, 'I', 'i' }, /* GPIOx_IN_EN */
{ 0x04, 0x04, 'O', 'o' }, /* GPIOx_OUT_EN */
{ 0x08, 0x08, 't', 'T' }, /* GPIOx_OUT_OD_EN */
{ 0x18, 0x18, 'P', 'p' }, /* GPIOx_OUT_PU_EN */
{ 0x1c, 0x1c, 'D', 'd' }, /* GPIOx_OUT_PD_EN */
};
/**
* Gets the register offset for the GPIO bank.
* Low (0-15) starts at 0x00, high (16-31) starts at 0x80
*/
static inline u32 cs5535_lowhigh_base(int reg)
{
return (reg & 0x10) << 3;
}
static ssize_t cs5535_gpio_write(struct file *file, const char __user *data,
size_t len, loff_t *ppos)
{
u32 m = iminor(file->f_path.dentry->d_inode);
int i, j;
u32 base = gpio_base + cs5535_lowhigh_base(m);
u32 m0, m1;
char c;
/**
* Creates the mask for atomic bit programming.
* The high 16 bits and the low 16 bits are used to set the mask.
* For example, GPIO 15 maps to 31,15: 0,1 => On; 1,0=> Off
*/
m1 = 1 << (m & 0x0F);
m0 = m1 << 16;
for (i = 0; i < len; ++i) {
if (get_user(c, data+i))
return -EFAULT;
for (j = 0; j < ARRAY_SIZE(rm); j++) {
if (c == rm[j].on) {
outl(m1, base + rm[j].wr_offset);
/* If enabling output, turn off AUX 1 and AUX 2 */
if (c == 'O') {
outl(m0, base + 0x10);
outl(m0, base + 0x14);
}
break;
} else if (c == rm[j].off) {
outl(m0, base + rm[j].wr_offset);
break;
}
}
}
*ppos = 0;
return len;
}
static ssize_t cs5535_gpio_read(struct file *file, char __user *buf,
size_t len, loff_t *ppos)
{
u32 m = iminor(file->f_path.dentry->d_inode);
u32 base = gpio_base + cs5535_lowhigh_base(m);
int rd_bit = 1 << (m & 0x0f);
int i;
char ch;
ssize_t count = 0;
if (*ppos >= ARRAY_SIZE(rm))
return 0;
for (i = *ppos; (i < (*ppos + len)) && (i < ARRAY_SIZE(rm)); i++) {
ch = (inl(base + rm[i].rd_offset) & rd_bit) ?
rm[i].on : rm[i].off;
if (put_user(ch, buf+count))
return -EFAULT;
count++;
}
/* add a line-feed if there is room */
if ((i == ARRAY_SIZE(rm)) && (count < len)) {
put_user('\n', buf + count);
count++;
}
*ppos += count;
return count;
}
static int cs5535_gpio_open(struct inode *inode, struct file *file)
{
u32 m = iminor(inode);
/* the mask says which pins are usable by this driver */
if ((mask & (1 << m)) == 0)
return -EINVAL;
return nonseekable_open(inode, file);
}
static const struct file_operations cs5535_gpio_fops = {
.owner = THIS_MODULE,
.write = cs5535_gpio_write,
.read = cs5535_gpio_read,
.open = cs5535_gpio_open
};
static int __init cs5535_gpio_init(void)
{
dev_t dev_id;
u32 low, hi;
int retval;
if (pci_dev_present(divil_pci) == 0) {
printk(KERN_WARNING NAME ": DIVIL not found\n");
return -ENODEV;
}
/* Grab the GPIO I/O range */
rdmsr(MSR_LBAR_GPIO, low, hi);
/* Check the mask and whether GPIO is enabled (sanity check) */
if (hi != 0x0000f001) {
printk(KERN_WARNING NAME ": GPIO not enabled\n");
return -ENODEV;
}
/* Mask off the IO base address */
gpio_base = low & 0x0000ff00;
/**
* Some GPIO pins
* 31-29,23 : reserved (always mask out)
* 28 : Power Button
* 26 : PME#
* 22-16 : LPC
* 14,15 : SMBus
* 9,8 : UART1
* 7 : PCI INTB
* 3,4 : UART2/DDC
* 2 : IDE_IRQ0
* 0 : PCI INTA
*
* If a mask was not specified, be conservative and only allow:
* 1,2,5,6,10-13,24,25,27
*/
if (mask != 0)
mask &= 0x1f7fffff;
else
mask = 0x0b003c66;
if (!request_region(gpio_base, CS5535_GPIO_SIZE, NAME)) {
printk(KERN_ERR NAME ": can't allocate I/O for GPIO\n");
return -ENODEV;
}
if (major) {
dev_id = MKDEV(major, 0);
retval = register_chrdev_region(dev_id, CS5535_GPIO_COUNT,
NAME);
} else {
retval = alloc_chrdev_region(&dev_id, 0, CS5535_GPIO_COUNT,
NAME);
major = MAJOR(dev_id);
}
if (retval) {
release_region(gpio_base, CS5535_GPIO_SIZE);
return -1;
}
printk(KERN_DEBUG NAME ": base=%#x mask=%#lx major=%d\n",
gpio_base, mask, major);
cdev_init(&cs5535_gpio_cdev, &cs5535_gpio_fops);
cdev_add(&cs5535_gpio_cdev, dev_id, CS5535_GPIO_COUNT);
return 0;
}
static void __exit cs5535_gpio_cleanup(void)
{
dev_t dev_id = MKDEV(major, 0);
cdev_del(&cs5535_gpio_cdev);
unregister_chrdev_region(dev_id, CS5535_GPIO_COUNT);
release_region(gpio_base, CS5535_GPIO_SIZE);
}
module_init(cs5535_gpio_init);
module_exit(cs5535_gpio_cleanup);
| gpl-2.0 |
friedrich420/AEL_NOTE4_N910FXXU1ANK4 | drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c | 2271 | 22784 | /*******************************************************************************
STMMAC Ethtool support
Copyright (C) 2007-2009 STMicroelectronics Ltd
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 <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/interrupt.h>
#include <linux/mii.h>
#include <linux/phy.h>
#include <linux/net_tstamp.h>
#include <asm/io.h>
#include "stmmac.h"
#include "dwmac_dma.h"
#define REG_SPACE_SIZE 0x1054
#define MAC100_ETHTOOL_NAME "st_mac100"
#define GMAC_ETHTOOL_NAME "st_gmac"
struct stmmac_stats {
char stat_string[ETH_GSTRING_LEN];
int sizeof_stat;
int stat_offset;
};
#define STMMAC_STAT(m) \
{ #m, FIELD_SIZEOF(struct stmmac_extra_stats, m), \
offsetof(struct stmmac_priv, xstats.m)}
static const struct stmmac_stats stmmac_gstrings_stats[] = {
/* Transmit errors */
STMMAC_STAT(tx_underflow),
STMMAC_STAT(tx_carrier),
STMMAC_STAT(tx_losscarrier),
STMMAC_STAT(vlan_tag),
STMMAC_STAT(tx_deferred),
STMMAC_STAT(tx_vlan),
STMMAC_STAT(tx_jabber),
STMMAC_STAT(tx_frame_flushed),
STMMAC_STAT(tx_payload_error),
STMMAC_STAT(tx_ip_header_error),
/* Receive errors */
STMMAC_STAT(rx_desc),
STMMAC_STAT(sa_filter_fail),
STMMAC_STAT(overflow_error),
STMMAC_STAT(ipc_csum_error),
STMMAC_STAT(rx_collision),
STMMAC_STAT(rx_crc),
STMMAC_STAT(dribbling_bit),
STMMAC_STAT(rx_length),
STMMAC_STAT(rx_mii),
STMMAC_STAT(rx_multicast),
STMMAC_STAT(rx_gmac_overflow),
STMMAC_STAT(rx_watchdog),
STMMAC_STAT(da_rx_filter_fail),
STMMAC_STAT(sa_rx_filter_fail),
STMMAC_STAT(rx_missed_cntr),
STMMAC_STAT(rx_overflow_cntr),
STMMAC_STAT(rx_vlan),
/* Tx/Rx IRQ error info */
STMMAC_STAT(tx_undeflow_irq),
STMMAC_STAT(tx_process_stopped_irq),
STMMAC_STAT(tx_jabber_irq),
STMMAC_STAT(rx_overflow_irq),
STMMAC_STAT(rx_buf_unav_irq),
STMMAC_STAT(rx_process_stopped_irq),
STMMAC_STAT(rx_watchdog_irq),
STMMAC_STAT(tx_early_irq),
STMMAC_STAT(fatal_bus_error_irq),
/* Tx/Rx IRQ Events */
STMMAC_STAT(rx_early_irq),
STMMAC_STAT(threshold),
STMMAC_STAT(tx_pkt_n),
STMMAC_STAT(rx_pkt_n),
STMMAC_STAT(normal_irq_n),
STMMAC_STAT(rx_normal_irq_n),
STMMAC_STAT(napi_poll),
STMMAC_STAT(tx_normal_irq_n),
STMMAC_STAT(tx_clean),
STMMAC_STAT(tx_reset_ic_bit),
STMMAC_STAT(irq_receive_pmt_irq_n),
/* MMC info */
STMMAC_STAT(mmc_tx_irq_n),
STMMAC_STAT(mmc_rx_irq_n),
STMMAC_STAT(mmc_rx_csum_offload_irq_n),
/* EEE */
STMMAC_STAT(irq_tx_path_in_lpi_mode_n),
STMMAC_STAT(irq_tx_path_exit_lpi_mode_n),
STMMAC_STAT(irq_rx_path_in_lpi_mode_n),
STMMAC_STAT(irq_rx_path_exit_lpi_mode_n),
STMMAC_STAT(phy_eee_wakeup_error_n),
/* Extended RDES status */
STMMAC_STAT(ip_hdr_err),
STMMAC_STAT(ip_payload_err),
STMMAC_STAT(ip_csum_bypassed),
STMMAC_STAT(ipv4_pkt_rcvd),
STMMAC_STAT(ipv6_pkt_rcvd),
STMMAC_STAT(rx_msg_type_ext_no_ptp),
STMMAC_STAT(rx_msg_type_sync),
STMMAC_STAT(rx_msg_type_follow_up),
STMMAC_STAT(rx_msg_type_delay_req),
STMMAC_STAT(rx_msg_type_delay_resp),
STMMAC_STAT(rx_msg_type_pdelay_req),
STMMAC_STAT(rx_msg_type_pdelay_resp),
STMMAC_STAT(rx_msg_type_pdelay_follow_up),
STMMAC_STAT(ptp_frame_type),
STMMAC_STAT(ptp_ver),
STMMAC_STAT(timestamp_dropped),
STMMAC_STAT(av_pkt_rcvd),
STMMAC_STAT(av_tagged_pkt_rcvd),
STMMAC_STAT(vlan_tag_priority_val),
STMMAC_STAT(l3_filter_match),
STMMAC_STAT(l4_filter_match),
STMMAC_STAT(l3_l4_filter_no_match),
/* PCS */
STMMAC_STAT(irq_pcs_ane_n),
STMMAC_STAT(irq_pcs_link_n),
STMMAC_STAT(irq_rgmii_n),
};
#define STMMAC_STATS_LEN ARRAY_SIZE(stmmac_gstrings_stats)
/* HW MAC Management counters (if supported) */
#define STMMAC_MMC_STAT(m) \
{ #m, FIELD_SIZEOF(struct stmmac_counters, m), \
offsetof(struct stmmac_priv, mmc.m)}
static const struct stmmac_stats stmmac_mmc[] = {
STMMAC_MMC_STAT(mmc_tx_octetcount_gb),
STMMAC_MMC_STAT(mmc_tx_framecount_gb),
STMMAC_MMC_STAT(mmc_tx_broadcastframe_g),
STMMAC_MMC_STAT(mmc_tx_multicastframe_g),
STMMAC_MMC_STAT(mmc_tx_64_octets_gb),
STMMAC_MMC_STAT(mmc_tx_65_to_127_octets_gb),
STMMAC_MMC_STAT(mmc_tx_128_to_255_octets_gb),
STMMAC_MMC_STAT(mmc_tx_256_to_511_octets_gb),
STMMAC_MMC_STAT(mmc_tx_512_to_1023_octets_gb),
STMMAC_MMC_STAT(mmc_tx_1024_to_max_octets_gb),
STMMAC_MMC_STAT(mmc_tx_unicast_gb),
STMMAC_MMC_STAT(mmc_tx_multicast_gb),
STMMAC_MMC_STAT(mmc_tx_broadcast_gb),
STMMAC_MMC_STAT(mmc_tx_underflow_error),
STMMAC_MMC_STAT(mmc_tx_singlecol_g),
STMMAC_MMC_STAT(mmc_tx_multicol_g),
STMMAC_MMC_STAT(mmc_tx_deferred),
STMMAC_MMC_STAT(mmc_tx_latecol),
STMMAC_MMC_STAT(mmc_tx_exesscol),
STMMAC_MMC_STAT(mmc_tx_carrier_error),
STMMAC_MMC_STAT(mmc_tx_octetcount_g),
STMMAC_MMC_STAT(mmc_tx_framecount_g),
STMMAC_MMC_STAT(mmc_tx_excessdef),
STMMAC_MMC_STAT(mmc_tx_pause_frame),
STMMAC_MMC_STAT(mmc_tx_vlan_frame_g),
STMMAC_MMC_STAT(mmc_rx_framecount_gb),
STMMAC_MMC_STAT(mmc_rx_octetcount_gb),
STMMAC_MMC_STAT(mmc_rx_octetcount_g),
STMMAC_MMC_STAT(mmc_rx_broadcastframe_g),
STMMAC_MMC_STAT(mmc_rx_multicastframe_g),
STMMAC_MMC_STAT(mmc_rx_crc_errror),
STMMAC_MMC_STAT(mmc_rx_align_error),
STMMAC_MMC_STAT(mmc_rx_run_error),
STMMAC_MMC_STAT(mmc_rx_jabber_error),
STMMAC_MMC_STAT(mmc_rx_undersize_g),
STMMAC_MMC_STAT(mmc_rx_oversize_g),
STMMAC_MMC_STAT(mmc_rx_64_octets_gb),
STMMAC_MMC_STAT(mmc_rx_65_to_127_octets_gb),
STMMAC_MMC_STAT(mmc_rx_128_to_255_octets_gb),
STMMAC_MMC_STAT(mmc_rx_256_to_511_octets_gb),
STMMAC_MMC_STAT(mmc_rx_512_to_1023_octets_gb),
STMMAC_MMC_STAT(mmc_rx_1024_to_max_octets_gb),
STMMAC_MMC_STAT(mmc_rx_unicast_g),
STMMAC_MMC_STAT(mmc_rx_length_error),
STMMAC_MMC_STAT(mmc_rx_autofrangetype),
STMMAC_MMC_STAT(mmc_rx_pause_frames),
STMMAC_MMC_STAT(mmc_rx_fifo_overflow),
STMMAC_MMC_STAT(mmc_rx_vlan_frames_gb),
STMMAC_MMC_STAT(mmc_rx_watchdog_error),
STMMAC_MMC_STAT(mmc_rx_ipc_intr_mask),
STMMAC_MMC_STAT(mmc_rx_ipc_intr),
STMMAC_MMC_STAT(mmc_rx_ipv4_gd),
STMMAC_MMC_STAT(mmc_rx_ipv4_hderr),
STMMAC_MMC_STAT(mmc_rx_ipv4_nopay),
STMMAC_MMC_STAT(mmc_rx_ipv4_frag),
STMMAC_MMC_STAT(mmc_rx_ipv4_udsbl),
STMMAC_MMC_STAT(mmc_rx_ipv4_gd_octets),
STMMAC_MMC_STAT(mmc_rx_ipv4_hderr_octets),
STMMAC_MMC_STAT(mmc_rx_ipv4_nopay_octets),
STMMAC_MMC_STAT(mmc_rx_ipv4_frag_octets),
STMMAC_MMC_STAT(mmc_rx_ipv4_udsbl_octets),
STMMAC_MMC_STAT(mmc_rx_ipv6_gd_octets),
STMMAC_MMC_STAT(mmc_rx_ipv6_hderr_octets),
STMMAC_MMC_STAT(mmc_rx_ipv6_nopay_octets),
STMMAC_MMC_STAT(mmc_rx_ipv6_gd),
STMMAC_MMC_STAT(mmc_rx_ipv6_hderr),
STMMAC_MMC_STAT(mmc_rx_ipv6_nopay),
STMMAC_MMC_STAT(mmc_rx_udp_gd),
STMMAC_MMC_STAT(mmc_rx_udp_err),
STMMAC_MMC_STAT(mmc_rx_tcp_gd),
STMMAC_MMC_STAT(mmc_rx_tcp_err),
STMMAC_MMC_STAT(mmc_rx_icmp_gd),
STMMAC_MMC_STAT(mmc_rx_icmp_err),
STMMAC_MMC_STAT(mmc_rx_udp_gd_octets),
STMMAC_MMC_STAT(mmc_rx_udp_err_octets),
STMMAC_MMC_STAT(mmc_rx_tcp_gd_octets),
STMMAC_MMC_STAT(mmc_rx_tcp_err_octets),
STMMAC_MMC_STAT(mmc_rx_icmp_gd_octets),
STMMAC_MMC_STAT(mmc_rx_icmp_err_octets),
};
#define STMMAC_MMC_STATS_LEN ARRAY_SIZE(stmmac_mmc)
static void stmmac_ethtool_getdrvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct stmmac_priv *priv = netdev_priv(dev);
if (priv->plat->has_gmac)
strlcpy(info->driver, GMAC_ETHTOOL_NAME, sizeof(info->driver));
else
strlcpy(info->driver, MAC100_ETHTOOL_NAME,
sizeof(info->driver));
strlcpy(info->version, DRV_MODULE_VERSION, sizeof(info->version));
}
static int stmmac_ethtool_getsettings(struct net_device *dev,
struct ethtool_cmd *cmd)
{
struct stmmac_priv *priv = netdev_priv(dev);
struct phy_device *phy = priv->phydev;
int rc;
if ((priv->pcs & STMMAC_PCS_RGMII) || (priv->pcs & STMMAC_PCS_SGMII)) {
struct rgmii_adv adv;
if (!priv->xstats.pcs_link) {
ethtool_cmd_speed_set(cmd, SPEED_UNKNOWN);
cmd->duplex = DUPLEX_UNKNOWN;
return 0;
}
cmd->duplex = priv->xstats.pcs_duplex;
ethtool_cmd_speed_set(cmd, priv->xstats.pcs_speed);
/* Get and convert ADV/LP_ADV from the HW AN registers */
if (priv->hw->mac->get_adv)
priv->hw->mac->get_adv(priv->ioaddr, &adv);
else
return -EOPNOTSUPP; /* should never happen indeed */
/* Encoding of PSE bits is defined in 802.3z, 37.2.1.4 */
if (adv.pause & STMMAC_PCS_PAUSE)
cmd->advertising |= ADVERTISED_Pause;
if (adv.pause & STMMAC_PCS_ASYM_PAUSE)
cmd->advertising |= ADVERTISED_Asym_Pause;
if (adv.lp_pause & STMMAC_PCS_PAUSE)
cmd->lp_advertising |= ADVERTISED_Pause;
if (adv.lp_pause & STMMAC_PCS_ASYM_PAUSE)
cmd->lp_advertising |= ADVERTISED_Asym_Pause;
/* Reg49[3] always set because ANE is always supported */
cmd->autoneg = ADVERTISED_Autoneg;
cmd->supported |= SUPPORTED_Autoneg;
cmd->advertising |= ADVERTISED_Autoneg;
cmd->lp_advertising |= ADVERTISED_Autoneg;
if (adv.duplex) {
cmd->supported |= (SUPPORTED_1000baseT_Full |
SUPPORTED_100baseT_Full |
SUPPORTED_10baseT_Full);
cmd->advertising |= (ADVERTISED_1000baseT_Full |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Full);
} else {
cmd->supported |= (SUPPORTED_1000baseT_Half |
SUPPORTED_100baseT_Half |
SUPPORTED_10baseT_Half);
cmd->advertising |= (ADVERTISED_1000baseT_Half |
ADVERTISED_100baseT_Half |
ADVERTISED_10baseT_Half);
}
if (adv.lp_duplex)
cmd->lp_advertising |= (ADVERTISED_1000baseT_Full |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Full);
else
cmd->lp_advertising |= (ADVERTISED_1000baseT_Half |
ADVERTISED_100baseT_Half |
ADVERTISED_10baseT_Half);
cmd->port = PORT_OTHER;
return 0;
}
if (phy == NULL) {
pr_err("%s: %s: PHY is not registered\n",
__func__, dev->name);
return -ENODEV;
}
if (!netif_running(dev)) {
pr_err("%s: interface is disabled: we cannot track "
"link speed / duplex setting\n", dev->name);
return -EBUSY;
}
cmd->transceiver = XCVR_INTERNAL;
spin_lock_irq(&priv->lock);
rc = phy_ethtool_gset(phy, cmd);
spin_unlock_irq(&priv->lock);
return rc;
}
static int stmmac_ethtool_setsettings(struct net_device *dev,
struct ethtool_cmd *cmd)
{
struct stmmac_priv *priv = netdev_priv(dev);
struct phy_device *phy = priv->phydev;
int rc;
if ((priv->pcs & STMMAC_PCS_RGMII) || (priv->pcs & STMMAC_PCS_SGMII)) {
u32 mask = ADVERTISED_Autoneg | ADVERTISED_Pause;
/* Only support ANE */
if (cmd->autoneg != AUTONEG_ENABLE)
return -EINVAL;
if (cmd->autoneg == AUTONEG_ENABLE) {
mask &= (ADVERTISED_1000baseT_Half |
ADVERTISED_1000baseT_Full |
ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full |
ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full);
spin_lock(&priv->lock);
if (priv->hw->mac->ctrl_ane)
priv->hw->mac->ctrl_ane(priv->ioaddr, 1);
spin_unlock(&priv->lock);
}
return 0;
}
spin_lock(&priv->lock);
rc = phy_ethtool_sset(phy, cmd);
spin_unlock(&priv->lock);
return rc;
}
static u32 stmmac_ethtool_getmsglevel(struct net_device *dev)
{
struct stmmac_priv *priv = netdev_priv(dev);
return priv->msg_enable;
}
static void stmmac_ethtool_setmsglevel(struct net_device *dev, u32 level)
{
struct stmmac_priv *priv = netdev_priv(dev);
priv->msg_enable = level;
}
static int stmmac_check_if_running(struct net_device *dev)
{
if (!netif_running(dev))
return -EBUSY;
return 0;
}
static int stmmac_ethtool_get_regs_len(struct net_device *dev)
{
return REG_SPACE_SIZE;
}
static void stmmac_ethtool_gregs(struct net_device *dev,
struct ethtool_regs *regs, void *space)
{
int i;
u32 *reg_space = (u32 *) space;
struct stmmac_priv *priv = netdev_priv(dev);
memset(reg_space, 0x0, REG_SPACE_SIZE);
if (!priv->plat->has_gmac) {
/* MAC registers */
for (i = 0; i < 12; i++)
reg_space[i] = readl(priv->ioaddr + (i * 4));
/* DMA registers */
for (i = 0; i < 9; i++)
reg_space[i + 12] =
readl(priv->ioaddr + (DMA_BUS_MODE + (i * 4)));
reg_space[22] = readl(priv->ioaddr + DMA_CUR_TX_BUF_ADDR);
reg_space[23] = readl(priv->ioaddr + DMA_CUR_RX_BUF_ADDR);
} else {
/* MAC registers */
for (i = 0; i < 55; i++)
reg_space[i] = readl(priv->ioaddr + (i * 4));
/* DMA registers */
for (i = 0; i < 22; i++)
reg_space[i + 55] =
readl(priv->ioaddr + (DMA_BUS_MODE + (i * 4)));
}
}
static void
stmmac_get_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pause)
{
struct stmmac_priv *priv = netdev_priv(netdev);
if (priv->pcs) /* FIXME */
return;
spin_lock(&priv->lock);
pause->rx_pause = 0;
pause->tx_pause = 0;
pause->autoneg = priv->phydev->autoneg;
if (priv->flow_ctrl & FLOW_RX)
pause->rx_pause = 1;
if (priv->flow_ctrl & FLOW_TX)
pause->tx_pause = 1;
spin_unlock(&priv->lock);
}
static int
stmmac_set_pauseparam(struct net_device *netdev,
struct ethtool_pauseparam *pause)
{
struct stmmac_priv *priv = netdev_priv(netdev);
struct phy_device *phy = priv->phydev;
int new_pause = FLOW_OFF;
int ret = 0;
if (priv->pcs) /* FIXME */
return -EOPNOTSUPP;
spin_lock(&priv->lock);
if (pause->rx_pause)
new_pause |= FLOW_RX;
if (pause->tx_pause)
new_pause |= FLOW_TX;
priv->flow_ctrl = new_pause;
phy->autoneg = pause->autoneg;
if (phy->autoneg) {
if (netif_running(netdev))
ret = phy_start_aneg(phy);
} else
priv->hw->mac->flow_ctrl(priv->ioaddr, phy->duplex,
priv->flow_ctrl, priv->pause);
spin_unlock(&priv->lock);
return ret;
}
static void stmmac_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *dummy, u64 *data)
{
struct stmmac_priv *priv = netdev_priv(dev);
int i, j = 0;
/* Update the DMA HW counters for dwmac10/100 */
if (!priv->plat->has_gmac)
priv->hw->dma->dma_diagnostic_fr(&dev->stats,
(void *) &priv->xstats,
priv->ioaddr);
else {
/* If supported, for new GMAC chips expose the MMC counters */
if (priv->dma_cap.rmon) {
dwmac_mmc_read(priv->ioaddr, &priv->mmc);
for (i = 0; i < STMMAC_MMC_STATS_LEN; i++) {
char *p;
p = (char *)priv + stmmac_mmc[i].stat_offset;
data[j++] = (stmmac_mmc[i].sizeof_stat ==
sizeof(u64)) ? (*(u64 *)p) :
(*(u32 *)p);
}
}
if (priv->eee_enabled) {
int val = phy_get_eee_err(priv->phydev);
if (val)
priv->xstats.phy_eee_wakeup_error_n = val;
}
}
for (i = 0; i < STMMAC_STATS_LEN; i++) {
char *p = (char *)priv + stmmac_gstrings_stats[i].stat_offset;
data[j++] = (stmmac_gstrings_stats[i].sizeof_stat ==
sizeof(u64)) ? (*(u64 *)p) : (*(u32 *)p);
}
}
static int stmmac_get_sset_count(struct net_device *netdev, int sset)
{
struct stmmac_priv *priv = netdev_priv(netdev);
int len;
switch (sset) {
case ETH_SS_STATS:
len = STMMAC_STATS_LEN;
if (priv->dma_cap.rmon)
len += STMMAC_MMC_STATS_LEN;
return len;
default:
return -EOPNOTSUPP;
}
}
static void stmmac_get_strings(struct net_device *dev, u32 stringset, u8 *data)
{
int i;
u8 *p = data;
struct stmmac_priv *priv = netdev_priv(dev);
switch (stringset) {
case ETH_SS_STATS:
if (priv->dma_cap.rmon)
for (i = 0; i < STMMAC_MMC_STATS_LEN; i++) {
memcpy(p, stmmac_mmc[i].stat_string,
ETH_GSTRING_LEN);
p += ETH_GSTRING_LEN;
}
for (i = 0; i < STMMAC_STATS_LEN; i++) {
memcpy(p, stmmac_gstrings_stats[i].stat_string,
ETH_GSTRING_LEN);
p += ETH_GSTRING_LEN;
}
break;
default:
WARN_ON(1);
break;
}
}
/* Currently only support WOL through Magic packet. */
static void stmmac_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct stmmac_priv *priv = netdev_priv(dev);
spin_lock_irq(&priv->lock);
if (device_can_wakeup(priv->device)) {
wol->supported = WAKE_MAGIC | WAKE_UCAST;
wol->wolopts = priv->wolopts;
}
spin_unlock_irq(&priv->lock);
}
static int stmmac_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct stmmac_priv *priv = netdev_priv(dev);
u32 support = WAKE_MAGIC | WAKE_UCAST;
/* By default almost all GMAC devices support the WoL via
* magic frame but we can disable it if the HW capability
* register shows no support for pmt_magic_frame. */
if ((priv->hw_cap_support) && (!priv->dma_cap.pmt_magic_frame))
wol->wolopts &= ~WAKE_MAGIC;
if (!device_can_wakeup(priv->device))
return -EINVAL;
if (wol->wolopts & ~support)
return -EINVAL;
if (wol->wolopts) {
pr_info("stmmac: wakeup enable\n");
device_set_wakeup_enable(priv->device, 1);
enable_irq_wake(priv->wol_irq);
} else {
device_set_wakeup_enable(priv->device, 0);
disable_irq_wake(priv->wol_irq);
}
spin_lock_irq(&priv->lock);
priv->wolopts = wol->wolopts;
spin_unlock_irq(&priv->lock);
return 0;
}
static int stmmac_ethtool_op_get_eee(struct net_device *dev,
struct ethtool_eee *edata)
{
struct stmmac_priv *priv = netdev_priv(dev);
if (!priv->dma_cap.eee)
return -EOPNOTSUPP;
edata->eee_enabled = priv->eee_enabled;
edata->eee_active = priv->eee_active;
edata->tx_lpi_timer = priv->tx_lpi_timer;
return phy_ethtool_get_eee(priv->phydev, edata);
}
static int stmmac_ethtool_op_set_eee(struct net_device *dev,
struct ethtool_eee *edata)
{
struct stmmac_priv *priv = netdev_priv(dev);
priv->eee_enabled = edata->eee_enabled;
if (!priv->eee_enabled)
stmmac_disable_eee_mode(priv);
else {
/* We are asking for enabling the EEE but it is safe
* to verify all by invoking the eee_init function.
* In case of failure it will return an error.
*/
priv->eee_enabled = stmmac_eee_init(priv);
if (!priv->eee_enabled)
return -EOPNOTSUPP;
/* Do not change tx_lpi_timer in case of failure */
priv->tx_lpi_timer = edata->tx_lpi_timer;
}
return phy_ethtool_set_eee(priv->phydev, edata);
}
static u32 stmmac_usec2riwt(u32 usec, struct stmmac_priv *priv)
{
unsigned long clk = clk_get_rate(priv->stmmac_clk);
if (!clk)
return 0;
return (usec * (clk / 1000000)) / 256;
}
static u32 stmmac_riwt2usec(u32 riwt, struct stmmac_priv *priv)
{
unsigned long clk = clk_get_rate(priv->stmmac_clk);
if (!clk)
return 0;
return (riwt * 256) / (clk / 1000000);
}
static int stmmac_get_coalesce(struct net_device *dev,
struct ethtool_coalesce *ec)
{
struct stmmac_priv *priv = netdev_priv(dev);
ec->tx_coalesce_usecs = priv->tx_coal_timer;
ec->tx_max_coalesced_frames = priv->tx_coal_frames;
if (priv->use_riwt)
ec->rx_coalesce_usecs = stmmac_riwt2usec(priv->rx_riwt, priv);
return 0;
}
static int stmmac_set_coalesce(struct net_device *dev,
struct ethtool_coalesce *ec)
{
struct stmmac_priv *priv = netdev_priv(dev);
unsigned int rx_riwt;
/* Check not supported parameters */
if ((ec->rx_max_coalesced_frames) || (ec->rx_coalesce_usecs_irq) ||
(ec->rx_max_coalesced_frames_irq) || (ec->tx_coalesce_usecs_irq) ||
(ec->use_adaptive_rx_coalesce) || (ec->use_adaptive_tx_coalesce) ||
(ec->pkt_rate_low) || (ec->rx_coalesce_usecs_low) ||
(ec->rx_max_coalesced_frames_low) || (ec->tx_coalesce_usecs_high) ||
(ec->tx_max_coalesced_frames_low) || (ec->pkt_rate_high) ||
(ec->tx_coalesce_usecs_low) || (ec->rx_coalesce_usecs_high) ||
(ec->rx_max_coalesced_frames_high) ||
(ec->tx_max_coalesced_frames_irq) ||
(ec->stats_block_coalesce_usecs) ||
(ec->tx_max_coalesced_frames_high) || (ec->rate_sample_interval))
return -EOPNOTSUPP;
if (ec->rx_coalesce_usecs == 0)
return -EINVAL;
if ((ec->tx_coalesce_usecs == 0) &&
(ec->tx_max_coalesced_frames == 0))
return -EINVAL;
if ((ec->tx_coalesce_usecs > STMMAC_COAL_TX_TIMER) ||
(ec->tx_max_coalesced_frames > STMMAC_TX_MAX_FRAMES))
return -EINVAL;
rx_riwt = stmmac_usec2riwt(ec->rx_coalesce_usecs, priv);
if ((rx_riwt > MAX_DMA_RIWT) || (rx_riwt < MIN_DMA_RIWT))
return -EINVAL;
else if (!priv->use_riwt)
return -EOPNOTSUPP;
/* Only copy relevant parameters, ignore all others. */
priv->tx_coal_frames = ec->tx_max_coalesced_frames;
priv->tx_coal_timer = ec->tx_coalesce_usecs;
priv->rx_riwt = rx_riwt;
priv->hw->dma->rx_watchdog(priv->ioaddr, priv->rx_riwt);
return 0;
}
static int stmmac_get_ts_info(struct net_device *dev,
struct ethtool_ts_info *info)
{
struct stmmac_priv *priv = netdev_priv(dev);
if ((priv->hwts_tx_en) && (priv->hwts_rx_en)) {
info->so_timestamping = SOF_TIMESTAMPING_TX_HARDWARE |
SOF_TIMESTAMPING_RX_HARDWARE |
SOF_TIMESTAMPING_RAW_HARDWARE;
if (priv->ptp_clock)
info->phc_index = ptp_clock_index(priv->ptp_clock);
info->tx_types = (1 << HWTSTAMP_TX_OFF) | (1 << HWTSTAMP_TX_ON);
info->rx_filters = ((1 << HWTSTAMP_FILTER_NONE) |
(1 << HWTSTAMP_FILTER_PTP_V1_L4_EVENT) |
(1 << HWTSTAMP_FILTER_PTP_V1_L4_SYNC) |
(1 << HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ) |
(1 << HWTSTAMP_FILTER_PTP_V2_L4_EVENT) |
(1 << HWTSTAMP_FILTER_PTP_V2_L4_SYNC) |
(1 << HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ) |
(1 << HWTSTAMP_FILTER_PTP_V2_EVENT) |
(1 << HWTSTAMP_FILTER_PTP_V2_SYNC) |
(1 << HWTSTAMP_FILTER_PTP_V2_DELAY_REQ) |
(1 << HWTSTAMP_FILTER_ALL));
return 0;
} else
return ethtool_op_get_ts_info(dev, info);
}
static const struct ethtool_ops stmmac_ethtool_ops = {
.begin = stmmac_check_if_running,
.get_drvinfo = stmmac_ethtool_getdrvinfo,
.get_settings = stmmac_ethtool_getsettings,
.set_settings = stmmac_ethtool_setsettings,
.get_msglevel = stmmac_ethtool_getmsglevel,
.set_msglevel = stmmac_ethtool_setmsglevel,
.get_regs = stmmac_ethtool_gregs,
.get_regs_len = stmmac_ethtool_get_regs_len,
.get_link = ethtool_op_get_link,
.get_pauseparam = stmmac_get_pauseparam,
.set_pauseparam = stmmac_set_pauseparam,
.get_ethtool_stats = stmmac_get_ethtool_stats,
.get_strings = stmmac_get_strings,
.get_wol = stmmac_get_wol,
.set_wol = stmmac_set_wol,
.get_eee = stmmac_ethtool_op_get_eee,
.set_eee = stmmac_ethtool_op_set_eee,
.get_sset_count = stmmac_get_sset_count,
.get_ts_info = stmmac_get_ts_info,
.get_coalesce = stmmac_get_coalesce,
.set_coalesce = stmmac_set_coalesce,
};
void stmmac_set_ethtool_ops(struct net_device *netdev)
{
SET_ETHTOOL_OPS(netdev, &stmmac_ethtool_ops);
}
| gpl-2.0 |
NooNameR/bravo_kernel_3.0 | drivers/staging/rtl8187se/ieee80211/ieee80211_softmac.c | 2527 | 81530 | /* IEEE 802.11 SoftMAC layer
* Copyright (c) 2005 Andrea Merello <andreamrl@tiscali.it>
*
* Mostly extracted from the rtl8180-sa2400 driver for the
* in-kernel generic ieee802.11 stack.
*
* Few lines might be stolen from other part of the ieee80211
* stack. Copyright who own it's copyright
*
* WPA code stolen from the ipw2200 driver.
* Copyright who own it's copyright.
*
* released under the GPL
*/
#include "ieee80211.h"
#include <linux/random.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/version.h>
#include <asm/uaccess.h>
#include "dot11d.h"
u8 rsn_authen_cipher_suite[16][4] = {
{0x00,0x0F,0xAC,0x00}, //Use group key, //Reserved
{0x00,0x0F,0xAC,0x01}, //WEP-40 //RSNA default
{0x00,0x0F,0xAC,0x02}, //TKIP //NONE //{used just as default}
{0x00,0x0F,0xAC,0x03}, //WRAP-historical
{0x00,0x0F,0xAC,0x04}, //CCMP
{0x00,0x0F,0xAC,0x05}, //WEP-104
};
short ieee80211_is_54g(struct ieee80211_network net)
{
return ((net.rates_ex_len > 0) || (net.rates_len > 4));
}
short ieee80211_is_shortslot(struct ieee80211_network net)
{
return (net.capability & WLAN_CAPABILITY_SHORT_SLOT);
}
/* returns the total length needed for pleacing the RATE MFIE
* tag and the EXTENDED RATE MFIE tag if needed.
* It encludes two bytes per tag for the tag itself and its len
*/
unsigned int ieee80211_MFIE_rate_len(struct ieee80211_device *ieee)
{
unsigned int rate_len = 0;
if (ieee->modulation & IEEE80211_CCK_MODULATION)
rate_len = IEEE80211_CCK_RATE_LEN + 2;
if (ieee->modulation & IEEE80211_OFDM_MODULATION)
rate_len += IEEE80211_OFDM_RATE_LEN + 2;
return rate_len;
}
/* pleace the MFIE rate, tag to the memory (double) poined.
* Then it updates the pointer so that
* it points after the new MFIE tag added.
*/
void ieee80211_MFIE_Brate(struct ieee80211_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & IEEE80211_CCK_MODULATION){
*tag++ = MFIE_TYPE_RATES;
*tag++ = 4;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
}
/* We may add an option for custom rates that specific HW might support */
*tag_p = tag;
}
void ieee80211_MFIE_Grate(struct ieee80211_device *ieee, u8 **tag_p)
{
u8 *tag = *tag_p;
if (ieee->modulation & IEEE80211_OFDM_MODULATION){
*tag++ = MFIE_TYPE_RATES_EX;
*tag++ = 8;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
*tag++ = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
}
/* We may add an option for custom rates that specific HW might support */
*tag_p = tag;
}
void ieee80211_WMM_Info(struct ieee80211_device *ieee, u8 **tag_p) {
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC; //0
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0x50;
*tag++ = 0xf2;
*tag++ = 0x02;//5
*tag++ = 0x00;
*tag++ = 0x01;
#ifdef SUPPORT_USPD
if(ieee->current_network.wmm_info & 0x80) {
*tag++ = 0x0f|MAX_SP_Len;
} else {
*tag++ = MAX_SP_Len;
}
#else
*tag++ = MAX_SP_Len;
#endif
*tag_p = tag;
}
void ieee80211_TURBO_Info(struct ieee80211_device *ieee, u8 **tag_p) {
u8 *tag = *tag_p;
*tag++ = MFIE_TYPE_GENERIC; //0
*tag++ = 7;
*tag++ = 0x00;
*tag++ = 0xe0;
*tag++ = 0x4c;
*tag++ = 0x01;//5
*tag++ = 0x02;
*tag++ = 0x11;
*tag++ = 0x00;
*tag_p = tag;
printk(KERN_ALERT "This is enable turbo mode IE process\n");
}
void enqueue_mgmt(struct ieee80211_device *ieee, struct sk_buff *skb)
{
int nh;
nh = (ieee->mgmt_queue_head +1) % MGMT_QUEUE_NUM;
/*
* if the queue is full but we have newer frames then
* just overwrites the oldest.
*
* if (nh == ieee->mgmt_queue_tail)
* return -1;
*/
ieee->mgmt_queue_head = nh;
ieee->mgmt_queue_ring[nh] = skb;
//return 0;
}
struct sk_buff *dequeue_mgmt(struct ieee80211_device *ieee)
{
struct sk_buff *ret;
if(ieee->mgmt_queue_tail == ieee->mgmt_queue_head)
return NULL;
ret = ieee->mgmt_queue_ring[ieee->mgmt_queue_tail];
ieee->mgmt_queue_tail =
(ieee->mgmt_queue_tail+1) % MGMT_QUEUE_NUM;
return ret;
}
void init_mgmt_queue(struct ieee80211_device *ieee)
{
ieee->mgmt_queue_tail = ieee->mgmt_queue_head = 0;
}
void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl);
inline void softmac_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
{
unsigned long flags;
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct ieee80211_hdr_3addr *header=
(struct ieee80211_hdr_3addr *) skb->data;
spin_lock_irqsave(&ieee->lock, flags);
/* called with 2nd param 0, no mgmt lock required */
ieee80211_sta_wakeup(ieee,0);
if(single){
if(ieee->queue_stop){
enqueue_mgmt(ieee,skb);
}else{
header->seq_ctrl = cpu_to_le16(ieee->seq_ctrl[0]<<4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
ieee->dev->trans_start = jiffies;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
}
spin_unlock_irqrestore(&ieee->lock, flags);
}else{
spin_unlock_irqrestore(&ieee->lock, flags);
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags);
header->seq_ctrl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
ieee->dev->trans_start = jiffies;
ieee->softmac_hard_start_xmit(skb,ieee->dev);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags);
}
}
inline void softmac_ps_mgmt_xmit(struct sk_buff *skb, struct ieee80211_device *ieee)
{
short single = ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE;
struct ieee80211_hdr_3addr *header =
(struct ieee80211_hdr_3addr *) skb->data;
if(single){
header->seq_ctrl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
ieee->dev->trans_start = jiffies;
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
}else{
header->seq_ctrl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
/* avoid watchdog triggers */
ieee->dev->trans_start = jiffies;
ieee->softmac_hard_start_xmit(skb,ieee->dev);
}
// dev_kfree_skb_any(skb);//edit by thomas
}
//by amy for power save
inline struct sk_buff *ieee80211_disassociate_skb(
struct ieee80211_network *beacon,
struct ieee80211_device *ieee,
u8 asRsn)
{
struct sk_buff *skb;
struct ieee80211_disassoc_frame *disass;
skb = dev_alloc_skb(sizeof(struct ieee80211_disassoc_frame));
if (!skb)
return NULL;
disass = (struct ieee80211_disassoc_frame *) skb_put(skb,sizeof(struct ieee80211_disassoc_frame));
disass->header.frame_control = cpu_to_le16(IEEE80211_STYPE_DISASSOC);
disass->header.duration_id = 0;
memcpy(disass->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(disass->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(disass->header.addr3, beacon->bssid, ETH_ALEN);
disass->reasoncode = asRsn;
return skb;
}
void
SendDisassociation(
struct ieee80211_device *ieee,
u8* asSta,
u8 asRsn
)
{
struct ieee80211_network *beacon = &ieee->current_network;
struct sk_buff *skb;
skb = ieee80211_disassociate_skb(beacon,ieee,asRsn);
if (skb){
softmac_mgmt_xmit(skb, ieee);
//dev_kfree_skb_any(skb);//edit by thomas
}
}
//by amy for power save
inline struct sk_buff *ieee80211_probe_req(struct ieee80211_device *ieee)
{
unsigned int len,rate_len;
u8 *tag;
struct sk_buff *skb;
struct ieee80211_probe_request *req;
len = ieee->current_network.ssid_len;
rate_len = ieee80211_MFIE_rate_len(ieee);
skb = dev_alloc_skb(sizeof(struct ieee80211_probe_request) +
2 + len + rate_len);
if (!skb)
return NULL;
req = (struct ieee80211_probe_request *) skb_put(skb,sizeof(struct ieee80211_probe_request));
req->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_REQ);
req->header.duration_id = 0; //FIXME: is this OK ?
memset(req->header.addr1, 0xff, ETH_ALEN);
memcpy(req->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memset(req->header.addr3, 0xff, ETH_ALEN);
tag = (u8 *) skb_put(skb,len+2+rate_len);
*tag++ = MFIE_TYPE_SSID;
*tag++ = len;
memcpy(tag, ieee->current_network.ssid, len);
tag += len;
ieee80211_MFIE_Brate(ieee,&tag);
ieee80211_MFIE_Grate(ieee,&tag);
return skb;
}
struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee);
void ext_ieee80211_send_beacon_wq(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
//unsigned long flags;
skb = ieee80211_get_beacon_(ieee);
if (skb){
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_beacons++;
dev_kfree_skb_any(skb);//edit by thomas
}
//printk(KERN_WARNING "[1] beacon sending!\n");
ieee->beacon_timer.expires = jiffies +
(MSECS( ieee->current_network.beacon_interval -5));
//spin_lock_irqsave(&ieee->beacon_lock,flags);
if(ieee->beacon_txing)
add_timer(&ieee->beacon_timer);
//spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_send_beacon(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
//unsigned long flags;
skb = ieee80211_get_beacon_(ieee);
if (skb){
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_beacons++;
dev_kfree_skb_any(skb);//edit by thomas
}
//printk(KERN_WARNING "[1] beacon sending!\n");
ieee->beacon_timer.expires = jiffies +
(MSECS( ieee->current_network.beacon_interval -5));
//spin_lock_irqsave(&ieee->beacon_lock,flags);
if(ieee->beacon_txing)
add_timer(&ieee->beacon_timer);
//spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_send_beacon_cb(unsigned long _ieee)
{
struct ieee80211_device *ieee =
(struct ieee80211_device *) _ieee;
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock, flags);
ieee80211_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock, flags);
}
void ieee80211_send_probe(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
skb = ieee80211_probe_req(ieee);
if (skb){
softmac_mgmt_xmit(skb, ieee);
ieee->softmac_stats.tx_probe_rq++;
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_send_probe_requests(struct ieee80211_device *ieee)
{
if (ieee->active_scan && (ieee->softmac_features & IEEE_SOFTMAC_PROBERQ)){
ieee80211_send_probe(ieee);
ieee80211_send_probe(ieee);
}
}
/* this performs syncro scan blocking the caller until all channels
* in the allowed channel map has been checked.
*/
void ieee80211_softmac_scan_syncro(struct ieee80211_device *ieee)
{
short ch = 0;
u8 channel_map[MAX_CHANNEL_NUMBER+1];
memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
down(&ieee->scan_sem);
// printk("==================> Sync scan\n");
while(1)
{
do{
ch++;
if (ch > MAX_CHANNEL_NUMBER)
goto out; /* scan completed */
}while(!channel_map[ch]);
/* this function can be called in two situations
* 1- We have switched to ad-hoc mode and we are
* performing a complete syncro scan before conclude
* there are no interesting cell and to create a
* new one. In this case the link state is
* IEEE80211_NOLINK until we found an interesting cell.
* If so the ieee8021_new_net, called by the RX path
* will set the state to IEEE80211_LINKED, so we stop
* scanning
* 2- We are linked and the root uses run iwlist scan.
* So we switch to IEEE80211_LINKED_SCANNING to remember
* that we are still logically linked (not interested in
* new network events, despite for updating the net list,
* but we are temporarly 'unlinked' as the driver shall
* not filter RX frames and the channel is changing.
* So the only situation in witch are interested is to check
* if the state become LINKED because of the #1 situation
*/
if (ieee->state == IEEE80211_LINKED)
goto out;
ieee->set_chan(ieee->dev, ch);
// printk("=====>channel=%d ",ch);
if(channel_map[ch] == 1)
{
// printk("====send probe request\n");
ieee80211_send_probe_requests(ieee);
}
/* this prevent excessive time wait when we
* need to wait for a syncro scan to end..
*/
if (ieee->sync_scan_hurryup)
goto out;
msleep_interruptible_rtl(IEEE80211_SOFTMAC_SCAN_TIME);
}
out:
ieee->sync_scan_hurryup = 0;
up(&ieee->scan_sem);
if(IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
}
void ieee80211_softmac_ips_scan_syncro(struct ieee80211_device *ieee)
{
int ch;
unsigned int watch_dog = 0;
u8 channel_map[MAX_CHANNEL_NUMBER+1];
memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
down(&ieee->scan_sem);
ch = ieee->current_network.channel;
// if(ieee->sync_scan_hurryup)
// {
// printk("stop scan sync\n");
// goto out;
// }
// printk("=======hh===============>ips scan\n");
while(1)
{
/* this function can be called in two situations
* 1- We have switched to ad-hoc mode and we are
* performing a complete syncro scan before conclude
* there are no interesting cell and to create a
* new one. In this case the link state is
* IEEE80211_NOLINK until we found an interesting cell.
* If so the ieee8021_new_net, called by the RX path
* will set the state to IEEE80211_LINKED, so we stop
* scanning
* 2- We are linked and the root uses run iwlist scan.
* So we switch to IEEE80211_LINKED_SCANNING to remember
* that we are still logically linked (not interested in
* new network events, despite for updating the net list,
* but we are temporarly 'unlinked' as the driver shall
* not filter RX frames and the channel is changing.
* So the only situation in witch are interested is to check
* if the state become LINKED because of the #1 situation
*/
if (ieee->state == IEEE80211_LINKED)
{
goto out;
}
if(channel_map[ieee->current_network.channel] > 0)
{
ieee->set_chan(ieee->dev, ieee->current_network.channel);
// printk("======>channel=%d ",ieee->current_network.channel);
}
if(channel_map[ieee->current_network.channel] == 1)
{
// printk("====send probe request\n");
ieee80211_send_probe_requests(ieee);
}
/* this prevent excessive time wait when we
* need to wait for a syncro scan to end..
*/
// if (ieee->sync_scan_hurryup)
// goto out;
msleep_interruptible_rtl(IEEE80211_SOFTMAC_SCAN_TIME);
do{
if (watch_dog++ >= MAX_CHANNEL_NUMBER)
// if (++watch_dog >= 15);//MAX_CHANNEL_NUMBER) //YJ,modified,080630
goto out; /* scan completed */
ieee->current_network.channel = (ieee->current_network.channel + 1)%MAX_CHANNEL_NUMBER;
}while(!channel_map[ieee->current_network.channel]);
}
out:
//ieee->sync_scan_hurryup = 0;
//ieee->set_chan(ieee->dev, ch);
//ieee->current_network.channel = ch;
ieee->actscanning = false;
up(&ieee->scan_sem);
if(IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
}
void ieee80211_softmac_scan_wq(struct work_struct *work)
{
struct delayed_work *dwork = to_delayed_work(work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, softmac_scan_wq);
static short watchdog = 0;
u8 channel_map[MAX_CHANNEL_NUMBER+1];
memcpy(channel_map, GET_DOT11D_INFO(ieee)->channel_map, MAX_CHANNEL_NUMBER+1);
// printk("ieee80211_softmac_scan_wq ENABLE_IPS\n");
// printk("in %s\n",__func__);
down(&ieee->scan_sem);
do{
ieee->current_network.channel =
(ieee->current_network.channel + 1) % MAX_CHANNEL_NUMBER;
if (watchdog++ > MAX_CHANNEL_NUMBER)
goto out; /* no good chans */
}while(!channel_map[ieee->current_network.channel]);
//printk("current_network.channel:%d\n", ieee->current_network.channel);
if (ieee->scanning == 0 )
{
printk("error out, scanning = 0\n");
goto out;
}
ieee->set_chan(ieee->dev, ieee->current_network.channel);
if(channel_map[ieee->current_network.channel] == 1)
ieee80211_send_probe_requests(ieee);
queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq, IEEE80211_SOFTMAC_SCAN_TIME);
up(&ieee->scan_sem);
return;
out:
ieee->actscanning = false;
watchdog = 0;
ieee->scanning = 0;
up(&ieee->scan_sem);
if(IS_DOT11D_ENABLE(ieee))
DOT11D_ScanComplete(ieee);
return;
}
void ieee80211_beacons_start(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock,flags);
ieee->beacon_txing = 1;
ieee80211_send_beacon(ieee);
spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_beacons_stop(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->beacon_lock,flags);
ieee->beacon_txing = 0;
del_timer_sync(&ieee->beacon_timer);
spin_unlock_irqrestore(&ieee->beacon_lock,flags);
}
void ieee80211_stop_send_beacons(struct ieee80211_device *ieee)
{
if(ieee->stop_send_beacons)
ieee->stop_send_beacons(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
ieee80211_beacons_stop(ieee);
}
void ieee80211_start_send_beacons(struct ieee80211_device *ieee)
{
if(ieee->start_send_beacons)
ieee->start_send_beacons(ieee->dev);
if(ieee->softmac_features & IEEE_SOFTMAC_BEACONS)
ieee80211_beacons_start(ieee);
}
void ieee80211_softmac_stop_scan(struct ieee80211_device *ieee)
{
// unsigned long flags;
//ieee->sync_scan_hurryup = 1;
down(&ieee->scan_sem);
// spin_lock_irqsave(&ieee->lock, flags);
if (ieee->scanning == 1){
ieee->scanning = 0;
//del_timer_sync(&ieee->scan_timer);
cancel_delayed_work(&ieee->softmac_scan_wq);
}
// spin_unlock_irqrestore(&ieee->lock, flags);
up(&ieee->scan_sem);
}
void ieee80211_stop_scan(struct ieee80211_device *ieee)
{
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
ieee80211_softmac_stop_scan(ieee);
else
ieee->stop_scan(ieee->dev);
}
/* called with ieee->lock held */
void ieee80211_rtl_start_scan(struct ieee80211_device *ieee)
{
if(IS_DOT11D_ENABLE(ieee) )
{
if(IS_COUNTRY_IE_VALID(ieee))
{
RESET_CIE_WATCHDOG(ieee);
}
}
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN){
if (ieee->scanning == 0)
{
ieee->scanning = 1;
//ieee80211_softmac_scan(ieee);
// queue_work(ieee->wq, &ieee->softmac_scan_wq);
//care this,1203,2007,by lawrence
#if 1
queue_delayed_work(ieee->wq, &ieee->softmac_scan_wq,0);
#endif
}
}else
ieee->start_scan(ieee->dev);
}
/* called with wx_sem held */
void ieee80211_start_scan_syncro(struct ieee80211_device *ieee)
{
if(IS_DOT11D_ENABLE(ieee) )
{
if(IS_COUNTRY_IE_VALID(ieee))
{
RESET_CIE_WATCHDOG(ieee);
}
}
ieee->sync_scan_hurryup = 0;
if (ieee->softmac_features & IEEE_SOFTMAC_SCAN)
ieee80211_softmac_scan_syncro(ieee);
else
ieee->scan_syncro(ieee->dev);
}
inline struct sk_buff *ieee80211_authentication_req(struct ieee80211_network *beacon,
struct ieee80211_device *ieee, int challengelen)
{
struct sk_buff *skb;
struct ieee80211_authentication *auth;
skb = dev_alloc_skb(sizeof(struct ieee80211_authentication) + challengelen);
if (!skb) return NULL;
auth = (struct ieee80211_authentication *)
skb_put(skb, sizeof(struct ieee80211_authentication));
auth->header.frame_ctl = IEEE80211_STYPE_AUTH;
if (challengelen) auth->header.frame_ctl |= IEEE80211_FCTL_WEP;
auth->header.duration_id = 0x013a; //FIXME
memcpy(auth->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr3, beacon->bssid, ETH_ALEN);
auth->algorithm = ieee->open_wep ? WLAN_AUTH_OPEN : WLAN_AUTH_SHARED_KEY;
auth->transaction = cpu_to_le16(ieee->associate_seq);
ieee->associate_seq++;
auth->status = cpu_to_le16(WLAN_STATUS_SUCCESS);
return skb;
}
static struct sk_buff* ieee80211_probe_resp(struct ieee80211_device *ieee, u8 *dest)
{
u8 *tag;
int beacon_size;
struct ieee80211_probe_response *beacon_buf;
struct sk_buff *skb;
int encrypt;
int atim_len,erp_len;
struct ieee80211_crypt_data* crypt;
char *ssid = ieee->current_network.ssid;
int ssid_len = ieee->current_network.ssid_len;
int rate_len = ieee->current_network.rates_len+2;
int rate_ex_len = ieee->current_network.rates_ex_len;
int wpa_ie_len = ieee->wpa_ie_len;
if(rate_ex_len > 0) rate_ex_len+=2;
if(ieee->current_network.capability & WLAN_CAPABILITY_IBSS)
atim_len = 4;
else
atim_len = 0;
if(ieee80211_is_54g(ieee->current_network))
erp_len = 3;
else
erp_len = 0;
beacon_size = sizeof(struct ieee80211_probe_response)+
ssid_len
+3 //channel
+rate_len
+rate_ex_len
+atim_len
+wpa_ie_len
+erp_len;
skb = dev_alloc_skb(beacon_size);
if (!skb)
return NULL;
beacon_buf = (struct ieee80211_probe_response*) skb_put(skb, beacon_size);
memcpy (beacon_buf->header.addr1, dest,ETH_ALEN);
memcpy (beacon_buf->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy (beacon_buf->header.addr3, ieee->current_network.bssid, ETH_ALEN);
beacon_buf->header.duration_id = 0; //FIXME
beacon_buf->beacon_interval =
cpu_to_le16(ieee->current_network.beacon_interval);
beacon_buf->capability =
cpu_to_le16(ieee->current_network.capability & WLAN_CAPABILITY_IBSS);
if(ieee->short_slot && (ieee->current_network.capability & WLAN_CAPABILITY_SHORT_SLOT))
cpu_to_le16((beacon_buf->capability |= WLAN_CAPABILITY_SHORT_SLOT));
crypt = ieee->crypt[ieee->tx_keyidx];
encrypt = ieee->host_encrypt && crypt && crypt->ops &&
((0 == strcmp(crypt->ops->name, "WEP")) || wpa_ie_len);
if (encrypt)
beacon_buf->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
beacon_buf->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_PROBE_RESP);
beacon_buf->info_element.id = MFIE_TYPE_SSID;
beacon_buf->info_element.len = ssid_len;
tag = (u8*) beacon_buf->info_element.data;
memcpy(tag, ssid, ssid_len);
tag += ssid_len;
*(tag++) = MFIE_TYPE_RATES;
*(tag++) = rate_len-2;
memcpy(tag,ieee->current_network.rates,rate_len-2);
tag+=rate_len-2;
*(tag++) = MFIE_TYPE_DS_SET;
*(tag++) = 1;
*(tag++) = ieee->current_network.channel;
if(atim_len){
*(tag++) = MFIE_TYPE_IBSS_SET;
*(tag++) = 2;
*((u16*)(tag)) = cpu_to_le16(ieee->current_network.atim_window);
tag+=2;
}
if(erp_len){
*(tag++) = MFIE_TYPE_ERP;
*(tag++) = 1;
*(tag++) = 0;
}
if(rate_ex_len){
*(tag++) = MFIE_TYPE_RATES_EX;
*(tag++) = rate_ex_len-2;
memcpy(tag,ieee->current_network.rates_ex,rate_ex_len-2);
tag+=rate_ex_len-2;
}
if (wpa_ie_len)
{
if (ieee->iw_mode == IW_MODE_ADHOC)
{//as Windows will set pairwise key same as the group key which is not allowed in Linux, so set this for IOT issue. WB 2008.07.07
memcpy(&ieee->wpa_ie[14], &ieee->wpa_ie[8], 4);
}
memcpy(tag, ieee->wpa_ie, ieee->wpa_ie_len);
}
skb->dev = ieee->dev;
return skb;
}
struct sk_buff* ieee80211_assoc_resp(struct ieee80211_device *ieee, u8 *dest)
{
struct sk_buff *skb;
u8* tag;
struct ieee80211_crypt_data* crypt;
struct ieee80211_assoc_response_frame *assoc;
short encrypt;
unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
int len = sizeof(struct ieee80211_assoc_response_frame) + rate_len;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
assoc = (struct ieee80211_assoc_response_frame *)
skb_put(skb,sizeof(struct ieee80211_assoc_response_frame));
assoc->header.frame_control = cpu_to_le16(IEEE80211_STYPE_ASSOC_RESP);
memcpy(assoc->header.addr1, dest,ETH_ALEN);
memcpy(assoc->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(assoc->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
assoc->capability = cpu_to_le16(ieee->iw_mode == IW_MODE_MASTER ?
WLAN_CAPABILITY_BSS : WLAN_CAPABILITY_IBSS);
if(ieee->short_slot)
assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
if (ieee->host_encrypt)
crypt = ieee->crypt[ieee->tx_keyidx];
else crypt = NULL;
encrypt = ( crypt && crypt->ops);
if (encrypt)
assoc->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
assoc->status = 0;
assoc->aid = cpu_to_le16(ieee->assoc_id);
if (ieee->assoc_id == 0x2007) ieee->assoc_id=0;
else ieee->assoc_id++;
tag = (u8*) skb_put(skb, rate_len);
ieee80211_MFIE_Brate(ieee, &tag);
ieee80211_MFIE_Grate(ieee, &tag);
return skb;
}
struct sk_buff* ieee80211_auth_resp(struct ieee80211_device *ieee,int status, u8 *dest)
{
struct sk_buff *skb;
struct ieee80211_authentication *auth;
skb = dev_alloc_skb(sizeof(struct ieee80211_authentication)+1);
if (!skb)
return NULL;
skb->len = sizeof(struct ieee80211_authentication);
auth = (struct ieee80211_authentication *)skb->data;
auth->status = cpu_to_le16(status);
auth->transaction = cpu_to_le16(2);
auth->algorithm = cpu_to_le16(WLAN_AUTH_OPEN);
memcpy(auth->header.addr3, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(auth->header.addr1, dest, ETH_ALEN);
auth->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_AUTH);
return skb;
}
struct sk_buff* ieee80211_null_func(struct ieee80211_device *ieee,short pwr)
{
struct sk_buff *skb;
struct ieee80211_hdr_3addr* hdr;
skb = dev_alloc_skb(sizeof(struct ieee80211_hdr_3addr));
if (!skb)
return NULL;
hdr = (struct ieee80211_hdr_3addr*)skb_put(skb,sizeof(struct ieee80211_hdr_3addr));
memcpy(hdr->addr1, ieee->current_network.bssid, ETH_ALEN);
memcpy(hdr->addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->addr3, ieee->current_network.bssid, ETH_ALEN);
hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA |
IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS |
(pwr ? IEEE80211_FCTL_PM:0));
return skb;
}
void ieee80211_resp_to_assoc_rq(struct ieee80211_device *ieee, u8* dest)
{
struct sk_buff *buf = ieee80211_assoc_resp(ieee, dest);
if (buf){
softmac_mgmt_xmit(buf, ieee);
dev_kfree_skb_any(buf);//edit by thomas
}
}
void ieee80211_resp_to_auth(struct ieee80211_device *ieee, int s, u8* dest)
{
struct sk_buff *buf = ieee80211_auth_resp(ieee, s, dest);
if (buf){
softmac_mgmt_xmit(buf, ieee);
dev_kfree_skb_any(buf);//edit by thomas
}
}
void ieee80211_resp_to_probe(struct ieee80211_device *ieee, u8 *dest)
{
struct sk_buff *buf = ieee80211_probe_resp(ieee, dest);
if (buf) {
softmac_mgmt_xmit(buf, ieee);
dev_kfree_skb_any(buf);//edit by thomas
}
}
inline struct sk_buff *ieee80211_association_req(struct ieee80211_network *beacon,struct ieee80211_device *ieee)
{
struct sk_buff *skb;
//unsigned long flags;
struct ieee80211_assoc_request_frame *hdr;
u8 *tag;
//short info_addr = 0;
//int i;
//u16 suite_count = 0;
//u8 suit_select = 0;
unsigned int wpa_len = beacon->wpa_ie_len;
//struct net_device *dev = ieee->dev;
//union iwreq_data wrqu;
//u8 *buff;
//u8 *p;
#if 1
// for testing purpose
unsigned int rsn_len = beacon->rsn_ie_len;
#else
unsigned int rsn_len = beacon->rsn_ie_len - 4;
#endif
unsigned int rate_len = ieee80211_MFIE_rate_len(ieee);
unsigned int wmm_info_len = beacon->QoS_Enable?9:0;
unsigned int turbo_info_len = beacon->Turbo_Enable?9:0;
u8 encry_proto = ieee->wpax_type_notify & 0xff;
//u8 pairwise_type = (ieee->wpax_type_notify >> 8) & 0xff;
//u8 authen_type = (ieee->wpax_type_notify >> 16) & 0xff;
int len = 0;
//[0] Notify type of encryption: WPA/WPA2
//[1] pair wise type
//[2] authen type
if(ieee->wpax_type_set) {
if (IEEE_PROTO_WPA == encry_proto) {
rsn_len = 0;
} else if (IEEE_PROTO_RSN == encry_proto) {
wpa_len = 0;
}
}
len = sizeof(struct ieee80211_assoc_request_frame)+
+ beacon->ssid_len//essid tagged val
+ rate_len//rates tagged val
+ wpa_len
+ rsn_len
+ wmm_info_len
+ turbo_info_len;
skb = dev_alloc_skb(len);
if (!skb)
return NULL;
hdr = (struct ieee80211_assoc_request_frame *)
skb_put(skb, sizeof(struct ieee80211_assoc_request_frame));
hdr->header.frame_control = IEEE80211_STYPE_ASSOC_REQ;
hdr->header.duration_id= 37; //FIXME
memcpy(hdr->header.addr1, beacon->bssid, ETH_ALEN);
memcpy(hdr->header.addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(hdr->header.addr3, beacon->bssid, ETH_ALEN);
memcpy(ieee->ap_mac_addr, beacon->bssid, ETH_ALEN);//for HW security, John
hdr->capability = cpu_to_le16(WLAN_CAPABILITY_BSS);
if (beacon->capability & WLAN_CAPABILITY_PRIVACY )
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_PRIVACY);
if (beacon->capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_PREAMBLE);
if(ieee->short_slot)
hdr->capability |= cpu_to_le16(WLAN_CAPABILITY_SHORT_SLOT);
hdr->listen_interval = 0xa; //FIXME
hdr->info_element.id = MFIE_TYPE_SSID;
hdr->info_element.len = beacon->ssid_len;
tag = skb_put(skb, beacon->ssid_len);
memcpy(tag, beacon->ssid, beacon->ssid_len);
tag = skb_put(skb, rate_len);
ieee80211_MFIE_Brate(ieee, &tag);
ieee80211_MFIE_Grate(ieee, &tag);
//add rsn==0 condition for ap's mix security mode(wpa+wpa2), john2007.8.9
//choose AES encryption as default algorithm while using mixed mode
tag = skb_put(skb,ieee->wpa_ie_len);
memcpy(tag,ieee->wpa_ie,ieee->wpa_ie_len);
tag = skb_put(skb,wmm_info_len);
if(wmm_info_len) {
ieee80211_WMM_Info(ieee, &tag);
}
tag = skb_put(skb,turbo_info_len);
if(turbo_info_len) {
ieee80211_TURBO_Info(ieee, &tag);
}
return skb;
}
void ieee80211_associate_abort(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock, flags);
ieee->associate_seq++;
/* don't scan, and avoid to have the RX path possibily
* try again to associate. Even do not react to AUTH or
* ASSOC response. Just wait for the retry wq to be scheduled.
* Here we will check if there are good nets to associate
* with, so we retry or just get back to NO_LINK and scanning
*/
if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING){
IEEE80211_DEBUG_MGMT("Authentication failed\n");
ieee->softmac_stats.no_auth_rs++;
}else{
IEEE80211_DEBUG_MGMT("Association failed\n");
ieee->softmac_stats.no_ass_rs++;
}
ieee->state = IEEE80211_ASSOCIATING_RETRY;
queue_delayed_work(ieee->wq, &ieee->associate_retry_wq,IEEE80211_SOFTMAC_ASSOC_RETRY_TIME);
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_associate_abort_cb(unsigned long dev)
{
ieee80211_associate_abort((struct ieee80211_device *) dev);
}
void ieee80211_associate_step1(struct ieee80211_device *ieee)
{
struct ieee80211_network *beacon = &ieee->current_network;
struct sk_buff *skb;
IEEE80211_DEBUG_MGMT("Stopping scan\n");
ieee->softmac_stats.tx_auth_rq++;
skb=ieee80211_authentication_req(beacon, ieee, 0);
if (!skb){
ieee80211_associate_abort(ieee);
}
else{
ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATING ;
IEEE80211_DEBUG_MGMT("Sending authentication request\n");
//printk("---Sending authentication request\n");
softmac_mgmt_xmit(skb, ieee);
//BUGON when you try to add_timer twice, using mod_timer may be better, john0709
if(!timer_pending(&ieee->associate_timer)){
ieee->associate_timer.expires = jiffies + (HZ / 2);
add_timer(&ieee->associate_timer);
}
//If call dev_kfree_skb_any,a warning will ocur....
//KERNEL: assertion (!atomic_read(&skb->users)) failed at net/core/dev.c (1708)
//So ... 1204 by lawrence.
//printk("\nIn %s,line %d call kfree skb.",__func__,__LINE__);
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_rtl_auth_challenge(struct ieee80211_device *ieee, u8 *challenge, int chlen)
{
u8 *c;
struct sk_buff *skb;
struct ieee80211_network *beacon = &ieee->current_network;
// int hlen = sizeof(struct ieee80211_authentication);
del_timer_sync(&ieee->associate_timer);
ieee->associate_seq++;
ieee->softmac_stats.tx_auth_rq++;
skb = ieee80211_authentication_req(beacon, ieee, chlen+2);
if (!skb)
ieee80211_associate_abort(ieee);
else{
c = skb_put(skb, chlen+2);
*(c++) = MFIE_TYPE_CHALLENGE;
*(c++) = chlen;
memcpy(c, challenge, chlen);
IEEE80211_DEBUG_MGMT("Sending authentication challenge response\n");
ieee80211_encrypt_fragment(ieee, skb, sizeof(struct ieee80211_hdr_3addr ));
softmac_mgmt_xmit(skb, ieee);
if (!timer_pending(&ieee->associate_timer)){
//printk("=========>add timer again, to crash\n");
ieee->associate_timer.expires = jiffies + (HZ / 2);
add_timer(&ieee->associate_timer);
}
dev_kfree_skb_any(skb);//edit by thomas
}
kfree(challenge);
}
void ieee80211_associate_step2(struct ieee80211_device *ieee)
{
struct sk_buff* skb;
struct ieee80211_network *beacon = &ieee->current_network;
del_timer_sync(&ieee->associate_timer);
IEEE80211_DEBUG_MGMT("Sending association request\n");
ieee->softmac_stats.tx_ass_rq++;
skb=ieee80211_association_req(beacon, ieee);
if (!skb)
ieee80211_associate_abort(ieee);
else{
softmac_mgmt_xmit(skb, ieee);
if (!timer_pending(&ieee->associate_timer)){
ieee->associate_timer.expires = jiffies + (HZ / 2);
add_timer(&ieee->associate_timer);
}
//dev_kfree_skb_any(skb);//edit by thomas
}
}
void ieee80211_associate_complete_wq(struct work_struct *work)
{
struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_complete_wq);
printk(KERN_INFO "Associated successfully\n");
if(ieee80211_is_54g(ieee->current_network) &&
(ieee->modulation & IEEE80211_OFDM_MODULATION)){
ieee->rate = 540;
printk(KERN_INFO"Using G rates\n");
}else{
ieee->rate = 110;
printk(KERN_INFO"Using B rates\n");
}
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
void ieee80211_associate_complete(struct ieee80211_device *ieee)
{
int i;
del_timer_sync(&ieee->associate_timer);
for(i = 0; i < 6; i++) {
//ieee->seq_ctrl[i] = 0;
}
ieee->state = IEEE80211_LINKED;
IEEE80211_DEBUG_MGMT("Successfully associated\n");
queue_work(ieee->wq, &ieee->associate_complete_wq);
}
void ieee80211_associate_procedure_wq(struct work_struct *work)
{
struct ieee80211_device *ieee = container_of(work, struct ieee80211_device, associate_procedure_wq);
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
ieee80211_stop_scan(ieee);
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->associate_seq = 1;
ieee80211_associate_step1(ieee);
up(&ieee->wx_sem);
}
inline void ieee80211_softmac_new_net(struct ieee80211_device *ieee, struct ieee80211_network *net)
{
u8 tmp_ssid[IW_ESSID_MAX_SIZE+1];
int tmp_ssid_len = 0;
short apset,ssidset,ssidbroad,apmatch,ssidmatch;
/* we are interested in new new only if we are not associated
* and we are not associating / authenticating
*/
if (ieee->state != IEEE80211_NOLINK)
return;
if ((ieee->iw_mode == IW_MODE_INFRA) && !(net->capability & WLAN_CAPABILITY_BSS))
return;
if ((ieee->iw_mode == IW_MODE_ADHOC) && !(net->capability & WLAN_CAPABILITY_IBSS))
return;
if (ieee->iw_mode == IW_MODE_INFRA || ieee->iw_mode == IW_MODE_ADHOC){
/* if the user specified the AP MAC, we need also the essid
* This could be obtained by beacons or, if the network does not
* broadcast it, it can be put manually.
*/
apset = ieee->wap_set;//(memcmp(ieee->current_network.bssid, zero,ETH_ALEN)!=0 );
ssidset = ieee->ssid_set;//ieee->current_network.ssid[0] != '\0';
ssidbroad = !(net->ssid_len == 0 || net->ssid[0]== '\0');
apmatch = (memcmp(ieee->current_network.bssid, net->bssid, ETH_ALEN)==0);
if(ieee->current_network.ssid_len != net->ssid_len)
ssidmatch = 0;
else
ssidmatch = (0==strncmp(ieee->current_network.ssid, net->ssid, net->ssid_len));
//printk("cur: %s, %d, net:%s, %d\n", ieee->current_network.ssid, ieee->current_network.ssid_len, net->ssid, net->ssid_len);
//printk("apset=%d apmatch=%d ssidset=%d ssidbroad=%d ssidmatch=%d\n",apset,apmatch,ssidset,ssidbroad,ssidmatch);
if ( /* if the user set the AP check if match.
* if the network does not broadcast essid we check the user supplyed ANY essid
* if the network does broadcast and the user does not set essid it is OK
* if the network does broadcast and the user did set essid chech if essid match
*/
( apset && apmatch &&
((ssidset && ssidbroad && ssidmatch) || (ssidbroad && !ssidset) || (!ssidbroad && ssidset)) ) ||
/* if the ap is not set, check that the user set the bssid
* and the network does bradcast and that those two bssid matches
*/
(!apset && ssidset && ssidbroad && ssidmatch)
){
/* if the essid is hidden replace it with the
* essid provided by the user.
*/
if (!ssidbroad){
strncpy(tmp_ssid, ieee->current_network.ssid, IW_ESSID_MAX_SIZE);
tmp_ssid_len = ieee->current_network.ssid_len;
}
memcpy(&ieee->current_network, net, sizeof(struct ieee80211_network));
if (!ssidbroad){
strncpy(ieee->current_network.ssid, tmp_ssid, IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len = tmp_ssid_len;
}
printk(KERN_INFO"Linking with %s: channel is %d\n",ieee->current_network.ssid,ieee->current_network.channel);
if (ieee->iw_mode == IW_MODE_INFRA){
ieee->state = IEEE80211_ASSOCIATING;
ieee->beinretry = false;
queue_work(ieee->wq, &ieee->associate_procedure_wq);
}else{
if(ieee80211_is_54g(ieee->current_network) &&
(ieee->modulation & IEEE80211_OFDM_MODULATION)){
ieee->rate = 540;
printk(KERN_INFO"Using G rates\n");
}else{
ieee->rate = 110;
printk(KERN_INFO"Using B rates\n");
}
ieee->state = IEEE80211_LINKED;
ieee->beinretry = false;
}
}
}
}
void ieee80211_softmac_check_all_nets(struct ieee80211_device *ieee)
{
unsigned long flags;
struct ieee80211_network *target;
spin_lock_irqsave(&ieee->lock, flags);
list_for_each_entry(target, &ieee->network_list, list) {
/* if the state become different that NOLINK means
* we had found what we are searching for
*/
if (ieee->state != IEEE80211_NOLINK)
break;
if (ieee->scan_age == 0 || time_after(target->last_scanned + ieee->scan_age, jiffies))
ieee80211_softmac_new_net(ieee, target);
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
static inline u16 auth_parse(struct sk_buff *skb, u8** challenge, int *chlen)
{
struct ieee80211_authentication *a;
u8 *t;
if (skb->len < (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n",skb->len);
return 0xcafe;
}
*challenge = NULL;
a = (struct ieee80211_authentication*) skb->data;
if(skb->len > (sizeof(struct ieee80211_authentication) +3)){
t = skb->data + sizeof(struct ieee80211_authentication);
if(*(t++) == MFIE_TYPE_CHALLENGE){
*chlen = *(t++);
*challenge = kmemdup(t, *chlen, GFP_ATOMIC);
if (!*challenge)
return -ENOMEM;
}
}
return cpu_to_le16(a->status);
}
int auth_rq_parse(struct sk_buff *skb,u8* dest)
{
struct ieee80211_authentication *a;
if (skb->len < (sizeof(struct ieee80211_authentication)-sizeof(struct ieee80211_info_element))){
IEEE80211_DEBUG_MGMT("invalid len in auth request: %d\n",skb->len);
return -1;
}
a = (struct ieee80211_authentication*) skb->data;
memcpy(dest,a->header.addr2, ETH_ALEN);
if (le16_to_cpu(a->algorithm) != WLAN_AUTH_OPEN)
return WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG;
return WLAN_STATUS_SUCCESS;
}
static short probe_rq_parse(struct ieee80211_device *ieee, struct sk_buff *skb, u8 *src)
{
u8 *tag;
u8 *skbend;
u8 *ssid=NULL;
u8 ssidlen = 0;
struct ieee80211_hdr_3addr *header =
(struct ieee80211_hdr_3addr *) skb->data;
if (skb->len < sizeof (struct ieee80211_hdr_3addr ))
return -1; /* corrupted */
memcpy(src,header->addr2, ETH_ALEN);
skbend = (u8*)skb->data + skb->len;
tag = skb->data + sizeof (struct ieee80211_hdr_3addr );
while (tag+1 < skbend){
if (*tag == 0){
ssid = tag+2;
ssidlen = *(tag+1);
break;
}
tag++; /* point to the len field */
tag = tag + *(tag); /* point to the last data byte of the tag */
tag++; /* point to the next tag */
}
//IEEE80211DMESG("Card MAC address is "MACSTR, MAC2STR(src));
if (ssidlen == 0) return 1;
if (!ssid) return 1; /* ssid not found in tagged param */
return (!strncmp(ssid, ieee->current_network.ssid, ssidlen));
}
int assoc_rq_parse(struct sk_buff *skb,u8* dest)
{
struct ieee80211_assoc_request_frame *a;
if (skb->len < (sizeof(struct ieee80211_assoc_request_frame) -
sizeof(struct ieee80211_info_element))) {
IEEE80211_DEBUG_MGMT("invalid len in auth request:%d \n", skb->len);
return -1;
}
a = (struct ieee80211_assoc_request_frame*) skb->data;
memcpy(dest,a->header.addr2,ETH_ALEN);
return 0;
}
static inline u16 assoc_parse(struct sk_buff *skb, int *aid)
{
struct ieee80211_assoc_response_frame *a;
if (skb->len < sizeof(struct ieee80211_assoc_response_frame)){
IEEE80211_DEBUG_MGMT("invalid len in auth resp: %d\n", skb->len);
return 0xcafe;
}
a = (struct ieee80211_assoc_response_frame*) skb->data;
*aid = le16_to_cpu(a->aid) & 0x3fff;
return le16_to_cpu(a->status);
}
static inline void
ieee80211_rx_probe_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
//IEEE80211DMESG("Rx probe");
ieee->softmac_stats.rx_probe_rq++;
//DMESG("Dest is "MACSTR, MAC2STR(dest));
if (probe_rq_parse(ieee, skb, dest)){
//IEEE80211DMESG("Was for me!");
ieee->softmac_stats.tx_probe_rs++;
ieee80211_resp_to_probe(ieee, dest);
}
}
inline void
ieee80211_rx_auth_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
int status;
//IEEE80211DMESG("Rx probe");
ieee->softmac_stats.rx_auth_rq++;
status = auth_rq_parse(skb, dest);
if (status != -1) {
ieee80211_resp_to_auth(ieee, status, dest);
}
//DMESG("Dest is "MACSTR, MAC2STR(dest));
}
inline void
ieee80211_rx_assoc_rq(struct ieee80211_device *ieee, struct sk_buff *skb)
{
u8 dest[ETH_ALEN];
//unsigned long flags;
ieee->softmac_stats.rx_ass_rq++;
if (assoc_rq_parse(skb,dest) != -1){
ieee80211_resp_to_assoc_rq(ieee, dest);
}
printk(KERN_INFO"New client associated: %pM\n", dest);
}
void ieee80211_sta_ps_send_null_frame(struct ieee80211_device *ieee, short pwr)
{
struct sk_buff *buf = ieee80211_null_func(ieee, pwr);
if (buf)
softmac_ps_mgmt_xmit(buf, ieee);
}
short ieee80211_sta_ps_sleep(struct ieee80211_device *ieee, u32 *time_h, u32 *time_l)
{
int timeout = 0;
u8 dtim;
/*if(ieee->ps == IEEE80211_PS_DISABLED ||
ieee->iw_mode != IW_MODE_INFRA ||
ieee->state != IEEE80211_LINKED)
return 0;
*/
dtim = ieee->current_network.dtim_data;
//printk("DTIM\n");
if(!(dtim & IEEE80211_DTIM_VALID))
return 0;
else
timeout = ieee->current_network.beacon_interval;
//printk("VALID\n");
ieee->current_network.dtim_data = IEEE80211_DTIM_INVALID;
if(dtim & ((IEEE80211_DTIM_UCAST | IEEE80211_DTIM_MBCAST)& ieee->ps))
return 2;
if(!time_after(jiffies, ieee->dev->trans_start + MSECS(timeout)))
return 0;
if(!time_after(jiffies, ieee->last_rx_ps_time + MSECS(timeout)))
return 0;
if((ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE ) &&
(ieee->mgmt_queue_tail != ieee->mgmt_queue_head))
return 0;
if(time_l){
*time_l = ieee->current_network.last_dtim_sta_time[0]
+ MSECS((ieee->current_network.beacon_interval));
//* ieee->current_network.dtim_period));
//printk("beacon_interval:%x, dtim_period:%x, totol to Msecs:%x, HZ:%x\n", ieee->current_network.beacon_interval, ieee->current_network.dtim_period, MSECS(((ieee->current_network.beacon_interval * ieee->current_network.dtim_period))), HZ);
}
if(time_h){
*time_h = ieee->current_network.last_dtim_sta_time[1];
if(time_l && *time_l < ieee->current_network.last_dtim_sta_time[0])
*time_h += 1;
}
return 1;
}
inline void ieee80211_sta_ps(struct ieee80211_device *ieee)
{
u32 th,tl;
short sleep;
unsigned long flags,flags2;
spin_lock_irqsave(&ieee->lock, flags);
if((ieee->ps == IEEE80211_PS_DISABLED ||
ieee->iw_mode != IW_MODE_INFRA ||
ieee->state != IEEE80211_LINKED)){
//#warning CHECK_LOCK_HERE
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
ieee80211_sta_wakeup(ieee, 1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
sleep = ieee80211_sta_ps_sleep(ieee,&th, &tl);
// printk("===>%s,%d[2 wake, 1 sleep, 0 do nothing], ieee->sta_sleep = %d\n",__func__, sleep,ieee->sta_sleep);
/* 2 wake, 1 sleep, 0 do nothing */
if(sleep == 0)
goto out;
if(sleep == 1){
if(ieee->sta_sleep == 1)
ieee->enter_sleep_state(ieee->dev,th,tl);
else if(ieee->sta_sleep == 0){
// printk("send null 1\n");
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
if(ieee->ps_is_queue_empty(ieee->dev)){
ieee->sta_sleep = 2;
ieee->ps_request_tx_ack(ieee->dev);
ieee80211_sta_ps_send_null_frame(ieee,1);
ieee->ps_th = th;
ieee->ps_tl = tl;
}
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
}else if(sleep == 2){
//#warning CHECK_LOCK_HERE
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
// printk("send wakeup packet\n");
ieee80211_sta_wakeup(ieee,1);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
out:
spin_unlock_irqrestore(&ieee->lock, flags);
}
void ieee80211_sta_wakeup(struct ieee80211_device *ieee, short nl)
{
if(ieee->sta_sleep == 0){
if(nl){
// printk("Warning: driver is probably failing to report TX ps error\n");
ieee->ps_request_tx_ack(ieee->dev);
ieee80211_sta_ps_send_null_frame(ieee, 0);
}
return;
}
if(ieee->sta_sleep == 1)
ieee->sta_wake_up(ieee->dev);
ieee->sta_sleep = 0;
if(nl){
ieee->ps_request_tx_ack(ieee->dev);
ieee80211_sta_ps_send_null_frame(ieee, 0);
}
}
void ieee80211_ps_tx_ack(struct ieee80211_device *ieee, short success)
{
unsigned long flags,flags2;
spin_lock_irqsave(&ieee->lock, flags);
if(ieee->sta_sleep == 2){
/* Null frame with PS bit set */
if(success){
// printk("==================> %s::enter sleep state\n",__func__);
ieee->sta_sleep = 1;
ieee->enter_sleep_state(ieee->dev,ieee->ps_th,ieee->ps_tl);
}
/* if the card report not success we can't be sure the AP
* has not RXed so we can't assume the AP believe us awake
*/
}
/* 21112005 - tx again null without PS bit if lost */
else {
if((ieee->sta_sleep == 0) && !success){
spin_lock_irqsave(&ieee->mgmt_tx_lock, flags2);
ieee80211_sta_ps_send_null_frame(ieee, 0);
spin_unlock_irqrestore(&ieee->mgmt_tx_lock, flags2);
}
}
spin_unlock_irqrestore(&ieee->lock, flags);
}
inline int
ieee80211_rx_frame_softmac(struct ieee80211_device *ieee, struct sk_buff *skb,
struct ieee80211_rx_stats *rx_stats, u16 type,
u16 stype)
{
struct ieee80211_hdr_3addr *header = (struct ieee80211_hdr_3addr *) skb->data;
u16 errcode;
u8* challenge=NULL;
int chlen=0;
int aid=0;
struct ieee80211_assoc_response_frame *assoc_resp;
struct ieee80211_info_element *info_element;
if(!ieee->proto_started)
return 0;
if(ieee->sta_sleep || (ieee->ps != IEEE80211_PS_DISABLED &&
ieee->iw_mode == IW_MODE_INFRA &&
ieee->state == IEEE80211_LINKED))
tasklet_schedule(&ieee->ps_task);
if (WLAN_FC_GET_STYPE(header->frame_control) != IEEE80211_STYPE_PROBE_RESP &&
WLAN_FC_GET_STYPE(header->frame_control) != IEEE80211_STYPE_BEACON)
ieee->last_rx_ps_time = jiffies;
switch (WLAN_FC_GET_STYPE(header->frame_control)) {
case IEEE80211_STYPE_ASSOC_RESP:
case IEEE80211_STYPE_REASSOC_RESP:
IEEE80211_DEBUG_MGMT("received [RE]ASSOCIATION RESPONSE (%d)\n",
WLAN_FC_GET_STYPE(header->frame_ctl));
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATED &&
ieee->iw_mode == IW_MODE_INFRA){
if (0 == (errcode=assoc_parse(skb, &aid))){
u16 left;
ieee->state=IEEE80211_LINKED;
ieee->assoc_id = aid;
ieee->softmac_stats.rx_ass_ok++;
//printk(KERN_WARNING "nic_type = %s", (rx_stats->nic_type == 1)?"rtl8187":"rtl8187B");
if(1 == rx_stats->nic_type) //card type is 8187
{
goto associate_complete;
}
assoc_resp = (struct ieee80211_assoc_response_frame*)skb->data;
info_element = &assoc_resp->info_element;
left = skb->len - ((void*)info_element - (void*)assoc_resp);
while (left >= sizeof(struct ieee80211_info_element_hdr)) {
if (sizeof(struct ieee80211_info_element_hdr) + info_element->len > left) {
printk(KERN_WARNING "[re]associate reeponse error!");
return 1;
}
switch (info_element->id) {
case MFIE_TYPE_GENERIC:
IEEE80211_DEBUG_SCAN("MFIE_TYPE_GENERIC: %d bytes\n", info_element->len);
if (info_element->len >= 8 &&
info_element->data[0] == 0x00 &&
info_element->data[1] == 0x50 &&
info_element->data[2] == 0xf2 &&
info_element->data[3] == 0x02 &&
info_element->data[4] == 0x01) {
// Not care about version at present.
//WMM Parameter Element
memcpy(ieee->current_network.wmm_param,(u8*)(info_element->data\
+ 8),(info_element->len - 8));
if (((ieee->current_network.wmm_info^info_element->data[6])& \
0x0f)||(!ieee->init_wmmparam_flag)) {
// refresh parameter element for current network
// update the register parameter for hardware
ieee->init_wmmparam_flag = 1;
queue_work(ieee->wq, &ieee->wmm_param_update_wq);
}
//update info_element for current network
ieee->current_network.wmm_info = info_element->data[6];
}
break;
default:
//nothing to do at present!!!
break;
}
left -= sizeof(struct ieee80211_info_element_hdr) +
info_element->len;
info_element = (struct ieee80211_info_element *)
&info_element->data[info_element->len];
}
if(!ieee->init_wmmparam_flag) //legacy AP, reset the AC_xx_param register
{
queue_work(ieee->wq,&ieee->wmm_param_update_wq);
ieee->init_wmmparam_flag = 1;//indicate AC_xx_param upated since last associate
}
associate_complete:
ieee80211_associate_complete(ieee);
}else{
ieee->softmac_stats.rx_ass_err++;
IEEE80211_DEBUG_MGMT(
"Association response status code 0x%x\n",
errcode);
ieee80211_associate_abort(ieee);
}
}
break;
case IEEE80211_STYPE_ASSOC_REQ:
case IEEE80211_STYPE_REASSOC_REQ:
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
ieee->iw_mode == IW_MODE_MASTER)
ieee80211_rx_assoc_rq(ieee, skb);
break;
case IEEE80211_STYPE_AUTH:
if (ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE){
if (ieee->state == IEEE80211_ASSOCIATING_AUTHENTICATING &&
ieee->iw_mode == IW_MODE_INFRA){
IEEE80211_DEBUG_MGMT("Received authentication response");
if (0 == (errcode=auth_parse(skb, &challenge, &chlen))){
if(ieee->open_wep || !challenge){
ieee->state = IEEE80211_ASSOCIATING_AUTHENTICATED;
ieee->softmac_stats.rx_auth_rs_ok++;
ieee80211_associate_step2(ieee);
}else{
ieee80211_rtl_auth_challenge(ieee, challenge, chlen);
}
}else{
ieee->softmac_stats.rx_auth_rs_err++;
IEEE80211_DEBUG_MGMT("Authentication respose status code 0x%x",errcode);
ieee80211_associate_abort(ieee);
}
}else if (ieee->iw_mode == IW_MODE_MASTER){
ieee80211_rx_auth_rq(ieee, skb);
}
}
break;
case IEEE80211_STYPE_PROBE_REQ:
if ((ieee->softmac_features & IEEE_SOFTMAC_PROBERS) &&
((ieee->iw_mode == IW_MODE_ADHOC ||
ieee->iw_mode == IW_MODE_MASTER) &&
ieee->state == IEEE80211_LINKED))
ieee80211_rx_probe_rq(ieee, skb);
break;
case IEEE80211_STYPE_DISASSOC:
case IEEE80211_STYPE_DEAUTH:
/* FIXME for now repeat all the association procedure
* both for disassociation and deauthentication
*/
if ((ieee->softmac_features & IEEE_SOFTMAC_ASSOCIATE) &&
(ieee->state == IEEE80211_LINKED) &&
(ieee->iw_mode == IW_MODE_INFRA) &&
(!memcmp(header->addr2,ieee->current_network.bssid,ETH_ALEN))){
ieee->state = IEEE80211_ASSOCIATING;
ieee->softmac_stats.reassoc++;
//notify_wx_assoc_event(ieee); //YJ,del,080828, do not notify os here
queue_work(ieee->wq, &ieee->associate_procedure_wq);
}
break;
default:
return -1;
break;
}
//dev_kfree_skb_any(skb);
return 0;
}
/* following are for a simpler TX queue management.
* Instead of using netif_[stop/wake]_queue the driver
* will uses these two function (plus a reset one), that
* will internally uses the kernel netif_* and takes
* care of the ieee802.11 fragmentation.
* So the driver receives a fragment per time and might
* call the stop function when it want without take care
* to have enough room to TX an entire packet.
* This might be useful if each fragment need it's own
* descriptor, thus just keep a total free memory > than
* the max fragmentation threshold is not enough.. If the
* ieee802.11 stack passed a TXB struct then you needed
* to keep N free descriptors where
* N = MAX_PACKET_SIZE / MIN_FRAG_TRESHOLD
* In this way you need just one and the 802.11 stack
* will take care of buffering fragments and pass them to
* to the driver later, when it wakes the queue.
*/
void ieee80211_softmac_xmit(struct ieee80211_txb *txb, struct ieee80211_device *ieee)
{
unsigned long flags;
int i;
spin_lock_irqsave(&ieee->lock,flags);
/* called with 2nd parm 0, no tx mgmt lock required */
ieee80211_sta_wakeup(ieee,0);
for(i = 0; i < txb->nr_frags; i++) {
if (ieee->queue_stop){
ieee->tx_pending.txb = txb;
ieee->tx_pending.frag = i;
goto exit;
}else{
ieee->softmac_data_hard_start_xmit(
txb->fragments[i],
ieee->dev,ieee->rate);
//(i+1)<txb->nr_frags);
ieee->stats.tx_packets++;
ieee->stats.tx_bytes += txb->fragments[i]->len;
ieee->dev->trans_start = jiffies;
}
}
ieee80211_txb_free(txb);
exit:
spin_unlock_irqrestore(&ieee->lock,flags);
}
/* called with ieee->lock acquired */
void ieee80211_resume_tx(struct ieee80211_device *ieee)
{
int i;
for(i = ieee->tx_pending.frag; i < ieee->tx_pending.txb->nr_frags; i++) {
if (ieee->queue_stop){
ieee->tx_pending.frag = i;
return;
}else{
ieee->softmac_data_hard_start_xmit(
ieee->tx_pending.txb->fragments[i],
ieee->dev,ieee->rate);
//(i+1)<ieee->tx_pending.txb->nr_frags);
ieee->stats.tx_packets++;
ieee->dev->trans_start = jiffies;
}
}
ieee80211_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
void ieee80211_reset_queue(struct ieee80211_device *ieee)
{
unsigned long flags;
spin_lock_irqsave(&ieee->lock,flags);
init_mgmt_queue(ieee);
if (ieee->tx_pending.txb){
ieee80211_txb_free(ieee->tx_pending.txb);
ieee->tx_pending.txb = NULL;
}
ieee->queue_stop = 0;
spin_unlock_irqrestore(&ieee->lock,flags);
}
void ieee80211_rtl_wake_queue(struct ieee80211_device *ieee)
{
unsigned long flags;
struct sk_buff *skb;
struct ieee80211_hdr_3addr *header;
spin_lock_irqsave(&ieee->lock,flags);
if (! ieee->queue_stop) goto exit;
ieee->queue_stop = 0;
if(ieee->softmac_features & IEEE_SOFTMAC_SINGLE_QUEUE){
while (!ieee->queue_stop && (skb = dequeue_mgmt(ieee))){
header = (struct ieee80211_hdr_3addr *) skb->data;
header->seq_ctrl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
//printk(KERN_ALERT "ieee80211_wake_queue \n");
ieee->softmac_data_hard_start_xmit(skb,ieee->dev,ieee->basic_rate);
dev_kfree_skb_any(skb);//edit by thomas
}
}
if (!ieee->queue_stop && ieee->tx_pending.txb)
ieee80211_resume_tx(ieee);
if (!ieee->queue_stop && netif_queue_stopped(ieee->dev)){
ieee->softmac_stats.swtxawake++;
netif_wake_queue(ieee->dev);
}
exit :
spin_unlock_irqrestore(&ieee->lock,flags);
}
void ieee80211_rtl_stop_queue(struct ieee80211_device *ieee)
{
//unsigned long flags;
//spin_lock_irqsave(&ieee->lock,flags);
if (! netif_queue_stopped(ieee->dev)){
netif_stop_queue(ieee->dev);
ieee->softmac_stats.swtxstop++;
}
ieee->queue_stop = 1;
//spin_unlock_irqrestore(&ieee->lock,flags);
}
inline void ieee80211_randomize_cell(struct ieee80211_device *ieee)
{
get_random_bytes(ieee->current_network.bssid, ETH_ALEN);
/* an IBSS cell address must have the two less significant
* bits of the first byte = 2
*/
ieee->current_network.bssid[0] &= ~0x01;
ieee->current_network.bssid[0] |= 0x02;
}
/* called in user context only */
void ieee80211_start_master_bss(struct ieee80211_device *ieee)
{
ieee->assoc_id = 1;
if (ieee->current_network.ssid_len == 0){
strncpy(ieee->current_network.ssid,
IEEE80211_DEFAULT_TX_ESSID,
IW_ESSID_MAX_SIZE);
ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
memcpy(ieee->current_network.bssid, ieee->dev->dev_addr, ETH_ALEN);
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->state = IEEE80211_LINKED;
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
void ieee80211_start_monitor_mode(struct ieee80211_device *ieee)
{
if(ieee->raw_tx){
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
}
}
void ieee80211_start_ibss_wq(struct work_struct *work)
{
struct delayed_work *dwork = to_delayed_work(work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, start_ibss_wq);
/* iwconfig mode ad-hoc will schedule this and return
* on the other hand this will block further iwconfig SET
* operations because of the wx_sem hold.
* Anyway some most set operations set a flag to speed-up
* (abort) this wq (when syncro scanning) before sleeping
* on the semaphore
*/
down(&ieee->wx_sem);
if (ieee->current_network.ssid_len == 0){
strcpy(ieee->current_network.ssid,IEEE80211_DEFAULT_TX_ESSID);
ieee->current_network.ssid_len = strlen(IEEE80211_DEFAULT_TX_ESSID);
ieee->ssid_set = 1;
}
/* check if we have this cell in our network list */
ieee80211_softmac_check_all_nets(ieee);
if(ieee->state == IEEE80211_NOLINK)
ieee->current_network.channel = 10;
/* if not then the state is not linked. Maybe the user swithced to
* ad-hoc mode just after being in monitor mode, or just after
* being very few time in managed mode (so the card have had no
* time to scan all the chans..) or we have just run up the iface
* after setting ad-hoc mode. So we have to give another try..
* Here, in ibss mode, should be safe to do this without extra care
* (in bss mode we had to make sure no-one tryed to associate when
* we had just checked the ieee->state and we was going to start the
* scan) beacause in ibss mode the ieee80211_new_net function, when
* finds a good net, just set the ieee->state to IEEE80211_LINKED,
* so, at worst, we waste a bit of time to initiate an unneeded syncro
* scan, that will stop at the first round because it sees the state
* associated.
*/
if (ieee->state == IEEE80211_NOLINK)
ieee80211_start_scan_syncro(ieee);
/* the network definitively is not here.. create a new cell */
if (ieee->state == IEEE80211_NOLINK){
printk("creating new IBSS cell\n");
if(!ieee->wap_set)
ieee80211_randomize_cell(ieee);
if(ieee->modulation & IEEE80211_CCK_MODULATION){
ieee->current_network.rates_len = 4;
ieee->current_network.rates[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_1MB;
ieee->current_network.rates[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_2MB;
ieee->current_network.rates[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_5MB;
ieee->current_network.rates[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_CCK_RATE_11MB;
}else
ieee->current_network.rates_len = 0;
if(ieee->modulation & IEEE80211_OFDM_MODULATION){
ieee->current_network.rates_ex_len = 8;
ieee->current_network.rates_ex[0] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_6MB;
ieee->current_network.rates_ex[1] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_9MB;
ieee->current_network.rates_ex[2] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_12MB;
ieee->current_network.rates_ex[3] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_18MB;
ieee->current_network.rates_ex[4] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_24MB;
ieee->current_network.rates_ex[5] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_36MB;
ieee->current_network.rates_ex[6] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_48MB;
ieee->current_network.rates_ex[7] = IEEE80211_BASIC_RATE_MASK | IEEE80211_OFDM_RATE_54MB;
ieee->rate = 540;
}else{
ieee->current_network.rates_ex_len = 0;
ieee->rate = 110;
}
// By default, WMM function will be disabled in IBSS mode
ieee->current_network.QoS_Enable = 0;
ieee->current_network.atim_window = 0;
ieee->current_network.capability = WLAN_CAPABILITY_IBSS;
if(ieee->short_slot)
ieee->current_network.capability |= WLAN_CAPABILITY_SHORT_SLOT;
}
ieee->state = IEEE80211_LINKED;
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->link_change(ieee->dev);
notify_wx_assoc_event(ieee);
ieee80211_start_send_beacons(ieee);
printk(KERN_WARNING "after sending beacon packet!\n");
if (ieee->data_hard_resume)
ieee->data_hard_resume(ieee->dev);
netif_carrier_on(ieee->dev);
up(&ieee->wx_sem);
}
inline void ieee80211_start_ibss(struct ieee80211_device *ieee)
{
queue_delayed_work(ieee->wq, &ieee->start_ibss_wq, 100);
}
/* this is called only in user context, with wx_sem held */
void ieee80211_start_bss(struct ieee80211_device *ieee)
{
unsigned long flags;
//
// Ref: 802.11d 11.1.3.3
// STA shall not start a BSS unless properly formed Beacon frame including a Country IE.
//
if(IS_DOT11D_ENABLE(ieee) && !IS_COUNTRY_IE_VALID(ieee))
{
if(! ieee->bGlobalDomain)
{
return;
}
}
/* check if we have already found the net we
* are interested in (if any).
* if not (we are disassociated and we are not
* in associating / authenticating phase) start the background scanning.
*/
ieee80211_softmac_check_all_nets(ieee);
/* ensure no-one start an associating process (thus setting
* the ieee->state to ieee80211_ASSOCIATING) while we
* have just cheked it and we are going to enable scan.
* The ieee80211_new_net function is always called with
* lock held (from both ieee80211_softmac_check_all_nets and
* the rx path), so we cannot be in the middle of such function
*/
spin_lock_irqsave(&ieee->lock, flags);
//#ifdef ENABLE_IPS
// printk("start bss ENABLE_IPS\n");
//#else
if (ieee->state == IEEE80211_NOLINK){
ieee->actscanning = true;
ieee80211_rtl_start_scan(ieee);
}
//#endif
spin_unlock_irqrestore(&ieee->lock, flags);
}
/* called only in userspace context */
void ieee80211_disassociate(struct ieee80211_device *ieee)
{
netif_carrier_off(ieee->dev);
if (ieee->softmac_features & IEEE_SOFTMAC_TX_QUEUE)
ieee80211_reset_queue(ieee);
if (ieee->data_hard_stop)
ieee->data_hard_stop(ieee->dev);
if(IS_DOT11D_ENABLE(ieee))
Dot11d_Reset(ieee);
ieee->link_change(ieee->dev);
if (ieee->state == IEEE80211_LINKED)
notify_wx_assoc_event(ieee);
ieee->state = IEEE80211_NOLINK;
}
void ieee80211_associate_retry_wq(struct work_struct *work)
{
struct delayed_work *dwork = to_delayed_work(work);
struct ieee80211_device *ieee = container_of(dwork, struct ieee80211_device, associate_retry_wq);
unsigned long flags;
down(&ieee->wx_sem);
if(!ieee->proto_started)
goto exit;
if(ieee->state != IEEE80211_ASSOCIATING_RETRY)
goto exit;
/* until we do not set the state to IEEE80211_NOLINK
* there are no possibility to have someone else trying
* to start an association procdure (we get here with
* ieee->state = IEEE80211_ASSOCIATING).
* When we set the state to IEEE80211_NOLINK it is possible
* that the RX path run an attempt to associate, but
* both ieee80211_softmac_check_all_nets and the
* RX path works with ieee->lock held so there are no
* problems. If we are still disassociated then start a scan.
* the lock here is necessary to ensure no one try to start
* an association procedure when we have just checked the
* state and we are going to start the scan.
*/
ieee->state = IEEE80211_NOLINK;
ieee->beinretry = true;
ieee80211_softmac_check_all_nets(ieee);
spin_lock_irqsave(&ieee->lock, flags);
if(ieee->state == IEEE80211_NOLINK){
ieee->beinretry = false;
ieee->actscanning = true;
ieee80211_rtl_start_scan(ieee);
}
//YJ,add,080828, notify os here
if(ieee->state == IEEE80211_NOLINK)
{
notify_wx_assoc_event(ieee);
}
//YJ,add,080828,end
spin_unlock_irqrestore(&ieee->lock, flags);
exit:
up(&ieee->wx_sem);
}
struct sk_buff *ieee80211_get_beacon_(struct ieee80211_device *ieee)
{
u8 broadcast_addr[] = {0xff,0xff,0xff,0xff,0xff,0xff};
struct sk_buff *skb = NULL;
struct ieee80211_probe_response *b;
skb = ieee80211_probe_resp(ieee, broadcast_addr);
if (!skb)
return NULL;
b = (struct ieee80211_probe_response *) skb->data;
b->header.frame_ctl = cpu_to_le16(IEEE80211_STYPE_BEACON);
return skb;
}
struct sk_buff *ieee80211_get_beacon(struct ieee80211_device *ieee)
{
struct sk_buff *skb;
struct ieee80211_probe_response *b;
skb = ieee80211_get_beacon_(ieee);
if(!skb)
return NULL;
b = (struct ieee80211_probe_response *) skb->data;
b->header.seq_ctrl = cpu_to_le16(ieee->seq_ctrl[0] << 4);
if (ieee->seq_ctrl[0] == 0xFFF)
ieee->seq_ctrl[0] = 0;
else
ieee->seq_ctrl[0]++;
return skb;
}
void ieee80211_softmac_stop_protocol(struct ieee80211_device *ieee)
{
ieee->sync_scan_hurryup = 1;
down(&ieee->wx_sem);
ieee80211_stop_protocol(ieee);
up(&ieee->wx_sem);
}
void ieee80211_stop_protocol(struct ieee80211_device *ieee)
{
if (!ieee->proto_started)
return;
ieee->proto_started = 0;
ieee80211_stop_send_beacons(ieee);
if((ieee->iw_mode == IW_MODE_INFRA)&&(ieee->state == IEEE80211_LINKED)) {
SendDisassociation(ieee,NULL,WLAN_REASON_DISASSOC_STA_HAS_LEFT);
}
del_timer_sync(&ieee->associate_timer);
cancel_delayed_work(&ieee->associate_retry_wq);
cancel_delayed_work(&ieee->start_ibss_wq);
ieee80211_stop_scan(ieee);
ieee80211_disassociate(ieee);
}
void ieee80211_softmac_start_protocol(struct ieee80211_device *ieee)
{
ieee->sync_scan_hurryup = 0;
down(&ieee->wx_sem);
ieee80211_start_protocol(ieee);
up(&ieee->wx_sem);
}
void ieee80211_start_protocol(struct ieee80211_device *ieee)
{
short ch = 0;
int i = 0;
if (ieee->proto_started)
return;
ieee->proto_started = 1;
if (ieee->current_network.channel == 0){
do{
ch++;
if (ch > MAX_CHANNEL_NUMBER)
return; /* no channel found */
}while(!GET_DOT11D_INFO(ieee)->channel_map[ch]);
ieee->current_network.channel = ch;
}
if (ieee->current_network.beacon_interval == 0)
ieee->current_network.beacon_interval = 100;
ieee->set_chan(ieee->dev,ieee->current_network.channel);
for(i = 0; i < 17; i++) {
ieee->last_rxseq_num[i] = -1;
ieee->last_rxfrag_num[i] = -1;
ieee->last_packet_time[i] = 0;
}
ieee->init_wmmparam_flag = 0;//reinitialize AC_xx_PARAM registers.
/* if the user set the MAC of the ad-hoc cell and then
* switch to managed mode, shall we make sure that association
* attempts does not fail just because the user provide the essid
* and the nic is still checking for the AP MAC ??
*/
switch (ieee->iw_mode) {
case IW_MODE_AUTO:
ieee->iw_mode = IW_MODE_INFRA;
//not set break here intentionly
case IW_MODE_INFRA:
ieee80211_start_bss(ieee);
break;
case IW_MODE_ADHOC:
ieee80211_start_ibss(ieee);
break;
case IW_MODE_MASTER:
ieee80211_start_master_bss(ieee);
break;
case IW_MODE_MONITOR:
ieee80211_start_monitor_mode(ieee);
break;
default:
ieee->iw_mode = IW_MODE_INFRA;
ieee80211_start_bss(ieee);
break;
}
}
#define DRV_NAME "Ieee80211"
void ieee80211_softmac_init(struct ieee80211_device *ieee)
{
int i;
memset(&ieee->current_network, 0, sizeof(struct ieee80211_network));
ieee->state = IEEE80211_NOLINK;
ieee->sync_scan_hurryup = 0;
for(i = 0; i < 5; i++) {
ieee->seq_ctrl[i] = 0;
}
ieee->assoc_id = 0;
ieee->queue_stop = 0;
ieee->scanning = 0;
ieee->softmac_features = 0; //so IEEE2100-like driver are happy
ieee->wap_set = 0;
ieee->ssid_set = 0;
ieee->proto_started = 0;
ieee->basic_rate = IEEE80211_DEFAULT_BASIC_RATE;
ieee->rate = 3;
//#ifdef ENABLE_LPS
ieee->ps = IEEE80211_PS_MBCAST|IEEE80211_PS_UNICAST;
//#else
// ieee->ps = IEEE80211_PS_DISABLED;
//#endif
ieee->sta_sleep = 0;
//by amy
ieee->bInactivePs = false;
ieee->actscanning = false;
ieee->ListenInterval = 2;
ieee->NumRxDataInPeriod = 0; //YJ,add,080828
ieee->NumRxBcnInPeriod = 0; //YJ,add,080828
ieee->NumRxOkTotal = 0;//+by amy 080312
ieee->NumRxUnicast = 0;//YJ,add,080828,for keep alive
ieee->beinretry = false;
ieee->bHwRadioOff = false;
//by amy
init_mgmt_queue(ieee);
ieee->tx_pending.txb = NULL;
init_timer(&ieee->associate_timer);
ieee->associate_timer.data = (unsigned long)ieee;
ieee->associate_timer.function = ieee80211_associate_abort_cb;
init_timer(&ieee->beacon_timer);
ieee->beacon_timer.data = (unsigned long) ieee;
ieee->beacon_timer.function = ieee80211_send_beacon_cb;
#ifdef PF_SYNCTHREAD
ieee->wq = create_workqueue(DRV_NAME,0);
#else
ieee->wq = create_workqueue(DRV_NAME);
#endif
INIT_DELAYED_WORK(&ieee->start_ibss_wq,(void*) ieee80211_start_ibss_wq);
INIT_WORK(&ieee->associate_complete_wq,(void*) ieee80211_associate_complete_wq);
INIT_WORK(&ieee->associate_procedure_wq,(void*) ieee80211_associate_procedure_wq);
INIT_DELAYED_WORK(&ieee->softmac_scan_wq,(void*) ieee80211_softmac_scan_wq);
INIT_DELAYED_WORK(&ieee->associate_retry_wq,(void*) ieee80211_associate_retry_wq);
INIT_WORK(&ieee->wx_sync_scan_wq,(void*) ieee80211_wx_sync_scan_wq);
// INIT_WORK(&ieee->watch_dog_wq,(void*) ieee80211_watch_dog_wq);
sema_init(&ieee->wx_sem, 1);
sema_init(&ieee->scan_sem, 1);
spin_lock_init(&ieee->mgmt_tx_lock);
spin_lock_init(&ieee->beacon_lock);
tasklet_init(&ieee->ps_task,
(void(*)(unsigned long)) ieee80211_sta_ps,
(unsigned long)ieee);
ieee->pDot11dInfo = kmalloc(sizeof(RT_DOT11D_INFO), GFP_ATOMIC);
}
void ieee80211_softmac_free(struct ieee80211_device *ieee)
{
down(&ieee->wx_sem);
del_timer_sync(&ieee->associate_timer);
cancel_delayed_work(&ieee->associate_retry_wq);
//add for RF power on power of by lizhaoming 080512
cancel_delayed_work(&ieee->GPIOChangeRFWorkItem);
destroy_workqueue(ieee->wq);
kfree(ieee->pDot11dInfo);
up(&ieee->wx_sem);
}
/********************************************************
* Start of WPA code. *
* this is stolen from the ipw2200 driver *
********************************************************/
static int ieee80211_wpa_enable(struct ieee80211_device *ieee, int value)
{
/* This is called when wpa_supplicant loads and closes the driver
* interface. */
printk("%s WPA\n",value ? "enabling" : "disabling");
ieee->wpa_enabled = value;
return 0;
}
void ieee80211_wpa_assoc_frame(struct ieee80211_device *ieee, char *wpa_ie, int wpa_ie_len)
{
/* make sure WPA is enabled */
ieee80211_wpa_enable(ieee, 1);
ieee80211_disassociate(ieee);
}
static int ieee80211_wpa_mlme(struct ieee80211_device *ieee, int command, int reason)
{
int ret = 0;
switch (command) {
case IEEE_MLME_STA_DEAUTH:
// silently ignore
break;
case IEEE_MLME_STA_DISASSOC:
ieee80211_disassociate(ieee);
break;
default:
printk("Unknown MLME request: %d\n", command);
ret = -EOPNOTSUPP;
}
return ret;
}
static int ieee80211_wpa_set_wpa_ie(struct ieee80211_device *ieee,
struct ieee_param *param, int plen)
{
u8 *buf;
if (param->u.wpa_ie.len > MAX_WPA_IE_LEN ||
(param->u.wpa_ie.len && param->u.wpa_ie.data == NULL))
return -EINVAL;
if (param->u.wpa_ie.len) {
buf = kmemdup(param->u.wpa_ie.data, param->u.wpa_ie.len,
GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
kfree(ieee->wpa_ie);
ieee->wpa_ie = buf;
ieee->wpa_ie_len = param->u.wpa_ie.len;
} else {
kfree(ieee->wpa_ie);
ieee->wpa_ie = NULL;
ieee->wpa_ie_len = 0;
}
ieee80211_wpa_assoc_frame(ieee, ieee->wpa_ie, ieee->wpa_ie_len);
return 0;
}
#define AUTH_ALG_OPEN_SYSTEM 0x1
#define AUTH_ALG_SHARED_KEY 0x2
static int ieee80211_wpa_set_auth_algs(struct ieee80211_device *ieee, int value)
{
struct ieee80211_security sec = {
.flags = SEC_AUTH_MODE,
};
int ret = 0;
if (value & AUTH_ALG_SHARED_KEY) {
sec.auth_mode = WLAN_AUTH_SHARED_KEY;
ieee->open_wep = 0;
} else {
sec.auth_mode = WLAN_AUTH_OPEN;
ieee->open_wep = 1;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
else
ret = -EOPNOTSUPP;
return ret;
}
static int ieee80211_wpa_set_param(struct ieee80211_device *ieee, u8 name, u32 value)
{
int ret=0;
unsigned long flags;
switch (name) {
case IEEE_PARAM_WPA_ENABLED:
ret = ieee80211_wpa_enable(ieee, value);
break;
case IEEE_PARAM_TKIP_COUNTERMEASURES:
ieee->tkip_countermeasures=value;
break;
case IEEE_PARAM_DROP_UNENCRYPTED: {
/* HACK:
*
* wpa_supplicant calls set_wpa_enabled when the driver
* is loaded and unloaded, regardless of if WPA is being
* used. No other calls are made which can be used to
* determine if encryption will be used or not prior to
* association being expected. If encryption is not being
* used, drop_unencrypted is set to false, else true -- we
* can use this to determine if the CAP_PRIVACY_ON bit should
* be set.
*/
struct ieee80211_security sec = {
.flags = SEC_ENABLED,
.enabled = value,
};
ieee->drop_unencrypted = value;
/* We only change SEC_LEVEL for open mode. Others
* are set by ipw_wpa_set_encryption.
*/
if (!value) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_0;
}
else {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
}
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
break;
}
case IEEE_PARAM_PRIVACY_INVOKED:
ieee->privacy_invoked=value;
break;
case IEEE_PARAM_AUTH_ALGS:
ret = ieee80211_wpa_set_auth_algs(ieee, value);
break;
case IEEE_PARAM_IEEE_802_1X:
ieee->ieee802_1x=value;
break;
case IEEE_PARAM_WPAX_SELECT:
// added for WPA2 mixed mode
//printk(KERN_WARNING "------------------------>wpax value = %x\n", value);
spin_lock_irqsave(&ieee->wpax_suitlist_lock,flags);
ieee->wpax_type_set = 1;
ieee->wpax_type_notify = value;
spin_unlock_irqrestore(&ieee->wpax_suitlist_lock,flags);
break;
default:
printk("Unknown WPA param: %d\n",name);
ret = -EOPNOTSUPP;
}
return ret;
}
/* implementation borrowed from hostap driver */
static int ieee80211_wpa_set_encryption(struct ieee80211_device *ieee,
struct ieee_param *param, int param_len)
{
int ret = 0;
struct ieee80211_crypto_ops *ops;
struct ieee80211_crypt_data **crypt;
struct ieee80211_security sec = {
.flags = 0,
};
param->u.crypt.err = 0;
param->u.crypt.alg[IEEE_CRYPT_ALG_NAME_LEN - 1] = '\0';
if (param_len !=
(int) ((char *) param->u.crypt.key - (char *) param) +
param->u.crypt.key_len) {
printk("Len mismatch %d, %d\n", param_len,
param->u.crypt.key_len);
return -EINVAL;
}
if (param->sta_addr[0] == 0xff && param->sta_addr[1] == 0xff &&
param->sta_addr[2] == 0xff && param->sta_addr[3] == 0xff &&
param->sta_addr[4] == 0xff && param->sta_addr[5] == 0xff) {
if (param->u.crypt.idx >= WEP_KEYS)
return -EINVAL;
crypt = &ieee->crypt[param->u.crypt.idx];
} else {
return -EINVAL;
}
if (strcmp(param->u.crypt.alg, "none") == 0) {
if (crypt) {
sec.enabled = 0;
// FIXME FIXME
//sec.encrypt = 0;
sec.level = SEC_LEVEL_0;
sec.flags |= SEC_ENABLED | SEC_LEVEL;
ieee80211_crypt_delayed_deinit(ieee, crypt);
}
goto done;
}
sec.enabled = 1;
// FIXME FIXME
// sec.encrypt = 1;
sec.flags |= SEC_ENABLED;
/* IPW HW cannot build TKIP MIC, host decryption still needed. */
if (!(ieee->host_encrypt || ieee->host_decrypt) &&
strcmp(param->u.crypt.alg, "TKIP"))
goto skip_host_crypt;
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
if (ops == NULL && strcmp(param->u.crypt.alg, "WEP") == 0)
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
else if (ops == NULL && strcmp(param->u.crypt.alg, "TKIP") == 0)
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
else if (ops == NULL && strcmp(param->u.crypt.alg, "CCMP") == 0)
ops = ieee80211_get_crypto_ops(param->u.crypt.alg);
if (ops == NULL) {
printk("unknown crypto alg '%s'\n", param->u.crypt.alg);
param->u.crypt.err = IEEE_CRYPT_ERR_UNKNOWN_ALG;
ret = -EINVAL;
goto done;
}
if (*crypt == NULL || (*crypt)->ops != ops) {
struct ieee80211_crypt_data *new_crypt;
ieee80211_crypt_delayed_deinit(ieee, crypt);
new_crypt = kmalloc(sizeof(*new_crypt), GFP_KERNEL);
if (new_crypt == NULL) {
ret = -ENOMEM;
goto done;
}
memset(new_crypt, 0, sizeof(struct ieee80211_crypt_data));
new_crypt->ops = ops;
if (new_crypt->ops)
new_crypt->priv =
new_crypt->ops->init(param->u.crypt.idx);
if (new_crypt->priv == NULL) {
kfree(new_crypt);
param->u.crypt.err = IEEE_CRYPT_ERR_CRYPT_INIT_FAILED;
ret = -EINVAL;
goto done;
}
*crypt = new_crypt;
}
if (param->u.crypt.key_len > 0 && (*crypt)->ops->set_key &&
(*crypt)->ops->set_key(param->u.crypt.key,
param->u.crypt.key_len, param->u.crypt.seq,
(*crypt)->priv) < 0) {
printk("key setting failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_KEY_SET_FAILED;
ret = -EINVAL;
goto done;
}
skip_host_crypt:
if (param->u.crypt.set_tx) {
ieee->tx_keyidx = param->u.crypt.idx;
sec.active_key = param->u.crypt.idx;
sec.flags |= SEC_ACTIVE_KEY;
} else
sec.flags &= ~SEC_ACTIVE_KEY;
if (param->u.crypt.alg != NULL) {
memcpy(sec.keys[param->u.crypt.idx],
param->u.crypt.key,
param->u.crypt.key_len);
sec.key_sizes[param->u.crypt.idx] = param->u.crypt.key_len;
sec.flags |= (1 << param->u.crypt.idx);
if (strcmp(param->u.crypt.alg, "WEP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_1;
} else if (strcmp(param->u.crypt.alg, "TKIP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_2;
} else if (strcmp(param->u.crypt.alg, "CCMP") == 0) {
sec.flags |= SEC_LEVEL;
sec.level = SEC_LEVEL_3;
}
}
done:
if (ieee->set_security)
ieee->set_security(ieee->dev, &sec);
/* Do not reset port if card is in Managed mode since resetting will
* generate new IEEE 802.11 authentication which may end up in looping
* with IEEE 802.1X. If your hardware requires a reset after WEP
* configuration (for example... Prism2), implement the reset_port in
* the callbacks structures used to initialize the 802.11 stack. */
if (ieee->reset_on_keychange &&
ieee->iw_mode != IW_MODE_INFRA &&
ieee->reset_port &&
ieee->reset_port(ieee->dev)) {
printk("reset_port failed\n");
param->u.crypt.err = IEEE_CRYPT_ERR_CARD_CONF_FAILED;
return -EINVAL;
}
return ret;
}
int ieee80211_wpa_supplicant_ioctl(struct ieee80211_device *ieee, struct iw_point *p)
{
struct ieee_param *param;
int ret=0;
down(&ieee->wx_sem);
//IEEE_DEBUG_INFO("wpa_supplicant: len=%d\n", p->length);
if (p->length < sizeof(struct ieee_param) || !p->pointer){
ret = -EINVAL;
goto out;
}
param = kmalloc(p->length, GFP_KERNEL);
if (param == NULL){
ret = -ENOMEM;
goto out;
}
if (copy_from_user(param, p->pointer, p->length)) {
kfree(param);
ret = -EFAULT;
goto out;
}
switch (param->cmd) {
case IEEE_CMD_SET_WPA_PARAM:
ret = ieee80211_wpa_set_param(ieee, param->u.wpa_param.name,
param->u.wpa_param.value);
break;
case IEEE_CMD_SET_WPA_IE:
ret = ieee80211_wpa_set_wpa_ie(ieee, param, p->length);
break;
case IEEE_CMD_SET_ENCRYPTION:
ret = ieee80211_wpa_set_encryption(ieee, param, p->length);
break;
case IEEE_CMD_MLME:
ret = ieee80211_wpa_mlme(ieee, param->u.mlme.command,
param->u.mlme.reason_code);
break;
default:
printk("Unknown WPA supplicant request: %d\n",param->cmd);
ret = -EOPNOTSUPP;
break;
}
if (ret == 0 && copy_to_user(p->pointer, param, p->length))
ret = -EFAULT;
kfree(param);
out:
up(&ieee->wx_sem);
return ret;
}
void notify_wx_assoc_event(struct ieee80211_device *ieee)
{
union iwreq_data wrqu;
wrqu.ap_addr.sa_family = ARPHRD_ETHER;
if (ieee->state == IEEE80211_LINKED)
memcpy(wrqu.ap_addr.sa_data, ieee->current_network.bssid, ETH_ALEN);
else
memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
wireless_send_event(ieee->dev, SIOCGIWAP, &wrqu, NULL);
}
| gpl-2.0 |
hastalafiesta/HKernel | drivers/net/fs_enet/mii-fec.c | 2527 | 6073 | /*
* Combined Ethernet driver for Motorola MPC8xx and MPC82xx.
*
* Copyright (c) 2003 Intracom S.A.
* by Pantelis Antoniou <panto@intracom.gr>
*
* 2005 (c) MontaVista Software, Inc.
* Vitaly Bordug <vbordug@ru.mvista.com>
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/ptrace.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/bitops.h>
#include <linux/platform_device.h>
#include <linux/of_platform.h>
#include <asm/pgtable.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <asm/mpc5xxx.h>
#include "fs_enet.h"
#include "fec.h"
/* Make MII read/write commands for the FEC.
*/
#define mk_mii_read(REG) (0x60020000 | ((REG & 0x1f) << 18))
#define mk_mii_write(REG, VAL) (0x50020000 | ((REG & 0x1f) << 18) | (VAL & 0xffff))
#define mk_mii_end 0
#define FEC_MII_LOOPS 10000
static int fs_enet_fec_mii_read(struct mii_bus *bus , int phy_id, int location)
{
struct fec_info* fec = bus->priv;
struct fec __iomem *fecp = fec->fecp;
int i, ret = -1;
BUG_ON((in_be32(&fecp->fec_r_cntrl) & FEC_RCNTRL_MII_MODE) == 0);
/* Add PHY address to register command. */
out_be32(&fecp->fec_mii_data, (phy_id << 23) | mk_mii_read(location));
for (i = 0; i < FEC_MII_LOOPS; i++)
if ((in_be32(&fecp->fec_ievent) & FEC_ENET_MII) != 0)
break;
if (i < FEC_MII_LOOPS) {
out_be32(&fecp->fec_ievent, FEC_ENET_MII);
ret = in_be32(&fecp->fec_mii_data) & 0xffff;
}
return ret;
}
static int fs_enet_fec_mii_write(struct mii_bus *bus, int phy_id, int location, u16 val)
{
struct fec_info* fec = bus->priv;
struct fec __iomem *fecp = fec->fecp;
int i;
/* this must never happen */
BUG_ON((in_be32(&fecp->fec_r_cntrl) & FEC_RCNTRL_MII_MODE) == 0);
/* Add PHY address to register command. */
out_be32(&fecp->fec_mii_data, (phy_id << 23) | mk_mii_write(location, val));
for (i = 0; i < FEC_MII_LOOPS; i++)
if ((in_be32(&fecp->fec_ievent) & FEC_ENET_MII) != 0)
break;
if (i < FEC_MII_LOOPS)
out_be32(&fecp->fec_ievent, FEC_ENET_MII);
return 0;
}
static int fs_enet_fec_mii_reset(struct mii_bus *bus)
{
/* nothing here - for now */
return 0;
}
static struct of_device_id fs_enet_mdio_fec_match[];
static int __devinit fs_enet_mdio_probe(struct platform_device *ofdev)
{
const struct of_device_id *match;
struct resource res;
struct mii_bus *new_bus;
struct fec_info *fec;
int (*get_bus_freq)(struct device_node *);
int ret = -ENOMEM, clock, speed;
match = of_match_device(fs_enet_mdio_fec_match, &ofdev->dev);
if (!match)
return -EINVAL;
get_bus_freq = match->data;
new_bus = mdiobus_alloc();
if (!new_bus)
goto out;
fec = kzalloc(sizeof(struct fec_info), GFP_KERNEL);
if (!fec)
goto out_mii;
new_bus->priv = fec;
new_bus->name = "FEC MII Bus";
new_bus->read = &fs_enet_fec_mii_read;
new_bus->write = &fs_enet_fec_mii_write;
new_bus->reset = &fs_enet_fec_mii_reset;
ret = of_address_to_resource(ofdev->dev.of_node, 0, &res);
if (ret)
goto out_res;
snprintf(new_bus->id, MII_BUS_ID_SIZE, "%x", res.start);
fec->fecp = ioremap(res.start, res.end - res.start + 1);
if (!fec->fecp)
goto out_fec;
if (get_bus_freq) {
clock = get_bus_freq(ofdev->dev.of_node);
if (!clock) {
/* Use maximum divider if clock is unknown */
dev_warn(&ofdev->dev, "could not determine IPS clock\n");
clock = 0x3F * 5000000;
}
} else
clock = ppc_proc_freq;
/*
* Scale for a MII clock <= 2.5 MHz
* Note that only 6 bits (25:30) are available for MII speed.
*/
speed = (clock + 4999999) / 5000000;
if (speed > 0x3F) {
speed = 0x3F;
dev_err(&ofdev->dev,
"MII clock (%d Hz) exceeds max (2.5 MHz)\n",
clock / speed);
}
fec->mii_speed = speed << 1;
setbits32(&fec->fecp->fec_r_cntrl, FEC_RCNTRL_MII_MODE);
setbits32(&fec->fecp->fec_ecntrl, FEC_ECNTRL_PINMUX |
FEC_ECNTRL_ETHER_EN);
out_be32(&fec->fecp->fec_ievent, FEC_ENET_MII);
clrsetbits_be32(&fec->fecp->fec_mii_speed, 0x7E, fec->mii_speed);
new_bus->phy_mask = ~0;
new_bus->irq = kmalloc(sizeof(int) * PHY_MAX_ADDR, GFP_KERNEL);
if (!new_bus->irq)
goto out_unmap_regs;
new_bus->parent = &ofdev->dev;
dev_set_drvdata(&ofdev->dev, new_bus);
ret = of_mdiobus_register(new_bus, ofdev->dev.of_node);
if (ret)
goto out_free_irqs;
return 0;
out_free_irqs:
dev_set_drvdata(&ofdev->dev, NULL);
kfree(new_bus->irq);
out_unmap_regs:
iounmap(fec->fecp);
out_res:
out_fec:
kfree(fec);
out_mii:
mdiobus_free(new_bus);
out:
return ret;
}
static int fs_enet_mdio_remove(struct platform_device *ofdev)
{
struct mii_bus *bus = dev_get_drvdata(&ofdev->dev);
struct fec_info *fec = bus->priv;
mdiobus_unregister(bus);
dev_set_drvdata(&ofdev->dev, NULL);
kfree(bus->irq);
iounmap(fec->fecp);
kfree(fec);
mdiobus_free(bus);
return 0;
}
static struct of_device_id fs_enet_mdio_fec_match[] = {
{
.compatible = "fsl,pq1-fec-mdio",
},
#if defined(CONFIG_PPC_MPC512x)
{
.compatible = "fsl,mpc5121-fec-mdio",
.data = mpc5xxx_get_bus_frequency,
},
#endif
{},
};
MODULE_DEVICE_TABLE(of, fs_enet_mdio_fec_match);
static struct platform_driver fs_enet_fec_mdio_driver = {
.driver = {
.name = "fsl-fec-mdio",
.owner = THIS_MODULE,
.of_match_table = fs_enet_mdio_fec_match,
},
.probe = fs_enet_mdio_probe,
.remove = fs_enet_mdio_remove,
};
static int fs_enet_mdio_fec_init(void)
{
return platform_driver_register(&fs_enet_fec_mdio_driver);
}
static void fs_enet_mdio_fec_exit(void)
{
platform_driver_unregister(&fs_enet_fec_mdio_driver);
}
module_init(fs_enet_mdio_fec_init);
module_exit(fs_enet_mdio_fec_exit);
| gpl-2.0 |
Sharlion/android_kernel_lenovo_msm8992 | arch/mips/math-emu/dp_sub.c | 2527 | 4950 | /* IEEE754 floating point arithmetic
* double precision: common utilities
*/
/*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* ########################################################################
*
* This program is free software; you can distribute 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 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 "ieee754dp.h"
ieee754dp ieee754dp_sub(ieee754dp x, ieee754dp y)
{
COMPXDP;
COMPYDP;
EXPLODEXDP;
EXPLODEYDP;
CLEARCX;
FLUSHXDP;
FLUSHYDP;
switch (CLPAIR(xc, yc)) {
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_INF):
SETCX(IEEE754_INVALID_OPERATION);
return ieee754dp_nanxcpt(ieee754dp_indef(), "sub", x, y);
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_QNAN):
return y;
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_INF):
return x;
/* Infinity handling
*/
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_INF):
if (xs != ys)
return x;
SETCX(IEEE754_INVALID_OPERATION);
return ieee754dp_xcpt(ieee754dp_indef(), "sub", x, y);
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_INF):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_INF):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_INF):
return ieee754dp_inf(ys ^ 1);
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_DNORM):
return x;
/* Zero handling
*/
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_ZERO):
if (xs != ys)
return x;
else
return ieee754dp_zero(ieee754_csr.rm ==
IEEE754_RD);
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_ZERO):
return x;
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_DNORM):
/* quick fix up */
DPSIGN(y) ^= 1;
return y;
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_DNORM):
DPDNORMX;
/* FALL THROUGH */
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_DNORM):
/* normalize ym,ye */
DPDNORMY;
break;
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_NORM):
/* normalize xm,xe */
DPDNORMX;
break;
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_NORM):
break;
}
/* flip sign of y and handle as add */
ys ^= 1;
assert(xm & DP_HIDDEN_BIT);
assert(ym & DP_HIDDEN_BIT);
/* provide guard,round and stick bit dpace */
xm <<= 3;
ym <<= 3;
if (xe > ye) {
/* have to shift y fraction right to align
*/
int s = xe - ye;
ym = XDPSRS(ym, s);
ye += s;
} else if (ye > xe) {
/* have to shift x fraction right to align
*/
int s = ye - xe;
xm = XDPSRS(xm, s);
xe += s;
}
assert(xe == ye);
assert(xe <= DP_EMAX);
if (xs == ys) {
/* generate 28 bit result of adding two 27 bit numbers
*/
xm = xm + ym;
xe = xe;
xs = xs;
if (xm >> (DP_MBITS + 1 + 3)) { /* carry out */
xm = XDPSRS1(xm); /* shift preserving sticky */
xe++;
}
} else {
if (xm >= ym) {
xm = xm - ym;
xe = xe;
xs = xs;
} else {
xm = ym - xm;
xe = xe;
xs = ys;
}
if (xm == 0) {
if (ieee754_csr.rm == IEEE754_RD)
return ieee754dp_zero(1); /* round negative inf. => sign = -1 */
else
return ieee754dp_zero(0); /* other round modes => sign = 1 */
}
/* normalize to rounding precision
*/
while ((xm >> (DP_MBITS + 3)) == 0) {
xm <<= 1;
xe--;
}
}
DPNORMRET2(xs, xe, xm, "sub", x, y);
}
| gpl-2.0 |
str90/RK3188_tablet_kernel_sources | drivers/staging/tm6000/tm6000-core.c | 2783 | 26288 | /*
* tm6000-core.c - driver for TM5600/TM6000/TM6010 USB video capture devices
*
* Copyright (C) 2006-2007 Mauro Carvalho Chehab <mchehab@infradead.org>
*
* Copyright (C) 2007 Michel Ludwig <michel.ludwig@gmail.com>
* - DVB-T support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation version 2
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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/kernel.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/i2c.h>
#include "tm6000.h"
#include "tm6000-regs.h"
#include <media/v4l2-common.h>
#include <media/tuner.h>
#define USB_TIMEOUT (5 * HZ) /* ms */
int tm6000_read_write_usb(struct tm6000_core *dev, u8 req_type, u8 req,
u16 value, u16 index, u8 *buf, u16 len)
{
int ret, i;
unsigned int pipe;
u8 *data = NULL;
if (len)
data = kzalloc(len, GFP_KERNEL);
if (req_type & USB_DIR_IN)
pipe = usb_rcvctrlpipe(dev->udev, 0);
else {
pipe = usb_sndctrlpipe(dev->udev, 0);
memcpy(data, buf, len);
}
if (tm6000_debug & V4L2_DEBUG_I2C) {
printk("(dev %p, pipe %08x): ", dev->udev, pipe);
printk("%s: %02x %02x %02x %02x %02x %02x %02x %02x ",
(req_type & USB_DIR_IN) ? " IN" : "OUT",
req_type, req, value&0xff, value>>8, index&0xff,
index>>8, len&0xff, len>>8);
if (!(req_type & USB_DIR_IN)) {
printk(">>> ");
for (i = 0; i < len; i++)
printk(" %02x", buf[i]);
printk("\n");
}
}
ret = usb_control_msg(dev->udev, pipe, req, req_type, value, index,
data, len, USB_TIMEOUT);
if (req_type & USB_DIR_IN)
memcpy(buf, data, len);
if (tm6000_debug & V4L2_DEBUG_I2C) {
if (ret < 0) {
if (req_type & USB_DIR_IN)
printk("<<< (len=%d)\n", len);
printk("%s: Error #%d\n", __FUNCTION__, ret);
} else if (req_type & USB_DIR_IN) {
printk("<<< ");
for (i = 0; i < len; i++)
printk(" %02x", buf[i]);
printk("\n");
}
}
kfree(data);
msleep(5);
return ret;
}
int tm6000_set_reg(struct tm6000_core *dev, u8 req, u16 value, u16 index)
{
return
tm6000_read_write_usb(dev, USB_DIR_OUT | USB_TYPE_VENDOR,
req, value, index, NULL, 0);
}
EXPORT_SYMBOL_GPL(tm6000_set_reg);
int tm6000_get_reg(struct tm6000_core *dev, u8 req, u16 value, u16 index)
{
int rc;
u8 buf[1];
rc = tm6000_read_write_usb(dev, USB_DIR_IN | USB_TYPE_VENDOR, req,
value, index, buf, 1);
if (rc < 0)
return rc;
return *buf;
}
EXPORT_SYMBOL_GPL(tm6000_get_reg);
int tm6000_set_reg_mask(struct tm6000_core *dev, u8 req, u16 value,
u16 index, u16 mask)
{
int rc;
u8 buf[1];
u8 new_index;
rc = tm6000_read_write_usb(dev, USB_DIR_IN | USB_TYPE_VENDOR, req,
value, index, buf, 1);
if (rc < 0)
return rc;
new_index = (buf[0] & ~mask) | (index & mask);
if (new_index == index)
return 0;
return tm6000_read_write_usb(dev, USB_DIR_OUT | USB_TYPE_VENDOR,
req, value, new_index, NULL, 0);
}
EXPORT_SYMBOL_GPL(tm6000_set_reg_mask);
int tm6000_get_reg16(struct tm6000_core *dev, u8 req, u16 value, u16 index)
{
int rc;
u8 buf[2];
rc = tm6000_read_write_usb(dev, USB_DIR_IN | USB_TYPE_VENDOR, req,
value, index, buf, 2);
if (rc < 0)
return rc;
return buf[1]|buf[0]<<8;
}
int tm6000_get_reg32(struct tm6000_core *dev, u8 req, u16 value, u16 index)
{
int rc;
u8 buf[4];
rc = tm6000_read_write_usb(dev, USB_DIR_IN | USB_TYPE_VENDOR, req,
value, index, buf, 4);
if (rc < 0)
return rc;
return buf[3] | buf[2] << 8 | buf[1] << 16 | buf[0] << 24;
}
int tm6000_i2c_reset(struct tm6000_core *dev, u16 tsleep)
{
int rc;
rc = tm6000_set_reg(dev, REQ_03_SET_GET_MCU_PIN, TM6000_GPIO_CLK, 0);
if (rc < 0)
return rc;
msleep(tsleep);
rc = tm6000_set_reg(dev, REQ_03_SET_GET_MCU_PIN, TM6000_GPIO_CLK, 1);
msleep(tsleep);
return rc;
}
void tm6000_set_fourcc_format(struct tm6000_core *dev)
{
if (dev->dev_type == TM6010) {
int val;
val = tm6000_get_reg(dev, TM6010_REQ07_RCC_ACTIVE_VIDEO_IF, 0) & 0xfc;
if (dev->fourcc == V4L2_PIX_FMT_UYVY)
tm6000_set_reg(dev, TM6010_REQ07_RCC_ACTIVE_VIDEO_IF, val);
else
tm6000_set_reg(dev, TM6010_REQ07_RCC_ACTIVE_VIDEO_IF, val | 1);
} else {
if (dev->fourcc == V4L2_PIX_FMT_UYVY)
tm6000_set_reg(dev, TM6010_REQ07_RC1_TRESHOLD, 0xd0);
else
tm6000_set_reg(dev, TM6010_REQ07_RC1_TRESHOLD, 0x90);
}
}
static void tm6000_set_vbi(struct tm6000_core *dev)
{
/*
* FIXME:
* VBI lines and start/end are different between 60Hz and 50Hz
* So, it is very likely that we need to change the config to
* something that takes it into account, doing something different
* if (dev->norm & V4L2_STD_525_60)
*/
if (dev->dev_type == TM6010) {
tm6000_set_reg(dev, TM6010_REQ07_R3F_RESET, 0x01);
tm6000_set_reg(dev, TM6010_REQ07_R41_TELETEXT_VBI_CODE1, 0x27);
tm6000_set_reg(dev, TM6010_REQ07_R42_VBI_DATA_HIGH_LEVEL, 0x55);
tm6000_set_reg(dev, TM6010_REQ07_R43_VBI_DATA_TYPE_LINE7, 0x66);
tm6000_set_reg(dev, TM6010_REQ07_R44_VBI_DATA_TYPE_LINE8, 0x66);
tm6000_set_reg(dev, TM6010_REQ07_R45_VBI_DATA_TYPE_LINE9, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R46_VBI_DATA_TYPE_LINE10, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R47_VBI_DATA_TYPE_LINE11, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R48_VBI_DATA_TYPE_LINE12, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R49_VBI_DATA_TYPE_LINE13, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R4A_VBI_DATA_TYPE_LINE14, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R4B_VBI_DATA_TYPE_LINE15, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R4C_VBI_DATA_TYPE_LINE16, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R4D_VBI_DATA_TYPE_LINE17, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R4E_VBI_DATA_TYPE_LINE18, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R4F_VBI_DATA_TYPE_LINE19, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R50_VBI_DATA_TYPE_LINE20, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R51_VBI_DATA_TYPE_LINE21, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R52_VBI_DATA_TYPE_LINE22, 0x66);
tm6000_set_reg(dev,
TM6010_REQ07_R53_VBI_DATA_TYPE_LINE23, 0x00);
tm6000_set_reg(dev,
TM6010_REQ07_R54_VBI_DATA_TYPE_RLINES, 0x00);
tm6000_set_reg(dev,
TM6010_REQ07_R55_VBI_LOOP_FILTER_GAIN, 0x01);
tm6000_set_reg(dev,
TM6010_REQ07_R56_VBI_LOOP_FILTER_I_GAIN, 0x00);
tm6000_set_reg(dev,
TM6010_REQ07_R57_VBI_LOOP_FILTER_P_GAIN, 0x02);
tm6000_set_reg(dev, TM6010_REQ07_R58_VBI_CAPTION_DTO1, 0x35);
tm6000_set_reg(dev, TM6010_REQ07_R59_VBI_CAPTION_DTO0, 0xa0);
tm6000_set_reg(dev, TM6010_REQ07_R5A_VBI_TELETEXT_DTO1, 0x11);
tm6000_set_reg(dev, TM6010_REQ07_R5B_VBI_TELETEXT_DTO0, 0x4c);
tm6000_set_reg(dev, TM6010_REQ07_R40_TELETEXT_VBI_CODE0, 0x01);
tm6000_set_reg(dev, TM6010_REQ07_R3F_RESET, 0x00);
}
}
int tm6000_init_analog_mode(struct tm6000_core *dev)
{
struct v4l2_frequency f;
if (dev->dev_type == TM6010) {
/* Enable video and audio */
tm6000_set_reg_mask(dev, TM6010_REQ07_RCC_ACTIVE_VIDEO_IF,
0x60, 0x60);
/* Disable TS input */
tm6000_set_reg_mask(dev, TM6010_REQ07_RC0_ACTIVE_VIDEO_SOURCE,
0x00, 0x40);
} else {
/* Enables soft reset */
tm6000_set_reg(dev, TM6010_REQ07_R3F_RESET, 0x01);
if (dev->scaler)
/* Disable Hfilter and Enable TS Drop err */
tm6000_set_reg(dev, TM6010_REQ07_RC0_ACTIVE_VIDEO_SOURCE, 0x20);
else /* Enable Hfilter and disable TS Drop err */
tm6000_set_reg(dev, TM6010_REQ07_RC0_ACTIVE_VIDEO_SOURCE, 0x80);
tm6000_set_reg(dev, TM6010_REQ07_RC3_HSTART1, 0x88);
tm6000_set_reg(dev, TM6000_REQ07_RDA_CLK_SEL, 0x23);
tm6000_set_reg(dev, TM6010_REQ07_RD1_ADDR_FOR_REQ1, 0xc0);
tm6000_set_reg(dev, TM6010_REQ07_RD2_ADDR_FOR_REQ2, 0xd8);
tm6000_set_reg(dev, TM6010_REQ07_RD6_ENDP_REQ1_REQ2, 0x06);
tm6000_set_reg(dev, TM6000_REQ07_RDF_PWDOWN_ACLK, 0x1f);
/* AP Software reset */
tm6000_set_reg(dev, TM6010_REQ07_RFF_SOFT_RESET, 0x08);
tm6000_set_reg(dev, TM6010_REQ07_RFF_SOFT_RESET, 0x00);
tm6000_set_fourcc_format(dev);
/* Disables soft reset */
tm6000_set_reg(dev, TM6010_REQ07_R3F_RESET, 0x00);
}
msleep(20);
/* Tuner firmware can now be loaded */
/*
* FIXME: This is a hack! xc3028 "sleeps" when no channel is detected
* for more than a few seconds. Not sure why, as this behavior does
* not happen on other devices with xc3028. So, I suspect that it
* is yet another bug at tm6000. After start sleeping, decoding
* doesn't start automatically. Instead, it requires some
* I2C commands to wake it up. As we want to have image at the
* beginning, we needed to add this hack. The better would be to
* discover some way to make tm6000 to wake up without this hack.
*/
f.frequency = dev->freq;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, &f);
msleep(100);
tm6000_set_standard(dev);
tm6000_set_vbi(dev);
tm6000_set_audio_bitrate(dev, 48000);
/* switch dvb led off */
if (dev->gpio.dvb_led) {
tm6000_set_reg(dev, REQ_03_SET_GET_MCU_PIN,
dev->gpio.dvb_led, 0x01);
}
return 0;
}
int tm6000_init_digital_mode(struct tm6000_core *dev)
{
if (dev->dev_type == TM6010) {
/* Disable video and audio */
tm6000_set_reg_mask(dev, TM6010_REQ07_RCC_ACTIVE_VIDEO_IF,
0x00, 0x60);
/* Enable TS input */
tm6000_set_reg_mask(dev, TM6010_REQ07_RC0_ACTIVE_VIDEO_SOURCE,
0x40, 0x40);
/* all power down, but not the digital data port */
tm6000_set_reg(dev, TM6010_REQ07_RFE_POWER_DOWN, 0x28);
tm6000_set_reg(dev, TM6010_REQ08_RE2_POWER_DOWN_CTRL1, 0xfc);
tm6000_set_reg(dev, TM6010_REQ08_RE6_POWER_DOWN_CTRL2, 0xff);
} else {
tm6000_set_reg(dev, TM6010_REQ07_RFF_SOFT_RESET, 0x08);
tm6000_set_reg(dev, TM6010_REQ07_RFF_SOFT_RESET, 0x00);
tm6000_set_reg(dev, TM6010_REQ07_R3F_RESET, 0x01);
tm6000_set_reg(dev, TM6000_REQ07_RDF_PWDOWN_ACLK, 0x08);
tm6000_set_reg(dev, TM6000_REQ07_RE2_VADC_STATUS_CTL, 0x0c);
tm6000_set_reg(dev, TM6000_REQ07_RE8_VADC_PWDOWN_CTL, 0xff);
tm6000_set_reg(dev, TM6000_REQ07_REB_VADC_AADC_MODE, 0xd8);
tm6000_set_reg(dev, TM6010_REQ07_RC0_ACTIVE_VIDEO_SOURCE, 0x40);
tm6000_set_reg(dev, TM6010_REQ07_RC1_TRESHOLD, 0xd0);
tm6000_set_reg(dev, TM6010_REQ07_RC3_HSTART1, 0x09);
tm6000_set_reg(dev, TM6000_REQ07_RDA_CLK_SEL, 0x37);
tm6000_set_reg(dev, TM6010_REQ07_RD1_ADDR_FOR_REQ1, 0xd8);
tm6000_set_reg(dev, TM6010_REQ07_RD2_ADDR_FOR_REQ2, 0xc0);
tm6000_set_reg(dev, TM6010_REQ07_RD6_ENDP_REQ1_REQ2, 0x60);
tm6000_set_reg(dev, TM6000_REQ07_RE2_VADC_STATUS_CTL, 0x0c);
tm6000_set_reg(dev, TM6000_REQ07_RE8_VADC_PWDOWN_CTL, 0xff);
tm6000_set_reg(dev, TM6000_REQ07_REB_VADC_AADC_MODE, 0x08);
msleep(50);
tm6000_set_reg(dev, REQ_04_EN_DISABLE_MCU_INT, 0x0020, 0x00);
msleep(50);
tm6000_set_reg(dev, REQ_04_EN_DISABLE_MCU_INT, 0x0020, 0x01);
msleep(50);
tm6000_set_reg(dev, REQ_04_EN_DISABLE_MCU_INT, 0x0020, 0x00);
msleep(100);
}
/* switch dvb led on */
if (dev->gpio.dvb_led) {
tm6000_set_reg(dev, REQ_03_SET_GET_MCU_PIN,
dev->gpio.dvb_led, 0x00);
}
return 0;
}
EXPORT_SYMBOL(tm6000_init_digital_mode);
struct reg_init {
u8 req;
u8 reg;
u8 val;
};
/* The meaning of those initializations are unknown */
struct reg_init tm6000_init_tab[] = {
/* REG VALUE */
{ TM6000_REQ07_RDF_PWDOWN_ACLK, 0x1f },
{ TM6010_REQ07_RFF_SOFT_RESET, 0x08 },
{ TM6010_REQ07_RFF_SOFT_RESET, 0x00 },
{ TM6010_REQ07_RD5_POWERSAVE, 0x4f },
{ TM6000_REQ07_RDA_CLK_SEL, 0x23 },
{ TM6000_REQ07_RDB_OUT_SEL, 0x08 },
{ TM6000_REQ07_RE2_VADC_STATUS_CTL, 0x00 },
{ TM6000_REQ07_RE3_VADC_INP_LPF_SEL1, 0x10 },
{ TM6000_REQ07_RE5_VADC_INP_LPF_SEL2, 0x00 },
{ TM6000_REQ07_RE8_VADC_PWDOWN_CTL, 0x00 },
{ TM6000_REQ07_REB_VADC_AADC_MODE, 0x64 }, /* 48000 bits/sample, external input */
{ TM6000_REQ07_REE_VADC_CTRL_SEL_CONTROL, 0xc2 },
{ TM6010_REQ07_R3F_RESET, 0x01 }, /* Start of soft reset */
{ TM6010_REQ07_R00_VIDEO_CONTROL0, 0x00 },
{ TM6010_REQ07_R01_VIDEO_CONTROL1, 0x07 },
{ TM6010_REQ07_R02_VIDEO_CONTROL2, 0x5f },
{ TM6010_REQ07_R03_YC_SEP_CONTROL, 0x00 },
{ TM6010_REQ07_R05_NOISE_THRESHOLD, 0x64 },
{ TM6010_REQ07_R07_OUTPUT_CONTROL, 0x01 },
{ TM6010_REQ07_R08_LUMA_CONTRAST_ADJ, 0x82 },
{ TM6010_REQ07_R09_LUMA_BRIGHTNESS_ADJ, 0x36 },
{ TM6010_REQ07_R0A_CHROMA_SATURATION_ADJ, 0x50 },
{ TM6010_REQ07_R0C_CHROMA_AGC_CONTROL, 0x6a },
{ TM6010_REQ07_R11_AGC_PEAK_CONTROL, 0xc9 },
{ TM6010_REQ07_R12_AGC_GATE_STARTH, 0x07 },
{ TM6010_REQ07_R13_AGC_GATE_STARTL, 0x3b },
{ TM6010_REQ07_R14_AGC_GATE_WIDTH, 0x47 },
{ TM6010_REQ07_R15_AGC_BP_DELAY, 0x6f },
{ TM6010_REQ07_R17_HLOOP_MAXSTATE, 0xcd },
{ TM6010_REQ07_R18_CHROMA_DTO_INCREMENT3, 0x1e },
{ TM6010_REQ07_R19_CHROMA_DTO_INCREMENT2, 0x8b },
{ TM6010_REQ07_R1A_CHROMA_DTO_INCREMENT1, 0xa2 },
{ TM6010_REQ07_R1B_CHROMA_DTO_INCREMENT0, 0xe9 },
{ TM6010_REQ07_R1C_HSYNC_DTO_INCREMENT3, 0x1c },
{ TM6010_REQ07_R1D_HSYNC_DTO_INCREMENT2, 0xcc },
{ TM6010_REQ07_R1E_HSYNC_DTO_INCREMENT1, 0xcc },
{ TM6010_REQ07_R1F_HSYNC_DTO_INCREMENT0, 0xcd },
{ TM6010_REQ07_R20_HSYNC_RISING_EDGE_TIME, 0x3c },
{ TM6010_REQ07_R21_HSYNC_PHASE_OFFSET, 0x3c },
{ TM6010_REQ07_R2D_CHROMA_BURST_END, 0x48 },
{ TM6010_REQ07_R2E_ACTIVE_VIDEO_HSTART, 0x88 },
{ TM6010_REQ07_R30_ACTIVE_VIDEO_VSTART, 0x22 },
{ TM6010_REQ07_R31_ACTIVE_VIDEO_VHIGHT, 0x61 },
{ TM6010_REQ07_R32_VSYNC_HLOCK_MIN, 0x74 },
{ TM6010_REQ07_R33_VSYNC_HLOCK_MAX, 0x1c },
{ TM6010_REQ07_R34_VSYNC_AGC_MIN, 0x74 },
{ TM6010_REQ07_R35_VSYNC_AGC_MAX, 0x1c },
{ TM6010_REQ07_R36_VSYNC_VBI_MIN, 0x7a },
{ TM6010_REQ07_R37_VSYNC_VBI_MAX, 0x26 },
{ TM6010_REQ07_R38_VSYNC_THRESHOLD, 0x40 },
{ TM6010_REQ07_R39_VSYNC_TIME_CONSTANT, 0x0a },
{ TM6010_REQ07_R42_VBI_DATA_HIGH_LEVEL, 0x55 },
{ TM6010_REQ07_R51_VBI_DATA_TYPE_LINE21, 0x11 },
{ TM6010_REQ07_R55_VBI_LOOP_FILTER_GAIN, 0x01 },
{ TM6010_REQ07_R57_VBI_LOOP_FILTER_P_GAIN, 0x02 },
{ TM6010_REQ07_R58_VBI_CAPTION_DTO1, 0x35 },
{ TM6010_REQ07_R59_VBI_CAPTION_DTO0, 0xa0 },
{ TM6010_REQ07_R80_COMB_FILTER_TRESHOLD, 0x15 },
{ TM6010_REQ07_R82_COMB_FILTER_CONFIG, 0x42 },
{ TM6010_REQ07_RC1_TRESHOLD, 0xd0 },
{ TM6010_REQ07_RC3_HSTART1, 0x88 },
{ TM6010_REQ07_R3F_RESET, 0x00 }, /* End of the soft reset */
{ TM6010_REQ05_R18_IMASK7, 0x00 },
};
struct reg_init tm6010_init_tab[] = {
{ TM6010_REQ07_RC0_ACTIVE_VIDEO_SOURCE, 0x00 },
{ TM6010_REQ07_RC4_HSTART0, 0xa0 },
{ TM6010_REQ07_RC6_HEND0, 0x40 },
{ TM6010_REQ07_RCA_VEND0, 0x31 },
{ TM6010_REQ07_RCC_ACTIVE_VIDEO_IF, 0xe1 },
{ TM6010_REQ07_RE0_DVIDEO_SOURCE, 0x03 },
{ TM6010_REQ07_RFE_POWER_DOWN, 0x7f },
{ TM6010_REQ08_RE2_POWER_DOWN_CTRL1, 0xf0 },
{ TM6010_REQ08_RE3_ADC_IN1_SEL, 0xf4 },
{ TM6010_REQ08_RE4_ADC_IN2_SEL, 0xf8 },
{ TM6010_REQ08_RE6_POWER_DOWN_CTRL2, 0x00 },
{ TM6010_REQ08_REA_BUFF_DRV_CTRL, 0xf2 },
{ TM6010_REQ08_REB_SIF_GAIN_CTRL, 0xf0 },
{ TM6010_REQ08_REC_REVERSE_YC_CTRL, 0xc2 },
{ TM6010_REQ08_RF0_DAUDIO_INPUT_CONFIG, 0x60 },
{ TM6010_REQ08_RF1_AADC_POWER_DOWN, 0xfc },
{ TM6010_REQ07_R3F_RESET, 0x01 },
{ TM6010_REQ07_R00_VIDEO_CONTROL0, 0x00 },
{ TM6010_REQ07_R01_VIDEO_CONTROL1, 0x07 },
{ TM6010_REQ07_R02_VIDEO_CONTROL2, 0x5f },
{ TM6010_REQ07_R03_YC_SEP_CONTROL, 0x00 },
{ TM6010_REQ07_R05_NOISE_THRESHOLD, 0x64 },
{ TM6010_REQ07_R07_OUTPUT_CONTROL, 0x01 },
{ TM6010_REQ07_R08_LUMA_CONTRAST_ADJ, 0x82 },
{ TM6010_REQ07_R09_LUMA_BRIGHTNESS_ADJ, 0x36 },
{ TM6010_REQ07_R0A_CHROMA_SATURATION_ADJ, 0x50 },
{ TM6010_REQ07_R0C_CHROMA_AGC_CONTROL, 0x6a },
{ TM6010_REQ07_R11_AGC_PEAK_CONTROL, 0xc9 },
{ TM6010_REQ07_R12_AGC_GATE_STARTH, 0x07 },
{ TM6010_REQ07_R13_AGC_GATE_STARTL, 0x3b },
{ TM6010_REQ07_R14_AGC_GATE_WIDTH, 0x47 },
{ TM6010_REQ07_R15_AGC_BP_DELAY, 0x6f },
{ TM6010_REQ07_R17_HLOOP_MAXSTATE, 0xcd },
{ TM6010_REQ07_R18_CHROMA_DTO_INCREMENT3, 0x1e },
{ TM6010_REQ07_R19_CHROMA_DTO_INCREMENT2, 0x8b },
{ TM6010_REQ07_R1A_CHROMA_DTO_INCREMENT1, 0xa2 },
{ TM6010_REQ07_R1B_CHROMA_DTO_INCREMENT0, 0xe9 },
{ TM6010_REQ07_R1C_HSYNC_DTO_INCREMENT3, 0x1c },
{ TM6010_REQ07_R1D_HSYNC_DTO_INCREMENT2, 0xcc },
{ TM6010_REQ07_R1E_HSYNC_DTO_INCREMENT1, 0xcc },
{ TM6010_REQ07_R1F_HSYNC_DTO_INCREMENT0, 0xcd },
{ TM6010_REQ07_R20_HSYNC_RISING_EDGE_TIME, 0x3c },
{ TM6010_REQ07_R21_HSYNC_PHASE_OFFSET, 0x3c },
{ TM6010_REQ07_R2D_CHROMA_BURST_END, 0x48 },
{ TM6010_REQ07_R2E_ACTIVE_VIDEO_HSTART, 0x88 },
{ TM6010_REQ07_R30_ACTIVE_VIDEO_VSTART, 0x22 },
{ TM6010_REQ07_R31_ACTIVE_VIDEO_VHIGHT, 0x61 },
{ TM6010_REQ07_R32_VSYNC_HLOCK_MIN, 0x74 },
{ TM6010_REQ07_R33_VSYNC_HLOCK_MAX, 0x1c },
{ TM6010_REQ07_R34_VSYNC_AGC_MIN, 0x74 },
{ TM6010_REQ07_R35_VSYNC_AGC_MAX, 0x1c },
{ TM6010_REQ07_R36_VSYNC_VBI_MIN, 0x7a },
{ TM6010_REQ07_R37_VSYNC_VBI_MAX, 0x26 },
{ TM6010_REQ07_R38_VSYNC_THRESHOLD, 0x40 },
{ TM6010_REQ07_R39_VSYNC_TIME_CONSTANT, 0x0a },
{ TM6010_REQ07_R42_VBI_DATA_HIGH_LEVEL, 0x55 },
{ TM6010_REQ07_R51_VBI_DATA_TYPE_LINE21, 0x11 },
{ TM6010_REQ07_R55_VBI_LOOP_FILTER_GAIN, 0x01 },
{ TM6010_REQ07_R57_VBI_LOOP_FILTER_P_GAIN, 0x02 },
{ TM6010_REQ07_R58_VBI_CAPTION_DTO1, 0x35 },
{ TM6010_REQ07_R59_VBI_CAPTION_DTO0, 0xa0 },
{ TM6010_REQ07_R80_COMB_FILTER_TRESHOLD, 0x15 },
{ TM6010_REQ07_R82_COMB_FILTER_CONFIG, 0x42 },
{ TM6010_REQ07_RC1_TRESHOLD, 0xd0 },
{ TM6010_REQ07_RC3_HSTART1, 0x88 },
{ TM6010_REQ07_R3F_RESET, 0x00 },
{ TM6010_REQ05_R18_IMASK7, 0x00 },
{ TM6010_REQ07_RD8_IR_LEADER1, 0xaa },
{ TM6010_REQ07_RD8_IR_LEADER0, 0x30 },
{ TM6010_REQ07_RD8_IR_PULSE_CNT1, 0x20 },
{ TM6010_REQ07_RD8_IR_PULSE_CNT0, 0xd0 },
{ REQ_04_EN_DISABLE_MCU_INT, 0x02, 0x00 },
{ TM6010_REQ07_RD8_IR, 0x2f },
/* set remote wakeup key:any key wakeup */
{ TM6010_REQ07_RE5_REMOTE_WAKEUP, 0xfe },
{ TM6010_REQ07_RD8_IR_WAKEUP_SEL, 0xff },
};
int tm6000_init(struct tm6000_core *dev)
{
int board, rc = 0, i, size;
struct reg_init *tab;
/* Check board revision */
board = tm6000_get_reg32(dev, REQ_40_GET_VERSION, 0, 0);
if (board >= 0) {
switch (board & 0xff) {
case 0xf3:
printk(KERN_INFO "Found tm6000\n");
if (dev->dev_type != TM6000)
dev->dev_type = TM6000;
break;
case 0xf4:
printk(KERN_INFO "Found tm6010\n");
if (dev->dev_type != TM6010)
dev->dev_type = TM6010;
break;
default:
printk(KERN_INFO "Unknown board version = 0x%08x\n", board);
}
} else
printk(KERN_ERR "Error %i while retrieving board version\n", board);
if (dev->dev_type == TM6010) {
tab = tm6010_init_tab;
size = ARRAY_SIZE(tm6010_init_tab);
} else {
tab = tm6000_init_tab;
size = ARRAY_SIZE(tm6000_init_tab);
}
/* Load board's initialization table */
for (i = 0; i < size; i++) {
rc = tm6000_set_reg(dev, tab[i].req, tab[i].reg, tab[i].val);
if (rc < 0) {
printk(KERN_ERR "Error %i while setting req %d, "
"reg %d to value %d\n", rc,
tab[i].req, tab[i].reg, tab[i].val);
return rc;
}
}
msleep(5); /* Just to be conservative */
rc = tm6000_cards_setup(dev);
return rc;
}
int tm6000_set_audio_bitrate(struct tm6000_core *dev, int bitrate)
{
int val = 0;
u8 areg_f0 = 0x60; /* ADC MCLK = 250 Fs */
u8 areg_0a = 0x91; /* SIF 48KHz */
switch (bitrate) {
case 48000:
areg_f0 = 0x60; /* ADC MCLK = 250 Fs */
areg_0a = 0x91; /* SIF 48KHz */
dev->audio_bitrate = bitrate;
break;
case 32000:
areg_f0 = 0x00; /* ADC MCLK = 375 Fs */
areg_0a = 0x90; /* SIF 32KHz */
dev->audio_bitrate = bitrate;
break;
default:
return -EINVAL;
}
/* enable I2S, if we use sif or external I2S device */
if (dev->dev_type == TM6010) {
val = tm6000_set_reg(dev, TM6010_REQ08_R0A_A_I2S_MOD, areg_0a);
if (val < 0)
return val;
val = tm6000_set_reg_mask(dev, TM6010_REQ08_RF0_DAUDIO_INPUT_CONFIG,
areg_f0, 0xf0);
if (val < 0)
return val;
} else {
val = tm6000_set_reg_mask(dev, TM6000_REQ07_REB_VADC_AADC_MODE,
areg_f0, 0xf0);
if (val < 0)
return val;
}
return 0;
}
EXPORT_SYMBOL_GPL(tm6000_set_audio_bitrate);
int tm6000_set_audio_rinput(struct tm6000_core *dev)
{
if (dev->dev_type == TM6010) {
/* Audio crossbar setting, default SIF1 */
u8 areg_f0;
switch (dev->rinput.amux) {
case TM6000_AMUX_SIF1:
case TM6000_AMUX_SIF2:
areg_f0 = 0x03;
break;
case TM6000_AMUX_ADC1:
areg_f0 = 0x00;
break;
case TM6000_AMUX_ADC2:
areg_f0 = 0x08;
break;
case TM6000_AMUX_I2S:
areg_f0 = 0x04;
break;
default:
printk(KERN_INFO "%s: audio input dosn't support\n",
dev->name);
return 0;
break;
}
/* Set audio input crossbar */
tm6000_set_reg_mask(dev, TM6010_REQ08_RF0_DAUDIO_INPUT_CONFIG,
areg_f0, 0x0f);
} else {
u8 areg_eb;
/* Audio setting, default LINE1 */
switch (dev->rinput.amux) {
case TM6000_AMUX_ADC1:
areg_eb = 0x00;
break;
case TM6000_AMUX_ADC2:
areg_eb = 0x04;
break;
default:
printk(KERN_INFO "%s: audio input dosn't support\n",
dev->name);
return 0;
break;
}
/* Set audio input */
tm6000_set_reg_mask(dev, TM6000_REQ07_REB_VADC_AADC_MODE,
areg_eb, 0x0f);
}
return 0;
}
void tm6010_set_mute_sif(struct tm6000_core *dev, u8 mute)
{
u8 mute_reg = 0;
if (mute)
mute_reg = 0x08;
tm6000_set_reg_mask(dev, TM6010_REQ08_R0A_A_I2S_MOD, mute_reg, 0x08);
}
void tm6010_set_mute_adc(struct tm6000_core *dev, u8 mute)
{
u8 mute_reg = 0;
if (mute)
mute_reg = 0x20;
if (dev->dev_type == TM6010) {
tm6000_set_reg_mask(dev, TM6010_REQ08_RF2_LEFT_CHANNEL_VOL,
mute_reg, 0x20);
tm6000_set_reg_mask(dev, TM6010_REQ08_RF3_RIGHT_CHANNEL_VOL,
mute_reg, 0x20);
} else {
tm6000_set_reg_mask(dev, TM6000_REQ07_REC_VADC_AADC_LVOL,
mute_reg, 0x20);
tm6000_set_reg_mask(dev, TM6000_REQ07_RED_VADC_AADC_RVOL,
mute_reg, 0x20);
}
}
int tm6000_tvaudio_set_mute(struct tm6000_core *dev, u8 mute)
{
enum tm6000_mux mux;
if (dev->radio)
mux = dev->rinput.amux;
else
mux = dev->vinput[dev->input].amux;
switch (mux) {
case TM6000_AMUX_SIF1:
case TM6000_AMUX_SIF2:
if (dev->dev_type == TM6010)
tm6010_set_mute_sif(dev, mute);
else {
printk(KERN_INFO "ERROR: TM5600 and TM6000 don't has"
" SIF audio inputs. Please check the %s"
" configuration.\n", dev->name);
return -EINVAL;
}
break;
case TM6000_AMUX_ADC1:
case TM6000_AMUX_ADC2:
tm6010_set_mute_adc(dev, mute);
break;
default:
return -EINVAL;
break;
}
return 0;
}
void tm6010_set_volume_sif(struct tm6000_core *dev, int vol)
{
u8 vol_reg;
vol_reg = vol & 0x0F;
if (vol < 0)
vol_reg |= 0x40;
tm6000_set_reg(dev, TM6010_REQ08_R07_A_LEFT_VOL, vol_reg);
tm6000_set_reg(dev, TM6010_REQ08_R08_A_RIGHT_VOL, vol_reg);
}
void tm6010_set_volume_adc(struct tm6000_core *dev, int vol)
{
u8 vol_reg;
vol_reg = (vol + 0x10) & 0x1f;
if (dev->dev_type == TM6010) {
tm6000_set_reg(dev, TM6010_REQ08_RF2_LEFT_CHANNEL_VOL, vol_reg);
tm6000_set_reg(dev, TM6010_REQ08_RF3_RIGHT_CHANNEL_VOL, vol_reg);
} else {
tm6000_set_reg(dev, TM6000_REQ07_REC_VADC_AADC_LVOL, vol_reg);
tm6000_set_reg(dev, TM6000_REQ07_RED_VADC_AADC_RVOL, vol_reg);
}
}
void tm6000_set_volume(struct tm6000_core *dev, int vol)
{
enum tm6000_mux mux;
if (dev->radio) {
mux = dev->rinput.amux;
vol += 8; /* Offset to 0 dB */
} else
mux = dev->vinput[dev->input].amux;
switch (mux) {
case TM6000_AMUX_SIF1:
case TM6000_AMUX_SIF2:
if (dev->dev_type == TM6010)
tm6010_set_volume_sif(dev, vol);
else
printk(KERN_INFO "ERROR: TM5600 and TM6000 don't has"
" SIF audio inputs. Please check the %s"
" configuration.\n", dev->name);
break;
case TM6000_AMUX_ADC1:
case TM6000_AMUX_ADC2:
tm6010_set_volume_adc(dev, vol);
break;
default:
break;
}
}
static LIST_HEAD(tm6000_devlist);
static DEFINE_MUTEX(tm6000_devlist_mutex);
/*
* tm6000_realease_resource()
*/
void tm6000_remove_from_devlist(struct tm6000_core *dev)
{
mutex_lock(&tm6000_devlist_mutex);
list_del(&dev->devlist);
mutex_unlock(&tm6000_devlist_mutex);
};
void tm6000_add_into_devlist(struct tm6000_core *dev)
{
mutex_lock(&tm6000_devlist_mutex);
list_add_tail(&dev->devlist, &tm6000_devlist);
mutex_unlock(&tm6000_devlist_mutex);
};
/*
* Extension interface
*/
static LIST_HEAD(tm6000_extension_devlist);
int tm6000_call_fillbuf(struct tm6000_core *dev, enum tm6000_ops_type type,
char *buf, int size)
{
struct tm6000_ops *ops = NULL;
/* FIXME: tm6000_extension_devlist_lock should be a spinlock */
if (!list_empty(&tm6000_extension_devlist)) {
list_for_each_entry(ops, &tm6000_extension_devlist, next) {
if (ops->fillbuf && ops->type == type)
ops->fillbuf(dev, buf, size);
}
}
return 0;
}
int tm6000_register_extension(struct tm6000_ops *ops)
{
struct tm6000_core *dev = NULL;
mutex_lock(&tm6000_devlist_mutex);
list_add_tail(&ops->next, &tm6000_extension_devlist);
list_for_each_entry(dev, &tm6000_devlist, devlist) {
ops->init(dev);
printk(KERN_INFO "%s: Initialized (%s) extension\n",
dev->name, ops->name);
}
mutex_unlock(&tm6000_devlist_mutex);
return 0;
}
EXPORT_SYMBOL(tm6000_register_extension);
void tm6000_unregister_extension(struct tm6000_ops *ops)
{
struct tm6000_core *dev = NULL;
mutex_lock(&tm6000_devlist_mutex);
list_for_each_entry(dev, &tm6000_devlist, devlist)
ops->fini(dev);
printk(KERN_INFO "tm6000: Remove (%s) extension\n", ops->name);
list_del(&ops->next);
mutex_unlock(&tm6000_devlist_mutex);
}
EXPORT_SYMBOL(tm6000_unregister_extension);
void tm6000_init_extension(struct tm6000_core *dev)
{
struct tm6000_ops *ops = NULL;
mutex_lock(&tm6000_devlist_mutex);
if (!list_empty(&tm6000_extension_devlist)) {
list_for_each_entry(ops, &tm6000_extension_devlist, next) {
if (ops->init)
ops->init(dev);
}
}
mutex_unlock(&tm6000_devlist_mutex);
}
void tm6000_close_extension(struct tm6000_core *dev)
{
struct tm6000_ops *ops = NULL;
mutex_lock(&tm6000_devlist_mutex);
if (!list_empty(&tm6000_extension_devlist)) {
list_for_each_entry(ops, &tm6000_extension_devlist, next) {
if (ops->fini)
ops->fini(dev);
}
}
mutex_unlock(&tm6000_devlist_mutex);
}
| gpl-2.0 |
TimmyTossPot/rk30-kernel | drivers/mtd/maps/dc21285.c | 2783 | 5705 | /*
* MTD map driver for flash on the DC21285 (the StrongARM-110 companion chip)
*
* (C) 2000 Nicolas Pitre <nico@fluxnic.net>
*
* This code is GPL
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <asm/io.h>
#include <asm/hardware/dec21285.h>
#include <asm/mach-types.h>
static struct mtd_info *dc21285_mtd;
#ifdef CONFIG_ARCH_NETWINDER
/*
* This is really ugly, but it seams to be the only
* realiable way to do it, as the cpld state machine
* is unpredictible. So we have a 25us penalty per
* write access.
*/
static void nw_en_write(void)
{
unsigned long flags;
/*
* we want to write a bit pattern XXX1 to Xilinx to enable
* the write gate, which will be open for about the next 2ms.
*/
spin_lock_irqsave(&nw_gpio_lock, flags);
nw_cpld_modify(CPLD_FLASH_WR_ENABLE, CPLD_FLASH_WR_ENABLE);
spin_unlock_irqrestore(&nw_gpio_lock, flags);
/*
* let the ISA bus to catch on...
*/
udelay(25);
}
#else
#define nw_en_write() do { } while (0)
#endif
static map_word dc21285_read8(struct map_info *map, unsigned long ofs)
{
map_word val;
val.x[0] = *(uint8_t*)(map->virt + ofs);
return val;
}
static map_word dc21285_read16(struct map_info *map, unsigned long ofs)
{
map_word val;
val.x[0] = *(uint16_t*)(map->virt + ofs);
return val;
}
static map_word dc21285_read32(struct map_info *map, unsigned long ofs)
{
map_word val;
val.x[0] = *(uint32_t*)(map->virt + ofs);
return val;
}
static void dc21285_copy_from(struct map_info *map, void *to, unsigned long from, ssize_t len)
{
memcpy(to, (void*)(map->virt + from), len);
}
static void dc21285_write8(struct map_info *map, const map_word d, unsigned long adr)
{
if (machine_is_netwinder())
nw_en_write();
*CSR_ROMWRITEREG = adr & 3;
adr &= ~3;
*(uint8_t*)(map->virt + adr) = d.x[0];
}
static void dc21285_write16(struct map_info *map, const map_word d, unsigned long adr)
{
if (machine_is_netwinder())
nw_en_write();
*CSR_ROMWRITEREG = adr & 3;
adr &= ~3;
*(uint16_t*)(map->virt + adr) = d.x[0];
}
static void dc21285_write32(struct map_info *map, const map_word d, unsigned long adr)
{
if (machine_is_netwinder())
nw_en_write();
*(uint32_t*)(map->virt + adr) = d.x[0];
}
static void dc21285_copy_to_32(struct map_info *map, unsigned long to, const void *from, ssize_t len)
{
while (len > 0) {
map_word d;
d.x[0] = *((uint32_t*)from);
dc21285_write32(map, d, to);
from += 4;
to += 4;
len -= 4;
}
}
static void dc21285_copy_to_16(struct map_info *map, unsigned long to, const void *from, ssize_t len)
{
while (len > 0) {
map_word d;
d.x[0] = *((uint16_t*)from);
dc21285_write16(map, d, to);
from += 2;
to += 2;
len -= 2;
}
}
static void dc21285_copy_to_8(struct map_info *map, unsigned long to, const void *from, ssize_t len)
{
map_word d;
d.x[0] = *((uint8_t*)from);
dc21285_write8(map, d, to);
from++;
to++;
len--;
}
static struct map_info dc21285_map = {
.name = "DC21285 flash",
.phys = NO_XIP,
.size = 16*1024*1024,
.copy_from = dc21285_copy_from,
};
/* Partition stuff */
static struct mtd_partition *dc21285_parts;
static const char *probes[] = { "RedBoot", "cmdlinepart", NULL };
static int __init init_dc21285(void)
{
int nrparts;
/* Determine bankwidth */
switch (*CSR_SA110_CNTL & (3<<14)) {
case SA110_CNTL_ROMWIDTH_8:
dc21285_map.bankwidth = 1;
dc21285_map.read = dc21285_read8;
dc21285_map.write = dc21285_write8;
dc21285_map.copy_to = dc21285_copy_to_8;
break;
case SA110_CNTL_ROMWIDTH_16:
dc21285_map.bankwidth = 2;
dc21285_map.read = dc21285_read16;
dc21285_map.write = dc21285_write16;
dc21285_map.copy_to = dc21285_copy_to_16;
break;
case SA110_CNTL_ROMWIDTH_32:
dc21285_map.bankwidth = 4;
dc21285_map.read = dc21285_read32;
dc21285_map.write = dc21285_write32;
dc21285_map.copy_to = dc21285_copy_to_32;
break;
default:
printk (KERN_ERR "DC21285 flash: undefined bankwidth\n");
return -ENXIO;
}
printk (KERN_NOTICE "DC21285 flash support (%d-bit bankwidth)\n",
dc21285_map.bankwidth*8);
/* Let's map the flash area */
dc21285_map.virt = ioremap(DC21285_FLASH, 16*1024*1024);
if (!dc21285_map.virt) {
printk("Failed to ioremap\n");
return -EIO;
}
if (machine_is_ebsa285()) {
dc21285_mtd = do_map_probe("cfi_probe", &dc21285_map);
} else {
dc21285_mtd = do_map_probe("jedec_probe", &dc21285_map);
}
if (!dc21285_mtd) {
iounmap(dc21285_map.virt);
return -ENXIO;
}
dc21285_mtd->owner = THIS_MODULE;
nrparts = parse_mtd_partitions(dc21285_mtd, probes, &dc21285_parts, 0);
mtd_device_register(dc21285_mtd, dc21285_parts, nrparts);
if(machine_is_ebsa285()) {
/*
* Flash timing is determined with bits 19-16 of the
* CSR_SA110_CNTL. The value is the number of wait cycles, or
* 0 for 16 cycles (the default). Cycles are 20 ns.
* Here we use 7 for 140 ns flash chips.
*/
/* access time */
*CSR_SA110_CNTL = ((*CSR_SA110_CNTL & ~0x000f0000) | (7 << 16));
/* burst time */
*CSR_SA110_CNTL = ((*CSR_SA110_CNTL & ~0x00f00000) | (7 << 20));
/* tristate time */
*CSR_SA110_CNTL = ((*CSR_SA110_CNTL & ~0x0f000000) | (7 << 24));
}
return 0;
}
static void __exit cleanup_dc21285(void)
{
mtd_device_unregister(dc21285_mtd);
if (dc21285_parts)
kfree(dc21285_parts);
map_destroy(dc21285_mtd);
iounmap(dc21285_map.virt);
}
module_init(init_dc21285);
module_exit(cleanup_dc21285);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Nicolas Pitre <nico@fluxnic.net>");
MODULE_DESCRIPTION("MTD map driver for DC21285 boards");
| gpl-2.0 |
CyanHacker-Lollipop/kernel_sony_msm8974pro | drivers/net/wireless/ath/ath9k/dfs_debug.c | 4831 | 2503 | /*
* Copyright (c) 2008-2011 Atheros Communications Inc.
* Copyright (c) 2011 Neratec Solutions AG
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/debugfs.h>
#include <linux/export.h>
#include "ath9k.h"
#include "dfs_debug.h"
#define ATH9K_DFS_STAT(s, p) \
len += snprintf(buf + len, size - len, "%28s : %10u\n", s, \
sc->debug.stats.dfs_stats.p);
static ssize_t read_file_dfs(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath_softc *sc = file->private_data;
struct ath9k_hw_version *hw_ver = &sc->sc_ah->hw_version;
char *buf;
unsigned int len = 0, size = 8000;
ssize_t retval = 0;
buf = kzalloc(size, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
len += snprintf(buf + len, size - len, "DFS support for "
"macVersion = 0x%x, macRev = 0x%x: %s\n",
hw_ver->macVersion, hw_ver->macRev,
(sc->sc_ah->caps.hw_caps & ATH9K_HW_CAP_DFS) ?
"enabled" : "disabled");
ATH9K_DFS_STAT("DFS pulses detected ", pulses_detected);
ATH9K_DFS_STAT("Datalen discards ", datalen_discards);
ATH9K_DFS_STAT("RSSI discards ", rssi_discards);
ATH9K_DFS_STAT("BW info discards ", bwinfo_discards);
ATH9K_DFS_STAT("Primary channel pulses ", pri_phy_errors);
ATH9K_DFS_STAT("Secondary channel pulses", ext_phy_errors);
ATH9K_DFS_STAT("Dual channel pulses ", dc_phy_errors);
if (len > size)
len = size;
retval = simple_read_from_buffer(user_buf, count, ppos, buf, len);
kfree(buf);
return retval;
}
static const struct file_operations fops_dfs_stats = {
.read = read_file_dfs,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
void ath9k_dfs_init_debug(struct ath_softc *sc)
{
debugfs_create_file("dfs_stats", S_IRUSR,
sc->debug.debugfs_phy, sc, &fops_dfs_stats);
}
| gpl-2.0 |
flar2/evita-ElementalX | drivers/net/wireless/rtl818x/rtl8180/dev.c | 5087 | 33111 |
/*
* Linux device driver for RTL8180 / RTL8185
*
* Copyright 2007 Michael Wu <flamingice@sourmilk.net>
* Copyright 2007 Andrea Merello <andreamrl@tiscali.it>
*
* Based on the r8180 driver, which is:
* Copyright 2004-2005 Andrea Merello <andreamrl@tiscali.it>, et al.
*
* Thanks to Realtek for their support!
*
* 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/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/etherdevice.h>
#include <linux/eeprom_93cx6.h>
#include <linux/module.h>
#include <net/mac80211.h>
#include "rtl8180.h"
#include "rtl8225.h"
#include "sa2400.h"
#include "max2820.h"
#include "grf5101.h"
MODULE_AUTHOR("Michael Wu <flamingice@sourmilk.net>");
MODULE_AUTHOR("Andrea Merello <andreamrl@tiscali.it>");
MODULE_DESCRIPTION("RTL8180 / RTL8185 PCI wireless driver");
MODULE_LICENSE("GPL");
static DEFINE_PCI_DEVICE_TABLE(rtl8180_table) = {
/* rtl8185 */
{ PCI_DEVICE(PCI_VENDOR_ID_REALTEK, 0x8185) },
{ PCI_DEVICE(PCI_VENDOR_ID_BELKIN, 0x700f) },
{ PCI_DEVICE(PCI_VENDOR_ID_BELKIN, 0x701f) },
/* rtl8180 */
{ PCI_DEVICE(PCI_VENDOR_ID_REALTEK, 0x8180) },
{ PCI_DEVICE(0x1799, 0x6001) },
{ PCI_DEVICE(0x1799, 0x6020) },
{ PCI_DEVICE(PCI_VENDOR_ID_DLINK, 0x3300) },
{ }
};
MODULE_DEVICE_TABLE(pci, rtl8180_table);
static const struct ieee80211_rate rtl818x_rates[] = {
{ .bitrate = 10, .hw_value = 0, },
{ .bitrate = 20, .hw_value = 1, },
{ .bitrate = 55, .hw_value = 2, },
{ .bitrate = 110, .hw_value = 3, },
{ .bitrate = 60, .hw_value = 4, },
{ .bitrate = 90, .hw_value = 5, },
{ .bitrate = 120, .hw_value = 6, },
{ .bitrate = 180, .hw_value = 7, },
{ .bitrate = 240, .hw_value = 8, },
{ .bitrate = 360, .hw_value = 9, },
{ .bitrate = 480, .hw_value = 10, },
{ .bitrate = 540, .hw_value = 11, },
};
static const struct ieee80211_channel rtl818x_channels[] = {
{ .center_freq = 2412 },
{ .center_freq = 2417 },
{ .center_freq = 2422 },
{ .center_freq = 2427 },
{ .center_freq = 2432 },
{ .center_freq = 2437 },
{ .center_freq = 2442 },
{ .center_freq = 2447 },
{ .center_freq = 2452 },
{ .center_freq = 2457 },
{ .center_freq = 2462 },
{ .center_freq = 2467 },
{ .center_freq = 2472 },
{ .center_freq = 2484 },
};
void rtl8180_write_phy(struct ieee80211_hw *dev, u8 addr, u32 data)
{
struct rtl8180_priv *priv = dev->priv;
int i = 10;
u32 buf;
buf = (data << 8) | addr;
rtl818x_iowrite32(priv, (__le32 __iomem *)&priv->map->PHY[0], buf | 0x80);
while (i--) {
rtl818x_iowrite32(priv, (__le32 __iomem *)&priv->map->PHY[0], buf);
if (rtl818x_ioread8(priv, &priv->map->PHY[2]) == (data & 0xFF))
return;
}
}
static void rtl8180_handle_rx(struct ieee80211_hw *dev)
{
struct rtl8180_priv *priv = dev->priv;
unsigned int count = 32;
u8 signal, agc, sq;
while (count--) {
struct rtl8180_rx_desc *entry = &priv->rx_ring[priv->rx_idx];
struct sk_buff *skb = priv->rx_buf[priv->rx_idx];
u32 flags = le32_to_cpu(entry->flags);
if (flags & RTL818X_RX_DESC_FLAG_OWN)
return;
if (unlikely(flags & (RTL818X_RX_DESC_FLAG_DMA_FAIL |
RTL818X_RX_DESC_FLAG_FOF |
RTL818X_RX_DESC_FLAG_RX_ERR)))
goto done;
else {
u32 flags2 = le32_to_cpu(entry->flags2);
struct ieee80211_rx_status rx_status = {0};
struct sk_buff *new_skb = dev_alloc_skb(MAX_RX_SIZE);
if (unlikely(!new_skb))
goto done;
pci_unmap_single(priv->pdev,
*((dma_addr_t *)skb->cb),
MAX_RX_SIZE, PCI_DMA_FROMDEVICE);
skb_put(skb, flags & 0xFFF);
rx_status.antenna = (flags2 >> 15) & 1;
rx_status.rate_idx = (flags >> 20) & 0xF;
agc = (flags2 >> 17) & 0x7F;
if (priv->r8185) {
if (rx_status.rate_idx > 3)
signal = 90 - clamp_t(u8, agc, 25, 90);
else
signal = 95 - clamp_t(u8, agc, 30, 95);
} else {
sq = flags2 & 0xff;
signal = priv->rf->calc_rssi(agc, sq);
}
rx_status.signal = signal;
rx_status.freq = dev->conf.channel->center_freq;
rx_status.band = dev->conf.channel->band;
rx_status.mactime = le64_to_cpu(entry->tsft);
rx_status.flag |= RX_FLAG_MACTIME_MPDU;
if (flags & RTL818X_RX_DESC_FLAG_CRC32_ERR)
rx_status.flag |= RX_FLAG_FAILED_FCS_CRC;
memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status));
ieee80211_rx_irqsafe(dev, skb);
skb = new_skb;
priv->rx_buf[priv->rx_idx] = skb;
*((dma_addr_t *) skb->cb) =
pci_map_single(priv->pdev, skb_tail_pointer(skb),
MAX_RX_SIZE, PCI_DMA_FROMDEVICE);
}
done:
entry->rx_buf = cpu_to_le32(*((dma_addr_t *)skb->cb));
entry->flags = cpu_to_le32(RTL818X_RX_DESC_FLAG_OWN |
MAX_RX_SIZE);
if (priv->rx_idx == 31)
entry->flags |= cpu_to_le32(RTL818X_RX_DESC_FLAG_EOR);
priv->rx_idx = (priv->rx_idx + 1) % 32;
}
}
static void rtl8180_handle_tx(struct ieee80211_hw *dev, unsigned int prio)
{
struct rtl8180_priv *priv = dev->priv;
struct rtl8180_tx_ring *ring = &priv->tx_ring[prio];
while (skb_queue_len(&ring->queue)) {
struct rtl8180_tx_desc *entry = &ring->desc[ring->idx];
struct sk_buff *skb;
struct ieee80211_tx_info *info;
u32 flags = le32_to_cpu(entry->flags);
if (flags & RTL818X_TX_DESC_FLAG_OWN)
return;
ring->idx = (ring->idx + 1) % ring->entries;
skb = __skb_dequeue(&ring->queue);
pci_unmap_single(priv->pdev, le32_to_cpu(entry->tx_buf),
skb->len, PCI_DMA_TODEVICE);
info = IEEE80211_SKB_CB(skb);
ieee80211_tx_info_clear_status(info);
if (!(info->flags & IEEE80211_TX_CTL_NO_ACK) &&
(flags & RTL818X_TX_DESC_FLAG_TX_OK))
info->flags |= IEEE80211_TX_STAT_ACK;
info->status.rates[0].count = (flags & 0xFF) + 1;
info->status.rates[1].idx = -1;
ieee80211_tx_status_irqsafe(dev, skb);
if (ring->entries - skb_queue_len(&ring->queue) == 2)
ieee80211_wake_queue(dev, prio);
}
}
static irqreturn_t rtl8180_interrupt(int irq, void *dev_id)
{
struct ieee80211_hw *dev = dev_id;
struct rtl8180_priv *priv = dev->priv;
u16 reg;
spin_lock(&priv->lock);
reg = rtl818x_ioread16(priv, &priv->map->INT_STATUS);
if (unlikely(reg == 0xFFFF)) {
spin_unlock(&priv->lock);
return IRQ_HANDLED;
}
rtl818x_iowrite16(priv, &priv->map->INT_STATUS, reg);
if (reg & (RTL818X_INT_TXB_OK | RTL818X_INT_TXB_ERR))
rtl8180_handle_tx(dev, 3);
if (reg & (RTL818X_INT_TXH_OK | RTL818X_INT_TXH_ERR))
rtl8180_handle_tx(dev, 2);
if (reg & (RTL818X_INT_TXN_OK | RTL818X_INT_TXN_ERR))
rtl8180_handle_tx(dev, 1);
if (reg & (RTL818X_INT_TXL_OK | RTL818X_INT_TXL_ERR))
rtl8180_handle_tx(dev, 0);
if (reg & (RTL818X_INT_RX_OK | RTL818X_INT_RX_ERR))
rtl8180_handle_rx(dev);
spin_unlock(&priv->lock);
return IRQ_HANDLED;
}
static void rtl8180_tx(struct ieee80211_hw *dev, struct sk_buff *skb)
{
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct rtl8180_priv *priv = dev->priv;
struct rtl8180_tx_ring *ring;
struct rtl8180_tx_desc *entry;
unsigned long flags;
unsigned int idx, prio;
dma_addr_t mapping;
u32 tx_flags;
u8 rc_flags;
u16 plcp_len = 0;
__le16 rts_duration = 0;
prio = skb_get_queue_mapping(skb);
ring = &priv->tx_ring[prio];
mapping = pci_map_single(priv->pdev, skb->data,
skb->len, PCI_DMA_TODEVICE);
tx_flags = RTL818X_TX_DESC_FLAG_OWN | RTL818X_TX_DESC_FLAG_FS |
RTL818X_TX_DESC_FLAG_LS |
(ieee80211_get_tx_rate(dev, info)->hw_value << 24) |
skb->len;
if (priv->r8185)
tx_flags |= RTL818X_TX_DESC_FLAG_DMA |
RTL818X_TX_DESC_FLAG_NO_ENC;
rc_flags = info->control.rates[0].flags;
if (rc_flags & IEEE80211_TX_RC_USE_RTS_CTS) {
tx_flags |= RTL818X_TX_DESC_FLAG_RTS;
tx_flags |= ieee80211_get_rts_cts_rate(dev, info)->hw_value << 19;
} else if (rc_flags & IEEE80211_TX_RC_USE_CTS_PROTECT) {
tx_flags |= RTL818X_TX_DESC_FLAG_CTS;
tx_flags |= ieee80211_get_rts_cts_rate(dev, info)->hw_value << 19;
}
if (rc_flags & IEEE80211_TX_RC_USE_RTS_CTS)
rts_duration = ieee80211_rts_duration(dev, priv->vif, skb->len,
info);
if (!priv->r8185) {
unsigned int remainder;
plcp_len = DIV_ROUND_UP(16 * (skb->len + 4),
(ieee80211_get_tx_rate(dev, info)->bitrate * 2) / 10);
remainder = (16 * (skb->len + 4)) %
((ieee80211_get_tx_rate(dev, info)->bitrate * 2) / 10);
if (remainder <= 6)
plcp_len |= 1 << 15;
}
spin_lock_irqsave(&priv->lock, flags);
if (info->flags & IEEE80211_TX_CTL_ASSIGN_SEQ) {
if (info->flags & IEEE80211_TX_CTL_FIRST_FRAGMENT)
priv->seqno += 0x10;
hdr->seq_ctrl &= cpu_to_le16(IEEE80211_SCTL_FRAG);
hdr->seq_ctrl |= cpu_to_le16(priv->seqno);
}
idx = (ring->idx + skb_queue_len(&ring->queue)) % ring->entries;
entry = &ring->desc[idx];
entry->rts_duration = rts_duration;
entry->plcp_len = cpu_to_le16(plcp_len);
entry->tx_buf = cpu_to_le32(mapping);
entry->frame_len = cpu_to_le32(skb->len);
entry->flags2 = info->control.rates[1].idx >= 0 ?
ieee80211_get_alt_retry_rate(dev, info, 0)->bitrate << 4 : 0;
entry->retry_limit = info->control.rates[0].count;
entry->flags = cpu_to_le32(tx_flags);
__skb_queue_tail(&ring->queue, skb);
if (ring->entries - skb_queue_len(&ring->queue) < 2)
ieee80211_stop_queue(dev, prio);
spin_unlock_irqrestore(&priv->lock, flags);
rtl818x_iowrite8(priv, &priv->map->TX_DMA_POLLING, (1 << (prio + 4)));
}
void rtl8180_set_anaparam(struct rtl8180_priv *priv, u32 anaparam)
{
u8 reg;
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_CONFIG);
reg = rtl818x_ioread8(priv, &priv->map->CONFIG3);
rtl818x_iowrite8(priv, &priv->map->CONFIG3,
reg | RTL818X_CONFIG3_ANAPARAM_WRITE);
rtl818x_iowrite32(priv, &priv->map->ANAPARAM, anaparam);
rtl818x_iowrite8(priv, &priv->map->CONFIG3,
reg & ~RTL818X_CONFIG3_ANAPARAM_WRITE);
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_NORMAL);
}
static int rtl8180_init_hw(struct ieee80211_hw *dev)
{
struct rtl8180_priv *priv = dev->priv;
u16 reg;
rtl818x_iowrite8(priv, &priv->map->CMD, 0);
rtl818x_ioread8(priv, &priv->map->CMD);
msleep(10);
/* reset */
rtl818x_iowrite16(priv, &priv->map->INT_MASK, 0);
rtl818x_ioread8(priv, &priv->map->CMD);
reg = rtl818x_ioread8(priv, &priv->map->CMD);
reg &= (1 << 1);
reg |= RTL818X_CMD_RESET;
rtl818x_iowrite8(priv, &priv->map->CMD, RTL818X_CMD_RESET);
rtl818x_ioread8(priv, &priv->map->CMD);
msleep(200);
/* check success of reset */
if (rtl818x_ioread8(priv, &priv->map->CMD) & RTL818X_CMD_RESET) {
wiphy_err(dev->wiphy, "reset timeout!\n");
return -ETIMEDOUT;
}
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_LOAD);
rtl818x_ioread8(priv, &priv->map->CMD);
msleep(200);
if (rtl818x_ioread8(priv, &priv->map->CONFIG3) & (1 << 3)) {
/* For cardbus */
reg = rtl818x_ioread8(priv, &priv->map->CONFIG3);
reg |= 1 << 1;
rtl818x_iowrite8(priv, &priv->map->CONFIG3, reg);
reg = rtl818x_ioread16(priv, &priv->map->FEMR);
reg |= (1 << 15) | (1 << 14) | (1 << 4);
rtl818x_iowrite16(priv, &priv->map->FEMR, reg);
}
rtl818x_iowrite8(priv, &priv->map->MSR, 0);
if (!priv->r8185)
rtl8180_set_anaparam(priv, priv->anaparam);
rtl818x_iowrite32(priv, &priv->map->RDSAR, priv->rx_ring_dma);
rtl818x_iowrite32(priv, &priv->map->TBDA, priv->tx_ring[3].dma);
rtl818x_iowrite32(priv, &priv->map->THPDA, priv->tx_ring[2].dma);
rtl818x_iowrite32(priv, &priv->map->TNPDA, priv->tx_ring[1].dma);
rtl818x_iowrite32(priv, &priv->map->TLPDA, priv->tx_ring[0].dma);
/* TODO: necessary? specs indicate not */
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_CONFIG);
reg = rtl818x_ioread8(priv, &priv->map->CONFIG2);
rtl818x_iowrite8(priv, &priv->map->CONFIG2, reg & ~(1 << 3));
if (priv->r8185) {
reg = rtl818x_ioread8(priv, &priv->map->CONFIG2);
rtl818x_iowrite8(priv, &priv->map->CONFIG2, reg | (1 << 4));
}
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_NORMAL);
/* TODO: set CONFIG5 for calibrating AGC on rtl8180 + philips radio? */
/* TODO: turn off hw wep on rtl8180 */
rtl818x_iowrite32(priv, &priv->map->INT_TIMEOUT, 0);
if (priv->r8185) {
rtl818x_iowrite8(priv, &priv->map->WPA_CONF, 0);
rtl818x_iowrite8(priv, &priv->map->RATE_FALLBACK, 0x81);
rtl818x_iowrite8(priv, &priv->map->RESP_RATE, (8 << 4) | 0);
rtl818x_iowrite16(priv, &priv->map->BRSR, 0x01F3);
/* TODO: set ClkRun enable? necessary? */
reg = rtl818x_ioread8(priv, &priv->map->GP_ENABLE);
rtl818x_iowrite8(priv, &priv->map->GP_ENABLE, reg & ~(1 << 6));
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_CONFIG);
reg = rtl818x_ioread8(priv, &priv->map->CONFIG3);
rtl818x_iowrite8(priv, &priv->map->CONFIG3, reg | (1 << 2));
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_NORMAL);
} else {
rtl818x_iowrite16(priv, &priv->map->BRSR, 0x1);
rtl818x_iowrite8(priv, &priv->map->SECURITY, 0);
rtl818x_iowrite8(priv, &priv->map->PHY_DELAY, 0x6);
rtl818x_iowrite8(priv, &priv->map->CARRIER_SENSE_COUNTER, 0x4C);
}
priv->rf->init(dev);
if (priv->r8185)
rtl818x_iowrite16(priv, &priv->map->BRSR, 0x01F3);
return 0;
}
static int rtl8180_init_rx_ring(struct ieee80211_hw *dev)
{
struct rtl8180_priv *priv = dev->priv;
struct rtl8180_rx_desc *entry;
int i;
priv->rx_ring = pci_alloc_consistent(priv->pdev,
sizeof(*priv->rx_ring) * 32,
&priv->rx_ring_dma);
if (!priv->rx_ring || (unsigned long)priv->rx_ring & 0xFF) {
wiphy_err(dev->wiphy, "Cannot allocate RX ring\n");
return -ENOMEM;
}
memset(priv->rx_ring, 0, sizeof(*priv->rx_ring) * 32);
priv->rx_idx = 0;
for (i = 0; i < 32; i++) {
struct sk_buff *skb = dev_alloc_skb(MAX_RX_SIZE);
dma_addr_t *mapping;
entry = &priv->rx_ring[i];
if (!skb)
return 0;
priv->rx_buf[i] = skb;
mapping = (dma_addr_t *)skb->cb;
*mapping = pci_map_single(priv->pdev, skb_tail_pointer(skb),
MAX_RX_SIZE, PCI_DMA_FROMDEVICE);
entry->rx_buf = cpu_to_le32(*mapping);
entry->flags = cpu_to_le32(RTL818X_RX_DESC_FLAG_OWN |
MAX_RX_SIZE);
}
entry->flags |= cpu_to_le32(RTL818X_RX_DESC_FLAG_EOR);
return 0;
}
static void rtl8180_free_rx_ring(struct ieee80211_hw *dev)
{
struct rtl8180_priv *priv = dev->priv;
int i;
for (i = 0; i < 32; i++) {
struct sk_buff *skb = priv->rx_buf[i];
if (!skb)
continue;
pci_unmap_single(priv->pdev,
*((dma_addr_t *)skb->cb),
MAX_RX_SIZE, PCI_DMA_FROMDEVICE);
kfree_skb(skb);
}
pci_free_consistent(priv->pdev, sizeof(*priv->rx_ring) * 32,
priv->rx_ring, priv->rx_ring_dma);
priv->rx_ring = NULL;
}
static int rtl8180_init_tx_ring(struct ieee80211_hw *dev,
unsigned int prio, unsigned int entries)
{
struct rtl8180_priv *priv = dev->priv;
struct rtl8180_tx_desc *ring;
dma_addr_t dma;
int i;
ring = pci_alloc_consistent(priv->pdev, sizeof(*ring) * entries, &dma);
if (!ring || (unsigned long)ring & 0xFF) {
wiphy_err(dev->wiphy, "Cannot allocate TX ring (prio = %d)\n",
prio);
return -ENOMEM;
}
memset(ring, 0, sizeof(*ring)*entries);
priv->tx_ring[prio].desc = ring;
priv->tx_ring[prio].dma = dma;
priv->tx_ring[prio].idx = 0;
priv->tx_ring[prio].entries = entries;
skb_queue_head_init(&priv->tx_ring[prio].queue);
for (i = 0; i < entries; i++)
ring[i].next_tx_desc =
cpu_to_le32((u32)dma + ((i + 1) % entries) * sizeof(*ring));
return 0;
}
static void rtl8180_free_tx_ring(struct ieee80211_hw *dev, unsigned int prio)
{
struct rtl8180_priv *priv = dev->priv;
struct rtl8180_tx_ring *ring = &priv->tx_ring[prio];
while (skb_queue_len(&ring->queue)) {
struct rtl8180_tx_desc *entry = &ring->desc[ring->idx];
struct sk_buff *skb = __skb_dequeue(&ring->queue);
pci_unmap_single(priv->pdev, le32_to_cpu(entry->tx_buf),
skb->len, PCI_DMA_TODEVICE);
kfree_skb(skb);
ring->idx = (ring->idx + 1) % ring->entries;
}
pci_free_consistent(priv->pdev, sizeof(*ring->desc)*ring->entries,
ring->desc, ring->dma);
ring->desc = NULL;
}
static int rtl8180_start(struct ieee80211_hw *dev)
{
struct rtl8180_priv *priv = dev->priv;
int ret, i;
u32 reg;
ret = rtl8180_init_rx_ring(dev);
if (ret)
return ret;
for (i = 0; i < 4; i++)
if ((ret = rtl8180_init_tx_ring(dev, i, 16)))
goto err_free_rings;
ret = rtl8180_init_hw(dev);
if (ret)
goto err_free_rings;
rtl818x_iowrite32(priv, &priv->map->RDSAR, priv->rx_ring_dma);
rtl818x_iowrite32(priv, &priv->map->TBDA, priv->tx_ring[3].dma);
rtl818x_iowrite32(priv, &priv->map->THPDA, priv->tx_ring[2].dma);
rtl818x_iowrite32(priv, &priv->map->TNPDA, priv->tx_ring[1].dma);
rtl818x_iowrite32(priv, &priv->map->TLPDA, priv->tx_ring[0].dma);
ret = request_irq(priv->pdev->irq, rtl8180_interrupt,
IRQF_SHARED, KBUILD_MODNAME, dev);
if (ret) {
wiphy_err(dev->wiphy, "failed to register IRQ handler\n");
goto err_free_rings;
}
rtl818x_iowrite16(priv, &priv->map->INT_MASK, 0xFFFF);
rtl818x_iowrite32(priv, &priv->map->MAR[0], ~0);
rtl818x_iowrite32(priv, &priv->map->MAR[1], ~0);
reg = RTL818X_RX_CONF_ONLYERLPKT |
RTL818X_RX_CONF_RX_AUTORESETPHY |
RTL818X_RX_CONF_MGMT |
RTL818X_RX_CONF_DATA |
(7 << 8 /* MAX RX DMA */) |
RTL818X_RX_CONF_BROADCAST |
RTL818X_RX_CONF_NICMAC;
if (priv->r8185)
reg |= RTL818X_RX_CONF_CSDM1 | RTL818X_RX_CONF_CSDM2;
else {
reg |= (priv->rfparam & RF_PARAM_CARRIERSENSE1)
? RTL818X_RX_CONF_CSDM1 : 0;
reg |= (priv->rfparam & RF_PARAM_CARRIERSENSE2)
? RTL818X_RX_CONF_CSDM2 : 0;
}
priv->rx_conf = reg;
rtl818x_iowrite32(priv, &priv->map->RX_CONF, reg);
if (priv->r8185) {
reg = rtl818x_ioread8(priv, &priv->map->CW_CONF);
reg &= ~RTL818X_CW_CONF_PERPACKET_CW_SHIFT;
reg |= RTL818X_CW_CONF_PERPACKET_RETRY_SHIFT;
rtl818x_iowrite8(priv, &priv->map->CW_CONF, reg);
reg = rtl818x_ioread8(priv, &priv->map->TX_AGC_CTL);
reg &= ~RTL818X_TX_AGC_CTL_PERPACKET_GAIN_SHIFT;
reg &= ~RTL818X_TX_AGC_CTL_PERPACKET_ANTSEL_SHIFT;
reg |= RTL818X_TX_AGC_CTL_FEEDBACK_ANT;
rtl818x_iowrite8(priv, &priv->map->TX_AGC_CTL, reg);
/* disable early TX */
rtl818x_iowrite8(priv, (u8 __iomem *)priv->map + 0xec, 0x3f);
}
reg = rtl818x_ioread32(priv, &priv->map->TX_CONF);
reg |= (6 << 21 /* MAX TX DMA */) |
RTL818X_TX_CONF_NO_ICV;
if (priv->r8185)
reg &= ~RTL818X_TX_CONF_PROBE_DTS;
else
reg &= ~RTL818X_TX_CONF_HW_SEQNUM;
/* different meaning, same value on both rtl8185 and rtl8180 */
reg &= ~RTL818X_TX_CONF_SAT_HWPLCP;
rtl818x_iowrite32(priv, &priv->map->TX_CONF, reg);
reg = rtl818x_ioread8(priv, &priv->map->CMD);
reg |= RTL818X_CMD_RX_ENABLE;
reg |= RTL818X_CMD_TX_ENABLE;
rtl818x_iowrite8(priv, &priv->map->CMD, reg);
return 0;
err_free_rings:
rtl8180_free_rx_ring(dev);
for (i = 0; i < 4; i++)
if (priv->tx_ring[i].desc)
rtl8180_free_tx_ring(dev, i);
return ret;
}
static void rtl8180_stop(struct ieee80211_hw *dev)
{
struct rtl8180_priv *priv = dev->priv;
u8 reg;
int i;
rtl818x_iowrite16(priv, &priv->map->INT_MASK, 0);
reg = rtl818x_ioread8(priv, &priv->map->CMD);
reg &= ~RTL818X_CMD_TX_ENABLE;
reg &= ~RTL818X_CMD_RX_ENABLE;
rtl818x_iowrite8(priv, &priv->map->CMD, reg);
priv->rf->stop(dev);
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_CONFIG);
reg = rtl818x_ioread8(priv, &priv->map->CONFIG4);
rtl818x_iowrite8(priv, &priv->map->CONFIG4, reg | RTL818X_CONFIG4_VCOOFF);
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_NORMAL);
free_irq(priv->pdev->irq, dev);
rtl8180_free_rx_ring(dev);
for (i = 0; i < 4; i++)
rtl8180_free_tx_ring(dev, i);
}
static u64 rtl8180_get_tsf(struct ieee80211_hw *dev,
struct ieee80211_vif *vif)
{
struct rtl8180_priv *priv = dev->priv;
return rtl818x_ioread32(priv, &priv->map->TSFT[0]) |
(u64)(rtl818x_ioread32(priv, &priv->map->TSFT[1])) << 32;
}
static void rtl8180_beacon_work(struct work_struct *work)
{
struct rtl8180_vif *vif_priv =
container_of(work, struct rtl8180_vif, beacon_work.work);
struct ieee80211_vif *vif =
container_of((void *)vif_priv, struct ieee80211_vif, drv_priv);
struct ieee80211_hw *dev = vif_priv->dev;
struct ieee80211_mgmt *mgmt;
struct sk_buff *skb;
/* don't overflow the tx ring */
if (ieee80211_queue_stopped(dev, 0))
goto resched;
/* grab a fresh beacon */
skb = ieee80211_beacon_get(dev, vif);
if (!skb)
goto resched;
/*
* update beacon timestamp w/ TSF value
* TODO: make hardware update beacon timestamp
*/
mgmt = (struct ieee80211_mgmt *)skb->data;
mgmt->u.beacon.timestamp = cpu_to_le64(rtl8180_get_tsf(dev, vif));
/* TODO: use actual beacon queue */
skb_set_queue_mapping(skb, 0);
rtl8180_tx(dev, skb);
resched:
/*
* schedule next beacon
* TODO: use hardware support for beacon timing
*/
schedule_delayed_work(&vif_priv->beacon_work,
usecs_to_jiffies(1024 * vif->bss_conf.beacon_int));
}
static int rtl8180_add_interface(struct ieee80211_hw *dev,
struct ieee80211_vif *vif)
{
struct rtl8180_priv *priv = dev->priv;
struct rtl8180_vif *vif_priv;
/*
* We only support one active interface at a time.
*/
if (priv->vif)
return -EBUSY;
switch (vif->type) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
break;
default:
return -EOPNOTSUPP;
}
priv->vif = vif;
/* Initialize driver private area */
vif_priv = (struct rtl8180_vif *)&vif->drv_priv;
vif_priv->dev = dev;
INIT_DELAYED_WORK(&vif_priv->beacon_work, rtl8180_beacon_work);
vif_priv->enable_beacon = false;
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_CONFIG);
rtl818x_iowrite32(priv, (__le32 __iomem *)&priv->map->MAC[0],
le32_to_cpu(*(__le32 *)vif->addr));
rtl818x_iowrite16(priv, (__le16 __iomem *)&priv->map->MAC[4],
le16_to_cpu(*(__le16 *)(vif->addr + 4)));
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_NORMAL);
return 0;
}
static void rtl8180_remove_interface(struct ieee80211_hw *dev,
struct ieee80211_vif *vif)
{
struct rtl8180_priv *priv = dev->priv;
priv->vif = NULL;
}
static int rtl8180_config(struct ieee80211_hw *dev, u32 changed)
{
struct rtl8180_priv *priv = dev->priv;
struct ieee80211_conf *conf = &dev->conf;
priv->rf->set_chan(dev, conf);
return 0;
}
static void rtl8180_bss_info_changed(struct ieee80211_hw *dev,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *info,
u32 changed)
{
struct rtl8180_priv *priv = dev->priv;
struct rtl8180_vif *vif_priv;
int i;
u8 reg;
vif_priv = (struct rtl8180_vif *)&vif->drv_priv;
if (changed & BSS_CHANGED_BSSID) {
for (i = 0; i < ETH_ALEN; i++)
rtl818x_iowrite8(priv, &priv->map->BSSID[i],
info->bssid[i]);
if (is_valid_ether_addr(info->bssid)) {
if (vif->type == NL80211_IFTYPE_ADHOC)
reg = RTL818X_MSR_ADHOC;
else
reg = RTL818X_MSR_INFRA;
} else
reg = RTL818X_MSR_NO_LINK;
rtl818x_iowrite8(priv, &priv->map->MSR, reg);
}
if (changed & BSS_CHANGED_ERP_SLOT && priv->rf->conf_erp)
priv->rf->conf_erp(dev, info);
if (changed & BSS_CHANGED_BEACON_ENABLED)
vif_priv->enable_beacon = info->enable_beacon;
if (changed & (BSS_CHANGED_BEACON_ENABLED | BSS_CHANGED_BEACON)) {
cancel_delayed_work_sync(&vif_priv->beacon_work);
if (vif_priv->enable_beacon)
schedule_work(&vif_priv->beacon_work.work);
}
}
static u64 rtl8180_prepare_multicast(struct ieee80211_hw *dev,
struct netdev_hw_addr_list *mc_list)
{
return netdev_hw_addr_list_count(mc_list);
}
static void rtl8180_configure_filter(struct ieee80211_hw *dev,
unsigned int changed_flags,
unsigned int *total_flags,
u64 multicast)
{
struct rtl8180_priv *priv = dev->priv;
if (changed_flags & FIF_FCSFAIL)
priv->rx_conf ^= RTL818X_RX_CONF_FCS;
if (changed_flags & FIF_CONTROL)
priv->rx_conf ^= RTL818X_RX_CONF_CTRL;
if (changed_flags & FIF_OTHER_BSS)
priv->rx_conf ^= RTL818X_RX_CONF_MONITOR;
if (*total_flags & FIF_ALLMULTI || multicast > 0)
priv->rx_conf |= RTL818X_RX_CONF_MULTICAST;
else
priv->rx_conf &= ~RTL818X_RX_CONF_MULTICAST;
*total_flags = 0;
if (priv->rx_conf & RTL818X_RX_CONF_FCS)
*total_flags |= FIF_FCSFAIL;
if (priv->rx_conf & RTL818X_RX_CONF_CTRL)
*total_flags |= FIF_CONTROL;
if (priv->rx_conf & RTL818X_RX_CONF_MONITOR)
*total_flags |= FIF_OTHER_BSS;
if (priv->rx_conf & RTL818X_RX_CONF_MULTICAST)
*total_flags |= FIF_ALLMULTI;
rtl818x_iowrite32(priv, &priv->map->RX_CONF, priv->rx_conf);
}
static const struct ieee80211_ops rtl8180_ops = {
.tx = rtl8180_tx,
.start = rtl8180_start,
.stop = rtl8180_stop,
.add_interface = rtl8180_add_interface,
.remove_interface = rtl8180_remove_interface,
.config = rtl8180_config,
.bss_info_changed = rtl8180_bss_info_changed,
.prepare_multicast = rtl8180_prepare_multicast,
.configure_filter = rtl8180_configure_filter,
.get_tsf = rtl8180_get_tsf,
};
static void rtl8180_eeprom_register_read(struct eeprom_93cx6 *eeprom)
{
struct ieee80211_hw *dev = eeprom->data;
struct rtl8180_priv *priv = dev->priv;
u8 reg = rtl818x_ioread8(priv, &priv->map->EEPROM_CMD);
eeprom->reg_data_in = reg & RTL818X_EEPROM_CMD_WRITE;
eeprom->reg_data_out = reg & RTL818X_EEPROM_CMD_READ;
eeprom->reg_data_clock = reg & RTL818X_EEPROM_CMD_CK;
eeprom->reg_chip_select = reg & RTL818X_EEPROM_CMD_CS;
}
static void rtl8180_eeprom_register_write(struct eeprom_93cx6 *eeprom)
{
struct ieee80211_hw *dev = eeprom->data;
struct rtl8180_priv *priv = dev->priv;
u8 reg = 2 << 6;
if (eeprom->reg_data_in)
reg |= RTL818X_EEPROM_CMD_WRITE;
if (eeprom->reg_data_out)
reg |= RTL818X_EEPROM_CMD_READ;
if (eeprom->reg_data_clock)
reg |= RTL818X_EEPROM_CMD_CK;
if (eeprom->reg_chip_select)
reg |= RTL818X_EEPROM_CMD_CS;
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, reg);
rtl818x_ioread8(priv, &priv->map->EEPROM_CMD);
udelay(10);
}
static int __devinit rtl8180_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
struct ieee80211_hw *dev;
struct rtl8180_priv *priv;
unsigned long mem_addr, mem_len;
unsigned int io_addr, io_len;
int err, i;
struct eeprom_93cx6 eeprom;
const char *chip_name, *rf_name = NULL;
u32 reg;
u16 eeprom_val;
u8 mac_addr[ETH_ALEN];
err = pci_enable_device(pdev);
if (err) {
printk(KERN_ERR "%s (rtl8180): Cannot enable new PCI device\n",
pci_name(pdev));
return err;
}
err = pci_request_regions(pdev, KBUILD_MODNAME);
if (err) {
printk(KERN_ERR "%s (rtl8180): Cannot obtain PCI resources\n",
pci_name(pdev));
return err;
}
io_addr = pci_resource_start(pdev, 0);
io_len = pci_resource_len(pdev, 0);
mem_addr = pci_resource_start(pdev, 1);
mem_len = pci_resource_len(pdev, 1);
if (mem_len < sizeof(struct rtl818x_csr) ||
io_len < sizeof(struct rtl818x_csr)) {
printk(KERN_ERR "%s (rtl8180): Too short PCI resources\n",
pci_name(pdev));
err = -ENOMEM;
goto err_free_reg;
}
if ((err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) ||
(err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)))) {
printk(KERN_ERR "%s (rtl8180): No suitable DMA available\n",
pci_name(pdev));
goto err_free_reg;
}
pci_set_master(pdev);
dev = ieee80211_alloc_hw(sizeof(*priv), &rtl8180_ops);
if (!dev) {
printk(KERN_ERR "%s (rtl8180): ieee80211 alloc failed\n",
pci_name(pdev));
err = -ENOMEM;
goto err_free_reg;
}
priv = dev->priv;
priv->pdev = pdev;
dev->max_rates = 2;
SET_IEEE80211_DEV(dev, &pdev->dev);
pci_set_drvdata(pdev, dev);
priv->map = pci_iomap(pdev, 1, mem_len);
if (!priv->map)
priv->map = pci_iomap(pdev, 0, io_len);
if (!priv->map) {
printk(KERN_ERR "%s (rtl8180): Cannot map device memory\n",
pci_name(pdev));
goto err_free_dev;
}
BUILD_BUG_ON(sizeof(priv->channels) != sizeof(rtl818x_channels));
BUILD_BUG_ON(sizeof(priv->rates) != sizeof(rtl818x_rates));
memcpy(priv->channels, rtl818x_channels, sizeof(rtl818x_channels));
memcpy(priv->rates, rtl818x_rates, sizeof(rtl818x_rates));
priv->band.band = IEEE80211_BAND_2GHZ;
priv->band.channels = priv->channels;
priv->band.n_channels = ARRAY_SIZE(rtl818x_channels);
priv->band.bitrates = priv->rates;
priv->band.n_bitrates = 4;
dev->wiphy->bands[IEEE80211_BAND_2GHZ] = &priv->band;
dev->flags = IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING |
IEEE80211_HW_RX_INCLUDES_FCS |
IEEE80211_HW_SIGNAL_UNSPEC;
dev->vif_data_size = sizeof(struct rtl8180_vif);
dev->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC);
dev->queues = 1;
dev->max_signal = 65;
reg = rtl818x_ioread32(priv, &priv->map->TX_CONF);
reg &= RTL818X_TX_CONF_HWVER_MASK;
switch (reg) {
case RTL818X_TX_CONF_R8180_ABCD:
chip_name = "RTL8180";
break;
case RTL818X_TX_CONF_R8180_F:
chip_name = "RTL8180vF";
break;
case RTL818X_TX_CONF_R8185_ABC:
chip_name = "RTL8185";
break;
case RTL818X_TX_CONF_R8185_D:
chip_name = "RTL8185vD";
break;
default:
printk(KERN_ERR "%s (rtl8180): Unknown chip! (0x%x)\n",
pci_name(pdev), reg >> 25);
goto err_iounmap;
}
priv->r8185 = reg & RTL818X_TX_CONF_R8185_ABC;
if (priv->r8185) {
priv->band.n_bitrates = ARRAY_SIZE(rtl818x_rates);
pci_try_set_mwi(pdev);
}
eeprom.data = dev;
eeprom.register_read = rtl8180_eeprom_register_read;
eeprom.register_write = rtl8180_eeprom_register_write;
if (rtl818x_ioread32(priv, &priv->map->RX_CONF) & (1 << 6))
eeprom.width = PCI_EEPROM_WIDTH_93C66;
else
eeprom.width = PCI_EEPROM_WIDTH_93C46;
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_PROGRAM);
rtl818x_ioread8(priv, &priv->map->EEPROM_CMD);
udelay(10);
eeprom_93cx6_read(&eeprom, 0x06, &eeprom_val);
eeprom_val &= 0xFF;
switch (eeprom_val) {
case 1: rf_name = "Intersil";
break;
case 2: rf_name = "RFMD";
break;
case 3: priv->rf = &sa2400_rf_ops;
break;
case 4: priv->rf = &max2820_rf_ops;
break;
case 5: priv->rf = &grf5101_rf_ops;
break;
case 9: priv->rf = rtl8180_detect_rf(dev);
break;
case 10:
rf_name = "RTL8255";
break;
default:
printk(KERN_ERR "%s (rtl8180): Unknown RF! (0x%x)\n",
pci_name(pdev), eeprom_val);
goto err_iounmap;
}
if (!priv->rf) {
printk(KERN_ERR "%s (rtl8180): %s RF frontend not supported!\n",
pci_name(pdev), rf_name);
goto err_iounmap;
}
eeprom_93cx6_read(&eeprom, 0x17, &eeprom_val);
priv->csthreshold = eeprom_val >> 8;
if (!priv->r8185) {
__le32 anaparam;
eeprom_93cx6_multiread(&eeprom, 0xD, (__le16 *)&anaparam, 2);
priv->anaparam = le32_to_cpu(anaparam);
eeprom_93cx6_read(&eeprom, 0x19, &priv->rfparam);
}
eeprom_93cx6_multiread(&eeprom, 0x7, (__le16 *)mac_addr, 3);
if (!is_valid_ether_addr(mac_addr)) {
printk(KERN_WARNING "%s (rtl8180): Invalid hwaddr! Using"
" randomly generated MAC addr\n", pci_name(pdev));
random_ether_addr(mac_addr);
}
SET_IEEE80211_PERM_ADDR(dev, mac_addr);
/* CCK TX power */
for (i = 0; i < 14; i += 2) {
u16 txpwr;
eeprom_93cx6_read(&eeprom, 0x10 + (i >> 1), &txpwr);
priv->channels[i].hw_value = txpwr & 0xFF;
priv->channels[i + 1].hw_value = txpwr >> 8;
}
/* OFDM TX power */
if (priv->r8185) {
for (i = 0; i < 14; i += 2) {
u16 txpwr;
eeprom_93cx6_read(&eeprom, 0x20 + (i >> 1), &txpwr);
priv->channels[i].hw_value |= (txpwr & 0xFF) << 8;
priv->channels[i + 1].hw_value |= txpwr & 0xFF00;
}
}
rtl818x_iowrite8(priv, &priv->map->EEPROM_CMD, RTL818X_EEPROM_CMD_NORMAL);
spin_lock_init(&priv->lock);
err = ieee80211_register_hw(dev);
if (err) {
printk(KERN_ERR "%s (rtl8180): Cannot register device\n",
pci_name(pdev));
goto err_iounmap;
}
wiphy_info(dev->wiphy, "hwaddr %pm, %s + %s\n",
mac_addr, chip_name, priv->rf->name);
return 0;
err_iounmap:
iounmap(priv->map);
err_free_dev:
pci_set_drvdata(pdev, NULL);
ieee80211_free_hw(dev);
err_free_reg:
pci_release_regions(pdev);
pci_disable_device(pdev);
return err;
}
static void __devexit rtl8180_remove(struct pci_dev *pdev)
{
struct ieee80211_hw *dev = pci_get_drvdata(pdev);
struct rtl8180_priv *priv;
if (!dev)
return;
ieee80211_unregister_hw(dev);
priv = dev->priv;
pci_iounmap(pdev, priv->map);
pci_release_regions(pdev);
pci_disable_device(pdev);
ieee80211_free_hw(dev);
}
#ifdef CONFIG_PM
static int rtl8180_suspend(struct pci_dev *pdev, pm_message_t state)
{
pci_save_state(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
static int rtl8180_resume(struct pci_dev *pdev)
{
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
return 0;
}
#endif /* CONFIG_PM */
static struct pci_driver rtl8180_driver = {
.name = KBUILD_MODNAME,
.id_table = rtl8180_table,
.probe = rtl8180_probe,
.remove = __devexit_p(rtl8180_remove),
#ifdef CONFIG_PM
.suspend = rtl8180_suspend,
.resume = rtl8180_resume,
#endif /* CONFIG_PM */
};
static int __init rtl8180_init(void)
{
return pci_register_driver(&rtl8180_driver);
}
static void __exit rtl8180_exit(void)
{
pci_unregister_driver(&rtl8180_driver);
}
module_init(rtl8180_init);
module_exit(rtl8180_exit);
| gpl-2.0 |
Nokius/android_kernel_oppo_n1 | drivers/scsi/libfc/fc_libfc.c | 7903 | 8920 | /*
* Copyright(c) 2009 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
* Maintained at www.Open-FCoE.org
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/scatterlist.h>
#include <linux/crc32.h>
#include <linux/module.h>
#include <scsi/libfc.h>
#include <scsi/fc_encode.h>
#include "fc_libfc.h"
MODULE_AUTHOR("Open-FCoE.org");
MODULE_DESCRIPTION("libfc");
MODULE_LICENSE("GPL v2");
unsigned int fc_debug_logging;
module_param_named(debug_logging, fc_debug_logging, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(debug_logging, "a bit mask of logging levels");
DEFINE_MUTEX(fc_prov_mutex);
static LIST_HEAD(fc_local_ports);
struct blocking_notifier_head fc_lport_notifier_head =
BLOCKING_NOTIFIER_INIT(fc_lport_notifier_head);
EXPORT_SYMBOL(fc_lport_notifier_head);
/*
* Providers which primarily send requests and PRLIs.
*/
struct fc4_prov *fc_active_prov[FC_FC4_PROV_SIZE] = {
[0] = &fc_rport_t0_prov,
[FC_TYPE_FCP] = &fc_rport_fcp_init,
};
/*
* Providers which receive requests.
*/
struct fc4_prov *fc_passive_prov[FC_FC4_PROV_SIZE] = {
[FC_TYPE_ELS] = &fc_lport_els_prov,
};
/**
* libfc_init() - Initialize libfc.ko
*/
static int __init libfc_init(void)
{
int rc = 0;
rc = fc_setup_fcp();
if (rc)
return rc;
rc = fc_setup_exch_mgr();
if (rc)
goto destroy_pkt_cache;
rc = fc_setup_rport();
if (rc)
goto destroy_em;
return rc;
destroy_em:
fc_destroy_exch_mgr();
destroy_pkt_cache:
fc_destroy_fcp();
return rc;
}
module_init(libfc_init);
/**
* libfc_exit() - Tear down libfc.ko
*/
static void __exit libfc_exit(void)
{
fc_destroy_fcp();
fc_destroy_exch_mgr();
fc_destroy_rport();
}
module_exit(libfc_exit);
/**
* fc_copy_buffer_to_sglist() - This routine copies the data of a buffer
* into a scatter-gather list (SG list).
*
* @buf: pointer to the data buffer.
* @len: the byte-length of the data buffer.
* @sg: pointer to the pointer of the SG list.
* @nents: pointer to the remaining number of entries in the SG list.
* @offset: pointer to the current offset in the SG list.
* @crc: pointer to the 32-bit crc value.
* If crc is NULL, CRC is not calculated.
*/
u32 fc_copy_buffer_to_sglist(void *buf, size_t len,
struct scatterlist *sg,
u32 *nents, size_t *offset,
u32 *crc)
{
size_t remaining = len;
u32 copy_len = 0;
while (remaining > 0 && sg) {
size_t off, sg_bytes;
void *page_addr;
if (*offset >= sg->length) {
/*
* Check for end and drop resources
* from the last iteration.
*/
if (!(*nents))
break;
--(*nents);
*offset -= sg->length;
sg = sg_next(sg);
continue;
}
sg_bytes = min(remaining, sg->length - *offset);
/*
* The scatterlist item may be bigger than PAGE_SIZE,
* but we are limited to mapping PAGE_SIZE at a time.
*/
off = *offset + sg->offset;
sg_bytes = min(sg_bytes,
(size_t)(PAGE_SIZE - (off & ~PAGE_MASK)));
page_addr = kmap_atomic(sg_page(sg) + (off >> PAGE_SHIFT));
if (crc)
*crc = crc32(*crc, buf, sg_bytes);
memcpy((char *)page_addr + (off & ~PAGE_MASK), buf, sg_bytes);
kunmap_atomic(page_addr);
buf += sg_bytes;
*offset += sg_bytes;
remaining -= sg_bytes;
copy_len += sg_bytes;
}
return copy_len;
}
/**
* fc_fill_hdr() - fill FC header fields based on request
* @fp: reply frame containing header to be filled in
* @in_fp: request frame containing header to use in filling in reply
* @r_ctl: R_CTL value for header
* @f_ctl: F_CTL value for header, with 0 pad
* @seq_cnt: sequence count for the header, ignored if frame has a sequence
* @parm_offset: parameter / offset value
*/
void fc_fill_hdr(struct fc_frame *fp, const struct fc_frame *in_fp,
enum fc_rctl r_ctl, u32 f_ctl, u16 seq_cnt, u32 parm_offset)
{
struct fc_frame_header *fh;
struct fc_frame_header *in_fh;
struct fc_seq *sp;
u32 fill;
fh = __fc_frame_header_get(fp);
in_fh = __fc_frame_header_get(in_fp);
if (f_ctl & FC_FC_END_SEQ) {
fill = -fr_len(fp) & 3;
if (fill) {
/* TODO, this may be a problem with fragmented skb */
memset(skb_put(fp_skb(fp), fill), 0, fill);
f_ctl |= fill;
}
fr_eof(fp) = FC_EOF_T;
} else {
WARN_ON(fr_len(fp) % 4 != 0); /* no pad to non last frame */
fr_eof(fp) = FC_EOF_N;
}
fh->fh_r_ctl = r_ctl;
memcpy(fh->fh_d_id, in_fh->fh_s_id, sizeof(fh->fh_d_id));
memcpy(fh->fh_s_id, in_fh->fh_d_id, sizeof(fh->fh_s_id));
fh->fh_type = in_fh->fh_type;
hton24(fh->fh_f_ctl, f_ctl);
fh->fh_ox_id = in_fh->fh_ox_id;
fh->fh_rx_id = in_fh->fh_rx_id;
fh->fh_cs_ctl = 0;
fh->fh_df_ctl = 0;
fh->fh_parm_offset = htonl(parm_offset);
sp = fr_seq(in_fp);
if (sp) {
fr_seq(fp) = sp;
fh->fh_seq_id = sp->id;
seq_cnt = sp->cnt;
} else {
fh->fh_seq_id = 0;
}
fh->fh_seq_cnt = ntohs(seq_cnt);
fr_sof(fp) = seq_cnt ? FC_SOF_N3 : FC_SOF_I3;
fr_encaps(fp) = fr_encaps(in_fp);
}
EXPORT_SYMBOL(fc_fill_hdr);
/**
* fc_fill_reply_hdr() - fill FC reply header fields based on request
* @fp: reply frame containing header to be filled in
* @in_fp: request frame containing header to use in filling in reply
* @r_ctl: R_CTL value for reply
* @parm_offset: parameter / offset value
*/
void fc_fill_reply_hdr(struct fc_frame *fp, const struct fc_frame *in_fp,
enum fc_rctl r_ctl, u32 parm_offset)
{
struct fc_seq *sp;
sp = fr_seq(in_fp);
if (sp)
fr_seq(fp) = fr_dev(in_fp)->tt.seq_start_next(sp);
fc_fill_hdr(fp, in_fp, r_ctl, FC_FCTL_RESP, 0, parm_offset);
}
EXPORT_SYMBOL(fc_fill_reply_hdr);
/**
* fc_fc4_conf_lport_params() - Modify "service_params" of specified lport
* if there is service provider (target provider) registered with libfc
* for specified "fc_ft_type"
* @lport: Local port which service_params needs to be modified
* @type: FC-4 type, such as FC_TYPE_FCP
*/
void fc_fc4_conf_lport_params(struct fc_lport *lport, enum fc_fh_type type)
{
struct fc4_prov *prov_entry;
BUG_ON(type >= FC_FC4_PROV_SIZE);
BUG_ON(!lport);
prov_entry = fc_passive_prov[type];
if (type == FC_TYPE_FCP) {
if (prov_entry && prov_entry->recv)
lport->service_params |= FCP_SPPF_TARG_FCN;
}
}
void fc_lport_iterate(void (*notify)(struct fc_lport *, void *), void *arg)
{
struct fc_lport *lport;
mutex_lock(&fc_prov_mutex);
list_for_each_entry(lport, &fc_local_ports, lport_list)
notify(lport, arg);
mutex_unlock(&fc_prov_mutex);
}
EXPORT_SYMBOL(fc_lport_iterate);
/**
* fc_fc4_register_provider() - register FC-4 upper-level provider.
* @type: FC-4 type, such as FC_TYPE_FCP
* @prov: structure describing provider including ops vector.
*
* Returns 0 on success, negative error otherwise.
*/
int fc_fc4_register_provider(enum fc_fh_type type, struct fc4_prov *prov)
{
struct fc4_prov **prov_entry;
int ret = 0;
if (type >= FC_FC4_PROV_SIZE)
return -EINVAL;
mutex_lock(&fc_prov_mutex);
prov_entry = (prov->recv ? fc_passive_prov : fc_active_prov) + type;
if (*prov_entry)
ret = -EBUSY;
else
*prov_entry = prov;
mutex_unlock(&fc_prov_mutex);
return ret;
}
EXPORT_SYMBOL(fc_fc4_register_provider);
/**
* fc_fc4_deregister_provider() - deregister FC-4 upper-level provider.
* @type: FC-4 type, such as FC_TYPE_FCP
* @prov: structure describing provider including ops vector.
*/
void fc_fc4_deregister_provider(enum fc_fh_type type, struct fc4_prov *prov)
{
BUG_ON(type >= FC_FC4_PROV_SIZE);
mutex_lock(&fc_prov_mutex);
if (prov->recv)
rcu_assign_pointer(fc_passive_prov[type], NULL);
else
rcu_assign_pointer(fc_active_prov[type], NULL);
mutex_unlock(&fc_prov_mutex);
synchronize_rcu();
}
EXPORT_SYMBOL(fc_fc4_deregister_provider);
/**
* fc_fc4_add_lport() - add new local port to list and run notifiers.
* @lport: The new local port.
*/
void fc_fc4_add_lport(struct fc_lport *lport)
{
mutex_lock(&fc_prov_mutex);
list_add_tail(&lport->lport_list, &fc_local_ports);
blocking_notifier_call_chain(&fc_lport_notifier_head,
FC_LPORT_EV_ADD, lport);
mutex_unlock(&fc_prov_mutex);
}
/**
* fc_fc4_del_lport() - remove local port from list and run notifiers.
* @lport: The new local port.
*/
void fc_fc4_del_lport(struct fc_lport *lport)
{
mutex_lock(&fc_prov_mutex);
list_del(&lport->lport_list);
blocking_notifier_call_chain(&fc_lport_notifier_head,
FC_LPORT_EV_DEL, lport);
mutex_unlock(&fc_prov_mutex);
}
| gpl-2.0 |
diego-ch/android_kernel_samsung_u8500 | Documentation/cgroups/cgroup_event_listener.c | 8415 | 2185 | /*
* cgroup_event_listener.c - Simple listener of cgroup events
*
* Copyright (C) Kirill A. Shutemov <kirill@shutemov.name>
*/
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/eventfd.h>
#define USAGE_STR "Usage: cgroup_event_listener <path-to-control-file> <args>\n"
int main(int argc, char **argv)
{
int efd = -1;
int cfd = -1;
int event_control = -1;
char event_control_path[PATH_MAX];
char line[LINE_MAX];
int ret;
if (argc != 3) {
fputs(USAGE_STR, stderr);
return 1;
}
cfd = open(argv[1], O_RDONLY);
if (cfd == -1) {
fprintf(stderr, "Cannot open %s: %s\n", argv[1],
strerror(errno));
goto out;
}
ret = snprintf(event_control_path, PATH_MAX, "%s/cgroup.event_control",
dirname(argv[1]));
if (ret >= PATH_MAX) {
fputs("Path to cgroup.event_control is too long\n", stderr);
goto out;
}
event_control = open(event_control_path, O_WRONLY);
if (event_control == -1) {
fprintf(stderr, "Cannot open %s: %s\n", event_control_path,
strerror(errno));
goto out;
}
efd = eventfd(0, 0);
if (efd == -1) {
perror("eventfd() failed");
goto out;
}
ret = snprintf(line, LINE_MAX, "%d %d %s", efd, cfd, argv[2]);
if (ret >= LINE_MAX) {
fputs("Arguments string is too long\n", stderr);
goto out;
}
ret = write(event_control, line, strlen(line) + 1);
if (ret == -1) {
perror("Cannot write to cgroup.event_control");
goto out;
}
while (1) {
uint64_t result;
ret = read(efd, &result, sizeof(result));
if (ret == -1) {
if (errno == EINTR)
continue;
perror("Cannot read from eventfd");
break;
}
assert(ret == sizeof(result));
ret = access(event_control_path, W_OK);
if ((ret == -1) && (errno == ENOENT)) {
puts("The cgroup seems to have removed.");
ret = 0;
break;
}
if (ret == -1) {
perror("cgroup.event_control "
"is not accessible any more");
break;
}
printf("%s %s: crossed\n", argv[1], argv[2]);
}
out:
if (efd >= 0)
close(efd);
if (event_control >= 0)
close(event_control);
if (cfd >= 0)
close(cfd);
return (ret != 0);
}
| gpl-2.0 |
invisiblek/kernel_808l | net/irda/ircomm/ircomm_ttp.c | 12511 | 10053 | /*********************************************************************
*
* Filename: ircomm_ttp.c
* Version: 1.0
* Description: Interface between IrCOMM and IrTTP
* Status: Stable
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Sun Jun 6 20:48:27 1999
* Modified at: Mon Dec 13 11:35:13 1999
* Modified by: Dag Brattli <dagb@cs.uit.no>
*
* Copyright (c) 1999 Dag Brattli, All Rights Reserved.
* Copyright (c) 2000-2003 Jean Tourrilhes <jt@hpl.hp.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
********************************************************************/
#include <linux/init.h>
#include <net/irda/irda.h>
#include <net/irda/irlmp.h>
#include <net/irda/iriap.h>
#include <net/irda/irttp.h>
#include <net/irda/ircomm_event.h>
#include <net/irda/ircomm_ttp.h>
static int ircomm_ttp_data_indication(void *instance, void *sap,
struct sk_buff *skb);
static void ircomm_ttp_connect_confirm(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb);
static void ircomm_ttp_connect_indication(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb);
static void ircomm_ttp_flow_indication(void *instance, void *sap,
LOCAL_FLOW cmd);
static void ircomm_ttp_disconnect_indication(void *instance, void *sap,
LM_REASON reason,
struct sk_buff *skb);
static int ircomm_ttp_data_request(struct ircomm_cb *self,
struct sk_buff *skb,
int clen);
static int ircomm_ttp_connect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info);
static int ircomm_ttp_connect_response(struct ircomm_cb *self,
struct sk_buff *userdata);
static int ircomm_ttp_disconnect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info);
/*
* Function ircomm_open_tsap (self)
*
*
*
*/
int ircomm_open_tsap(struct ircomm_cb *self)
{
notify_t notify;
IRDA_DEBUG(4, "%s()\n", __func__ );
/* Register callbacks */
irda_notify_init(¬ify);
notify.data_indication = ircomm_ttp_data_indication;
notify.connect_confirm = ircomm_ttp_connect_confirm;
notify.connect_indication = ircomm_ttp_connect_indication;
notify.flow_indication = ircomm_ttp_flow_indication;
notify.disconnect_indication = ircomm_ttp_disconnect_indication;
notify.instance = self;
strlcpy(notify.name, "IrCOMM", sizeof(notify.name));
self->tsap = irttp_open_tsap(LSAP_ANY, DEFAULT_INITIAL_CREDIT,
¬ify);
if (!self->tsap) {
IRDA_DEBUG(0, "%sfailed to allocate tsap\n", __func__ );
return -1;
}
self->slsap_sel = self->tsap->stsap_sel;
/*
* Initialize the call-table for issuing commands
*/
self->issue.data_request = ircomm_ttp_data_request;
self->issue.connect_request = ircomm_ttp_connect_request;
self->issue.connect_response = ircomm_ttp_connect_response;
self->issue.disconnect_request = ircomm_ttp_disconnect_request;
return 0;
}
/*
* Function ircomm_ttp_connect_request (self, userdata)
*
*
*
*/
static int ircomm_ttp_connect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info)
{
int ret = 0;
IRDA_DEBUG(4, "%s()\n", __func__ );
/* Don't forget to refcount it - should be NULL anyway */
if(userdata)
skb_get(userdata);
ret = irttp_connect_request(self->tsap, info->dlsap_sel,
info->saddr, info->daddr, NULL,
TTP_SAR_DISABLE, userdata);
return ret;
}
/*
* Function ircomm_ttp_connect_response (self, skb)
*
*
*
*/
static int ircomm_ttp_connect_response(struct ircomm_cb *self,
struct sk_buff *userdata)
{
int ret;
IRDA_DEBUG(4, "%s()\n", __func__ );
/* Don't forget to refcount it - should be NULL anyway */
if(userdata)
skb_get(userdata);
ret = irttp_connect_response(self->tsap, TTP_SAR_DISABLE, userdata);
return ret;
}
/*
* Function ircomm_ttp_data_request (self, userdata)
*
* Send IrCOMM data to IrTTP layer. Currently we do not try to combine
* control data with pure data, so they will be sent as separate frames.
* Should not be a big problem though, since control frames are rare. But
* some of them are sent after connection establishment, so this can
* increase the latency a bit.
*/
static int ircomm_ttp_data_request(struct ircomm_cb *self,
struct sk_buff *skb,
int clen)
{
int ret;
IRDA_ASSERT(skb != NULL, return -1;);
IRDA_DEBUG(2, "%s(), clen=%d\n", __func__ , clen);
/*
* Insert clen field, currently we either send data only, or control
* only frames, to make things easier and avoid queueing
*/
IRDA_ASSERT(skb_headroom(skb) >= IRCOMM_HEADER_SIZE, return -1;);
/* Don't forget to refcount it - see ircomm_tty_do_softint() */
skb_get(skb);
skb_push(skb, IRCOMM_HEADER_SIZE);
skb->data[0] = clen;
ret = irttp_data_request(self->tsap, skb);
if (ret) {
IRDA_ERROR("%s(), failed\n", __func__);
/* irttp_data_request already free the packet */
}
return ret;
}
/*
* Function ircomm_ttp_data_indication (instance, sap, skb)
*
* Incoming data
*
*/
static int ircomm_ttp_data_indication(void *instance, void *sap,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -1;);
IRDA_ASSERT(skb != NULL, return -1;);
ircomm_do_event(self, IRCOMM_TTP_DATA_INDICATION, skb, NULL);
/* Drop reference count - see ircomm_tty_data_indication(). */
dev_kfree_skb(skb);
return 0;
}
static void ircomm_ttp_connect_confirm(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
struct ircomm_info info;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
IRDA_ASSERT(qos != NULL, goto out;);
if (max_sdu_size != TTP_SAR_DISABLE) {
IRDA_ERROR("%s(), SAR not allowed for IrCOMM!\n",
__func__);
goto out;
}
info.max_data_size = irttp_get_max_seg_size(self->tsap)
- IRCOMM_HEADER_SIZE;
info.max_header_size = max_header_size + IRCOMM_HEADER_SIZE;
info.qos = qos;
ircomm_do_event(self, IRCOMM_TTP_CONNECT_CONFIRM, skb, &info);
out:
/* Drop reference count - see ircomm_tty_connect_confirm(). */
dev_kfree_skb(skb);
}
/*
* Function ircomm_ttp_connect_indication (instance, sap, qos, max_sdu_size,
* max_header_size, skb)
*
*
*
*/
static void ircomm_ttp_connect_indication(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *)instance;
struct ircomm_info info;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
IRDA_ASSERT(qos != NULL, goto out;);
if (max_sdu_size != TTP_SAR_DISABLE) {
IRDA_ERROR("%s(), SAR not allowed for IrCOMM!\n",
__func__);
goto out;
}
info.max_data_size = irttp_get_max_seg_size(self->tsap)
- IRCOMM_HEADER_SIZE;
info.max_header_size = max_header_size + IRCOMM_HEADER_SIZE;
info.qos = qos;
ircomm_do_event(self, IRCOMM_TTP_CONNECT_INDICATION, skb, &info);
out:
/* Drop reference count - see ircomm_tty_connect_indication(). */
dev_kfree_skb(skb);
}
/*
* Function ircomm_ttp_disconnect_request (self, userdata, info)
*
*
*
*/
static int ircomm_ttp_disconnect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info)
{
int ret;
/* Don't forget to refcount it - should be NULL anyway */
if(userdata)
skb_get(userdata);
ret = irttp_disconnect_request(self->tsap, userdata, P_NORMAL);
return ret;
}
/*
* Function ircomm_ttp_disconnect_indication (instance, sap, reason, skb)
*
*
*
*/
static void ircomm_ttp_disconnect_indication(void *instance, void *sap,
LM_REASON reason,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
struct ircomm_info info;
IRDA_DEBUG(2, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
info.reason = reason;
ircomm_do_event(self, IRCOMM_TTP_DISCONNECT_INDICATION, skb, &info);
/* Drop reference count - see ircomm_tty_disconnect_indication(). */
if(skb)
dev_kfree_skb(skb);
}
/*
* Function ircomm_ttp_flow_indication (instance, sap, cmd)
*
* Layer below is telling us to start or stop the flow of data
*
*/
static void ircomm_ttp_flow_indication(void *instance, void *sap,
LOCAL_FLOW cmd)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
if (self->notify.flow_indication)
self->notify.flow_indication(self->notify.instance, self, cmd);
}
| gpl-2.0 |
tvall43/android_kernel_grouper | net/irda/ircomm/ircomm_ttp.c | 12511 | 10053 | /*********************************************************************
*
* Filename: ircomm_ttp.c
* Version: 1.0
* Description: Interface between IrCOMM and IrTTP
* Status: Stable
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Sun Jun 6 20:48:27 1999
* Modified at: Mon Dec 13 11:35:13 1999
* Modified by: Dag Brattli <dagb@cs.uit.no>
*
* Copyright (c) 1999 Dag Brattli, All Rights Reserved.
* Copyright (c) 2000-2003 Jean Tourrilhes <jt@hpl.hp.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
********************************************************************/
#include <linux/init.h>
#include <net/irda/irda.h>
#include <net/irda/irlmp.h>
#include <net/irda/iriap.h>
#include <net/irda/irttp.h>
#include <net/irda/ircomm_event.h>
#include <net/irda/ircomm_ttp.h>
static int ircomm_ttp_data_indication(void *instance, void *sap,
struct sk_buff *skb);
static void ircomm_ttp_connect_confirm(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb);
static void ircomm_ttp_connect_indication(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb);
static void ircomm_ttp_flow_indication(void *instance, void *sap,
LOCAL_FLOW cmd);
static void ircomm_ttp_disconnect_indication(void *instance, void *sap,
LM_REASON reason,
struct sk_buff *skb);
static int ircomm_ttp_data_request(struct ircomm_cb *self,
struct sk_buff *skb,
int clen);
static int ircomm_ttp_connect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info);
static int ircomm_ttp_connect_response(struct ircomm_cb *self,
struct sk_buff *userdata);
static int ircomm_ttp_disconnect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info);
/*
* Function ircomm_open_tsap (self)
*
*
*
*/
int ircomm_open_tsap(struct ircomm_cb *self)
{
notify_t notify;
IRDA_DEBUG(4, "%s()\n", __func__ );
/* Register callbacks */
irda_notify_init(¬ify);
notify.data_indication = ircomm_ttp_data_indication;
notify.connect_confirm = ircomm_ttp_connect_confirm;
notify.connect_indication = ircomm_ttp_connect_indication;
notify.flow_indication = ircomm_ttp_flow_indication;
notify.disconnect_indication = ircomm_ttp_disconnect_indication;
notify.instance = self;
strlcpy(notify.name, "IrCOMM", sizeof(notify.name));
self->tsap = irttp_open_tsap(LSAP_ANY, DEFAULT_INITIAL_CREDIT,
¬ify);
if (!self->tsap) {
IRDA_DEBUG(0, "%sfailed to allocate tsap\n", __func__ );
return -1;
}
self->slsap_sel = self->tsap->stsap_sel;
/*
* Initialize the call-table for issuing commands
*/
self->issue.data_request = ircomm_ttp_data_request;
self->issue.connect_request = ircomm_ttp_connect_request;
self->issue.connect_response = ircomm_ttp_connect_response;
self->issue.disconnect_request = ircomm_ttp_disconnect_request;
return 0;
}
/*
* Function ircomm_ttp_connect_request (self, userdata)
*
*
*
*/
static int ircomm_ttp_connect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info)
{
int ret = 0;
IRDA_DEBUG(4, "%s()\n", __func__ );
/* Don't forget to refcount it - should be NULL anyway */
if(userdata)
skb_get(userdata);
ret = irttp_connect_request(self->tsap, info->dlsap_sel,
info->saddr, info->daddr, NULL,
TTP_SAR_DISABLE, userdata);
return ret;
}
/*
* Function ircomm_ttp_connect_response (self, skb)
*
*
*
*/
static int ircomm_ttp_connect_response(struct ircomm_cb *self,
struct sk_buff *userdata)
{
int ret;
IRDA_DEBUG(4, "%s()\n", __func__ );
/* Don't forget to refcount it - should be NULL anyway */
if(userdata)
skb_get(userdata);
ret = irttp_connect_response(self->tsap, TTP_SAR_DISABLE, userdata);
return ret;
}
/*
* Function ircomm_ttp_data_request (self, userdata)
*
* Send IrCOMM data to IrTTP layer. Currently we do not try to combine
* control data with pure data, so they will be sent as separate frames.
* Should not be a big problem though, since control frames are rare. But
* some of them are sent after connection establishment, so this can
* increase the latency a bit.
*/
static int ircomm_ttp_data_request(struct ircomm_cb *self,
struct sk_buff *skb,
int clen)
{
int ret;
IRDA_ASSERT(skb != NULL, return -1;);
IRDA_DEBUG(2, "%s(), clen=%d\n", __func__ , clen);
/*
* Insert clen field, currently we either send data only, or control
* only frames, to make things easier and avoid queueing
*/
IRDA_ASSERT(skb_headroom(skb) >= IRCOMM_HEADER_SIZE, return -1;);
/* Don't forget to refcount it - see ircomm_tty_do_softint() */
skb_get(skb);
skb_push(skb, IRCOMM_HEADER_SIZE);
skb->data[0] = clen;
ret = irttp_data_request(self->tsap, skb);
if (ret) {
IRDA_ERROR("%s(), failed\n", __func__);
/* irttp_data_request already free the packet */
}
return ret;
}
/*
* Function ircomm_ttp_data_indication (instance, sap, skb)
*
* Incoming data
*
*/
static int ircomm_ttp_data_indication(void *instance, void *sap,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -1;);
IRDA_ASSERT(skb != NULL, return -1;);
ircomm_do_event(self, IRCOMM_TTP_DATA_INDICATION, skb, NULL);
/* Drop reference count - see ircomm_tty_data_indication(). */
dev_kfree_skb(skb);
return 0;
}
static void ircomm_ttp_connect_confirm(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
struct ircomm_info info;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
IRDA_ASSERT(qos != NULL, goto out;);
if (max_sdu_size != TTP_SAR_DISABLE) {
IRDA_ERROR("%s(), SAR not allowed for IrCOMM!\n",
__func__);
goto out;
}
info.max_data_size = irttp_get_max_seg_size(self->tsap)
- IRCOMM_HEADER_SIZE;
info.max_header_size = max_header_size + IRCOMM_HEADER_SIZE;
info.qos = qos;
ircomm_do_event(self, IRCOMM_TTP_CONNECT_CONFIRM, skb, &info);
out:
/* Drop reference count - see ircomm_tty_connect_confirm(). */
dev_kfree_skb(skb);
}
/*
* Function ircomm_ttp_connect_indication (instance, sap, qos, max_sdu_size,
* max_header_size, skb)
*
*
*
*/
static void ircomm_ttp_connect_indication(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *)instance;
struct ircomm_info info;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
IRDA_ASSERT(qos != NULL, goto out;);
if (max_sdu_size != TTP_SAR_DISABLE) {
IRDA_ERROR("%s(), SAR not allowed for IrCOMM!\n",
__func__);
goto out;
}
info.max_data_size = irttp_get_max_seg_size(self->tsap)
- IRCOMM_HEADER_SIZE;
info.max_header_size = max_header_size + IRCOMM_HEADER_SIZE;
info.qos = qos;
ircomm_do_event(self, IRCOMM_TTP_CONNECT_INDICATION, skb, &info);
out:
/* Drop reference count - see ircomm_tty_connect_indication(). */
dev_kfree_skb(skb);
}
/*
* Function ircomm_ttp_disconnect_request (self, userdata, info)
*
*
*
*/
static int ircomm_ttp_disconnect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info)
{
int ret;
/* Don't forget to refcount it - should be NULL anyway */
if(userdata)
skb_get(userdata);
ret = irttp_disconnect_request(self->tsap, userdata, P_NORMAL);
return ret;
}
/*
* Function ircomm_ttp_disconnect_indication (instance, sap, reason, skb)
*
*
*
*/
static void ircomm_ttp_disconnect_indication(void *instance, void *sap,
LM_REASON reason,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
struct ircomm_info info;
IRDA_DEBUG(2, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
info.reason = reason;
ircomm_do_event(self, IRCOMM_TTP_DISCONNECT_INDICATION, skb, &info);
/* Drop reference count - see ircomm_tty_disconnect_indication(). */
if(skb)
dev_kfree_skb(skb);
}
/*
* Function ircomm_ttp_flow_indication (instance, sap, cmd)
*
* Layer below is telling us to start or stop the flow of data
*
*/
static void ircomm_ttp_flow_indication(void *instance, void *sap,
LOCAL_FLOW cmd)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
if (self->notify.flow_indication)
self->notify.flow_indication(self->notify.instance, self, cmd);
}
| gpl-2.0 |
ShinySide/HispAsian_Lollipop_J4 | net/irda/ircomm/ircomm_ttp.c | 12511 | 10053 | /*********************************************************************
*
* Filename: ircomm_ttp.c
* Version: 1.0
* Description: Interface between IrCOMM and IrTTP
* Status: Stable
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Sun Jun 6 20:48:27 1999
* Modified at: Mon Dec 13 11:35:13 1999
* Modified by: Dag Brattli <dagb@cs.uit.no>
*
* Copyright (c) 1999 Dag Brattli, All Rights Reserved.
* Copyright (c) 2000-2003 Jean Tourrilhes <jt@hpl.hp.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
********************************************************************/
#include <linux/init.h>
#include <net/irda/irda.h>
#include <net/irda/irlmp.h>
#include <net/irda/iriap.h>
#include <net/irda/irttp.h>
#include <net/irda/ircomm_event.h>
#include <net/irda/ircomm_ttp.h>
static int ircomm_ttp_data_indication(void *instance, void *sap,
struct sk_buff *skb);
static void ircomm_ttp_connect_confirm(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb);
static void ircomm_ttp_connect_indication(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb);
static void ircomm_ttp_flow_indication(void *instance, void *sap,
LOCAL_FLOW cmd);
static void ircomm_ttp_disconnect_indication(void *instance, void *sap,
LM_REASON reason,
struct sk_buff *skb);
static int ircomm_ttp_data_request(struct ircomm_cb *self,
struct sk_buff *skb,
int clen);
static int ircomm_ttp_connect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info);
static int ircomm_ttp_connect_response(struct ircomm_cb *self,
struct sk_buff *userdata);
static int ircomm_ttp_disconnect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info);
/*
* Function ircomm_open_tsap (self)
*
*
*
*/
int ircomm_open_tsap(struct ircomm_cb *self)
{
notify_t notify;
IRDA_DEBUG(4, "%s()\n", __func__ );
/* Register callbacks */
irda_notify_init(¬ify);
notify.data_indication = ircomm_ttp_data_indication;
notify.connect_confirm = ircomm_ttp_connect_confirm;
notify.connect_indication = ircomm_ttp_connect_indication;
notify.flow_indication = ircomm_ttp_flow_indication;
notify.disconnect_indication = ircomm_ttp_disconnect_indication;
notify.instance = self;
strlcpy(notify.name, "IrCOMM", sizeof(notify.name));
self->tsap = irttp_open_tsap(LSAP_ANY, DEFAULT_INITIAL_CREDIT,
¬ify);
if (!self->tsap) {
IRDA_DEBUG(0, "%sfailed to allocate tsap\n", __func__ );
return -1;
}
self->slsap_sel = self->tsap->stsap_sel;
/*
* Initialize the call-table for issuing commands
*/
self->issue.data_request = ircomm_ttp_data_request;
self->issue.connect_request = ircomm_ttp_connect_request;
self->issue.connect_response = ircomm_ttp_connect_response;
self->issue.disconnect_request = ircomm_ttp_disconnect_request;
return 0;
}
/*
* Function ircomm_ttp_connect_request (self, userdata)
*
*
*
*/
static int ircomm_ttp_connect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info)
{
int ret = 0;
IRDA_DEBUG(4, "%s()\n", __func__ );
/* Don't forget to refcount it - should be NULL anyway */
if(userdata)
skb_get(userdata);
ret = irttp_connect_request(self->tsap, info->dlsap_sel,
info->saddr, info->daddr, NULL,
TTP_SAR_DISABLE, userdata);
return ret;
}
/*
* Function ircomm_ttp_connect_response (self, skb)
*
*
*
*/
static int ircomm_ttp_connect_response(struct ircomm_cb *self,
struct sk_buff *userdata)
{
int ret;
IRDA_DEBUG(4, "%s()\n", __func__ );
/* Don't forget to refcount it - should be NULL anyway */
if(userdata)
skb_get(userdata);
ret = irttp_connect_response(self->tsap, TTP_SAR_DISABLE, userdata);
return ret;
}
/*
* Function ircomm_ttp_data_request (self, userdata)
*
* Send IrCOMM data to IrTTP layer. Currently we do not try to combine
* control data with pure data, so they will be sent as separate frames.
* Should not be a big problem though, since control frames are rare. But
* some of them are sent after connection establishment, so this can
* increase the latency a bit.
*/
static int ircomm_ttp_data_request(struct ircomm_cb *self,
struct sk_buff *skb,
int clen)
{
int ret;
IRDA_ASSERT(skb != NULL, return -1;);
IRDA_DEBUG(2, "%s(), clen=%d\n", __func__ , clen);
/*
* Insert clen field, currently we either send data only, or control
* only frames, to make things easier and avoid queueing
*/
IRDA_ASSERT(skb_headroom(skb) >= IRCOMM_HEADER_SIZE, return -1;);
/* Don't forget to refcount it - see ircomm_tty_do_softint() */
skb_get(skb);
skb_push(skb, IRCOMM_HEADER_SIZE);
skb->data[0] = clen;
ret = irttp_data_request(self->tsap, skb);
if (ret) {
IRDA_ERROR("%s(), failed\n", __func__);
/* irttp_data_request already free the packet */
}
return ret;
}
/*
* Function ircomm_ttp_data_indication (instance, sap, skb)
*
* Incoming data
*
*/
static int ircomm_ttp_data_indication(void *instance, void *sap,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return -1;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return -1;);
IRDA_ASSERT(skb != NULL, return -1;);
ircomm_do_event(self, IRCOMM_TTP_DATA_INDICATION, skb, NULL);
/* Drop reference count - see ircomm_tty_data_indication(). */
dev_kfree_skb(skb);
return 0;
}
static void ircomm_ttp_connect_confirm(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
struct ircomm_info info;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
IRDA_ASSERT(qos != NULL, goto out;);
if (max_sdu_size != TTP_SAR_DISABLE) {
IRDA_ERROR("%s(), SAR not allowed for IrCOMM!\n",
__func__);
goto out;
}
info.max_data_size = irttp_get_max_seg_size(self->tsap)
- IRCOMM_HEADER_SIZE;
info.max_header_size = max_header_size + IRCOMM_HEADER_SIZE;
info.qos = qos;
ircomm_do_event(self, IRCOMM_TTP_CONNECT_CONFIRM, skb, &info);
out:
/* Drop reference count - see ircomm_tty_connect_confirm(). */
dev_kfree_skb(skb);
}
/*
* Function ircomm_ttp_connect_indication (instance, sap, qos, max_sdu_size,
* max_header_size, skb)
*
*
*
*/
static void ircomm_ttp_connect_indication(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size,
__u8 max_header_size,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *)instance;
struct ircomm_info info;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
IRDA_ASSERT(skb != NULL, return;);
IRDA_ASSERT(qos != NULL, goto out;);
if (max_sdu_size != TTP_SAR_DISABLE) {
IRDA_ERROR("%s(), SAR not allowed for IrCOMM!\n",
__func__);
goto out;
}
info.max_data_size = irttp_get_max_seg_size(self->tsap)
- IRCOMM_HEADER_SIZE;
info.max_header_size = max_header_size + IRCOMM_HEADER_SIZE;
info.qos = qos;
ircomm_do_event(self, IRCOMM_TTP_CONNECT_INDICATION, skb, &info);
out:
/* Drop reference count - see ircomm_tty_connect_indication(). */
dev_kfree_skb(skb);
}
/*
* Function ircomm_ttp_disconnect_request (self, userdata, info)
*
*
*
*/
static int ircomm_ttp_disconnect_request(struct ircomm_cb *self,
struct sk_buff *userdata,
struct ircomm_info *info)
{
int ret;
/* Don't forget to refcount it - should be NULL anyway */
if(userdata)
skb_get(userdata);
ret = irttp_disconnect_request(self->tsap, userdata, P_NORMAL);
return ret;
}
/*
* Function ircomm_ttp_disconnect_indication (instance, sap, reason, skb)
*
*
*
*/
static void ircomm_ttp_disconnect_indication(void *instance, void *sap,
LM_REASON reason,
struct sk_buff *skb)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
struct ircomm_info info;
IRDA_DEBUG(2, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
info.reason = reason;
ircomm_do_event(self, IRCOMM_TTP_DISCONNECT_INDICATION, skb, &info);
/* Drop reference count - see ircomm_tty_disconnect_indication(). */
if(skb)
dev_kfree_skb(skb);
}
/*
* Function ircomm_ttp_flow_indication (instance, sap, cmd)
*
* Layer below is telling us to start or stop the flow of data
*
*/
static void ircomm_ttp_flow_indication(void *instance, void *sap,
LOCAL_FLOW cmd)
{
struct ircomm_cb *self = (struct ircomm_cb *) instance;
IRDA_DEBUG(4, "%s()\n", __func__ );
IRDA_ASSERT(self != NULL, return;);
IRDA_ASSERT(self->magic == IRCOMM_MAGIC, return;);
if (self->notify.flow_indication)
self->notify.flow_indication(self->notify.instance, self, cmd);
}
| gpl-2.0 |
anryl/shooteru_HTC | net/netfilter/xt_mark.c | 12767 | 2092 | /*
* xt_mark - Netfilter module to match NFMARK value
*
* (C) 1999-2001 Marc Boucher <marc@mbsi.ca>
* Copyright © CC Computer Consultants GmbH, 2007 - 2008
* Jan Engelhardt <jengelh@medozas.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netfilter/xt_mark.h>
#include <linux/netfilter/x_tables.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Marc Boucher <marc@mbsi.ca>");
MODULE_DESCRIPTION("Xtables: packet mark operations");
MODULE_ALIAS("ipt_mark");
MODULE_ALIAS("ip6t_mark");
MODULE_ALIAS("ipt_MARK");
MODULE_ALIAS("ip6t_MARK");
static unsigned int
mark_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct xt_mark_tginfo2 *info = par->targinfo;
skb->mark = (skb->mark & ~info->mask) ^ info->mark;
return XT_CONTINUE;
}
static bool
mark_mt(const struct sk_buff *skb, struct xt_action_param *par)
{
const struct xt_mark_mtinfo1 *info = par->matchinfo;
return ((skb->mark & info->mask) == info->mark) ^ info->invert;
}
static struct xt_target mark_tg_reg __read_mostly = {
.name = "MARK",
.revision = 2,
.family = NFPROTO_UNSPEC,
.target = mark_tg,
.targetsize = sizeof(struct xt_mark_tginfo2),
.me = THIS_MODULE,
};
static struct xt_match mark_mt_reg __read_mostly = {
.name = "mark",
.revision = 1,
.family = NFPROTO_UNSPEC,
.match = mark_mt,
.matchsize = sizeof(struct xt_mark_mtinfo1),
.me = THIS_MODULE,
};
static int __init mark_mt_init(void)
{
int ret;
ret = xt_register_target(&mark_tg_reg);
if (ret < 0)
return ret;
ret = xt_register_match(&mark_mt_reg);
if (ret < 0) {
xt_unregister_target(&mark_tg_reg);
return ret;
}
return 0;
}
static void __exit mark_mt_exit(void)
{
xt_unregister_match(&mark_mt_reg);
xt_unregister_target(&mark_tg_reg);
}
module_init(mark_mt_init);
module_exit(mark_mt_exit);
| gpl-2.0 |
rocky-wang/smart210_linux | drivers/virtio/virtio_pci.c | 736 | 19566 | /*
* Virtio PCI driver
*
* This module allows virtio devices to be used over a virtual PCI device.
* This can be used with QEMU based VMMs like KVM or Xen.
*
* Copyright IBM Corp. 2007
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*
*/
#include <linux/module.h>
#include <linux/list.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/virtio.h>
#include <linux/virtio_config.h>
#include <linux/virtio_ring.h>
#include <linux/virtio_pci.h>
#include <linux/highmem.h>
#include <linux/spinlock.h>
MODULE_AUTHOR("Anthony Liguori <aliguori@us.ibm.com>");
MODULE_DESCRIPTION("virtio-pci");
MODULE_LICENSE("GPL");
MODULE_VERSION("1");
/* Our device structure */
struct virtio_pci_device
{
struct virtio_device vdev;
struct pci_dev *pci_dev;
/* the IO mapping for the PCI config space */
void __iomem *ioaddr;
/* a list of queues so we can dispatch IRQs */
spinlock_t lock;
struct list_head virtqueues;
/* MSI-X support */
int msix_enabled;
int intx_enabled;
struct msix_entry *msix_entries;
/* Name strings for interrupts. This size should be enough,
* and I'm too lazy to allocate each name separately. */
char (*msix_names)[256];
/* Number of available vectors */
unsigned msix_vectors;
/* Vectors allocated, excluding per-vq vectors if any */
unsigned msix_used_vectors;
/* Whether we have vector per vq */
bool per_vq_vectors;
};
/* Constants for MSI-X */
/* Use first vector for configuration changes, second and the rest for
* virtqueues Thus, we need at least 2 vectors for MSI. */
enum {
VP_MSIX_CONFIG_VECTOR = 0,
VP_MSIX_VQ_VECTOR = 1,
};
struct virtio_pci_vq_info
{
/* the actual virtqueue */
struct virtqueue *vq;
/* the number of entries in the queue */
int num;
/* the index of the queue */
int queue_index;
/* the virtual address of the ring queue */
void *queue;
/* the list node for the virtqueues list */
struct list_head node;
/* MSI-X vector (or none) */
unsigned msix_vector;
};
/* Qumranet donated their vendor ID for devices 0x1000 thru 0x10FF. */
static struct pci_device_id virtio_pci_id_table[] = {
{ 0x1af4, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
{ 0 },
};
MODULE_DEVICE_TABLE(pci, virtio_pci_id_table);
/* Convert a generic virtio device to our structure */
static struct virtio_pci_device *to_vp_device(struct virtio_device *vdev)
{
return container_of(vdev, struct virtio_pci_device, vdev);
}
/* virtio config->get_features() implementation */
static u32 vp_get_features(struct virtio_device *vdev)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
/* When someone needs more than 32 feature bits, we'll need to
* steal a bit to indicate that the rest are somewhere else. */
return ioread32(vp_dev->ioaddr + VIRTIO_PCI_HOST_FEATURES);
}
/* virtio config->finalize_features() implementation */
static void vp_finalize_features(struct virtio_device *vdev)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
/* Give virtio_ring a chance to accept features. */
vring_transport_features(vdev);
/* We only support 32 feature bits. */
BUILD_BUG_ON(ARRAY_SIZE(vdev->features) != 1);
iowrite32(vdev->features[0], vp_dev->ioaddr+VIRTIO_PCI_GUEST_FEATURES);
}
/* virtio config->get() implementation */
static void vp_get(struct virtio_device *vdev, unsigned offset,
void *buf, unsigned len)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
void __iomem *ioaddr = vp_dev->ioaddr +
VIRTIO_PCI_CONFIG(vp_dev) + offset;
u8 *ptr = buf;
int i;
for (i = 0; i < len; i++)
ptr[i] = ioread8(ioaddr + i);
}
/* the config->set() implementation. it's symmetric to the config->get()
* implementation */
static void vp_set(struct virtio_device *vdev, unsigned offset,
const void *buf, unsigned len)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
void __iomem *ioaddr = vp_dev->ioaddr +
VIRTIO_PCI_CONFIG(vp_dev) + offset;
const u8 *ptr = buf;
int i;
for (i = 0; i < len; i++)
iowrite8(ptr[i], ioaddr + i);
}
/* config->{get,set}_status() implementations */
static u8 vp_get_status(struct virtio_device *vdev)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
return ioread8(vp_dev->ioaddr + VIRTIO_PCI_STATUS);
}
static void vp_set_status(struct virtio_device *vdev, u8 status)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
/* We should never be setting status to 0. */
BUG_ON(status == 0);
iowrite8(status, vp_dev->ioaddr + VIRTIO_PCI_STATUS);
}
static void vp_reset(struct virtio_device *vdev)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
/* 0 status means a reset. */
iowrite8(0, vp_dev->ioaddr + VIRTIO_PCI_STATUS);
}
/* the notify function used when creating a virt queue */
static void vp_notify(struct virtqueue *vq)
{
struct virtio_pci_device *vp_dev = to_vp_device(vq->vdev);
struct virtio_pci_vq_info *info = vq->priv;
/* we write the queue's selector into the notification register to
* signal the other end */
iowrite16(info->queue_index, vp_dev->ioaddr + VIRTIO_PCI_QUEUE_NOTIFY);
}
/* Handle a configuration change: Tell driver if it wants to know. */
static irqreturn_t vp_config_changed(int irq, void *opaque)
{
struct virtio_pci_device *vp_dev = opaque;
struct virtio_driver *drv;
drv = container_of(vp_dev->vdev.dev.driver,
struct virtio_driver, driver);
if (drv && drv->config_changed)
drv->config_changed(&vp_dev->vdev);
return IRQ_HANDLED;
}
/* Notify all virtqueues on an interrupt. */
static irqreturn_t vp_vring_interrupt(int irq, void *opaque)
{
struct virtio_pci_device *vp_dev = opaque;
struct virtio_pci_vq_info *info;
irqreturn_t ret = IRQ_NONE;
unsigned long flags;
spin_lock_irqsave(&vp_dev->lock, flags);
list_for_each_entry(info, &vp_dev->virtqueues, node) {
if (vring_interrupt(irq, info->vq) == IRQ_HANDLED)
ret = IRQ_HANDLED;
}
spin_unlock_irqrestore(&vp_dev->lock, flags);
return ret;
}
/* A small wrapper to also acknowledge the interrupt when it's handled.
* I really need an EIO hook for the vring so I can ack the interrupt once we
* know that we'll be handling the IRQ but before we invoke the callback since
* the callback may notify the host which results in the host attempting to
* raise an interrupt that we would then mask once we acknowledged the
* interrupt. */
static irqreturn_t vp_interrupt(int irq, void *opaque)
{
struct virtio_pci_device *vp_dev = opaque;
u8 isr;
/* reading the ISR has the effect of also clearing it so it's very
* important to save off the value. */
isr = ioread8(vp_dev->ioaddr + VIRTIO_PCI_ISR);
/* It's definitely not us if the ISR was not high */
if (!isr)
return IRQ_NONE;
/* Configuration change? Tell driver if it wants to know. */
if (isr & VIRTIO_PCI_ISR_CONFIG)
vp_config_changed(irq, opaque);
return vp_vring_interrupt(irq, opaque);
}
static void vp_free_vectors(struct virtio_device *vdev)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
int i;
if (vp_dev->intx_enabled) {
free_irq(vp_dev->pci_dev->irq, vp_dev);
vp_dev->intx_enabled = 0;
}
for (i = 0; i < vp_dev->msix_used_vectors; ++i)
free_irq(vp_dev->msix_entries[i].vector, vp_dev);
if (vp_dev->msix_enabled) {
/* Disable the vector used for configuration */
iowrite16(VIRTIO_MSI_NO_VECTOR,
vp_dev->ioaddr + VIRTIO_MSI_CONFIG_VECTOR);
/* Flush the write out to device */
ioread16(vp_dev->ioaddr + VIRTIO_MSI_CONFIG_VECTOR);
pci_disable_msix(vp_dev->pci_dev);
vp_dev->msix_enabled = 0;
vp_dev->msix_vectors = 0;
}
vp_dev->msix_used_vectors = 0;
kfree(vp_dev->msix_names);
vp_dev->msix_names = NULL;
kfree(vp_dev->msix_entries);
vp_dev->msix_entries = NULL;
}
static int vp_request_msix_vectors(struct virtio_device *vdev, int nvectors,
bool per_vq_vectors)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
const char *name = dev_name(&vp_dev->vdev.dev);
unsigned i, v;
int err = -ENOMEM;
vp_dev->msix_entries = kmalloc(nvectors * sizeof *vp_dev->msix_entries,
GFP_KERNEL);
if (!vp_dev->msix_entries)
goto error;
vp_dev->msix_names = kmalloc(nvectors * sizeof *vp_dev->msix_names,
GFP_KERNEL);
if (!vp_dev->msix_names)
goto error;
for (i = 0; i < nvectors; ++i)
vp_dev->msix_entries[i].entry = i;
/* pci_enable_msix returns positive if we can't get this many. */
err = pci_enable_msix(vp_dev->pci_dev, vp_dev->msix_entries, nvectors);
if (err > 0)
err = -ENOSPC;
if (err)
goto error;
vp_dev->msix_vectors = nvectors;
vp_dev->msix_enabled = 1;
/* Set the vector used for configuration */
v = vp_dev->msix_used_vectors;
snprintf(vp_dev->msix_names[v], sizeof *vp_dev->msix_names,
"%s-config", name);
err = request_irq(vp_dev->msix_entries[v].vector,
vp_config_changed, 0, vp_dev->msix_names[v],
vp_dev);
if (err)
goto error;
++vp_dev->msix_used_vectors;
iowrite16(v, vp_dev->ioaddr + VIRTIO_MSI_CONFIG_VECTOR);
/* Verify we had enough resources to assign the vector */
v = ioread16(vp_dev->ioaddr + VIRTIO_MSI_CONFIG_VECTOR);
if (v == VIRTIO_MSI_NO_VECTOR) {
err = -EBUSY;
goto error;
}
if (!per_vq_vectors) {
/* Shared vector for all VQs */
v = vp_dev->msix_used_vectors;
snprintf(vp_dev->msix_names[v], sizeof *vp_dev->msix_names,
"%s-virtqueues", name);
err = request_irq(vp_dev->msix_entries[v].vector,
vp_vring_interrupt, 0, vp_dev->msix_names[v],
vp_dev);
if (err)
goto error;
++vp_dev->msix_used_vectors;
}
return 0;
error:
vp_free_vectors(vdev);
return err;
}
static int vp_request_intx(struct virtio_device *vdev)
{
int err;
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
err = request_irq(vp_dev->pci_dev->irq, vp_interrupt,
IRQF_SHARED, dev_name(&vdev->dev), vp_dev);
if (!err)
vp_dev->intx_enabled = 1;
return err;
}
static struct virtqueue *setup_vq(struct virtio_device *vdev, unsigned index,
void (*callback)(struct virtqueue *vq),
const char *name,
u16 msix_vec)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
struct virtio_pci_vq_info *info;
struct virtqueue *vq;
unsigned long flags, size;
u16 num;
int err;
/* Select the queue we're interested in */
iowrite16(index, vp_dev->ioaddr + VIRTIO_PCI_QUEUE_SEL);
/* Check if queue is either not available or already active. */
num = ioread16(vp_dev->ioaddr + VIRTIO_PCI_QUEUE_NUM);
if (!num || ioread32(vp_dev->ioaddr + VIRTIO_PCI_QUEUE_PFN))
return ERR_PTR(-ENOENT);
/* allocate and fill out our structure the represents an active
* queue */
info = kmalloc(sizeof(struct virtio_pci_vq_info), GFP_KERNEL);
if (!info)
return ERR_PTR(-ENOMEM);
info->queue_index = index;
info->num = num;
info->msix_vector = msix_vec;
size = PAGE_ALIGN(vring_size(num, VIRTIO_PCI_VRING_ALIGN));
info->queue = alloc_pages_exact(size, GFP_KERNEL|__GFP_ZERO);
if (info->queue == NULL) {
err = -ENOMEM;
goto out_info;
}
/* activate the queue */
iowrite32(virt_to_phys(info->queue) >> VIRTIO_PCI_QUEUE_ADDR_SHIFT,
vp_dev->ioaddr + VIRTIO_PCI_QUEUE_PFN);
/* create the vring */
vq = vring_new_virtqueue(info->num, VIRTIO_PCI_VRING_ALIGN,
vdev, info->queue, vp_notify, callback, name);
if (!vq) {
err = -ENOMEM;
goto out_activate_queue;
}
vq->priv = info;
info->vq = vq;
if (msix_vec != VIRTIO_MSI_NO_VECTOR) {
iowrite16(msix_vec, vp_dev->ioaddr + VIRTIO_MSI_QUEUE_VECTOR);
msix_vec = ioread16(vp_dev->ioaddr + VIRTIO_MSI_QUEUE_VECTOR);
if (msix_vec == VIRTIO_MSI_NO_VECTOR) {
err = -EBUSY;
goto out_assign;
}
}
spin_lock_irqsave(&vp_dev->lock, flags);
list_add(&info->node, &vp_dev->virtqueues);
spin_unlock_irqrestore(&vp_dev->lock, flags);
return vq;
out_assign:
vring_del_virtqueue(vq);
out_activate_queue:
iowrite32(0, vp_dev->ioaddr + VIRTIO_PCI_QUEUE_PFN);
free_pages_exact(info->queue, size);
out_info:
kfree(info);
return ERR_PTR(err);
}
static void vp_del_vq(struct virtqueue *vq)
{
struct virtio_pci_device *vp_dev = to_vp_device(vq->vdev);
struct virtio_pci_vq_info *info = vq->priv;
unsigned long flags, size;
spin_lock_irqsave(&vp_dev->lock, flags);
list_del(&info->node);
spin_unlock_irqrestore(&vp_dev->lock, flags);
iowrite16(info->queue_index, vp_dev->ioaddr + VIRTIO_PCI_QUEUE_SEL);
if (vp_dev->msix_enabled) {
iowrite16(VIRTIO_MSI_NO_VECTOR,
vp_dev->ioaddr + VIRTIO_MSI_QUEUE_VECTOR);
/* Flush the write out to device */
ioread8(vp_dev->ioaddr + VIRTIO_PCI_ISR);
}
vring_del_virtqueue(vq);
/* Select and deactivate the queue */
iowrite32(0, vp_dev->ioaddr + VIRTIO_PCI_QUEUE_PFN);
size = PAGE_ALIGN(vring_size(info->num, VIRTIO_PCI_VRING_ALIGN));
free_pages_exact(info->queue, size);
kfree(info);
}
/* the config->del_vqs() implementation */
static void vp_del_vqs(struct virtio_device *vdev)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
struct virtqueue *vq, *n;
struct virtio_pci_vq_info *info;
list_for_each_entry_safe(vq, n, &vdev->vqs, list) {
info = vq->priv;
if (vp_dev->per_vq_vectors &&
info->msix_vector != VIRTIO_MSI_NO_VECTOR)
free_irq(vp_dev->msix_entries[info->msix_vector].vector,
vq);
vp_del_vq(vq);
}
vp_dev->per_vq_vectors = false;
vp_free_vectors(vdev);
}
static int vp_try_to_find_vqs(struct virtio_device *vdev, unsigned nvqs,
struct virtqueue *vqs[],
vq_callback_t *callbacks[],
const char *names[],
bool use_msix,
bool per_vq_vectors)
{
struct virtio_pci_device *vp_dev = to_vp_device(vdev);
u16 msix_vec;
int i, err, nvectors, allocated_vectors;
if (!use_msix) {
/* Old style: one normal interrupt for change and all vqs. */
err = vp_request_intx(vdev);
if (err)
goto error_request;
} else {
if (per_vq_vectors) {
/* Best option: one for change interrupt, one per vq. */
nvectors = 1;
for (i = 0; i < nvqs; ++i)
if (callbacks[i])
++nvectors;
} else {
/* Second best: one for change, shared for all vqs. */
nvectors = 2;
}
err = vp_request_msix_vectors(vdev, nvectors, per_vq_vectors);
if (err)
goto error_request;
}
vp_dev->per_vq_vectors = per_vq_vectors;
allocated_vectors = vp_dev->msix_used_vectors;
for (i = 0; i < nvqs; ++i) {
if (!callbacks[i] || !vp_dev->msix_enabled)
msix_vec = VIRTIO_MSI_NO_VECTOR;
else if (vp_dev->per_vq_vectors)
msix_vec = allocated_vectors++;
else
msix_vec = VP_MSIX_VQ_VECTOR;
vqs[i] = setup_vq(vdev, i, callbacks[i], names[i], msix_vec);
if (IS_ERR(vqs[i])) {
err = PTR_ERR(vqs[i]);
goto error_find;
}
if (!vp_dev->per_vq_vectors || msix_vec == VIRTIO_MSI_NO_VECTOR)
continue;
/* allocate per-vq irq if available and necessary */
snprintf(vp_dev->msix_names[msix_vec],
sizeof *vp_dev->msix_names,
"%s-%s",
dev_name(&vp_dev->vdev.dev), names[i]);
err = request_irq(vp_dev->msix_entries[msix_vec].vector,
vring_interrupt, 0,
vp_dev->msix_names[msix_vec],
vqs[i]);
if (err) {
vp_del_vq(vqs[i]);
goto error_find;
}
}
return 0;
error_find:
vp_del_vqs(vdev);
error_request:
return err;
}
/* the config->find_vqs() implementation */
static int vp_find_vqs(struct virtio_device *vdev, unsigned nvqs,
struct virtqueue *vqs[],
vq_callback_t *callbacks[],
const char *names[])
{
int err;
/* Try MSI-X with one vector per queue. */
err = vp_try_to_find_vqs(vdev, nvqs, vqs, callbacks, names, true, true);
if (!err)
return 0;
/* Fallback: MSI-X with one vector for config, one shared for queues. */
err = vp_try_to_find_vqs(vdev, nvqs, vqs, callbacks, names,
true, false);
if (!err)
return 0;
/* Finally fall back to regular interrupts. */
return vp_try_to_find_vqs(vdev, nvqs, vqs, callbacks, names,
false, false);
}
static struct virtio_config_ops virtio_pci_config_ops = {
.get = vp_get,
.set = vp_set,
.get_status = vp_get_status,
.set_status = vp_set_status,
.reset = vp_reset,
.find_vqs = vp_find_vqs,
.del_vqs = vp_del_vqs,
.get_features = vp_get_features,
.finalize_features = vp_finalize_features,
};
static void virtio_pci_release_dev(struct device *_d)
{
struct virtio_device *dev = container_of(_d, struct virtio_device,
dev);
struct virtio_pci_device *vp_dev = to_vp_device(dev);
kfree(vp_dev);
}
/* the PCI probing function */
static int __devinit virtio_pci_probe(struct pci_dev *pci_dev,
const struct pci_device_id *id)
{
struct virtio_pci_device *vp_dev;
int err;
/* We only own devices >= 0x1000 and <= 0x103f: leave the rest. */
if (pci_dev->device < 0x1000 || pci_dev->device > 0x103f)
return -ENODEV;
if (pci_dev->revision != VIRTIO_PCI_ABI_VERSION) {
printk(KERN_ERR "virtio_pci: expected ABI version %d, got %d\n",
VIRTIO_PCI_ABI_VERSION, pci_dev->revision);
return -ENODEV;
}
/* allocate our structure and fill it out */
vp_dev = kzalloc(sizeof(struct virtio_pci_device), GFP_KERNEL);
if (vp_dev == NULL)
return -ENOMEM;
vp_dev->vdev.dev.parent = &pci_dev->dev;
vp_dev->vdev.dev.release = virtio_pci_release_dev;
vp_dev->vdev.config = &virtio_pci_config_ops;
vp_dev->pci_dev = pci_dev;
INIT_LIST_HEAD(&vp_dev->virtqueues);
spin_lock_init(&vp_dev->lock);
/* Disable MSI/MSIX to bring device to a known good state. */
pci_msi_off(pci_dev);
/* enable the device */
err = pci_enable_device(pci_dev);
if (err)
goto out;
err = pci_request_regions(pci_dev, "virtio-pci");
if (err)
goto out_enable_device;
vp_dev->ioaddr = pci_iomap(pci_dev, 0, 0);
if (vp_dev->ioaddr == NULL)
goto out_req_regions;
pci_set_drvdata(pci_dev, vp_dev);
pci_set_master(pci_dev);
/* we use the subsystem vendor/device id as the virtio vendor/device
* id. this allows us to use the same PCI vendor/device id for all
* virtio devices and to identify the particular virtio driver by
* the subsystem ids */
vp_dev->vdev.id.vendor = pci_dev->subsystem_vendor;
vp_dev->vdev.id.device = pci_dev->subsystem_device;
/* finally register the virtio device */
err = register_virtio_device(&vp_dev->vdev);
if (err)
goto out_set_drvdata;
return 0;
out_set_drvdata:
pci_set_drvdata(pci_dev, NULL);
pci_iounmap(pci_dev, vp_dev->ioaddr);
out_req_regions:
pci_release_regions(pci_dev);
out_enable_device:
pci_disable_device(pci_dev);
out:
kfree(vp_dev);
return err;
}
static void __devexit virtio_pci_remove(struct pci_dev *pci_dev)
{
struct virtio_pci_device *vp_dev = pci_get_drvdata(pci_dev);
unregister_virtio_device(&vp_dev->vdev);
vp_del_vqs(&vp_dev->vdev);
pci_set_drvdata(pci_dev, NULL);
pci_iounmap(pci_dev, vp_dev->ioaddr);
pci_release_regions(pci_dev);
pci_disable_device(pci_dev);
}
#ifdef CONFIG_PM
static int virtio_pci_suspend(struct pci_dev *pci_dev, pm_message_t state)
{
pci_save_state(pci_dev);
pci_set_power_state(pci_dev, PCI_D3hot);
return 0;
}
static int virtio_pci_resume(struct pci_dev *pci_dev)
{
pci_restore_state(pci_dev);
pci_set_power_state(pci_dev, PCI_D0);
return 0;
}
#endif
static struct pci_driver virtio_pci_driver = {
.name = "virtio-pci",
.id_table = virtio_pci_id_table,
.probe = virtio_pci_probe,
.remove = __devexit_p(virtio_pci_remove),
#ifdef CONFIG_PM
.suspend = virtio_pci_suspend,
.resume = virtio_pci_resume,
#endif
};
static int __init virtio_pci_init(void)
{
return pci_register_driver(&virtio_pci_driver);
}
module_init(virtio_pci_init);
static void __exit virtio_pci_exit(void)
{
pci_unregister_driver(&virtio_pci_driver);
}
module_exit(virtio_pci_exit);
| gpl-2.0 |
oppo-source/Find7-kernel-source | drivers/media/platform/msm/wfd/mdp-4-subdev.c | 2016 | 6593 | /* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/msm_mdp.h>
#include <linux/slab.h>
#include <mach/iommu_domains.h>
#include <media/videobuf2-core.h>
#include "enc-subdev.h"
#include "mdp-subdev.h"
#include "wfd-util.h"
struct mdp_instance {
struct fb_info *mdp;
u32 height;
u32 width;
bool secure;
bool uses_iommu_split_domain;
};
int mdp_init(struct v4l2_subdev *sd, u32 val)
{
return 0;
}
int mdp_open(struct v4l2_subdev *sd, void *arg)
{
struct mdp_instance *inst = kzalloc(sizeof(struct mdp_instance),
GFP_KERNEL);
struct mdp_msg_ops *mops = arg;
int rc = 0;
struct fb_info *fbi = NULL;
if (!inst) {
WFD_MSG_ERR("Out of memory\n");
rc = -ENOMEM;
goto mdp_open_fail;
} else if (!mops) {
WFD_MSG_ERR("Invalid arguments\n");
rc = -EINVAL;
goto mdp_open_fail;
}
fbi = msm_fb_get_writeback_fb();
if (!fbi) {
WFD_MSG_ERR("Failed to acquire mdp instance\n");
rc = -ENODEV;
goto mdp_open_fail;
}
msm_fb_writeback_init(fbi);
inst->mdp = fbi;
inst->secure = mops->secure;
inst->uses_iommu_split_domain = mops->iommu_split_domain;
mops->cookie = inst;
return rc;
mdp_open_fail:
kfree(inst);
return rc;
}
int mdp_start(struct v4l2_subdev *sd, void *arg)
{
struct mdp_instance *inst = arg;
int rc = 0;
struct fb_info *fbi = NULL;
if (inst) {
rc = msm_fb_writeback_start(inst->mdp);
if (rc) {
WFD_MSG_ERR("Failed to start MDP mode\n");
goto exit;
}
fbi = msm_fb_get_writeback_fb();
if (!fbi) {
WFD_MSG_ERR("Failed to acquire mdp instance\n");
rc = -ENODEV;
goto exit;
}
}
exit:
return rc;
}
int mdp_stop(struct v4l2_subdev *sd, void *arg)
{
struct mdp_instance *inst = arg;
int rc = 0;
struct fb_info *fbi = NULL;
if (inst) {
rc = msm_fb_writeback_stop(inst->mdp);
if (rc) {
WFD_MSG_ERR("Failed to stop writeback mode\n");
return rc;
}
fbi = (struct fb_info *)inst->mdp;
}
return 0;
}
int mdp_close(struct v4l2_subdev *sd, void *arg)
{
struct mdp_instance *inst = arg;
struct fb_info *fbi = NULL;
if (inst) {
fbi = (struct fb_info *)inst->mdp;
msm_fb_writeback_terminate(fbi);
kfree(inst);
}
return 0;
}
int mdp_q_buffer(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct mdp_buf_info *binfo = arg;
struct msmfb_data fbdata;
struct mdp_instance *inst;
if (!binfo || !binfo->inst || !binfo->cookie) {
WFD_MSG_ERR("Invalid argument\n");
return -EINVAL;
}
inst = binfo->inst;
fbdata.offset = binfo->offset;
fbdata.memory_id = binfo->fd;
fbdata.iova = binfo->paddr;
fbdata.id = 0;
fbdata.flags = 0;
fbdata.priv = (uint32_t)binfo->cookie;
WFD_MSG_INFO("queue buffer to mdp with offset = %u, fd = %u, "\
"priv = %p, iova = %p\n",
fbdata.offset, fbdata.memory_id,
(void *)fbdata.priv, (void *)fbdata.iova);
rc = msm_fb_writeback_queue_buffer(inst->mdp, &fbdata);
if (rc)
WFD_MSG_ERR("Failed to queue buffer\n");
return rc;
}
int mdp_dq_buffer(struct v4l2_subdev *sd, void *arg)
{
int rc = 0;
struct mdp_buf_info *obuf = arg;
struct msmfb_data fbdata;
struct mdp_instance *inst;
if (!arg) {
WFD_MSG_ERR("Invalid argument\n");
return -EINVAL;
}
inst = obuf->inst;
fbdata.flags = MSMFB_WRITEBACK_DEQUEUE_BLOCKING;
rc = msm_fb_writeback_dequeue_buffer(inst->mdp, &fbdata);
if (rc) {
WFD_MSG_ERR("Failed to dequeue buffer\n");
return rc;
}
WFD_MSG_DBG("dequeue buf from mdp with priv = %u\n",
fbdata.priv);
obuf->cookie = (void *)fbdata.priv;
return rc;
}
int mdp_set_prop(struct v4l2_subdev *sd, void *arg)
{
struct mdp_prop *prop = (struct mdp_prop *)arg;
struct mdp_instance *inst = prop->inst;
if (!prop || !inst) {
WFD_MSG_ERR("Invalid arguments\n");
return -EINVAL;
}
inst->height = prop->height;
inst->width = prop->width;
return 0;
}
int mdp_mmap(struct v4l2_subdev *sd, void *arg)
{
int rc = 0, domain = -1;
struct mem_region_map *mmap = arg;
struct mem_region *mregion;
bool use_iommu = true;
struct mdp_instance *inst = NULL;
if (!mmap || !mmap->mregion || !mmap->cookie) {
WFD_MSG_ERR("Invalid argument\n");
return -EINVAL;
}
inst = mmap->cookie;
mregion = mmap->mregion;
if (mregion->size % SZ_4K != 0) {
WFD_MSG_ERR("Memregion not aligned to %d\n", SZ_4K);
return -EINVAL;
}
if (inst->uses_iommu_split_domain) {
if (inst->secure)
use_iommu = false;
else
domain = DISPLAY_WRITE_DOMAIN;
} else {
domain = DISPLAY_READ_DOMAIN;
}
if (use_iommu) {
rc = ion_map_iommu(mmap->ion_client, mregion->ion_handle,
domain, GEN_POOL, SZ_4K, 0,
(unsigned long *)&mregion->paddr,
(unsigned long *)&mregion->size,
0, 0);
} else {
rc = ion_phys(mmap->ion_client, mregion->ion_handle,
(unsigned long *)&mregion->paddr,
(size_t *)&mregion->size);
}
return rc;
}
int mdp_munmap(struct v4l2_subdev *sd, void *arg)
{
struct mem_region_map *mmap = arg;
struct mem_region *mregion;
bool use_iommu = false;
int domain = -1;
struct mdp_instance *inst = NULL;
if (!mmap || !mmap->mregion || !mmap->cookie) {
WFD_MSG_ERR("Invalid argument\n");
return -EINVAL;
}
inst = mmap->cookie;
mregion = mmap->mregion;
if (inst->uses_iommu_split_domain) {
if (inst->secure)
use_iommu = false;
else
domain = DISPLAY_WRITE_DOMAIN;
} else {
domain = DISPLAY_READ_DOMAIN;
}
if (use_iommu)
ion_unmap_iommu(mmap->ion_client,
mregion->ion_handle,
domain, GEN_POOL);
return 0;
}
long mdp_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
{
int rc = 0;
if (!sd) {
WFD_MSG_ERR("Invalid arguments\n");
return -EINVAL;
}
switch (cmd) {
case MDP_Q_BUFFER:
rc = mdp_q_buffer(sd, arg);
break;
case MDP_DQ_BUFFER:
rc = mdp_dq_buffer(sd, arg);
break;
case MDP_OPEN:
rc = mdp_open(sd, arg);
break;
case MDP_START:
rc = mdp_start(sd, arg);
break;
case MDP_STOP:
rc = mdp_stop(sd, arg);
break;
case MDP_SET_PROP:
rc = mdp_set_prop(sd, arg);
break;
case MDP_CLOSE:
rc = mdp_close(sd, arg);
break;
case MDP_MMAP:
rc = mdp_mmap(sd, arg);
break;
case MDP_MUNMAP:
rc = mdp_munmap(sd, arg);
break;
default:
WFD_MSG_ERR("IOCTL: %u not supported\n", cmd);
rc = -EINVAL;
break;
}
return rc;
}
| gpl-2.0 |
antmicro/linux-tk1 | drivers/net/wireless/ti/wl1251/rx.c | 2528 | 5927 | /*
* This file is part of wl1251
*
* Copyright (c) 1998-2007 Texas Instruments Incorporated
* Copyright (C) 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
*
*/
#include <linux/skbuff.h>
#include <linux/gfp.h>
#include <net/mac80211.h>
#include "wl1251.h"
#include "reg.h"
#include "io.h"
#include "rx.h"
#include "cmd.h"
#include "acx.h"
static void wl1251_rx_header(struct wl1251 *wl,
struct wl1251_rx_descriptor *desc)
{
u32 rx_packet_ring_addr;
rx_packet_ring_addr = wl->data_path->rx_packet_ring_addr;
if (wl->rx_current_buffer)
rx_packet_ring_addr += wl->data_path->rx_packet_ring_chunk_size;
wl1251_mem_read(wl, rx_packet_ring_addr, desc, sizeof(*desc));
}
static void wl1251_rx_status(struct wl1251 *wl,
struct wl1251_rx_descriptor *desc,
struct ieee80211_rx_status *status,
u8 beacon)
{
u64 mactime;
int ret;
memset(status, 0, sizeof(struct ieee80211_rx_status));
status->band = IEEE80211_BAND_2GHZ;
status->mactime = desc->timestamp;
/*
* The rx status timestamp is a 32 bits value while the TSF is a
* 64 bits one.
* For IBSS merging, TSF is mandatory, so we have to get it
* somehow, so we ask for ACX_TSF_INFO.
* That could be moved to the get_tsf() hook, but unfortunately,
* this one must be atomic, while our SPI routines can sleep.
*/
if ((wl->bss_type == BSS_TYPE_IBSS) && beacon) {
ret = wl1251_acx_tsf_info(wl, &mactime);
if (ret == 0)
status->mactime = mactime;
}
status->signal = desc->rssi;
/*
* FIXME: guessing that snr needs to be divided by two, otherwise
* the values don't make any sense
*/
wl->noise = desc->rssi - desc->snr / 2;
status->freq = ieee80211_channel_to_frequency(desc->channel,
status->band);
status->flag |= RX_FLAG_MACTIME_START;
if (desc->flags & RX_DESC_ENCRYPTION_MASK) {
status->flag |= RX_FLAG_IV_STRIPPED | RX_FLAG_MMIC_STRIPPED;
if (likely(!(desc->flags & RX_DESC_DECRYPT_FAIL)))
status->flag |= RX_FLAG_DECRYPTED;
if (unlikely(desc->flags & RX_DESC_MIC_FAIL))
status->flag |= RX_FLAG_MMIC_ERROR;
}
if (unlikely(!(desc->flags & RX_DESC_VALID_FCS)))
status->flag |= RX_FLAG_FAILED_FCS_CRC;
switch (desc->rate) {
/* skip 1 and 12 Mbps because they have same value 0x0a */
case RATE_2MBPS:
status->rate_idx = 1;
break;
case RATE_5_5MBPS:
status->rate_idx = 2;
break;
case RATE_11MBPS:
status->rate_idx = 3;
break;
case RATE_6MBPS:
status->rate_idx = 4;
break;
case RATE_9MBPS:
status->rate_idx = 5;
break;
case RATE_18MBPS:
status->rate_idx = 7;
break;
case RATE_24MBPS:
status->rate_idx = 8;
break;
case RATE_36MBPS:
status->rate_idx = 9;
break;
case RATE_48MBPS:
status->rate_idx = 10;
break;
case RATE_54MBPS:
status->rate_idx = 11;
break;
}
/* for 1 and 12 Mbps we have to check the modulation */
if (desc->rate == RATE_1MBPS) {
if (!(desc->mod_pre & OFDM_RATE_BIT))
/* CCK -> RATE_1MBPS */
status->rate_idx = 0;
else
/* OFDM -> RATE_12MBPS */
status->rate_idx = 6;
}
if (desc->mod_pre & SHORT_PREAMBLE_BIT)
status->flag |= RX_FLAG_SHORTPRE;
}
static void wl1251_rx_body(struct wl1251 *wl,
struct wl1251_rx_descriptor *desc)
{
struct sk_buff *skb;
struct ieee80211_rx_status status;
u8 *rx_buffer, beacon = 0;
u16 length, *fc;
u32 curr_id, last_id_inc, rx_packet_ring_addr;
length = WL1251_RX_ALIGN(desc->length - PLCP_HEADER_LENGTH);
curr_id = (desc->flags & RX_DESC_SEQNUM_MASK) >> RX_DESC_PACKETID_SHIFT;
last_id_inc = (wl->rx_last_id + 1) % (RX_MAX_PACKET_ID + 1);
if (last_id_inc != curr_id) {
wl1251_warning("curr ID:%d, last ID inc:%d",
curr_id, last_id_inc);
wl->rx_last_id = curr_id;
} else {
wl->rx_last_id = last_id_inc;
}
rx_packet_ring_addr = wl->data_path->rx_packet_ring_addr +
sizeof(struct wl1251_rx_descriptor) + 20;
if (wl->rx_current_buffer)
rx_packet_ring_addr += wl->data_path->rx_packet_ring_chunk_size;
skb = __dev_alloc_skb(length, GFP_KERNEL);
if (!skb) {
wl1251_error("Couldn't allocate RX frame");
return;
}
rx_buffer = skb_put(skb, length);
wl1251_mem_read(wl, rx_packet_ring_addr, rx_buffer, length);
/* The actual length doesn't include the target's alignment */
skb->len = desc->length - PLCP_HEADER_LENGTH;
fc = (u16 *)skb->data;
if ((*fc & IEEE80211_FCTL_STYPE) == IEEE80211_STYPE_BEACON)
beacon = 1;
wl1251_rx_status(wl, desc, &status, beacon);
wl1251_debug(DEBUG_RX, "rx skb 0x%p: %d B %s", skb, skb->len,
beacon ? "beacon" : "");
memcpy(IEEE80211_SKB_RXCB(skb), &status, sizeof(status));
ieee80211_rx_ni(wl->hw, skb);
}
static void wl1251_rx_ack(struct wl1251 *wl)
{
u32 data, addr;
if (wl->rx_current_buffer) {
addr = ACX_REG_INTERRUPT_TRIG_H;
data = INTR_TRIG_RX_PROC1;
} else {
addr = ACX_REG_INTERRUPT_TRIG;
data = INTR_TRIG_RX_PROC0;
}
wl1251_reg_write32(wl, addr, data);
/* Toggle buffer ring */
wl->rx_current_buffer = !wl->rx_current_buffer;
}
void wl1251_rx(struct wl1251 *wl)
{
struct wl1251_rx_descriptor *rx_desc;
if (wl->state != WL1251_STATE_ON)
return;
rx_desc = wl->rx_descriptor;
/* We first read the frame's header */
wl1251_rx_header(wl, rx_desc);
/* Now we can read the body */
wl1251_rx_body(wl, rx_desc);
/* Finally, we need to ACK the RX */
wl1251_rx_ack(wl);
}
| gpl-2.0 |
Clust3r/P8000-Kernel | arch/mips/pmcs-msp71xx/msp_irq_per.c | 2528 | 3083 | /*
* Copyright 2010 PMC-Sierra, Inc, derived from irq_cpu.c
*
* This file define the irq handler for MSP PER subsystem interrupts.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/bitops.h>
#include <asm/mipsregs.h>
#include <msp_cic_int.h>
#include <msp_regs.h>
/*
* Convenience Macro. Should be somewhere generic.
*/
#define get_current_vpe() \
((read_c0_tcbind() >> TCBIND_CURVPE_SHIFT) & TCBIND_CURVPE)
#ifdef CONFIG_SMP
/*
* The PER registers must be protected from concurrent access.
*/
static DEFINE_SPINLOCK(per_lock);
#endif
/* ensure writes to per are completed */
static inline void per_wmb(void)
{
const volatile void __iomem *per_mem = PER_INT_MSK_REG;
volatile u32 dummy_read;
wmb();
dummy_read = __raw_readl(per_mem);
dummy_read++;
}
static inline void unmask_per_irq(struct irq_data *d)
{
#ifdef CONFIG_SMP
unsigned long flags;
spin_lock_irqsave(&per_lock, flags);
*PER_INT_MSK_REG |= (1 << (d->irq - MSP_PER_INTBASE));
spin_unlock_irqrestore(&per_lock, flags);
#else
*PER_INT_MSK_REG |= (1 << (d->irq - MSP_PER_INTBASE));
#endif
per_wmb();
}
static inline void mask_per_irq(struct irq_data *d)
{
#ifdef CONFIG_SMP
unsigned long flags;
spin_lock_irqsave(&per_lock, flags);
*PER_INT_MSK_REG &= ~(1 << (d->irq - MSP_PER_INTBASE));
spin_unlock_irqrestore(&per_lock, flags);
#else
*PER_INT_MSK_REG &= ~(1 << (d->irq - MSP_PER_INTBASE));
#endif
per_wmb();
}
static inline void msp_per_irq_ack(struct irq_data *d)
{
mask_per_irq(d);
/*
* In the PER interrupt controller, only bits 11 and 10
* are write-to-clear, (SPI TX complete, SPI RX complete).
* It does nothing for any others.
*/
*PER_INT_STS_REG = (1 << (d->irq - MSP_PER_INTBASE));
}
#ifdef CONFIG_SMP
static int msp_per_irq_set_affinity(struct irq_data *d,
const struct cpumask *affinity, bool force)
{
/* WTF is this doing ????? */
unmask_per_irq(d);
return 0;
}
#endif
static struct irq_chip msp_per_irq_controller = {
.name = "MSP_PER",
.irq_enable = unmask_per_irq,
.irq_disable = mask_per_irq,
.irq_ack = msp_per_irq_ack,
#ifdef CONFIG_SMP
.irq_set_affinity = msp_per_irq_set_affinity,
#endif
};
void __init msp_per_irq_init(void)
{
int i;
/* Mask/clear interrupts. */
*PER_INT_MSK_REG = 0x00000000;
*PER_INT_STS_REG = 0xFFFFFFFF;
/* initialize all the IRQ descriptors */
for (i = MSP_PER_INTBASE; i < MSP_PER_INTBASE + 32; i++) {
irq_set_chip(i, &msp_per_irq_controller);
#ifdef CONFIG_MIPS_MT_SMTC
irq_hwmask[i] = C_IRQ4;
#endif
}
}
void msp_per_irq_dispatch(void)
{
u32 per_mask = *PER_INT_MSK_REG;
u32 per_status = *PER_INT_STS_REG;
u32 pending;
pending = per_status & per_mask;
if (pending) {
do_IRQ(ffs(pending) + MSP_PER_INTBASE - 1);
} else {
spurious_interrupt();
}
}
| gpl-2.0 |
reddv1/lucid-nexus-ics | drivers/mtd/devices/mtd_dataflash.c | 2784 | 25632 | /*
* Atmel AT45xxx DataFlash MTD driver for lightweight SPI framework
*
* Largely derived from at91_dataflash.c:
* Copyright (C) 2003-2005 SAN People (Pty) Ltd
*
* 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/init.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/math64.h>
#include <linux/spi/spi.h>
#include <linux/spi/flash.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
/*
* DataFlash is a kind of SPI flash. Most AT45 chips have two buffers in
* each chip, which may be used for double buffered I/O; but this driver
* doesn't (yet) use these for any kind of i/o overlap or prefetching.
*
* Sometimes DataFlash is packaged in MMC-format cards, although the
* MMC stack can't (yet?) distinguish between MMC and DataFlash
* protocols during enumeration.
*/
/* reads can bypass the buffers */
#define OP_READ_CONTINUOUS 0xE8
#define OP_READ_PAGE 0xD2
/* group B requests can run even while status reports "busy" */
#define OP_READ_STATUS 0xD7 /* group B */
/* move data between host and buffer */
#define OP_READ_BUFFER1 0xD4 /* group B */
#define OP_READ_BUFFER2 0xD6 /* group B */
#define OP_WRITE_BUFFER1 0x84 /* group B */
#define OP_WRITE_BUFFER2 0x87 /* group B */
/* erasing flash */
#define OP_ERASE_PAGE 0x81
#define OP_ERASE_BLOCK 0x50
/* move data between buffer and flash */
#define OP_TRANSFER_BUF1 0x53
#define OP_TRANSFER_BUF2 0x55
#define OP_MREAD_BUFFER1 0xD4
#define OP_MREAD_BUFFER2 0xD6
#define OP_MWERASE_BUFFER1 0x83
#define OP_MWERASE_BUFFER2 0x86
#define OP_MWRITE_BUFFER1 0x88 /* sector must be pre-erased */
#define OP_MWRITE_BUFFER2 0x89 /* sector must be pre-erased */
/* write to buffer, then write-erase to flash */
#define OP_PROGRAM_VIA_BUF1 0x82
#define OP_PROGRAM_VIA_BUF2 0x85
/* compare buffer to flash */
#define OP_COMPARE_BUF1 0x60
#define OP_COMPARE_BUF2 0x61
/* read flash to buffer, then write-erase to flash */
#define OP_REWRITE_VIA_BUF1 0x58
#define OP_REWRITE_VIA_BUF2 0x59
/* newer chips report JEDEC manufacturer and device IDs; chip
* serial number and OTP bits; and per-sector writeprotect.
*/
#define OP_READ_ID 0x9F
#define OP_READ_SECURITY 0x77
#define OP_WRITE_SECURITY_REVC 0x9A
#define OP_WRITE_SECURITY 0x9B /* revision D */
struct dataflash {
uint8_t command[4];
char name[24];
unsigned partitioned:1;
unsigned short page_offset; /* offset in flash address */
unsigned int page_size; /* of bytes per page */
struct mutex lock;
struct spi_device *spi;
struct mtd_info mtd;
};
/* ......................................................................... */
/*
* Return the status of the DataFlash device.
*/
static inline int dataflash_status(struct spi_device *spi)
{
/* NOTE: at45db321c over 25 MHz wants to write
* a dummy byte after the opcode...
*/
return spi_w8r8(spi, OP_READ_STATUS);
}
/*
* Poll the DataFlash device until it is READY.
* This usually takes 5-20 msec or so; more for sector erase.
*/
static int dataflash_waitready(struct spi_device *spi)
{
int status;
for (;;) {
status = dataflash_status(spi);
if (status < 0) {
DEBUG(MTD_DEBUG_LEVEL1, "%s: status %d?\n",
dev_name(&spi->dev), status);
status = 0;
}
if (status & (1 << 7)) /* RDY/nBSY */
return status;
msleep(3);
}
}
/* ......................................................................... */
/*
* Erase pages of flash.
*/
static int dataflash_erase(struct mtd_info *mtd, struct erase_info *instr)
{
struct dataflash *priv = mtd->priv;
struct spi_device *spi = priv->spi;
struct spi_transfer x = { .tx_dma = 0, };
struct spi_message msg;
unsigned blocksize = priv->page_size << 3;
uint8_t *command;
uint32_t rem;
DEBUG(MTD_DEBUG_LEVEL2, "%s: erase addr=0x%llx len 0x%llx\n",
dev_name(&spi->dev), (long long)instr->addr,
(long long)instr->len);
/* Sanity checks */
if (instr->addr + instr->len > mtd->size)
return -EINVAL;
div_u64_rem(instr->len, priv->page_size, &rem);
if (rem)
return -EINVAL;
div_u64_rem(instr->addr, priv->page_size, &rem);
if (rem)
return -EINVAL;
spi_message_init(&msg);
x.tx_buf = command = priv->command;
x.len = 4;
spi_message_add_tail(&x, &msg);
mutex_lock(&priv->lock);
while (instr->len > 0) {
unsigned int pageaddr;
int status;
int do_block;
/* Calculate flash page address; use block erase (for speed) if
* we're at a block boundary and need to erase the whole block.
*/
pageaddr = div_u64(instr->addr, priv->page_size);
do_block = (pageaddr & 0x7) == 0 && instr->len >= blocksize;
pageaddr = pageaddr << priv->page_offset;
command[0] = do_block ? OP_ERASE_BLOCK : OP_ERASE_PAGE;
command[1] = (uint8_t)(pageaddr >> 16);
command[2] = (uint8_t)(pageaddr >> 8);
command[3] = 0;
DEBUG(MTD_DEBUG_LEVEL3, "ERASE %s: (%x) %x %x %x [%i]\n",
do_block ? "block" : "page",
command[0], command[1], command[2], command[3],
pageaddr);
status = spi_sync(spi, &msg);
(void) dataflash_waitready(spi);
if (status < 0) {
printk(KERN_ERR "%s: erase %x, err %d\n",
dev_name(&spi->dev), pageaddr, status);
/* REVISIT: can retry instr->retries times; or
* giveup and instr->fail_addr = instr->addr;
*/
continue;
}
if (do_block) {
instr->addr += blocksize;
instr->len -= blocksize;
} else {
instr->addr += priv->page_size;
instr->len -= priv->page_size;
}
}
mutex_unlock(&priv->lock);
/* Inform MTD subsystem that erase is complete */
instr->state = MTD_ERASE_DONE;
mtd_erase_callback(instr);
return 0;
}
/*
* Read from the DataFlash device.
* from : Start offset in flash device
* len : Amount to read
* retlen : About of data actually read
* buf : Buffer containing the data
*/
static int dataflash_read(struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, u_char *buf)
{
struct dataflash *priv = mtd->priv;
struct spi_transfer x[2] = { { .tx_dma = 0, }, };
struct spi_message msg;
unsigned int addr;
uint8_t *command;
int status;
DEBUG(MTD_DEBUG_LEVEL2, "%s: read 0x%x..0x%x\n",
dev_name(&priv->spi->dev), (unsigned)from, (unsigned)(from + len));
*retlen = 0;
/* Sanity checks */
if (!len)
return 0;
if (from + len > mtd->size)
return -EINVAL;
/* Calculate flash page/byte address */
addr = (((unsigned)from / priv->page_size) << priv->page_offset)
+ ((unsigned)from % priv->page_size);
command = priv->command;
DEBUG(MTD_DEBUG_LEVEL3, "READ: (%x) %x %x %x\n",
command[0], command[1], command[2], command[3]);
spi_message_init(&msg);
x[0].tx_buf = command;
x[0].len = 8;
spi_message_add_tail(&x[0], &msg);
x[1].rx_buf = buf;
x[1].len = len;
spi_message_add_tail(&x[1], &msg);
mutex_lock(&priv->lock);
/* Continuous read, max clock = f(car) which may be less than
* the peak rate available. Some chips support commands with
* fewer "don't care" bytes. Both buffers stay unchanged.
*/
command[0] = OP_READ_CONTINUOUS;
command[1] = (uint8_t)(addr >> 16);
command[2] = (uint8_t)(addr >> 8);
command[3] = (uint8_t)(addr >> 0);
/* plus 4 "don't care" bytes */
status = spi_sync(priv->spi, &msg);
mutex_unlock(&priv->lock);
if (status >= 0) {
*retlen = msg.actual_length - 8;
status = 0;
} else
DEBUG(MTD_DEBUG_LEVEL1, "%s: read %x..%x --> %d\n",
dev_name(&priv->spi->dev),
(unsigned)from, (unsigned)(from + len),
status);
return status;
}
/*
* Write to the DataFlash device.
* to : Start offset in flash device
* len : Amount to write
* retlen : Amount of data actually written
* buf : Buffer containing the data
*/
static int dataflash_write(struct mtd_info *mtd, loff_t to, size_t len,
size_t * retlen, const u_char * buf)
{
struct dataflash *priv = mtd->priv;
struct spi_device *spi = priv->spi;
struct spi_transfer x[2] = { { .tx_dma = 0, }, };
struct spi_message msg;
unsigned int pageaddr, addr, offset, writelen;
size_t remaining = len;
u_char *writebuf = (u_char *) buf;
int status = -EINVAL;
uint8_t *command;
DEBUG(MTD_DEBUG_LEVEL2, "%s: write 0x%x..0x%x\n",
dev_name(&spi->dev), (unsigned)to, (unsigned)(to + len));
*retlen = 0;
/* Sanity checks */
if (!len)
return 0;
if ((to + len) > mtd->size)
return -EINVAL;
spi_message_init(&msg);
x[0].tx_buf = command = priv->command;
x[0].len = 4;
spi_message_add_tail(&x[0], &msg);
pageaddr = ((unsigned)to / priv->page_size);
offset = ((unsigned)to % priv->page_size);
if (offset + len > priv->page_size)
writelen = priv->page_size - offset;
else
writelen = len;
mutex_lock(&priv->lock);
while (remaining > 0) {
DEBUG(MTD_DEBUG_LEVEL3, "write @ %i:%i len=%i\n",
pageaddr, offset, writelen);
/* REVISIT:
* (a) each page in a sector must be rewritten at least
* once every 10K sibling erase/program operations.
* (b) for pages that are already erased, we could
* use WRITE+MWRITE not PROGRAM for ~30% speedup.
* (c) WRITE to buffer could be done while waiting for
* a previous MWRITE/MWERASE to complete ...
* (d) error handling here seems to be mostly missing.
*
* Two persistent bits per page, plus a per-sector counter,
* could support (a) and (b) ... we might consider using
* the second half of sector zero, which is just one block,
* to track that state. (On AT91, that sector should also
* support boot-from-DataFlash.)
*/
addr = pageaddr << priv->page_offset;
/* (1) Maybe transfer partial page to Buffer1 */
if (writelen != priv->page_size) {
command[0] = OP_TRANSFER_BUF1;
command[1] = (addr & 0x00FF0000) >> 16;
command[2] = (addr & 0x0000FF00) >> 8;
command[3] = 0;
DEBUG(MTD_DEBUG_LEVEL3, "TRANSFER: (%x) %x %x %x\n",
command[0], command[1], command[2], command[3]);
status = spi_sync(spi, &msg);
if (status < 0)
DEBUG(MTD_DEBUG_LEVEL1, "%s: xfer %u -> %d \n",
dev_name(&spi->dev), addr, status);
(void) dataflash_waitready(priv->spi);
}
/* (2) Program full page via Buffer1 */
addr += offset;
command[0] = OP_PROGRAM_VIA_BUF1;
command[1] = (addr & 0x00FF0000) >> 16;
command[2] = (addr & 0x0000FF00) >> 8;
command[3] = (addr & 0x000000FF);
DEBUG(MTD_DEBUG_LEVEL3, "PROGRAM: (%x) %x %x %x\n",
command[0], command[1], command[2], command[3]);
x[1].tx_buf = writebuf;
x[1].len = writelen;
spi_message_add_tail(x + 1, &msg);
status = spi_sync(spi, &msg);
spi_transfer_del(x + 1);
if (status < 0)
DEBUG(MTD_DEBUG_LEVEL1, "%s: pgm %u/%u -> %d \n",
dev_name(&spi->dev), addr, writelen, status);
(void) dataflash_waitready(priv->spi);
#ifdef CONFIG_MTD_DATAFLASH_WRITE_VERIFY
/* (3) Compare to Buffer1 */
addr = pageaddr << priv->page_offset;
command[0] = OP_COMPARE_BUF1;
command[1] = (addr & 0x00FF0000) >> 16;
command[2] = (addr & 0x0000FF00) >> 8;
command[3] = 0;
DEBUG(MTD_DEBUG_LEVEL3, "COMPARE: (%x) %x %x %x\n",
command[0], command[1], command[2], command[3]);
status = spi_sync(spi, &msg);
if (status < 0)
DEBUG(MTD_DEBUG_LEVEL1, "%s: compare %u -> %d \n",
dev_name(&spi->dev), addr, status);
status = dataflash_waitready(priv->spi);
/* Check result of the compare operation */
if (status & (1 << 6)) {
printk(KERN_ERR "%s: compare page %u, err %d\n",
dev_name(&spi->dev), pageaddr, status);
remaining = 0;
status = -EIO;
break;
} else
status = 0;
#endif /* CONFIG_MTD_DATAFLASH_WRITE_VERIFY */
remaining = remaining - writelen;
pageaddr++;
offset = 0;
writebuf += writelen;
*retlen += writelen;
if (remaining > priv->page_size)
writelen = priv->page_size;
else
writelen = remaining;
}
mutex_unlock(&priv->lock);
return status;
}
/* ......................................................................... */
#ifdef CONFIG_MTD_DATAFLASH_OTP
static int dataflash_get_otp_info(struct mtd_info *mtd,
struct otp_info *info, size_t len)
{
/* Report both blocks as identical: bytes 0..64, locked.
* Unless the user block changed from all-ones, we can't
* tell whether it's still writable; so we assume it isn't.
*/
info->start = 0;
info->length = 64;
info->locked = 1;
return sizeof(*info);
}
static ssize_t otp_read(struct spi_device *spi, unsigned base,
uint8_t *buf, loff_t off, size_t len)
{
struct spi_message m;
size_t l;
uint8_t *scratch;
struct spi_transfer t;
int status;
if (off > 64)
return -EINVAL;
if ((off + len) > 64)
len = 64 - off;
if (len == 0)
return len;
spi_message_init(&m);
l = 4 + base + off + len;
scratch = kzalloc(l, GFP_KERNEL);
if (!scratch)
return -ENOMEM;
/* OUT: OP_READ_SECURITY, 3 don't-care bytes, zeroes
* IN: ignore 4 bytes, data bytes 0..N (max 127)
*/
scratch[0] = OP_READ_SECURITY;
memset(&t, 0, sizeof t);
t.tx_buf = scratch;
t.rx_buf = scratch;
t.len = l;
spi_message_add_tail(&t, &m);
dataflash_waitready(spi);
status = spi_sync(spi, &m);
if (status >= 0) {
memcpy(buf, scratch + 4 + base + off, len);
status = len;
}
kfree(scratch);
return status;
}
static int dataflash_read_fact_otp(struct mtd_info *mtd,
loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct dataflash *priv = mtd->priv;
int status;
/* 64 bytes, from 0..63 ... start at 64 on-chip */
mutex_lock(&priv->lock);
status = otp_read(priv->spi, 64, buf, from, len);
mutex_unlock(&priv->lock);
if (status < 0)
return status;
*retlen = status;
return 0;
}
static int dataflash_read_user_otp(struct mtd_info *mtd,
loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct dataflash *priv = mtd->priv;
int status;
/* 64 bytes, from 0..63 ... start at 0 on-chip */
mutex_lock(&priv->lock);
status = otp_read(priv->spi, 0, buf, from, len);
mutex_unlock(&priv->lock);
if (status < 0)
return status;
*retlen = status;
return 0;
}
static int dataflash_write_user_otp(struct mtd_info *mtd,
loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct spi_message m;
const size_t l = 4 + 64;
uint8_t *scratch;
struct spi_transfer t;
struct dataflash *priv = mtd->priv;
int status;
if (len > 64)
return -EINVAL;
/* Strictly speaking, we *could* truncate the write ... but
* let's not do that for the only write that's ever possible.
*/
if ((from + len) > 64)
return -EINVAL;
/* OUT: OP_WRITE_SECURITY, 3 zeroes, 64 data-or-zero bytes
* IN: ignore all
*/
scratch = kzalloc(l, GFP_KERNEL);
if (!scratch)
return -ENOMEM;
scratch[0] = OP_WRITE_SECURITY;
memcpy(scratch + 4 + from, buf, len);
spi_message_init(&m);
memset(&t, 0, sizeof t);
t.tx_buf = scratch;
t.len = l;
spi_message_add_tail(&t, &m);
/* Write the OTP bits, if they've not yet been written.
* This modifies SRAM buffer1.
*/
mutex_lock(&priv->lock);
dataflash_waitready(priv->spi);
status = spi_sync(priv->spi, &m);
mutex_unlock(&priv->lock);
kfree(scratch);
if (status >= 0) {
status = 0;
*retlen = len;
}
return status;
}
static char *otp_setup(struct mtd_info *device, char revision)
{
device->get_fact_prot_info = dataflash_get_otp_info;
device->read_fact_prot_reg = dataflash_read_fact_otp;
device->get_user_prot_info = dataflash_get_otp_info;
device->read_user_prot_reg = dataflash_read_user_otp;
/* rev c parts (at45db321c and at45db1281 only!) use a
* different write procedure; not (yet?) implemented.
*/
if (revision > 'c')
device->write_user_prot_reg = dataflash_write_user_otp;
return ", OTP";
}
#else
static char *otp_setup(struct mtd_info *device, char revision)
{
return " (OTP)";
}
#endif
/* ......................................................................... */
/*
* Register DataFlash device with MTD subsystem.
*/
static int __devinit
add_dataflash_otp(struct spi_device *spi, char *name,
int nr_pages, int pagesize, int pageoffset, char revision)
{
struct dataflash *priv;
struct mtd_info *device;
struct flash_platform_data *pdata = spi->dev.platform_data;
char *otp_tag = "";
int err = 0;
struct mtd_partition *parts;
int nr_parts = 0;
priv = kzalloc(sizeof *priv, GFP_KERNEL);
if (!priv)
return -ENOMEM;
mutex_init(&priv->lock);
priv->spi = spi;
priv->page_size = pagesize;
priv->page_offset = pageoffset;
/* name must be usable with cmdlinepart */
sprintf(priv->name, "spi%d.%d-%s",
spi->master->bus_num, spi->chip_select,
name);
device = &priv->mtd;
device->name = (pdata && pdata->name) ? pdata->name : priv->name;
device->size = nr_pages * pagesize;
device->erasesize = pagesize;
device->writesize = pagesize;
device->owner = THIS_MODULE;
device->type = MTD_DATAFLASH;
device->flags = MTD_WRITEABLE;
device->erase = dataflash_erase;
device->read = dataflash_read;
device->write = dataflash_write;
device->priv = priv;
device->dev.parent = &spi->dev;
if (revision >= 'c')
otp_tag = otp_setup(device, revision);
dev_info(&spi->dev, "%s (%lld KBytes) pagesize %d bytes%s\n",
name, (long long)((device->size + 1023) >> 10),
pagesize, otp_tag);
dev_set_drvdata(&spi->dev, priv);
if (mtd_has_cmdlinepart()) {
static const char *part_probes[] = { "cmdlinepart", NULL, };
nr_parts = parse_mtd_partitions(device, part_probes, &parts,
0);
}
if (nr_parts <= 0 && pdata && pdata->parts) {
parts = pdata->parts;
nr_parts = pdata->nr_parts;
}
if (nr_parts > 0) {
priv->partitioned = 1;
err = mtd_device_register(device, parts, nr_parts);
goto out;
}
if (mtd_device_register(device, NULL, 0) == 1)
err = -ENODEV;
out:
if (!err)
return 0;
dev_set_drvdata(&spi->dev, NULL);
kfree(priv);
return err;
}
static inline int __devinit
add_dataflash(struct spi_device *spi, char *name,
int nr_pages, int pagesize, int pageoffset)
{
return add_dataflash_otp(spi, name, nr_pages, pagesize,
pageoffset, 0);
}
struct flash_info {
char *name;
/* JEDEC id has a high byte of zero plus three data bytes:
* the manufacturer id, then a two byte device id.
*/
uint32_t jedec_id;
/* The size listed here is what works with OP_ERASE_PAGE. */
unsigned nr_pages;
uint16_t pagesize;
uint16_t pageoffset;
uint16_t flags;
#define SUP_POW2PS 0x0002 /* supports 2^N byte pages */
#define IS_POW2PS 0x0001 /* uses 2^N byte pages */
};
static struct flash_info __devinitdata dataflash_data [] = {
/*
* NOTE: chips with SUP_POW2PS (rev D and up) need two entries,
* one with IS_POW2PS and the other without. The entry with the
* non-2^N byte page size can't name exact chip revisions without
* losing backwards compatibility for cmdlinepart.
*
* These newer chips also support 128-byte security registers (with
* 64 bytes one-time-programmable) and software write-protection.
*/
{ "AT45DB011B", 0x1f2200, 512, 264, 9, SUP_POW2PS},
{ "at45db011d", 0x1f2200, 512, 256, 8, SUP_POW2PS | IS_POW2PS},
{ "AT45DB021B", 0x1f2300, 1024, 264, 9, SUP_POW2PS},
{ "at45db021d", 0x1f2300, 1024, 256, 8, SUP_POW2PS | IS_POW2PS},
{ "AT45DB041x", 0x1f2400, 2048, 264, 9, SUP_POW2PS},
{ "at45db041d", 0x1f2400, 2048, 256, 8, SUP_POW2PS | IS_POW2PS},
{ "AT45DB081B", 0x1f2500, 4096, 264, 9, SUP_POW2PS},
{ "at45db081d", 0x1f2500, 4096, 256, 8, SUP_POW2PS | IS_POW2PS},
{ "AT45DB161x", 0x1f2600, 4096, 528, 10, SUP_POW2PS},
{ "at45db161d", 0x1f2600, 4096, 512, 9, SUP_POW2PS | IS_POW2PS},
{ "AT45DB321x", 0x1f2700, 8192, 528, 10, 0}, /* rev C */
{ "AT45DB321x", 0x1f2701, 8192, 528, 10, SUP_POW2PS},
{ "at45db321d", 0x1f2701, 8192, 512, 9, SUP_POW2PS | IS_POW2PS},
{ "AT45DB642x", 0x1f2800, 8192, 1056, 11, SUP_POW2PS},
{ "at45db642d", 0x1f2800, 8192, 1024, 10, SUP_POW2PS | IS_POW2PS},
};
static struct flash_info *__devinit jedec_probe(struct spi_device *spi)
{
int tmp;
uint8_t code = OP_READ_ID;
uint8_t id[3];
uint32_t jedec;
struct flash_info *info;
int status;
/* JEDEC also defines an optional "extended device information"
* string for after vendor-specific data, after the three bytes
* we use here. Supporting some chips might require using it.
*
* If the vendor ID isn't Atmel's (0x1f), assume this call failed.
* That's not an error; only rev C and newer chips handle it, and
* only Atmel sells these chips.
*/
tmp = spi_write_then_read(spi, &code, 1, id, 3);
if (tmp < 0) {
DEBUG(MTD_DEBUG_LEVEL0, "%s: error %d reading JEDEC ID\n",
dev_name(&spi->dev), tmp);
return ERR_PTR(tmp);
}
if (id[0] != 0x1f)
return NULL;
jedec = id[0];
jedec = jedec << 8;
jedec |= id[1];
jedec = jedec << 8;
jedec |= id[2];
for (tmp = 0, info = dataflash_data;
tmp < ARRAY_SIZE(dataflash_data);
tmp++, info++) {
if (info->jedec_id == jedec) {
DEBUG(MTD_DEBUG_LEVEL1, "%s: OTP, sector protect%s\n",
dev_name(&spi->dev),
(info->flags & SUP_POW2PS)
? ", binary pagesize" : ""
);
if (info->flags & SUP_POW2PS) {
status = dataflash_status(spi);
if (status < 0) {
DEBUG(MTD_DEBUG_LEVEL1,
"%s: status error %d\n",
dev_name(&spi->dev), status);
return ERR_PTR(status);
}
if (status & 0x1) {
if (info->flags & IS_POW2PS)
return info;
} else {
if (!(info->flags & IS_POW2PS))
return info;
}
} else
return info;
}
}
/*
* Treat other chips as errors ... we won't know the right page
* size (it might be binary) even when we can tell which density
* class is involved (legacy chip id scheme).
*/
dev_warn(&spi->dev, "JEDEC id %06x not handled\n", jedec);
return ERR_PTR(-ENODEV);
}
/*
* Detect and initialize DataFlash device, using JEDEC IDs on newer chips
* or else the ID code embedded in the status bits:
*
* Device Density ID code #Pages PageSize Offset
* AT45DB011B 1Mbit (128K) xx0011xx (0x0c) 512 264 9
* AT45DB021B 2Mbit (256K) xx0101xx (0x14) 1024 264 9
* AT45DB041B 4Mbit (512K) xx0111xx (0x1c) 2048 264 9
* AT45DB081B 8Mbit (1M) xx1001xx (0x24) 4096 264 9
* AT45DB0161B 16Mbit (2M) xx1011xx (0x2c) 4096 528 10
* AT45DB0321B 32Mbit (4M) xx1101xx (0x34) 8192 528 10
* AT45DB0642 64Mbit (8M) xx111xxx (0x3c) 8192 1056 11
* AT45DB1282 128Mbit (16M) xx0100xx (0x10) 16384 1056 11
*/
static int __devinit dataflash_probe(struct spi_device *spi)
{
int status;
struct flash_info *info;
/*
* Try to detect dataflash by JEDEC ID.
* If it succeeds we know we have either a C or D part.
* D will support power of 2 pagesize option.
* Both support the security register, though with different
* write procedures.
*/
info = jedec_probe(spi);
if (IS_ERR(info))
return PTR_ERR(info);
if (info != NULL)
return add_dataflash_otp(spi, info->name, info->nr_pages,
info->pagesize, info->pageoffset,
(info->flags & SUP_POW2PS) ? 'd' : 'c');
/*
* Older chips support only legacy commands, identifing
* capacity using bits in the status byte.
*/
status = dataflash_status(spi);
if (status <= 0 || status == 0xff) {
DEBUG(MTD_DEBUG_LEVEL1, "%s: status error %d\n",
dev_name(&spi->dev), status);
if (status == 0 || status == 0xff)
status = -ENODEV;
return status;
}
/* if there's a device there, assume it's dataflash.
* board setup should have set spi->max_speed_max to
* match f(car) for continuous reads, mode 0 or 3.
*/
switch (status & 0x3c) {
case 0x0c: /* 0 0 1 1 x x */
status = add_dataflash(spi, "AT45DB011B", 512, 264, 9);
break;
case 0x14: /* 0 1 0 1 x x */
status = add_dataflash(spi, "AT45DB021B", 1024, 264, 9);
break;
case 0x1c: /* 0 1 1 1 x x */
status = add_dataflash(spi, "AT45DB041x", 2048, 264, 9);
break;
case 0x24: /* 1 0 0 1 x x */
status = add_dataflash(spi, "AT45DB081B", 4096, 264, 9);
break;
case 0x2c: /* 1 0 1 1 x x */
status = add_dataflash(spi, "AT45DB161x", 4096, 528, 10);
break;
case 0x34: /* 1 1 0 1 x x */
status = add_dataflash(spi, "AT45DB321x", 8192, 528, 10);
break;
case 0x38: /* 1 1 1 x x x */
case 0x3c:
status = add_dataflash(spi, "AT45DB642x", 8192, 1056, 11);
break;
/* obsolete AT45DB1282 not (yet?) supported */
default:
DEBUG(MTD_DEBUG_LEVEL1, "%s: unsupported device (%x)\n",
dev_name(&spi->dev), status & 0x3c);
status = -ENODEV;
}
if (status < 0)
DEBUG(MTD_DEBUG_LEVEL1, "%s: add_dataflash --> %d\n",
dev_name(&spi->dev), status);
return status;
}
static int __devexit dataflash_remove(struct spi_device *spi)
{
struct dataflash *flash = dev_get_drvdata(&spi->dev);
int status;
DEBUG(MTD_DEBUG_LEVEL1, "%s: remove\n", dev_name(&spi->dev));
status = mtd_device_unregister(&flash->mtd);
if (status == 0) {
dev_set_drvdata(&spi->dev, NULL);
kfree(flash);
}
return status;
}
static struct spi_driver dataflash_driver = {
.driver = {
.name = "mtd_dataflash",
.bus = &spi_bus_type,
.owner = THIS_MODULE,
},
.probe = dataflash_probe,
.remove = __devexit_p(dataflash_remove),
/* FIXME: investigate suspend and resume... */
};
static int __init dataflash_init(void)
{
return spi_register_driver(&dataflash_driver);
}
module_init(dataflash_init);
static void __exit dataflash_exit(void)
{
spi_unregister_driver(&dataflash_driver);
}
module_exit(dataflash_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Andrew Victor, David Brownell");
MODULE_DESCRIPTION("MTD DataFlash driver");
MODULE_ALIAS("spi:mtd_dataflash");
| gpl-2.0 |
faux123/pantech_vega_racer_2_kernel | arch/x86/xen/multicalls.c | 2784 | 6322 | /*
* Xen hypercall batching.
*
* Xen allows multiple hypercalls to be issued at once, using the
* multicall interface. This allows the cost of trapping into the
* hypervisor to be amortized over several calls.
*
* This file implements a simple interface for multicalls. There's a
* per-cpu buffer of outstanding multicalls. When you want to queue a
* multicall for issuing, you can allocate a multicall slot for the
* call and its arguments, along with storage for space which is
* pointed to by the arguments (for passing pointers to structures,
* etc). When the multicall is actually issued, all the space for the
* commands and allocated memory is freed for reuse.
*
* Multicalls are flushed whenever any of the buffers get full, or
* when explicitly requested. There's no way to get per-multicall
* return results back. It will BUG if any of the multicalls fail.
*
* Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007
*/
#include <linux/percpu.h>
#include <linux/hardirq.h>
#include <linux/debugfs.h>
#include <asm/xen/hypercall.h>
#include "multicalls.h"
#include "debugfs.h"
#define MC_BATCH 32
#define MC_DEBUG 1
#define MC_ARGS (MC_BATCH * 16)
struct mc_buffer {
struct multicall_entry entries[MC_BATCH];
#if MC_DEBUG
struct multicall_entry debug[MC_BATCH];
void *caller[MC_BATCH];
#endif
unsigned char args[MC_ARGS];
struct callback {
void (*fn)(void *);
void *data;
} callbacks[MC_BATCH];
unsigned mcidx, argidx, cbidx;
};
static DEFINE_PER_CPU(struct mc_buffer, mc_buffer);
DEFINE_PER_CPU(unsigned long, xen_mc_irq_flags);
/* flush reasons 0- slots, 1- args, 2- callbacks */
enum flush_reasons
{
FL_SLOTS,
FL_ARGS,
FL_CALLBACKS,
FL_N_REASONS
};
#ifdef CONFIG_XEN_DEBUG_FS
#define NHYPERCALLS 40 /* not really */
static struct {
unsigned histo[MC_BATCH+1];
unsigned issued;
unsigned arg_total;
unsigned hypercalls;
unsigned histo_hypercalls[NHYPERCALLS];
unsigned flush[FL_N_REASONS];
} mc_stats;
static u8 zero_stats;
static inline void check_zero(void)
{
if (unlikely(zero_stats)) {
memset(&mc_stats, 0, sizeof(mc_stats));
zero_stats = 0;
}
}
static void mc_add_stats(const struct mc_buffer *mc)
{
int i;
check_zero();
mc_stats.issued++;
mc_stats.hypercalls += mc->mcidx;
mc_stats.arg_total += mc->argidx;
mc_stats.histo[mc->mcidx]++;
for(i = 0; i < mc->mcidx; i++) {
unsigned op = mc->entries[i].op;
if (op < NHYPERCALLS)
mc_stats.histo_hypercalls[op]++;
}
}
static void mc_stats_flush(enum flush_reasons idx)
{
check_zero();
mc_stats.flush[idx]++;
}
#else /* !CONFIG_XEN_DEBUG_FS */
static inline void mc_add_stats(const struct mc_buffer *mc)
{
}
static inline void mc_stats_flush(enum flush_reasons idx)
{
}
#endif /* CONFIG_XEN_DEBUG_FS */
void xen_mc_flush(void)
{
struct mc_buffer *b = &__get_cpu_var(mc_buffer);
int ret = 0;
unsigned long flags;
int i;
BUG_ON(preemptible());
/* Disable interrupts in case someone comes in and queues
something in the middle */
local_irq_save(flags);
mc_add_stats(b);
if (b->mcidx) {
#if MC_DEBUG
memcpy(b->debug, b->entries,
b->mcidx * sizeof(struct multicall_entry));
#endif
if (HYPERVISOR_multicall(b->entries, b->mcidx) != 0)
BUG();
for (i = 0; i < b->mcidx; i++)
if (b->entries[i].result < 0)
ret++;
#if MC_DEBUG
if (ret) {
printk(KERN_ERR "%d multicall(s) failed: cpu %d\n",
ret, smp_processor_id());
dump_stack();
for (i = 0; i < b->mcidx; i++) {
printk(KERN_DEBUG " call %2d/%d: op=%lu arg=[%lx] result=%ld\t%pF\n",
i+1, b->mcidx,
b->debug[i].op,
b->debug[i].args[0],
b->entries[i].result,
b->caller[i]);
}
}
#endif
b->mcidx = 0;
b->argidx = 0;
} else
BUG_ON(b->argidx != 0);
for (i = 0; i < b->cbidx; i++) {
struct callback *cb = &b->callbacks[i];
(*cb->fn)(cb->data);
}
b->cbidx = 0;
local_irq_restore(flags);
WARN_ON(ret);
}
struct multicall_space __xen_mc_entry(size_t args)
{
struct mc_buffer *b = &__get_cpu_var(mc_buffer);
struct multicall_space ret;
unsigned argidx = roundup(b->argidx, sizeof(u64));
BUG_ON(preemptible());
BUG_ON(b->argidx >= MC_ARGS);
if (b->mcidx == MC_BATCH ||
(argidx + args) >= MC_ARGS) {
mc_stats_flush(b->mcidx == MC_BATCH ? FL_SLOTS : FL_ARGS);
xen_mc_flush();
argidx = roundup(b->argidx, sizeof(u64));
}
ret.mc = &b->entries[b->mcidx];
#ifdef MC_DEBUG
b->caller[b->mcidx] = __builtin_return_address(0);
#endif
b->mcidx++;
ret.args = &b->args[argidx];
b->argidx = argidx + args;
BUG_ON(b->argidx >= MC_ARGS);
return ret;
}
struct multicall_space xen_mc_extend_args(unsigned long op, size_t size)
{
struct mc_buffer *b = &__get_cpu_var(mc_buffer);
struct multicall_space ret = { NULL, NULL };
BUG_ON(preemptible());
BUG_ON(b->argidx >= MC_ARGS);
if (b->mcidx == 0)
return ret;
if (b->entries[b->mcidx - 1].op != op)
return ret;
if ((b->argidx + size) >= MC_ARGS)
return ret;
ret.mc = &b->entries[b->mcidx - 1];
ret.args = &b->args[b->argidx];
b->argidx += size;
BUG_ON(b->argidx >= MC_ARGS);
return ret;
}
void xen_mc_callback(void (*fn)(void *), void *data)
{
struct mc_buffer *b = &__get_cpu_var(mc_buffer);
struct callback *cb;
if (b->cbidx == MC_BATCH) {
mc_stats_flush(FL_CALLBACKS);
xen_mc_flush();
}
cb = &b->callbacks[b->cbidx++];
cb->fn = fn;
cb->data = data;
}
#ifdef CONFIG_XEN_DEBUG_FS
static struct dentry *d_mc_debug;
static int __init xen_mc_debugfs(void)
{
struct dentry *d_xen = xen_init_debugfs();
if (d_xen == NULL)
return -ENOMEM;
d_mc_debug = debugfs_create_dir("multicalls", d_xen);
debugfs_create_u8("zero_stats", 0644, d_mc_debug, &zero_stats);
debugfs_create_u32("batches", 0444, d_mc_debug, &mc_stats.issued);
debugfs_create_u32("hypercalls", 0444, d_mc_debug, &mc_stats.hypercalls);
debugfs_create_u32("arg_total", 0444, d_mc_debug, &mc_stats.arg_total);
xen_debugfs_create_u32_array("batch_histo", 0444, d_mc_debug,
mc_stats.histo, MC_BATCH);
xen_debugfs_create_u32_array("hypercall_histo", 0444, d_mc_debug,
mc_stats.histo_hypercalls, NHYPERCALLS);
xen_debugfs_create_u32_array("flush_reasons", 0444, d_mc_debug,
mc_stats.flush, FL_N_REASONS);
return 0;
}
fs_initcall(xen_mc_debugfs);
#endif /* CONFIG_XEN_DEBUG_FS */
| gpl-2.0 |
kumajaya/android_kernel_samsung_lt01 | drivers/staging/go7007/go7007-driver.c | 3296 | 17074 | /*
* Copyright (C) 2005-2006 Micronas USA Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/unistd.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/firmware.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <asm/system.h>
#include <linux/videodev2.h>
#include <media/tuner.h>
#include <media/v4l2-common.h>
#include "go7007-priv.h"
#include "wis-i2c.h"
/*
* Wait for an interrupt to be delivered from the GO7007SB and return
* the associated value and data.
*
* Must be called with the hw_lock held.
*/
int go7007_read_interrupt(struct go7007 *go, u16 *value, u16 *data)
{
go->interrupt_available = 0;
go->hpi_ops->read_interrupt(go);
if (wait_event_timeout(go->interrupt_waitq,
go->interrupt_available, 5*HZ) < 0) {
v4l2_err(&go->v4l2_dev, "timeout waiting for read interrupt\n");
return -1;
}
if (!go->interrupt_available)
return -1;
go->interrupt_available = 0;
*value = go->interrupt_value & 0xfffe;
*data = go->interrupt_data;
return 0;
}
EXPORT_SYMBOL(go7007_read_interrupt);
/*
* Read a register/address on the GO7007SB.
*
* Must be called with the hw_lock held.
*/
int go7007_read_addr(struct go7007 *go, u16 addr, u16 *data)
{
int count = 100;
u16 value;
if (go7007_write_interrupt(go, 0x0010, addr) < 0)
return -EIO;
while (count-- > 0) {
if (go7007_read_interrupt(go, &value, data) == 0 &&
value == 0xa000)
return 0;
}
return -EIO;
}
EXPORT_SYMBOL(go7007_read_addr);
/*
* Send the boot firmware to the encoder, which just wakes it up and lets
* us talk to the GPIO pins and on-board I2C adapter.
*
* Must be called with the hw_lock held.
*/
static int go7007_load_encoder(struct go7007 *go)
{
const struct firmware *fw_entry;
char fw_name[] = "go7007fw.bin";
void *bounce;
int fw_len, rv = 0;
u16 intr_val, intr_data;
if (request_firmware(&fw_entry, fw_name, go->dev)) {
v4l2_err(go, "unable to load firmware from file "
"\"%s\"\n", fw_name);
return -1;
}
if (fw_entry->size < 16 || memcmp(fw_entry->data, "WISGO7007FW", 11)) {
v4l2_err(go, "file \"%s\" does not appear to be "
"go7007 firmware\n", fw_name);
release_firmware(fw_entry);
return -1;
}
fw_len = fw_entry->size - 16;
bounce = kmalloc(fw_len, GFP_KERNEL);
if (bounce == NULL) {
v4l2_err(go, "unable to allocate %d bytes for "
"firmware transfer\n", fw_len);
release_firmware(fw_entry);
return -1;
}
memcpy(bounce, fw_entry->data + 16, fw_len);
release_firmware(fw_entry);
if (go7007_interface_reset(go) < 0 ||
go7007_send_firmware(go, bounce, fw_len) < 0 ||
go7007_read_interrupt(go, &intr_val, &intr_data) < 0 ||
(intr_val & ~0x1) != 0x5a5a) {
v4l2_err(go, "error transferring firmware\n");
rv = -1;
}
kfree(bounce);
return rv;
}
MODULE_FIRMWARE("go7007fw.bin");
/*
* Boot the encoder and register the I2C adapter if requested. Do the
* minimum initialization necessary, since the board-specific code may
* still need to probe the board ID.
*
* Must NOT be called with the hw_lock held.
*/
int go7007_boot_encoder(struct go7007 *go, int init_i2c)
{
int ret;
mutex_lock(&go->hw_lock);
ret = go7007_load_encoder(go);
mutex_unlock(&go->hw_lock);
if (ret < 0)
return -1;
if (!init_i2c)
return 0;
if (go7007_i2c_init(go) < 0)
return -1;
go->i2c_adapter_online = 1;
return 0;
}
EXPORT_SYMBOL(go7007_boot_encoder);
/*
* Configure any hardware-related registers in the GO7007, such as GPIO
* pins and bus parameters, which are board-specific. This assumes
* the boot firmware has already been downloaded.
*
* Must be called with the hw_lock held.
*/
static int go7007_init_encoder(struct go7007 *go)
{
if (go->board_info->audio_flags & GO7007_AUDIO_I2S_MASTER) {
go7007_write_addr(go, 0x1000, 0x0811);
go7007_write_addr(go, 0x1000, 0x0c11);
}
if (go->board_id == GO7007_BOARDID_MATRIX_REV) {
/* Set GPIO pin 0 to be an output (audio clock control) */
go7007_write_addr(go, 0x3c82, 0x0001);
go7007_write_addr(go, 0x3c80, 0x00fe);
}
return 0;
}
/*
* Send the boot firmware to the GO7007 and configure the registers. This
* is the only way to stop the encoder once it has started streaming video.
*
* Must be called with the hw_lock held.
*/
int go7007_reset_encoder(struct go7007 *go)
{
if (go7007_load_encoder(go) < 0)
return -1;
return go7007_init_encoder(go);
}
/*
* Attempt to instantiate an I2C client by ID, probably loading a module.
*/
static int init_i2c_module(struct i2c_adapter *adapter, const char *type,
int addr)
{
struct go7007 *go = i2c_get_adapdata(adapter);
struct v4l2_device *v4l2_dev = &go->v4l2_dev;
if (v4l2_i2c_new_subdev(v4l2_dev, adapter, type, addr, NULL))
return 0;
printk(KERN_INFO "go7007: probing for module i2c:%s failed\n", type);
return -1;
}
/*
* Finalize the GO7007 hardware setup, register the on-board I2C adapter
* (if used on this board), load the I2C client driver for the sensor
* (SAA7115 or whatever) and other devices, and register the ALSA and V4L2
* interfaces.
*
* Must NOT be called with the hw_lock held.
*/
int go7007_register_encoder(struct go7007 *go)
{
int i, ret;
printk(KERN_INFO "go7007: registering new %s\n", go->name);
mutex_lock(&go->hw_lock);
ret = go7007_init_encoder(go);
mutex_unlock(&go->hw_lock);
if (ret < 0)
return -1;
/* v4l2 init must happen before i2c subdevs */
ret = go7007_v4l2_init(go);
if (ret < 0)
return ret;
if (!go->i2c_adapter_online &&
go->board_info->flags & GO7007_BOARD_USE_ONBOARD_I2C) {
if (go7007_i2c_init(go) < 0)
return -1;
go->i2c_adapter_online = 1;
}
if (go->i2c_adapter_online) {
for (i = 0; i < go->board_info->num_i2c_devs; ++i)
init_i2c_module(&go->i2c_adapter,
go->board_info->i2c_devs[i].type,
go->board_info->i2c_devs[i].addr);
if (go->board_id == GO7007_BOARDID_ADLINK_MPG24)
i2c_clients_command(&go->i2c_adapter,
DECODER_SET_CHANNEL, &go->channel_number);
}
if (go->board_info->flags & GO7007_BOARD_HAS_AUDIO) {
go->audio_enabled = 1;
go7007_snd_init(go);
}
return 0;
}
EXPORT_SYMBOL(go7007_register_encoder);
/*
* Send the encode firmware to the encoder, which will cause it
* to immediately start delivering the video and audio streams.
*
* Must be called with the hw_lock held.
*/
int go7007_start_encoder(struct go7007 *go)
{
u8 *fw;
int fw_len, rv = 0, i;
u16 intr_val, intr_data;
go->modet_enable = 0;
if (!go->dvd_mode)
for (i = 0; i < 4; ++i) {
if (go->modet[i].enable) {
go->modet_enable = 1;
continue;
}
go->modet[i].pixel_threshold = 32767;
go->modet[i].motion_threshold = 32767;
go->modet[i].mb_threshold = 32767;
}
if (go7007_construct_fw_image(go, &fw, &fw_len) < 0)
return -1;
if (go7007_send_firmware(go, fw, fw_len) < 0 ||
go7007_read_interrupt(go, &intr_val, &intr_data) < 0) {
v4l2_err(&go->v4l2_dev, "error transferring firmware\n");
rv = -1;
goto start_error;
}
go->state = STATE_DATA;
go->parse_length = 0;
go->seen_frame = 0;
if (go7007_stream_start(go) < 0) {
v4l2_err(&go->v4l2_dev, "error starting stream transfer\n");
rv = -1;
goto start_error;
}
start_error:
kfree(fw);
return rv;
}
/*
* Store a byte in the current video buffer, if there is one.
*/
static inline void store_byte(struct go7007_buffer *gobuf, u8 byte)
{
if (gobuf != NULL && gobuf->bytesused < GO7007_BUF_SIZE) {
unsigned int pgidx = gobuf->offset >> PAGE_SHIFT;
unsigned int pgoff = gobuf->offset & ~PAGE_MASK;
*((u8 *)page_address(gobuf->pages[pgidx]) + pgoff) = byte;
++gobuf->offset;
++gobuf->bytesused;
}
}
/*
* Deliver the last video buffer and get a new one to start writing to.
*/
static void frame_boundary(struct go7007 *go)
{
struct go7007_buffer *gobuf;
int i;
if (go->active_buf) {
if (go->active_buf->modet_active) {
if (go->active_buf->bytesused + 216 < GO7007_BUF_SIZE) {
for (i = 0; i < 216; ++i)
store_byte(go->active_buf,
go->active_map[i]);
go->active_buf->bytesused -= 216;
} else
go->active_buf->modet_active = 0;
}
go->active_buf->state = BUF_STATE_DONE;
wake_up_interruptible(&go->frame_waitq);
go->active_buf = NULL;
}
list_for_each_entry(gobuf, &go->stream, stream)
if (gobuf->state == BUF_STATE_QUEUED) {
gobuf->seq = go->next_seq;
do_gettimeofday(&gobuf->timestamp);
go->active_buf = gobuf;
break;
}
++go->next_seq;
}
static void write_bitmap_word(struct go7007 *go)
{
int x, y, i, stride = ((go->width >> 4) + 7) >> 3;
for (i = 0; i < 16; ++i) {
y = (((go->parse_length - 1) << 3) + i) / (go->width >> 4);
x = (((go->parse_length - 1) << 3) + i) % (go->width >> 4);
if (stride * y + (x >> 3) < sizeof(go->active_map))
go->active_map[stride * y + (x >> 3)] |=
(go->modet_word & 1) << (x & 0x7);
go->modet_word >>= 1;
}
}
/*
* Parse a chunk of the video stream into frames. The frames are not
* delimited by the hardware, so we have to parse the frame boundaries
* based on the type of video stream we're receiving.
*/
void go7007_parse_video_stream(struct go7007 *go, u8 *buf, int length)
{
int i, seq_start_code = -1, frame_start_code = -1;
spin_lock(&go->spinlock);
switch (go->format) {
case GO7007_FORMAT_MPEG4:
seq_start_code = 0xB0;
frame_start_code = 0xB6;
break;
case GO7007_FORMAT_MPEG1:
case GO7007_FORMAT_MPEG2:
seq_start_code = 0xB3;
frame_start_code = 0x00;
break;
}
for (i = 0; i < length; ++i) {
if (go->active_buf != NULL &&
go->active_buf->bytesused >= GO7007_BUF_SIZE - 3) {
v4l2_info(&go->v4l2_dev, "dropping oversized frame\n");
go->active_buf->offset -= go->active_buf->bytesused;
go->active_buf->bytesused = 0;
go->active_buf->modet_active = 0;
go->active_buf = NULL;
}
switch (go->state) {
case STATE_DATA:
switch (buf[i]) {
case 0x00:
go->state = STATE_00;
break;
case 0xFF:
go->state = STATE_FF;
break;
default:
store_byte(go->active_buf, buf[i]);
break;
}
break;
case STATE_00:
switch (buf[i]) {
case 0x00:
go->state = STATE_00_00;
break;
case 0xFF:
store_byte(go->active_buf, 0x00);
go->state = STATE_FF;
break;
default:
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, buf[i]);
go->state = STATE_DATA;
break;
}
break;
case STATE_00_00:
switch (buf[i]) {
case 0x00:
store_byte(go->active_buf, 0x00);
/* go->state remains STATE_00_00 */
break;
case 0x01:
go->state = STATE_00_00_01;
break;
case 0xFF:
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, 0x00);
go->state = STATE_FF;
break;
default:
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, buf[i]);
go->state = STATE_DATA;
break;
}
break;
case STATE_00_00_01:
if (buf[i] == 0xF8 && go->modet_enable == 0) {
/* MODET start code, but MODET not enabled */
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, 0x01);
store_byte(go->active_buf, 0xF8);
go->state = STATE_DATA;
break;
}
/* If this is the start of a new MPEG frame,
* get a new buffer */
if ((go->format == GO7007_FORMAT_MPEG1 ||
go->format == GO7007_FORMAT_MPEG2 ||
go->format == GO7007_FORMAT_MPEG4) &&
(buf[i] == seq_start_code ||
buf[i] == 0xB8 || /* GOP code */
buf[i] == frame_start_code)) {
if (go->active_buf == NULL || go->seen_frame)
frame_boundary(go);
if (buf[i] == frame_start_code) {
if (go->active_buf != NULL)
go->active_buf->frame_offset =
go->active_buf->offset;
go->seen_frame = 1;
} else {
go->seen_frame = 0;
}
}
/* Handle any special chunk types, or just write the
* start code to the (potentially new) buffer */
switch (buf[i]) {
case 0xF5: /* timestamp */
go->parse_length = 12;
go->state = STATE_UNPARSED;
break;
case 0xF6: /* vbi */
go->state = STATE_VBI_LEN_A;
break;
case 0xF8: /* MD map */
go->parse_length = 0;
memset(go->active_map, 0,
sizeof(go->active_map));
go->state = STATE_MODET_MAP;
break;
case 0xFF: /* Potential JPEG start code */
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, 0x01);
go->state = STATE_FF;
break;
default:
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, 0x00);
store_byte(go->active_buf, 0x01);
store_byte(go->active_buf, buf[i]);
go->state = STATE_DATA;
break;
}
break;
case STATE_FF:
switch (buf[i]) {
case 0x00:
store_byte(go->active_buf, 0xFF);
go->state = STATE_00;
break;
case 0xFF:
store_byte(go->active_buf, 0xFF);
/* go->state remains STATE_FF */
break;
case 0xD8:
if (go->format == GO7007_FORMAT_MJPEG)
frame_boundary(go);
/* fall through */
default:
store_byte(go->active_buf, 0xFF);
store_byte(go->active_buf, buf[i]);
go->state = STATE_DATA;
break;
}
break;
case STATE_VBI_LEN_A:
go->parse_length = buf[i] << 8;
go->state = STATE_VBI_LEN_B;
break;
case STATE_VBI_LEN_B:
go->parse_length |= buf[i];
if (go->parse_length > 0)
go->state = STATE_UNPARSED;
else
go->state = STATE_DATA;
break;
case STATE_MODET_MAP:
if (go->parse_length < 204) {
if (go->parse_length & 1) {
go->modet_word |= buf[i];
write_bitmap_word(go);
} else
go->modet_word = buf[i] << 8;
} else if (go->parse_length == 207 && go->active_buf) {
go->active_buf->modet_active = buf[i];
}
if (++go->parse_length == 208)
go->state = STATE_DATA;
break;
case STATE_UNPARSED:
if (--go->parse_length == 0)
go->state = STATE_DATA;
break;
}
}
spin_unlock(&go->spinlock);
}
EXPORT_SYMBOL(go7007_parse_video_stream);
/*
* Allocate a new go7007 struct. Used by the hardware-specific probe.
*/
struct go7007 *go7007_alloc(struct go7007_board_info *board, struct device *dev)
{
struct go7007 *go;
int i;
go = kmalloc(sizeof(struct go7007), GFP_KERNEL);
if (go == NULL)
return NULL;
go->dev = dev;
go->board_info = board;
go->board_id = 0;
go->tuner_type = -1;
go->channel_number = 0;
go->name[0] = 0;
mutex_init(&go->hw_lock);
init_waitqueue_head(&go->frame_waitq);
spin_lock_init(&go->spinlock);
go->video_dev = NULL;
go->ref_count = 0;
go->status = STATUS_INIT;
memset(&go->i2c_adapter, 0, sizeof(go->i2c_adapter));
go->i2c_adapter_online = 0;
go->interrupt_available = 0;
init_waitqueue_head(&go->interrupt_waitq);
go->in_use = 0;
go->input = 0;
if (board->sensor_flags & GO7007_SENSOR_TV) {
go->standard = GO7007_STD_NTSC;
go->width = 720;
go->height = 480;
go->sensor_framerate = 30000;
} else {
go->standard = GO7007_STD_OTHER;
go->width = board->sensor_width;
go->height = board->sensor_height;
go->sensor_framerate = board->sensor_framerate;
}
go->encoder_v_offset = board->sensor_v_offset;
go->encoder_h_offset = board->sensor_h_offset;
go->encoder_h_halve = 0;
go->encoder_v_halve = 0;
go->encoder_subsample = 0;
go->streaming = 0;
go->format = GO7007_FORMAT_MJPEG;
go->bitrate = 1500000;
go->fps_scale = 1;
go->pali = 0;
go->aspect_ratio = GO7007_RATIO_1_1;
go->gop_size = 0;
go->ipb = 0;
go->closed_gop = 0;
go->repeat_seqhead = 0;
go->seq_header_enable = 0;
go->gop_header_enable = 0;
go->dvd_mode = 0;
go->interlace_coding = 0;
for (i = 0; i < 4; ++i)
go->modet[i].enable = 0;
for (i = 0; i < 1624; ++i)
go->modet_map[i] = 0;
go->audio_deliver = NULL;
go->audio_enabled = 0;
INIT_LIST_HEAD(&go->stream);
return go;
}
EXPORT_SYMBOL(go7007_alloc);
/*
* Detach and unregister the encoder. The go7007 struct won't be freed
* until v4l2 finishes releasing its resources and all associated fds are
* closed by applications.
*/
void go7007_remove(struct go7007 *go)
{
if (go->i2c_adapter_online) {
if (i2c_del_adapter(&go->i2c_adapter) == 0)
go->i2c_adapter_online = 0;
else
v4l2_err(&go->v4l2_dev,
"error removing I2C adapter!\n");
}
if (go->audio_enabled)
go7007_snd_remove(go);
go7007_v4l2_remove(go);
}
EXPORT_SYMBOL(go7007_remove);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
IOKP-kitkat/kernel_samsung_jf | drivers/leds/leds-lp5523.c | 4832 | 27076 | /*
* lp5523.c - LP5523 LED Driver
*
* Copyright (C) 2010 Nokia Corporation
*
* Contact: Samu Onkalo <samu.p.onkalo@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/module.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/ctype.h>
#include <linux/spinlock.h>
#include <linux/wait.h>
#include <linux/leds.h>
#include <linux/leds-lp5523.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
#define LP5523_REG_ENABLE 0x00
#define LP5523_REG_OP_MODE 0x01
#define LP5523_REG_RATIOMETRIC_MSB 0x02
#define LP5523_REG_RATIOMETRIC_LSB 0x03
#define LP5523_REG_ENABLE_LEDS_MSB 0x04
#define LP5523_REG_ENABLE_LEDS_LSB 0x05
#define LP5523_REG_LED_CNTRL_BASE 0x06
#define LP5523_REG_LED_PWM_BASE 0x16
#define LP5523_REG_LED_CURRENT_BASE 0x26
#define LP5523_REG_CONFIG 0x36
#define LP5523_REG_CHANNEL1_PC 0x37
#define LP5523_REG_CHANNEL2_PC 0x38
#define LP5523_REG_CHANNEL3_PC 0x39
#define LP5523_REG_STATUS 0x3a
#define LP5523_REG_GPO 0x3b
#define LP5523_REG_VARIABLE 0x3c
#define LP5523_REG_RESET 0x3d
#define LP5523_REG_TEMP_CTRL 0x3e
#define LP5523_REG_TEMP_READ 0x3f
#define LP5523_REG_TEMP_WRITE 0x40
#define LP5523_REG_LED_TEST_CTRL 0x41
#define LP5523_REG_LED_TEST_ADC 0x42
#define LP5523_REG_ENG1_VARIABLE 0x45
#define LP5523_REG_ENG2_VARIABLE 0x46
#define LP5523_REG_ENG3_VARIABLE 0x47
#define LP5523_REG_MASTER_FADER1 0x48
#define LP5523_REG_MASTER_FADER2 0x49
#define LP5523_REG_MASTER_FADER3 0x4a
#define LP5523_REG_CH1_PROG_START 0x4c
#define LP5523_REG_CH2_PROG_START 0x4d
#define LP5523_REG_CH3_PROG_START 0x4e
#define LP5523_REG_PROG_PAGE_SEL 0x4f
#define LP5523_REG_PROG_MEM 0x50
#define LP5523_CMD_LOAD 0x15 /* 00010101 */
#define LP5523_CMD_RUN 0x2a /* 00101010 */
#define LP5523_CMD_DISABLED 0x00 /* 00000000 */
#define LP5523_ENABLE 0x40
#define LP5523_AUTO_INC 0x40
#define LP5523_PWR_SAVE 0x20
#define LP5523_PWM_PWR_SAVE 0x04
#define LP5523_CP_1 0x08
#define LP5523_CP_1_5 0x10
#define LP5523_CP_AUTO 0x18
#define LP5523_INT_CLK 0x01
#define LP5523_AUTO_CLK 0x02
#define LP5523_EN_LEDTEST 0x80
#define LP5523_LEDTEST_DONE 0x80
#define LP5523_DEFAULT_CURRENT 50 /* microAmps */
#define LP5523_PROGRAM_LENGTH 32 /* in bytes */
#define LP5523_PROGRAM_PAGES 6
#define LP5523_ADC_SHORTCIRC_LIM 80
#define LP5523_LEDS 9
#define LP5523_ENGINES 3
#define LP5523_ENG_MASK_BASE 0x30 /* 00110000 */
#define LP5523_ENG_STATUS_MASK 0x07 /* 00000111 */
#define LP5523_IRQ_FLAGS IRQF_TRIGGER_FALLING
#define LP5523_EXT_CLK_USED 0x08
#define LED_ACTIVE(mux, led) (!!(mux & (0x0001 << led)))
#define SHIFT_MASK(id) (((id) - 1) * 2)
struct lp5523_engine {
int id;
u8 mode;
u8 prog_page;
u8 mux_page;
u16 led_mux;
u8 engine_mask;
};
struct lp5523_led {
int id;
u8 chan_nr;
u8 led_current;
u8 max_current;
struct led_classdev cdev;
struct work_struct brightness_work;
u8 brightness;
};
struct lp5523_chip {
struct mutex lock; /* Serialize control */
struct i2c_client *client;
struct lp5523_engine engines[LP5523_ENGINES];
struct lp5523_led leds[LP5523_LEDS];
struct lp5523_platform_data *pdata;
u8 num_channels;
u8 num_leds;
};
static inline struct lp5523_led *cdev_to_led(struct led_classdev *cdev)
{
return container_of(cdev, struct lp5523_led, cdev);
}
static inline struct lp5523_chip *engine_to_lp5523(struct lp5523_engine *engine)
{
return container_of(engine, struct lp5523_chip,
engines[engine->id - 1]);
}
static inline struct lp5523_chip *led_to_lp5523(struct lp5523_led *led)
{
return container_of(led, struct lp5523_chip,
leds[led->id]);
}
static int lp5523_set_mode(struct lp5523_engine *engine, u8 mode);
static int lp5523_set_engine_mode(struct lp5523_engine *engine, u8 mode);
static int lp5523_load_program(struct lp5523_engine *engine, const u8 *pattern);
static void lp5523_led_brightness_work(struct work_struct *work);
static int lp5523_write(struct i2c_client *client, u8 reg, u8 value)
{
return i2c_smbus_write_byte_data(client, reg, value);
}
static int lp5523_read(struct i2c_client *client, u8 reg, u8 *buf)
{
s32 ret = i2c_smbus_read_byte_data(client, reg);
if (ret < 0)
return -EIO;
*buf = ret;
return 0;
}
static int lp5523_detect(struct i2c_client *client)
{
int ret;
u8 buf;
ret = lp5523_write(client, LP5523_REG_ENABLE, 0x40);
if (ret)
return ret;
ret = lp5523_read(client, LP5523_REG_ENABLE, &buf);
if (ret)
return ret;
if (buf == 0x40)
return 0;
else
return -ENODEV;
}
static int lp5523_configure(struct i2c_client *client)
{
struct lp5523_chip *chip = i2c_get_clientdata(client);
int ret = 0;
u8 status;
/* one pattern per engine setting led mux start and stop addresses */
static const u8 pattern[][LP5523_PROGRAM_LENGTH] = {
{ 0x9c, 0x30, 0x9c, 0xb0, 0x9d, 0x80, 0xd8, 0x00, 0},
{ 0x9c, 0x40, 0x9c, 0xc0, 0x9d, 0x80, 0xd8, 0x00, 0},
{ 0x9c, 0x50, 0x9c, 0xd0, 0x9d, 0x80, 0xd8, 0x00, 0},
};
ret |= lp5523_write(client, LP5523_REG_ENABLE, LP5523_ENABLE);
/* Chip startup time is 500 us, 1 - 2 ms gives some margin */
usleep_range(1000, 2000);
ret |= lp5523_write(client, LP5523_REG_CONFIG,
LP5523_AUTO_INC | LP5523_PWR_SAVE |
LP5523_CP_AUTO | LP5523_AUTO_CLK |
LP5523_PWM_PWR_SAVE);
/* turn on all leds */
ret |= lp5523_write(client, LP5523_REG_ENABLE_LEDS_MSB, 0x01);
ret |= lp5523_write(client, LP5523_REG_ENABLE_LEDS_LSB, 0xff);
/* hardcode 32 bytes of memory for each engine from program memory */
ret |= lp5523_write(client, LP5523_REG_CH1_PROG_START, 0x00);
ret |= lp5523_write(client, LP5523_REG_CH2_PROG_START, 0x10);
ret |= lp5523_write(client, LP5523_REG_CH3_PROG_START, 0x20);
/* write led mux address space for each channel */
ret |= lp5523_load_program(&chip->engines[0], pattern[0]);
ret |= lp5523_load_program(&chip->engines[1], pattern[1]);
ret |= lp5523_load_program(&chip->engines[2], pattern[2]);
if (ret) {
dev_err(&client->dev, "could not load mux programs\n");
return -1;
}
/* set all engines exec state and mode to run 00101010 */
ret |= lp5523_write(client, LP5523_REG_ENABLE,
(LP5523_CMD_RUN | LP5523_ENABLE));
ret |= lp5523_write(client, LP5523_REG_OP_MODE, LP5523_CMD_RUN);
if (ret) {
dev_err(&client->dev, "could not start mux programs\n");
return -1;
}
/* Let the programs run for couple of ms and check the engine status */
usleep_range(3000, 6000);
lp5523_read(client, LP5523_REG_STATUS, &status);
status &= LP5523_ENG_STATUS_MASK;
if (status == LP5523_ENG_STATUS_MASK) {
dev_dbg(&client->dev, "all engines configured\n");
} else {
dev_info(&client->dev, "status == %x\n", status);
dev_err(&client->dev, "cound not configure LED engine\n");
return -1;
}
dev_info(&client->dev, "disabling engines\n");
ret |= lp5523_write(client, LP5523_REG_OP_MODE, LP5523_CMD_DISABLED);
return ret;
}
static int lp5523_set_engine_mode(struct lp5523_engine *engine, u8 mode)
{
struct lp5523_chip *chip = engine_to_lp5523(engine);
struct i2c_client *client = chip->client;
int ret;
u8 engine_state;
ret = lp5523_read(client, LP5523_REG_OP_MODE, &engine_state);
if (ret)
goto fail;
engine_state &= ~(engine->engine_mask);
/* set mode only for this engine */
mode &= engine->engine_mask;
engine_state |= mode;
ret |= lp5523_write(client, LP5523_REG_OP_MODE, engine_state);
fail:
return ret;
}
static int lp5523_load_mux(struct lp5523_engine *engine, u16 mux)
{
struct lp5523_chip *chip = engine_to_lp5523(engine);
struct i2c_client *client = chip->client;
int ret = 0;
ret |= lp5523_set_engine_mode(engine, LP5523_CMD_LOAD);
ret |= lp5523_write(client, LP5523_REG_PROG_PAGE_SEL, engine->mux_page);
ret |= lp5523_write(client, LP5523_REG_PROG_MEM,
(u8)(mux >> 8));
ret |= lp5523_write(client, LP5523_REG_PROG_MEM + 1, (u8)(mux));
engine->led_mux = mux;
return ret;
}
static int lp5523_load_program(struct lp5523_engine *engine, const u8 *pattern)
{
struct lp5523_chip *chip = engine_to_lp5523(engine);
struct i2c_client *client = chip->client;
int ret = 0;
ret |= lp5523_set_engine_mode(engine, LP5523_CMD_LOAD);
ret |= lp5523_write(client, LP5523_REG_PROG_PAGE_SEL,
engine->prog_page);
ret |= i2c_smbus_write_i2c_block_data(client, LP5523_REG_PROG_MEM,
LP5523_PROGRAM_LENGTH, pattern);
return ret;
}
static int lp5523_run_program(struct lp5523_engine *engine)
{
struct lp5523_chip *chip = engine_to_lp5523(engine);
struct i2c_client *client = chip->client;
int ret;
ret = lp5523_write(client, LP5523_REG_ENABLE,
LP5523_CMD_RUN | LP5523_ENABLE);
if (ret)
goto fail;
ret = lp5523_set_engine_mode(engine, LP5523_CMD_RUN);
fail:
return ret;
}
static int lp5523_mux_parse(const char *buf, u16 *mux, size_t len)
{
int i;
u16 tmp_mux = 0;
len = len < LP5523_LEDS ? len : LP5523_LEDS;
for (i = 0; i < len; i++) {
switch (buf[i]) {
case '1':
tmp_mux |= (1 << i);
break;
case '0':
break;
case '\n':
i = len;
break;
default:
return -1;
}
}
*mux = tmp_mux;
return 0;
}
static void lp5523_mux_to_array(u16 led_mux, char *array)
{
int i, pos = 0;
for (i = 0; i < LP5523_LEDS; i++)
pos += sprintf(array + pos, "%x", LED_ACTIVE(led_mux, i));
array[pos] = '\0';
}
/*--------------------------------------------------------------*/
/* Sysfs interface */
/*--------------------------------------------------------------*/
static ssize_t show_engine_leds(struct device *dev,
struct device_attribute *attr,
char *buf, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lp5523_chip *chip = i2c_get_clientdata(client);
char mux[LP5523_LEDS + 1];
lp5523_mux_to_array(chip->engines[nr - 1].led_mux, mux);
return sprintf(buf, "%s\n", mux);
}
#define show_leds(nr) \
static ssize_t show_engine##nr##_leds(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
return show_engine_leds(dev, attr, buf, nr); \
}
show_leds(1)
show_leds(2)
show_leds(3)
static ssize_t store_engine_leds(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lp5523_chip *chip = i2c_get_clientdata(client);
u16 mux = 0;
ssize_t ret;
if (lp5523_mux_parse(buf, &mux, len))
return -EINVAL;
mutex_lock(&chip->lock);
ret = -EINVAL;
if (chip->engines[nr - 1].mode != LP5523_CMD_LOAD)
goto leave;
if (lp5523_load_mux(&chip->engines[nr - 1], mux))
goto leave;
ret = len;
leave:
mutex_unlock(&chip->lock);
return ret;
}
#define store_leds(nr) \
static ssize_t store_engine##nr##_leds(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t len) \
{ \
return store_engine_leds(dev, attr, buf, len, nr); \
}
store_leds(1)
store_leds(2)
store_leds(3)
static ssize_t lp5523_selftest(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct lp5523_chip *chip = i2c_get_clientdata(client);
int i, ret, pos = 0;
int led = 0;
u8 status, adc, vdd;
mutex_lock(&chip->lock);
ret = lp5523_read(chip->client, LP5523_REG_STATUS, &status);
if (ret < 0)
goto fail;
/* Check that ext clock is really in use if requested */
if ((chip->pdata) && (chip->pdata->clock_mode == LP5523_CLOCK_EXT))
if ((status & LP5523_EXT_CLK_USED) == 0)
goto fail;
/* Measure VDD (i.e. VBAT) first (channel 16 corresponds to VDD) */
lp5523_write(chip->client, LP5523_REG_LED_TEST_CTRL,
LP5523_EN_LEDTEST | 16);
usleep_range(3000, 6000); /* ADC conversion time is typically 2.7 ms */
ret = lp5523_read(chip->client, LP5523_REG_STATUS, &status);
if (!(status & LP5523_LEDTEST_DONE))
usleep_range(3000, 6000); /* Was not ready. Wait little bit */
ret |= lp5523_read(chip->client, LP5523_REG_LED_TEST_ADC, &vdd);
vdd--; /* There may be some fluctuation in measurement */
for (i = 0; i < LP5523_LEDS; i++) {
/* Skip non-existing channels */
if (chip->pdata->led_config[i].led_current == 0)
continue;
/* Set default current */
lp5523_write(chip->client,
LP5523_REG_LED_CURRENT_BASE + i,
chip->pdata->led_config[i].led_current);
lp5523_write(chip->client, LP5523_REG_LED_PWM_BASE + i, 0xff);
/* let current stabilize 2 - 4ms before measurements start */
usleep_range(2000, 4000);
lp5523_write(chip->client,
LP5523_REG_LED_TEST_CTRL,
LP5523_EN_LEDTEST | i);
/* ADC conversion time is 2.7 ms typically */
usleep_range(3000, 6000);
ret = lp5523_read(chip->client, LP5523_REG_STATUS, &status);
if (!(status & LP5523_LEDTEST_DONE))
usleep_range(3000, 6000);/* Was not ready. Wait. */
ret |= lp5523_read(chip->client, LP5523_REG_LED_TEST_ADC, &adc);
if (adc >= vdd || adc < LP5523_ADC_SHORTCIRC_LIM)
pos += sprintf(buf + pos, "LED %d FAIL\n", i);
lp5523_write(chip->client, LP5523_REG_LED_PWM_BASE + i, 0x00);
/* Restore current */
lp5523_write(chip->client,
LP5523_REG_LED_CURRENT_BASE + i,
chip->leds[led].led_current);
led++;
}
if (pos == 0)
pos = sprintf(buf, "OK\n");
goto release_lock;
fail:
pos = sprintf(buf, "FAIL\n");
release_lock:
mutex_unlock(&chip->lock);
return pos;
}
static void lp5523_set_brightness(struct led_classdev *cdev,
enum led_brightness brightness)
{
struct lp5523_led *led = cdev_to_led(cdev);
led->brightness = (u8)brightness;
schedule_work(&led->brightness_work);
}
static void lp5523_led_brightness_work(struct work_struct *work)
{
struct lp5523_led *led = container_of(work,
struct lp5523_led,
brightness_work);
struct lp5523_chip *chip = led_to_lp5523(led);
struct i2c_client *client = chip->client;
mutex_lock(&chip->lock);
lp5523_write(client, LP5523_REG_LED_PWM_BASE + led->chan_nr,
led->brightness);
mutex_unlock(&chip->lock);
}
static int lp5523_do_store_load(struct lp5523_engine *engine,
const char *buf, size_t len)
{
struct lp5523_chip *chip = engine_to_lp5523(engine);
struct i2c_client *client = chip->client;
int ret, nrchars, offset = 0, i = 0;
char c[3];
unsigned cmd;
u8 pattern[LP5523_PROGRAM_LENGTH] = {0};
while ((offset < len - 1) && (i < LP5523_PROGRAM_LENGTH)) {
/* separate sscanfs because length is working only for %s */
ret = sscanf(buf + offset, "%2s%n ", c, &nrchars);
ret = sscanf(c, "%2x", &cmd);
if (ret != 1)
goto fail;
pattern[i] = (u8)cmd;
offset += nrchars;
i++;
}
/* Each instruction is 16bit long. Check that length is even */
if (i % 2)
goto fail;
mutex_lock(&chip->lock);
if (engine->mode == LP5523_CMD_LOAD)
ret = lp5523_load_program(engine, pattern);
else
ret = -EINVAL;
mutex_unlock(&chip->lock);
if (ret) {
dev_err(&client->dev, "failed loading pattern\n");
return ret;
}
return len;
fail:
dev_err(&client->dev, "wrong pattern format\n");
return -EINVAL;
}
static ssize_t store_engine_load(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lp5523_chip *chip = i2c_get_clientdata(client);
return lp5523_do_store_load(&chip->engines[nr - 1], buf, len);
}
#define store_load(nr) \
static ssize_t store_engine##nr##_load(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t len) \
{ \
return store_engine_load(dev, attr, buf, len, nr); \
}
store_load(1)
store_load(2)
store_load(3)
static ssize_t show_engine_mode(struct device *dev,
struct device_attribute *attr,
char *buf, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lp5523_chip *chip = i2c_get_clientdata(client);
switch (chip->engines[nr - 1].mode) {
case LP5523_CMD_RUN:
return sprintf(buf, "run\n");
case LP5523_CMD_LOAD:
return sprintf(buf, "load\n");
case LP5523_CMD_DISABLED:
return sprintf(buf, "disabled\n");
default:
return sprintf(buf, "disabled\n");
}
}
#define show_mode(nr) \
static ssize_t show_engine##nr##_mode(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
return show_engine_mode(dev, attr, buf, nr); \
}
show_mode(1)
show_mode(2)
show_mode(3)
static ssize_t store_engine_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len, int nr)
{
struct i2c_client *client = to_i2c_client(dev);
struct lp5523_chip *chip = i2c_get_clientdata(client);
struct lp5523_engine *engine = &chip->engines[nr - 1];
mutex_lock(&chip->lock);
if (!strncmp(buf, "run", 3))
lp5523_set_mode(engine, LP5523_CMD_RUN);
else if (!strncmp(buf, "load", 4))
lp5523_set_mode(engine, LP5523_CMD_LOAD);
else if (!strncmp(buf, "disabled", 8))
lp5523_set_mode(engine, LP5523_CMD_DISABLED);
mutex_unlock(&chip->lock);
return len;
}
#define store_mode(nr) \
static ssize_t store_engine##nr##_mode(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t len) \
{ \
return store_engine_mode(dev, attr, buf, len, nr); \
}
store_mode(1)
store_mode(2)
store_mode(3)
static ssize_t show_max_current(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lp5523_led *led = cdev_to_led(led_cdev);
return sprintf(buf, "%d\n", led->max_current);
}
static ssize_t show_current(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lp5523_led *led = cdev_to_led(led_cdev);
return sprintf(buf, "%d\n", led->led_current);
}
static ssize_t store_current(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lp5523_led *led = cdev_to_led(led_cdev);
struct lp5523_chip *chip = led_to_lp5523(led);
ssize_t ret;
unsigned long curr;
if (strict_strtoul(buf, 0, &curr))
return -EINVAL;
if (curr > led->max_current)
return -EINVAL;
mutex_lock(&chip->lock);
ret = lp5523_write(chip->client,
LP5523_REG_LED_CURRENT_BASE + led->chan_nr,
(u8)curr);
mutex_unlock(&chip->lock);
if (ret < 0)
return ret;
led->led_current = (u8)curr;
return len;
}
/* led class device attributes */
static DEVICE_ATTR(led_current, S_IRUGO | S_IWUSR, show_current, store_current);
static DEVICE_ATTR(max_current, S_IRUGO , show_max_current, NULL);
static struct attribute *lp5523_led_attributes[] = {
&dev_attr_led_current.attr,
&dev_attr_max_current.attr,
NULL,
};
static struct attribute_group lp5523_led_attribute_group = {
.attrs = lp5523_led_attributes
};
/* device attributes */
static DEVICE_ATTR(engine1_mode, S_IRUGO | S_IWUSR,
show_engine1_mode, store_engine1_mode);
static DEVICE_ATTR(engine2_mode, S_IRUGO | S_IWUSR,
show_engine2_mode, store_engine2_mode);
static DEVICE_ATTR(engine3_mode, S_IRUGO | S_IWUSR,
show_engine3_mode, store_engine3_mode);
static DEVICE_ATTR(engine1_leds, S_IRUGO | S_IWUSR,
show_engine1_leds, store_engine1_leds);
static DEVICE_ATTR(engine2_leds, S_IRUGO | S_IWUSR,
show_engine2_leds, store_engine2_leds);
static DEVICE_ATTR(engine3_leds, S_IRUGO | S_IWUSR,
show_engine3_leds, store_engine3_leds);
static DEVICE_ATTR(engine1_load, S_IWUSR, NULL, store_engine1_load);
static DEVICE_ATTR(engine2_load, S_IWUSR, NULL, store_engine2_load);
static DEVICE_ATTR(engine3_load, S_IWUSR, NULL, store_engine3_load);
static DEVICE_ATTR(selftest, S_IRUGO, lp5523_selftest, NULL);
static struct attribute *lp5523_attributes[] = {
&dev_attr_engine1_mode.attr,
&dev_attr_engine2_mode.attr,
&dev_attr_engine3_mode.attr,
&dev_attr_selftest.attr,
&dev_attr_engine1_load.attr,
&dev_attr_engine1_leds.attr,
&dev_attr_engine2_load.attr,
&dev_attr_engine2_leds.attr,
&dev_attr_engine3_load.attr,
&dev_attr_engine3_leds.attr,
};
static const struct attribute_group lp5523_group = {
.attrs = lp5523_attributes,
};
static int lp5523_register_sysfs(struct i2c_client *client)
{
struct device *dev = &client->dev;
int ret;
ret = sysfs_create_group(&dev->kobj, &lp5523_group);
if (ret < 0)
return ret;
return 0;
}
static void lp5523_unregister_sysfs(struct i2c_client *client)
{
struct lp5523_chip *chip = i2c_get_clientdata(client);
struct device *dev = &client->dev;
int i;
sysfs_remove_group(&dev->kobj, &lp5523_group);
for (i = 0; i < chip->num_leds; i++)
sysfs_remove_group(&chip->leds[i].cdev.dev->kobj,
&lp5523_led_attribute_group);
}
/*--------------------------------------------------------------*/
/* Set chip operating mode */
/*--------------------------------------------------------------*/
static int lp5523_set_mode(struct lp5523_engine *engine, u8 mode)
{
int ret = 0;
/* if in that mode already do nothing, except for run */
if (mode == engine->mode && mode != LP5523_CMD_RUN)
return 0;
if (mode == LP5523_CMD_RUN) {
ret = lp5523_run_program(engine);
} else if (mode == LP5523_CMD_LOAD) {
lp5523_set_engine_mode(engine, LP5523_CMD_DISABLED);
lp5523_set_engine_mode(engine, LP5523_CMD_LOAD);
} else if (mode == LP5523_CMD_DISABLED) {
lp5523_set_engine_mode(engine, LP5523_CMD_DISABLED);
}
engine->mode = mode;
return ret;
}
/*--------------------------------------------------------------*/
/* Probe, Attach, Remove */
/*--------------------------------------------------------------*/
static int __init lp5523_init_engine(struct lp5523_engine *engine, int id)
{
if (id < 1 || id > LP5523_ENGINES)
return -1;
engine->id = id;
engine->engine_mask = LP5523_ENG_MASK_BASE >> SHIFT_MASK(id);
engine->prog_page = id - 1;
engine->mux_page = id + 2;
return 0;
}
static int __devinit lp5523_init_led(struct lp5523_led *led, struct device *dev,
int chan, struct lp5523_platform_data *pdata)
{
char name[32];
int res;
if (chan >= LP5523_LEDS)
return -EINVAL;
if (pdata->led_config[chan].led_current) {
led->led_current = pdata->led_config[chan].led_current;
led->max_current = pdata->led_config[chan].max_current;
led->chan_nr = pdata->led_config[chan].chan_nr;
if (led->chan_nr >= LP5523_LEDS) {
dev_err(dev, "Use channel numbers between 0 and %d\n",
LP5523_LEDS - 1);
return -EINVAL;
}
snprintf(name, sizeof(name), "%s:channel%d",
pdata->label ?: "lp5523", chan);
led->cdev.name = name;
led->cdev.brightness_set = lp5523_set_brightness;
res = led_classdev_register(dev, &led->cdev);
if (res < 0) {
dev_err(dev, "couldn't register led on channel %d\n",
chan);
return res;
}
res = sysfs_create_group(&led->cdev.dev->kobj,
&lp5523_led_attribute_group);
if (res < 0) {
dev_err(dev, "couldn't register current attribute\n");
led_classdev_unregister(&led->cdev);
return res;
}
} else {
led->led_current = 0;
}
return 0;
}
static int __devinit lp5523_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct lp5523_chip *chip;
struct lp5523_platform_data *pdata;
int ret, i, led;
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
i2c_set_clientdata(client, chip);
chip->client = client;
pdata = client->dev.platform_data;
if (!pdata) {
dev_err(&client->dev, "no platform data\n");
ret = -EINVAL;
goto fail1;
}
mutex_init(&chip->lock);
chip->pdata = pdata;
if (pdata->setup_resources) {
ret = pdata->setup_resources();
if (ret < 0)
goto fail1;
}
if (pdata->enable) {
pdata->enable(0);
usleep_range(1000, 2000); /* Keep enable down at least 1ms */
pdata->enable(1);
usleep_range(1000, 2000); /* 500us abs min. */
}
lp5523_write(client, LP5523_REG_RESET, 0xff);
usleep_range(10000, 20000); /*
* Exact value is not available. 10 - 20ms
* appears to be enough for reset.
*/
ret = lp5523_detect(client);
if (ret)
goto fail2;
dev_info(&client->dev, "LP5523 Programmable led chip found\n");
/* Initialize engines */
for (i = 0; i < ARRAY_SIZE(chip->engines); i++) {
ret = lp5523_init_engine(&chip->engines[i], i + 1);
if (ret) {
dev_err(&client->dev, "error initializing engine\n");
goto fail2;
}
}
ret = lp5523_configure(client);
if (ret < 0) {
dev_err(&client->dev, "error configuring chip\n");
goto fail2;
}
/* Initialize leds */
chip->num_channels = pdata->num_channels;
chip->num_leds = 0;
led = 0;
for (i = 0; i < pdata->num_channels; i++) {
/* Do not initialize channels that are not connected */
if (pdata->led_config[i].led_current == 0)
continue;
ret = lp5523_init_led(&chip->leds[led], &client->dev, i, pdata);
if (ret) {
dev_err(&client->dev, "error initializing leds\n");
goto fail3;
}
chip->num_leds++;
chip->leds[led].id = led;
/* Set LED current */
lp5523_write(client,
LP5523_REG_LED_CURRENT_BASE + chip->leds[led].chan_nr,
chip->leds[led].led_current);
INIT_WORK(&(chip->leds[led].brightness_work),
lp5523_led_brightness_work);
led++;
}
ret = lp5523_register_sysfs(client);
if (ret) {
dev_err(&client->dev, "registering sysfs failed\n");
goto fail3;
}
return ret;
fail3:
for (i = 0; i < chip->num_leds; i++) {
led_classdev_unregister(&chip->leds[i].cdev);
cancel_work_sync(&chip->leds[i].brightness_work);
}
fail2:
if (pdata->enable)
pdata->enable(0);
if (pdata->release_resources)
pdata->release_resources();
fail1:
kfree(chip);
return ret;
}
static int lp5523_remove(struct i2c_client *client)
{
struct lp5523_chip *chip = i2c_get_clientdata(client);
int i;
lp5523_unregister_sysfs(client);
for (i = 0; i < chip->num_leds; i++) {
led_classdev_unregister(&chip->leds[i].cdev);
cancel_work_sync(&chip->leds[i].brightness_work);
}
if (chip->pdata->enable)
chip->pdata->enable(0);
if (chip->pdata->release_resources)
chip->pdata->release_resources();
kfree(chip);
return 0;
}
static const struct i2c_device_id lp5523_id[] = {
{ "lp5523", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, lp5523_id);
static struct i2c_driver lp5523_driver = {
.driver = {
.name = "lp5523",
},
.probe = lp5523_probe,
.remove = lp5523_remove,
.id_table = lp5523_id,
};
module_i2c_driver(lp5523_driver);
MODULE_AUTHOR("Mathias Nyman <mathias.nyman@nokia.com>");
MODULE_DESCRIPTION("LP5523 LED engine");
MODULE_LICENSE("GPL");
| gpl-2.0 |
wwwhana/android_kernel_sony_wukong | drivers/net/ethernet/racal/ni5010.c | 5088 | 22863 | /* ni5010.c: A network driver for the MiCom-Interlan NI5010 ethercard.
*
* Copyright 1996,1997,2006 Jan-Pascal van Best and Andreas Mohr.
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* The authors may be reached as:
* janpascal@vanbest.org andi@lisas.de
*
* Sources:
* Donald Becker's "skeleton.c"
* Crynwr ni5010 packet driver
*
* Changes:
* v0.0: First test version
* v0.1: First working version
* v0.2:
* v0.3->v0.90: Now demand setting io and irq when loading as module
* 970430 v0.91: modified for Linux 2.1.14
* v0.92: Implemented Andreas' (better) NI5010 probe
* 970503 v0.93: Fixed auto-irq failure on warm reboot (JB)
* 970623 v1.00: First kernel version (AM)
* 970814 v1.01: Added detection of onboard receive buffer size (AM)
* 060611 v1.02: slight cleanup: email addresses, driver modernization.
* Bugs:
* - not SMP-safe (no locking of I/O accesses)
* - Note that you have to patch ifconfig for the new /proc/net/dev
* format. It gives incorrect stats otherwise.
*
* To do:
* Fix all bugs :-)
* Move some stuff to chipset_init()
* Handle xmt errors other than collisions
* Complete merge with Andreas' driver
* Implement ring buffers (Is this useful? You can't squeeze
* too many packet in a 2k buffer!)
* Implement DMA (Again, is this useful? Some docs say DMA is
* slower than programmed I/O)
*
* Compile with:
* gcc -O2 -fomit-frame-pointer -m486 -D__KERNEL__ \
* -DMODULE -c ni5010.c
*
* Insert with e.g.:
* insmod ni5010.ko io=0x300 irq=5
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include "ni5010.h"
static const char boardname[] = "NI5010";
static char version[] __initdata =
"ni5010.c: v1.02 20060611 Jan-Pascal van Best and Andreas Mohr\n";
/* bufsize_rcv == 0 means autoprobing */
static unsigned int bufsize_rcv;
#define JUMPERED_INTERRUPTS /* IRQ line jumpered on board */
#undef JUMPERED_DMA /* No DMA used */
#undef FULL_IODETECT /* Only detect in portlist */
#ifndef FULL_IODETECT
/* A zero-terminated list of I/O addresses to be probed. */
static unsigned int ports[] __initdata =
{ 0x300, 0x320, 0x340, 0x360, 0x380, 0x3a0, 0 };
#endif
/* Use 0 for production, 1 for verification, >2 for debug */
#ifndef NI5010_DEBUG
#define NI5010_DEBUG 0
#endif
/* Information that needs to be kept for each board. */
struct ni5010_local {
int o_pkt_size;
spinlock_t lock;
};
/* Index to functions, as function prototypes. */
static int ni5010_probe1(struct net_device *dev, int ioaddr);
static int ni5010_open(struct net_device *dev);
static int ni5010_send_packet(struct sk_buff *skb, struct net_device *dev);
static irqreturn_t ni5010_interrupt(int irq, void *dev_id);
static void ni5010_rx(struct net_device *dev);
static void ni5010_timeout(struct net_device *dev);
static int ni5010_close(struct net_device *dev);
static void ni5010_set_multicast_list(struct net_device *dev);
static void reset_receiver(struct net_device *dev);
static int process_xmt_interrupt(struct net_device *dev);
#define tx_done(dev) 1
static void hardware_send_packet(struct net_device *dev, char *buf, int length, int pad);
static void chipset_init(struct net_device *dev, int startp);
static void dump_packet(void *buf, int len);
static void ni5010_show_registers(struct net_device *dev);
static int io;
static int irq;
struct net_device * __init ni5010_probe(int unit)
{
struct net_device *dev = alloc_etherdev(sizeof(struct ni5010_local));
int *port;
int err = 0;
if (!dev)
return ERR_PTR(-ENOMEM);
if (unit >= 0) {
sprintf(dev->name, "eth%d", unit);
netdev_boot_setup_check(dev);
io = dev->base_addr;
irq = dev->irq;
}
PRINTK2((KERN_DEBUG "%s: Entering ni5010_probe\n", dev->name));
if (io > 0x1ff) { /* Check a single specified location. */
err = ni5010_probe1(dev, io);
} else if (io != 0) { /* Don't probe at all. */
err = -ENXIO;
} else {
#ifdef FULL_IODETECT
for (io=0x200; io<0x400 && ni5010_probe1(dev, io) ; io+=0x20)
;
if (io == 0x400)
err = -ENODEV;
#else
for (port = ports; *port && ni5010_probe1(dev, *port); port++)
;
if (!*port)
err = -ENODEV;
#endif /* FULL_IODETECT */
}
if (err)
goto out;
err = register_netdev(dev);
if (err)
goto out1;
return dev;
out1:
release_region(dev->base_addr, NI5010_IO_EXTENT);
out:
free_netdev(dev);
return ERR_PTR(err);
}
static inline int rd_port(int ioaddr)
{
inb(IE_RBUF);
return inb(IE_SAPROM);
}
static void __init trigger_irq(int ioaddr)
{
outb(0x00, EDLC_RESET); /* Clear EDLC hold RESET state */
outb(0x00, IE_RESET); /* Board reset */
outb(0x00, EDLC_XMASK); /* Disable all Xmt interrupts */
outb(0x00, EDLC_RMASK); /* Disable all Rcv interrupt */
outb(0xff, EDLC_XCLR); /* Clear all pending Xmt interrupts */
outb(0xff, EDLC_RCLR); /* Clear all pending Rcv interrupts */
/*
* Transmit packet mode: Ignore parity, Power xcvr,
* Enable loopback
*/
outb(XMD_IG_PAR | XMD_T_MODE | XMD_LBC, EDLC_XMODE);
outb(RMD_BROADCAST, EDLC_RMODE); /* Receive normal&broadcast */
outb(XM_ALL, EDLC_XMASK); /* Enable all Xmt interrupts */
udelay(50); /* FIXME: Necessary? */
outb(MM_EN_XMT|MM_MUX, IE_MMODE); /* Start transmission */
}
static const struct net_device_ops ni5010_netdev_ops = {
.ndo_open = ni5010_open,
.ndo_stop = ni5010_close,
.ndo_start_xmit = ni5010_send_packet,
.ndo_set_rx_mode = ni5010_set_multicast_list,
.ndo_tx_timeout = ni5010_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = eth_change_mtu,
};
/*
* This is the real probe routine. Linux has a history of friendly device
* probes on the ISA bus. A good device probes avoids doing writes, and
* verifies that the correct device exists and functions.
*/
static int __init ni5010_probe1(struct net_device *dev, int ioaddr)
{
static unsigned version_printed;
struct ni5010_local *lp;
int i;
unsigned int data = 0;
int boguscount = 40;
int err = -ENODEV;
dev->base_addr = ioaddr;
dev->irq = irq;
if (!request_region(ioaddr, NI5010_IO_EXTENT, boardname))
return -EBUSY;
/*
* This is no "official" probe method, I've rather tested which
* probe works best with my seven NI5010 cards
* (they have very different serial numbers)
* Suggestions or failure reports are very, very welcome !
* But I think it is a relatively good probe method
* since it doesn't use any "outb"
* It should be nearly 100% reliable !
* well-known WARNING: this probe method (like many others)
* will hang the system if a NE2000 card region is probed !
*
* - Andreas
*/
PRINTK2((KERN_DEBUG "%s: entering ni5010_probe1(%#3x)\n",
dev->name, ioaddr));
if (inb(ioaddr+0) == 0xff)
goto out;
while ( (rd_port(ioaddr) & rd_port(ioaddr) & rd_port(ioaddr) &
rd_port(ioaddr) & rd_port(ioaddr) & rd_port(ioaddr)) != 0xff)
{
if (boguscount-- == 0)
goto out;
}
PRINTK2((KERN_DEBUG "%s: I/O #1 passed!\n", dev->name));
for (i=0; i<32; i++)
if ( (data = rd_port(ioaddr)) != 0xff) break;
if (data==0xff)
goto out;
PRINTK2((KERN_DEBUG "%s: I/O #2 passed!\n", dev->name));
if ((data != SA_ADDR0) || (rd_port(ioaddr) != SA_ADDR1) ||
(rd_port(ioaddr) != SA_ADDR2))
goto out;
for (i=0; i<4; i++)
rd_port(ioaddr);
if ( (rd_port(ioaddr) != NI5010_MAGICVAL1) ||
(rd_port(ioaddr) != NI5010_MAGICVAL2) )
goto out;
PRINTK2((KERN_DEBUG "%s: I/O #3 passed!\n", dev->name));
if (NI5010_DEBUG && version_printed++ == 0)
printk(KERN_INFO "%s", version);
printk("NI5010 ethercard probe at 0x%x: ", ioaddr);
dev->base_addr = ioaddr;
for (i=0; i<6; i++) {
outw(i, IE_GP);
dev->dev_addr[i] = inb(IE_SAPROM);
}
printk("%pM ", dev->dev_addr);
PRINTK2((KERN_DEBUG "%s: I/O #4 passed!\n", dev->name));
#ifdef JUMPERED_INTERRUPTS
if (dev->irq == 0xff)
;
else if (dev->irq < 2) {
unsigned long irq_mask;
PRINTK2((KERN_DEBUG "%s: I/O #5 passed!\n", dev->name));
irq_mask = probe_irq_on();
trigger_irq(ioaddr);
mdelay(20);
dev->irq = probe_irq_off(irq_mask);
PRINTK2((KERN_DEBUG "%s: I/O #6 passed!\n", dev->name));
if (dev->irq == 0) {
err = -EAGAIN;
printk(KERN_WARNING "%s: no IRQ found!\n", dev->name);
goto out;
}
PRINTK2((KERN_DEBUG "%s: I/O #7 passed!\n", dev->name));
} else if (dev->irq == 2) {
dev->irq = 9;
}
#endif /* JUMPERED_INTERRUPTS */
PRINTK2((KERN_DEBUG "%s: I/O #9 passed!\n", dev->name));
/* DMA is not supported (yet?), so no use detecting it */
lp = netdev_priv(dev);
spin_lock_init(&lp->lock);
PRINTK2((KERN_DEBUG "%s: I/O #10 passed!\n", dev->name));
/* get the size of the onboard receive buffer
* higher addresses than bufsize are wrapped into real buffer
* i.e. data for offs. 0x801 is written to 0x1 with a 2K onboard buffer
*/
if (!bufsize_rcv) {
outb(1, IE_MMODE); /* Put Rcv buffer on system bus */
outw(0, IE_GP); /* Point GP at start of packet */
outb(0, IE_RBUF); /* set buffer byte 0 to 0 */
for (i = 1; i < 0xff; i++) {
outw(i << 8, IE_GP); /* Point GP at packet size to be tested */
outb(i, IE_RBUF);
outw(0x0, IE_GP); /* Point GP at start of packet */
data = inb(IE_RBUF);
if (data == i) break;
}
bufsize_rcv = i << 8;
outw(0, IE_GP); /* Point GP at start of packet */
outb(0, IE_RBUF); /* set buffer byte 0 to 0 again */
}
printk("-> bufsize rcv/xmt=%d/%d\n", bufsize_rcv, NI5010_BUFSIZE);
dev->netdev_ops = &ni5010_netdev_ops;
dev->watchdog_timeo = HZ/20;
dev->flags &= ~IFF_MULTICAST; /* Multicast doesn't work */
/* Shut up the ni5010 */
outb(0, EDLC_RMASK); /* Mask all receive interrupts */
outb(0, EDLC_XMASK); /* Mask all xmit interrupts */
outb(0xff, EDLC_RCLR); /* Kill all pending rcv interrupts */
outb(0xff, EDLC_XCLR); /* Kill all pending xmt interrupts */
printk(KERN_INFO "%s: NI5010 found at 0x%x, using IRQ %d", dev->name, ioaddr, dev->irq);
if (dev->dma)
printk(" & DMA %d", dev->dma);
printk(".\n");
return 0;
out:
release_region(dev->base_addr, NI5010_IO_EXTENT);
return err;
}
/*
* 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 a non-reboot way to recover if something goes wrong.
*/
static int ni5010_open(struct net_device *dev)
{
int ioaddr = dev->base_addr;
int i;
PRINTK2((KERN_DEBUG "%s: entering ni5010_open()\n", dev->name));
if (request_irq(dev->irq, ni5010_interrupt, 0, boardname, dev)) {
printk(KERN_WARNING "%s: Cannot get irq %#2x\n", dev->name, dev->irq);
return -EAGAIN;
}
PRINTK3((KERN_DEBUG "%s: passed open() #1\n", dev->name));
/*
* Always allocate the DMA channel after the IRQ,
* and clean up on failure.
*/
#ifdef JUMPERED_DMA
if (request_dma(dev->dma, cardname)) {
printk(KERN_WARNING "%s: Cannot get dma %#2x\n", dev->name, dev->dma);
free_irq(dev->irq, NULL);
return -EAGAIN;
}
#endif /* JUMPERED_DMA */
PRINTK3((KERN_DEBUG "%s: passed open() #2\n", dev->name));
/* Reset the hardware here. Don't forget to set the station address. */
outb(RS_RESET, EDLC_RESET); /* Hold up EDLC_RESET while configing board */
outb(0, IE_RESET); /* Hardware reset of ni5010 board */
outb(XMD_LBC, EDLC_XMODE); /* Only loopback xmits */
PRINTK3((KERN_DEBUG "%s: passed open() #3\n", dev->name));
/* Set the station address */
for(i = 0;i < 6; i++) {
outb(dev->dev_addr[i], EDLC_ADDR + i);
}
PRINTK3((KERN_DEBUG "%s: Initialising ni5010\n", dev->name));
outb(0, EDLC_XMASK); /* No xmit interrupts for now */
outb(XMD_IG_PAR | XMD_T_MODE | XMD_LBC, EDLC_XMODE);
/* Normal packet xmit mode */
outb(0xff, EDLC_XCLR); /* Clear all pending xmit interrupts */
outb(RMD_BROADCAST, EDLC_RMODE);
/* Receive broadcast and normal packets */
reset_receiver(dev); /* Ready ni5010 for receiving packets */
outb(0, EDLC_RESET); /* Un-reset the ni5010 */
netif_start_queue(dev);
if (NI5010_DEBUG) ni5010_show_registers(dev);
PRINTK((KERN_DEBUG "%s: open successful\n", dev->name));
return 0;
}
static void reset_receiver(struct net_device *dev)
{
int ioaddr = dev->base_addr;
PRINTK3((KERN_DEBUG "%s: resetting receiver\n", dev->name));
outw(0, IE_GP); /* Receive packet at start of buffer */
outb(0xff, EDLC_RCLR); /* Clear all pending rcv interrupts */
outb(0, IE_MMODE); /* Put EDLC to rcv buffer */
outb(MM_EN_RCV, IE_MMODE); /* Enable rcv */
outb(0xff, EDLC_RMASK); /* Enable all rcv interrupts */
}
static void ni5010_timeout(struct net_device *dev)
{
printk(KERN_WARNING "%s: transmit timed out, %s?\n", dev->name,
tx_done(dev) ? "IRQ conflict" : "network cable problem");
/* Try to restart the adaptor. */
/* FIXME: Give it a real kick here */
chipset_init(dev, 1);
dev->trans_start = jiffies; /* prevent tx timeout */
netif_wake_queue(dev);
}
static int ni5010_send_packet(struct sk_buff *skb, struct net_device *dev)
{
int length = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
PRINTK2((KERN_DEBUG "%s: entering ni5010_send_packet\n", dev->name));
/*
* Block sending
*/
netif_stop_queue(dev);
hardware_send_packet(dev, (unsigned char *)skb->data, skb->len, length-skb->len);
dev_kfree_skb (skb);
return NETDEV_TX_OK;
}
/*
* The typical workload of the driver:
* Handle the network interface interrupts.
*/
static irqreturn_t ni5010_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct ni5010_local *lp;
int ioaddr, status;
int xmit_was_error = 0;
PRINTK2((KERN_DEBUG "%s: entering ni5010_interrupt\n", dev->name));
ioaddr = dev->base_addr;
lp = netdev_priv(dev);
spin_lock(&lp->lock);
status = inb(IE_ISTAT);
PRINTK3((KERN_DEBUG "%s: IE_ISTAT = %#02x\n", dev->name, status));
if ((status & IS_R_INT) == 0) ni5010_rx(dev);
if ((status & IS_X_INT) == 0) {
xmit_was_error = process_xmt_interrupt(dev);
}
if ((status & IS_DMA_INT) == 0) {
PRINTK((KERN_DEBUG "%s: DMA complete (?)\n", dev->name));
outb(0, IE_DMA_RST); /* Reset DMA int */
}
if (!xmit_was_error)
reset_receiver(dev);
spin_unlock(&lp->lock);
return IRQ_HANDLED;
}
static void dump_packet(void *buf, int len)
{
int i;
printk(KERN_DEBUG "Packet length = %#4x\n", len);
for (i = 0; i < len; i++){
if (i % 16 == 0) printk(KERN_DEBUG "%#4.4x", i);
if (i % 2 == 0) printk(" ");
printk("%2.2x", ((unsigned char *)buf)[i]);
if (i % 16 == 15) printk("\n");
}
printk("\n");
}
/* We have a good packet, get it out of the buffer. */
static void ni5010_rx(struct net_device *dev)
{
int ioaddr = dev->base_addr;
unsigned char rcv_stat;
struct sk_buff *skb;
int i_pkt_size;
PRINTK2((KERN_DEBUG "%s: entering ni5010_rx()\n", dev->name));
rcv_stat = inb(EDLC_RSTAT);
PRINTK3((KERN_DEBUG "%s: EDLC_RSTAT = %#2x\n", dev->name, rcv_stat));
if ( (rcv_stat & RS_VALID_BITS) != RS_PKT_OK) {
PRINTK((KERN_INFO "%s: receive error.\n", dev->name));
dev->stats.rx_errors++;
if (rcv_stat & RS_RUNT) dev->stats.rx_length_errors++;
if (rcv_stat & RS_ALIGN) dev->stats.rx_frame_errors++;
if (rcv_stat & RS_CRC_ERR) dev->stats.rx_crc_errors++;
if (rcv_stat & RS_OFLW) dev->stats.rx_fifo_errors++;
outb(0xff, EDLC_RCLR); /* Clear the interrupt */
return;
}
outb(0xff, EDLC_RCLR); /* Clear the interrupt */
i_pkt_size = inw(IE_RCNT);
if (i_pkt_size > ETH_FRAME_LEN || i_pkt_size < 10 ) {
PRINTK((KERN_DEBUG "%s: Packet size error, packet size = %#4.4x\n",
dev->name, i_pkt_size));
dev->stats.rx_errors++;
dev->stats.rx_length_errors++;
return;
}
/* Malloc up new buffer. */
skb = netdev_alloc_skb(dev, i_pkt_size + 3);
if (skb == NULL) {
printk(KERN_WARNING "%s: Memory squeeze, dropping packet.\n", dev->name);
dev->stats.rx_dropped++;
return;
}
skb_reserve(skb, 2);
/* Read packet into buffer */
outb(MM_MUX, IE_MMODE); /* Rcv buffer to system bus */
outw(0, IE_GP); /* Seek to beginning of packet */
insb(IE_RBUF, skb_put(skb, i_pkt_size), i_pkt_size);
if (NI5010_DEBUG >= 4)
dump_packet(skb->data, skb->len);
skb->protocol = eth_type_trans(skb,dev);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += i_pkt_size;
PRINTK2((KERN_DEBUG "%s: Received packet, size=%#4.4x\n",
dev->name, i_pkt_size));
}
static int process_xmt_interrupt(struct net_device *dev)
{
struct ni5010_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
int xmit_stat;
PRINTK2((KERN_DEBUG "%s: entering process_xmt_interrupt\n", dev->name));
xmit_stat = inb(EDLC_XSTAT);
PRINTK3((KERN_DEBUG "%s: EDLC_XSTAT = %2.2x\n", dev->name, xmit_stat));
outb(0, EDLC_XMASK); /* Disable xmit IRQ's */
outb(0xff, EDLC_XCLR); /* Clear all pending xmit IRQ's */
if (xmit_stat & XS_COLL){
PRINTK((KERN_DEBUG "%s: collision detected, retransmitting\n",
dev->name));
outw(NI5010_BUFSIZE - lp->o_pkt_size, IE_GP);
/* outb(0, IE_MMODE); */ /* xmt buf on sysbus FIXME: needed ? */
outb(MM_EN_XMT | MM_MUX, IE_MMODE);
outb(XM_ALL, EDLC_XMASK); /* Enable xmt IRQ's */
dev->stats.collisions++;
return 1;
}
/* FIXME: handle other xmt error conditions */
dev->stats.tx_packets++;
dev->stats.tx_bytes += lp->o_pkt_size;
netif_wake_queue(dev);
PRINTK2((KERN_DEBUG "%s: sent packet, size=%#4.4x\n",
dev->name, lp->o_pkt_size));
return 0;
}
/* The inverse routine to ni5010_open(). */
static int ni5010_close(struct net_device *dev)
{
int ioaddr = dev->base_addr;
PRINTK2((KERN_DEBUG "%s: entering ni5010_close\n", dev->name));
#ifdef JUMPERED_INTERRUPTS
free_irq(dev->irq, NULL);
#endif
/* Put card in held-RESET state */
outb(0, IE_MMODE);
outb(RS_RESET, EDLC_RESET);
netif_stop_queue(dev);
PRINTK((KERN_DEBUG "%s: %s closed down\n", dev->name, boardname));
return 0;
}
/* Set or clear the multicast filter for this adaptor.
num_addrs == -1 Promiscuous mode, receive all packets
num_addrs == 0 Normal mode, clear multicast list
num_addrs > 0 Multicast mode, receive normal and MC packets, and do
best-effort filtering.
*/
static void ni5010_set_multicast_list(struct net_device *dev)
{
short ioaddr = dev->base_addr;
PRINTK2((KERN_DEBUG "%s: entering set_multicast_list\n", dev->name));
if (dev->flags & IFF_PROMISC || dev->flags & IFF_ALLMULTI ||
!netdev_mc_empty(dev)) {
outb(RMD_PROMISC, EDLC_RMODE); /* Enable promiscuous mode */
PRINTK((KERN_DEBUG "%s: Entering promiscuous mode\n", dev->name));
} else {
PRINTK((KERN_DEBUG "%s: Entering broadcast mode\n", dev->name));
outb(RMD_BROADCAST, EDLC_RMODE); /* Disable promiscuous mode, use normal mode */
}
}
static void hardware_send_packet(struct net_device *dev, char *buf, int length, int pad)
{
struct ni5010_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
unsigned long flags;
unsigned int buf_offs;
PRINTK2((KERN_DEBUG "%s: entering hardware_send_packet\n", dev->name));
if (length > ETH_FRAME_LEN) {
PRINTK((KERN_WARNING "%s: packet too large, not possible\n",
dev->name));
return;
}
if (NI5010_DEBUG) ni5010_show_registers(dev);
if (inb(IE_ISTAT) & IS_EN_XMT) {
PRINTK((KERN_WARNING "%s: sending packet while already transmitting, not possible\n",
dev->name));
return;
}
if (NI5010_DEBUG > 3) dump_packet(buf, length);
buf_offs = NI5010_BUFSIZE - length - pad;
spin_lock_irqsave(&lp->lock, flags);
lp->o_pkt_size = length + pad;
outb(0, EDLC_RMASK); /* Mask all receive interrupts */
outb(0, IE_MMODE); /* Put Xmit buffer on system bus */
outb(0xff, EDLC_RCLR); /* Clear out pending rcv interrupts */
outw(buf_offs, IE_GP); /* Point GP at start of packet */
outsb(IE_XBUF, buf, length); /* Put data in buffer */
while(pad--)
outb(0, IE_XBUF);
outw(buf_offs, IE_GP); /* Rewrite where packet starts */
/* should work without that outb() (Crynwr used it) */
/*outb(MM_MUX, IE_MMODE);*/ /* Xmt buffer to EDLC bus */
outb(MM_EN_XMT | MM_MUX, IE_MMODE); /* Begin transmission */
outb(XM_ALL, EDLC_XMASK); /* Cause interrupt after completion or fail */
spin_unlock_irqrestore(&lp->lock, flags);
netif_wake_queue(dev);
if (NI5010_DEBUG) ni5010_show_registers(dev);
}
static void chipset_init(struct net_device *dev, int startp)
{
/* FIXME: Move some stuff here */
PRINTK3((KERN_DEBUG "%s: doing NOTHING in chipset_init\n", dev->name));
}
static void ni5010_show_registers(struct net_device *dev)
{
int ioaddr = dev->base_addr;
PRINTK3((KERN_DEBUG "%s: XSTAT %#2.2x\n", dev->name, inb(EDLC_XSTAT)));
PRINTK3((KERN_DEBUG "%s: XMASK %#2.2x\n", dev->name, inb(EDLC_XMASK)));
PRINTK3((KERN_DEBUG "%s: RSTAT %#2.2x\n", dev->name, inb(EDLC_RSTAT)));
PRINTK3((KERN_DEBUG "%s: RMASK %#2.2x\n", dev->name, inb(EDLC_RMASK)));
PRINTK3((KERN_DEBUG "%s: RMODE %#2.2x\n", dev->name, inb(EDLC_RMODE)));
PRINTK3((KERN_DEBUG "%s: XMODE %#2.2x\n", dev->name, inb(EDLC_XMODE)));
PRINTK3((KERN_DEBUG "%s: ISTAT %#2.2x\n", dev->name, inb(IE_ISTAT)));
}
#ifdef MODULE
static struct net_device *dev_ni5010;
module_param(io, int, 0);
module_param(irq, int, 0);
MODULE_PARM_DESC(io, "ni5010 I/O base address");
MODULE_PARM_DESC(irq, "ni5010 IRQ number");
static int __init ni5010_init_module(void)
{
PRINTK2((KERN_DEBUG "%s: entering init_module\n", boardname));
/*
if(io <= 0 || irq == 0){
printk(KERN_WARNING "%s: Autoprobing not allowed for modules.\n", boardname);
printk(KERN_WARNING "%s: Set symbols 'io' and 'irq'\n", boardname);
return -EINVAL;
}
*/
if (io <= 0){
printk(KERN_WARNING "%s: Autoprobing for modules is hazardous, trying anyway..\n", boardname);
}
PRINTK2((KERN_DEBUG "%s: init_module irq=%#2x, io=%#3x\n", boardname, irq, io));
dev_ni5010 = ni5010_probe(-1);
if (IS_ERR(dev_ni5010))
return PTR_ERR(dev_ni5010);
return 0;
}
static void __exit ni5010_cleanup_module(void)
{
PRINTK2((KERN_DEBUG "%s: entering cleanup_module\n", boardname));
unregister_netdev(dev_ni5010);
release_region(dev_ni5010->base_addr, NI5010_IO_EXTENT);
free_netdev(dev_ni5010);
}
module_init(ni5010_init_module);
module_exit(ni5010_cleanup_module);
#endif /* MODULE */
MODULE_LICENSE("GPL");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.