repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
CheckYourScreen/Arsenic.Kernel_onyx-oos | arch/arm/nwfpe/single_cpdo.c | 15000 | 3563 | /*
NetWinder Floating Point Emulator
(c) Rebel.COM, 1998,1999
(c) Philip Blundell, 2001
Direct questions, comments to Scott Bambrough <scottb@netwinder.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 "fpa11.h"
#include "softfloat.h"
#include "fpopcode.h"
float32 float32_exp(float32 Fm);
float32 float32_ln(float32 Fm);
float32 float32_sin(float32 rFm);
float32 float32_cos(float32 rFm);
float32 float32_arcsin(float32 rFm);
float32 float32_arctan(float32 rFm);
float32 float32_log(float32 rFm);
float32 float32_tan(float32 rFm);
float32 float32_arccos(float32 rFm);
float32 float32_pow(float32 rFn, float32 rFm);
float32 float32_pol(float32 rFn, float32 rFm);
static float32 float32_rsf(struct roundingData *roundData, float32 rFn, float32 rFm)
{
return float32_sub(roundData, rFm, rFn);
}
static float32 float32_rdv(struct roundingData *roundData, float32 rFn, float32 rFm)
{
return float32_div(roundData, rFm, rFn);
}
static float32 (*const dyadic_single[16])(struct roundingData *, float32 rFn, float32 rFm) = {
[ADF_CODE >> 20] = float32_add,
[MUF_CODE >> 20] = float32_mul,
[SUF_CODE >> 20] = float32_sub,
[RSF_CODE >> 20] = float32_rsf,
[DVF_CODE >> 20] = float32_div,
[RDF_CODE >> 20] = float32_rdv,
[RMF_CODE >> 20] = float32_rem,
[FML_CODE >> 20] = float32_mul,
[FDV_CODE >> 20] = float32_div,
[FRD_CODE >> 20] = float32_rdv,
};
static float32 float32_mvf(struct roundingData *roundData, float32 rFm)
{
return rFm;
}
static float32 float32_mnf(struct roundingData *roundData, float32 rFm)
{
return rFm ^ 0x80000000;
}
static float32 float32_abs(struct roundingData *roundData, float32 rFm)
{
return rFm & 0x7fffffff;
}
static float32 (*const monadic_single[16])(struct roundingData*, float32 rFm) = {
[MVF_CODE >> 20] = float32_mvf,
[MNF_CODE >> 20] = float32_mnf,
[ABS_CODE >> 20] = float32_abs,
[RND_CODE >> 20] = float32_round_to_int,
[URD_CODE >> 20] = float32_round_to_int,
[SQT_CODE >> 20] = float32_sqrt,
[NRM_CODE >> 20] = float32_mvf,
};
unsigned int SingleCPDO(struct roundingData *roundData, const unsigned int opcode, FPREG * rFd)
{
FPA11 *fpa11 = GET_FPA11();
float32 rFm;
unsigned int Fm, opc_mask_shift;
Fm = getFm(opcode);
if (CONSTANT_FM(opcode)) {
rFm = getSingleConstant(Fm);
} else if (fpa11->fType[Fm] == typeSingle) {
rFm = fpa11->fpreg[Fm].fSingle;
} else {
return 0;
}
opc_mask_shift = (opcode & MASK_ARITHMETIC_OPCODE) >> 20;
if (!MONADIC_INSTRUCTION(opcode)) {
unsigned int Fn = getFn(opcode);
float32 rFn;
if (fpa11->fType[Fn] == typeSingle &&
dyadic_single[opc_mask_shift]) {
rFn = fpa11->fpreg[Fn].fSingle;
rFd->fSingle = dyadic_single[opc_mask_shift](roundData, rFn, rFm);
} else {
return 0;
}
} else {
if (monadic_single[opc_mask_shift]) {
rFd->fSingle = monadic_single[opc_mask_shift](roundData, rFm);
} else {
return 0;
}
}
return 1;
}
| gpl-2.0 |
oscardagrach/linux | drivers/net/can/grcan.c | 153 | 50892 | /*
* Socket CAN driver for Aeroflex Gaisler GRCAN and GRHCAN.
*
* 2012 (c) Aeroflex Gaisler AB
*
* This driver supports GRCAN and GRHCAN CAN controllers available in the GRLIB
* VHDL IP core library.
*
* Full documentation of the GRCAN core can be found here:
* http://www.gaisler.com/products/grlib/grip.pdf
*
* See "Documentation/devicetree/bindings/net/can/grcan.txt" for information on
* open firmware properties.
*
* See "Documentation/ABI/testing/sysfs-class-net-grcan" for information on the
* sysfs interface.
*
* See "Documentation/admin-guide/kernel-parameters.rst" for information on the module
* parameters.
*
* 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.
*
* Contributors: Andreas Larsson <andreas@gaisler.com>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/can/dev.h>
#include <linux/spinlock.h>
#include <linux/of_platform.h>
#include <linux/of_irq.h>
#include <linux/dma-mapping.h>
#define DRV_NAME "grcan"
#define GRCAN_NAPI_WEIGHT 32
#define GRCAN_RESERVE_SIZE(slot1, slot2) (((slot2) - (slot1)) / 4 - 1)
struct grcan_registers {
u32 conf; /* 0x00 */
u32 stat; /* 0x04 */
u32 ctrl; /* 0x08 */
u32 __reserved1[GRCAN_RESERVE_SIZE(0x08, 0x18)];
u32 smask; /* 0x18 - CanMASK */
u32 scode; /* 0x1c - CanCODE */
u32 __reserved2[GRCAN_RESERVE_SIZE(0x1c, 0x100)];
u32 pimsr; /* 0x100 */
u32 pimr; /* 0x104 */
u32 pisr; /* 0x108 */
u32 pir; /* 0x10C */
u32 imr; /* 0x110 */
u32 picr; /* 0x114 */
u32 __reserved3[GRCAN_RESERVE_SIZE(0x114, 0x200)];
u32 txctrl; /* 0x200 */
u32 txaddr; /* 0x204 */
u32 txsize; /* 0x208 */
u32 txwr; /* 0x20C */
u32 txrd; /* 0x210 */
u32 txirq; /* 0x214 */
u32 __reserved4[GRCAN_RESERVE_SIZE(0x214, 0x300)];
u32 rxctrl; /* 0x300 */
u32 rxaddr; /* 0x304 */
u32 rxsize; /* 0x308 */
u32 rxwr; /* 0x30C */
u32 rxrd; /* 0x310 */
u32 rxirq; /* 0x314 */
u32 rxmask; /* 0x318 */
u32 rxcode; /* 0x31C */
};
#define GRCAN_CONF_ABORT 0x00000001
#define GRCAN_CONF_ENABLE0 0x00000002
#define GRCAN_CONF_ENABLE1 0x00000004
#define GRCAN_CONF_SELECT 0x00000008
#define GRCAN_CONF_SILENT 0x00000010
#define GRCAN_CONF_SAM 0x00000020 /* Available in some hardware */
#define GRCAN_CONF_BPR 0x00000300 /* Note: not BRP */
#define GRCAN_CONF_RSJ 0x00007000
#define GRCAN_CONF_PS1 0x00f00000
#define GRCAN_CONF_PS2 0x000f0000
#define GRCAN_CONF_SCALER 0xff000000
#define GRCAN_CONF_OPERATION \
(GRCAN_CONF_ABORT | GRCAN_CONF_ENABLE0 | GRCAN_CONF_ENABLE1 \
| GRCAN_CONF_SELECT | GRCAN_CONF_SILENT | GRCAN_CONF_SAM)
#define GRCAN_CONF_TIMING \
(GRCAN_CONF_BPR | GRCAN_CONF_RSJ | GRCAN_CONF_PS1 \
| GRCAN_CONF_PS2 | GRCAN_CONF_SCALER)
#define GRCAN_CONF_RSJ_MIN 1
#define GRCAN_CONF_RSJ_MAX 4
#define GRCAN_CONF_PS1_MIN 1
#define GRCAN_CONF_PS1_MAX 15
#define GRCAN_CONF_PS2_MIN 2
#define GRCAN_CONF_PS2_MAX 8
#define GRCAN_CONF_SCALER_MIN 0
#define GRCAN_CONF_SCALER_MAX 255
#define GRCAN_CONF_SCALER_INC 1
#define GRCAN_CONF_BPR_BIT 8
#define GRCAN_CONF_RSJ_BIT 12
#define GRCAN_CONF_PS1_BIT 20
#define GRCAN_CONF_PS2_BIT 16
#define GRCAN_CONF_SCALER_BIT 24
#define GRCAN_STAT_PASS 0x000001
#define GRCAN_STAT_OFF 0x000002
#define GRCAN_STAT_OR 0x000004
#define GRCAN_STAT_AHBERR 0x000008
#define GRCAN_STAT_ACTIVE 0x000010
#define GRCAN_STAT_RXERRCNT 0x00ff00
#define GRCAN_STAT_TXERRCNT 0xff0000
#define GRCAN_STAT_ERRCTR_RELATED (GRCAN_STAT_PASS | GRCAN_STAT_OFF)
#define GRCAN_STAT_RXERRCNT_BIT 8
#define GRCAN_STAT_TXERRCNT_BIT 16
#define GRCAN_STAT_ERRCNT_WARNING_LIMIT 96
#define GRCAN_STAT_ERRCNT_PASSIVE_LIMIT 127
#define GRCAN_CTRL_RESET 0x2
#define GRCAN_CTRL_ENABLE 0x1
#define GRCAN_TXCTRL_ENABLE 0x1
#define GRCAN_TXCTRL_ONGOING 0x2
#define GRCAN_TXCTRL_SINGLE 0x4
#define GRCAN_RXCTRL_ENABLE 0x1
#define GRCAN_RXCTRL_ONGOING 0x2
/* Relative offset of IRQ sources to AMBA Plug&Play */
#define GRCAN_IRQIX_IRQ 0
#define GRCAN_IRQIX_TXSYNC 1
#define GRCAN_IRQIX_RXSYNC 2
#define GRCAN_IRQ_PASS 0x00001
#define GRCAN_IRQ_OFF 0x00002
#define GRCAN_IRQ_OR 0x00004
#define GRCAN_IRQ_RXAHBERR 0x00008
#define GRCAN_IRQ_TXAHBERR 0x00010
#define GRCAN_IRQ_RXIRQ 0x00020
#define GRCAN_IRQ_TXIRQ 0x00040
#define GRCAN_IRQ_RXFULL 0x00080
#define GRCAN_IRQ_TXEMPTY 0x00100
#define GRCAN_IRQ_RX 0x00200
#define GRCAN_IRQ_TX 0x00400
#define GRCAN_IRQ_RXSYNC 0x00800
#define GRCAN_IRQ_TXSYNC 0x01000
#define GRCAN_IRQ_RXERRCTR 0x02000
#define GRCAN_IRQ_TXERRCTR 0x04000
#define GRCAN_IRQ_RXMISS 0x08000
#define GRCAN_IRQ_TXLOSS 0x10000
#define GRCAN_IRQ_NONE 0
#define GRCAN_IRQ_ALL \
(GRCAN_IRQ_PASS | GRCAN_IRQ_OFF | GRCAN_IRQ_OR \
| GRCAN_IRQ_RXAHBERR | GRCAN_IRQ_TXAHBERR \
| GRCAN_IRQ_RXIRQ | GRCAN_IRQ_TXIRQ \
| GRCAN_IRQ_RXFULL | GRCAN_IRQ_TXEMPTY \
| GRCAN_IRQ_RX | GRCAN_IRQ_TX | GRCAN_IRQ_RXSYNC \
| GRCAN_IRQ_TXSYNC | GRCAN_IRQ_RXERRCTR \
| GRCAN_IRQ_TXERRCTR | GRCAN_IRQ_RXMISS \
| GRCAN_IRQ_TXLOSS)
#define GRCAN_IRQ_ERRCTR_RELATED (GRCAN_IRQ_RXERRCTR | GRCAN_IRQ_TXERRCTR \
| GRCAN_IRQ_PASS | GRCAN_IRQ_OFF)
#define GRCAN_IRQ_ERRORS (GRCAN_IRQ_ERRCTR_RELATED | GRCAN_IRQ_OR \
| GRCAN_IRQ_TXAHBERR | GRCAN_IRQ_RXAHBERR \
| GRCAN_IRQ_TXLOSS)
#define GRCAN_IRQ_DEFAULT (GRCAN_IRQ_RX | GRCAN_IRQ_TX | GRCAN_IRQ_ERRORS)
#define GRCAN_MSG_SIZE 16
#define GRCAN_MSG_IDE 0x80000000
#define GRCAN_MSG_RTR 0x40000000
#define GRCAN_MSG_BID 0x1ffc0000
#define GRCAN_MSG_EID 0x1fffffff
#define GRCAN_MSG_IDE_BIT 31
#define GRCAN_MSG_RTR_BIT 30
#define GRCAN_MSG_BID_BIT 18
#define GRCAN_MSG_EID_BIT 0
#define GRCAN_MSG_DLC 0xf0000000
#define GRCAN_MSG_TXERRC 0x00ff0000
#define GRCAN_MSG_RXERRC 0x0000ff00
#define GRCAN_MSG_DLC_BIT 28
#define GRCAN_MSG_TXERRC_BIT 16
#define GRCAN_MSG_RXERRC_BIT 8
#define GRCAN_MSG_AHBERR 0x00000008
#define GRCAN_MSG_OR 0x00000004
#define GRCAN_MSG_OFF 0x00000002
#define GRCAN_MSG_PASS 0x00000001
#define GRCAN_MSG_DATA_SLOT_INDEX(i) (2 + (i) / 4)
#define GRCAN_MSG_DATA_SHIFT(i) ((3 - (i) % 4) * 8)
#define GRCAN_BUFFER_ALIGNMENT 1024
#define GRCAN_DEFAULT_BUFFER_SIZE 1024
#define GRCAN_VALID_TR_SIZE_MASK 0x001fffc0
#define GRCAN_INVALID_BUFFER_SIZE(s) \
((s) == 0 || ((s) & ~GRCAN_VALID_TR_SIZE_MASK))
#if GRCAN_INVALID_BUFFER_SIZE(GRCAN_DEFAULT_BUFFER_SIZE)
#error "Invalid default buffer size"
#endif
struct grcan_dma_buffer {
size_t size;
void *buf;
dma_addr_t handle;
};
struct grcan_dma {
size_t base_size;
void *base_buf;
dma_addr_t base_handle;
struct grcan_dma_buffer tx;
struct grcan_dma_buffer rx;
};
/* GRCAN configuration parameters */
struct grcan_device_config {
unsigned short enable0;
unsigned short enable1;
unsigned short select;
unsigned int txsize;
unsigned int rxsize;
};
#define GRCAN_DEFAULT_DEVICE_CONFIG { \
.enable0 = 0, \
.enable1 = 0, \
.select = 0, \
.txsize = GRCAN_DEFAULT_BUFFER_SIZE, \
.rxsize = GRCAN_DEFAULT_BUFFER_SIZE, \
}
#define GRCAN_TXBUG_SAFE_GRLIB_VERSION 0x4100
#define GRLIB_VERSION_MASK 0xffff
/* GRCAN private data structure */
struct grcan_priv {
struct can_priv can; /* must be the first member */
struct net_device *dev;
struct napi_struct napi;
struct grcan_registers __iomem *regs; /* ioremap'ed registers */
struct grcan_device_config config;
struct grcan_dma dma;
struct sk_buff **echo_skb; /* We allocate this on our own */
u8 *txdlc; /* Length of queued frames */
/* The echo skb pointer, pointing into echo_skb and indicating which
* frames can be echoed back. See the "Notes on the tx cyclic buffer
* handling"-comment for grcan_start_xmit for more details.
*/
u32 eskbp;
/* Lock for controlling changes to the netif tx queue state, accesses to
* the echo_skb pointer eskbp and for making sure that a running reset
* and/or a close of the interface is done without interference from
* other parts of the code.
*
* The echo_skb pointer, eskbp, should only be accessed under this lock
* as it can be changed in several places and together with decisions on
* whether to wake up the tx queue.
*
* The tx queue must never be woken up if there is a running reset or
* close in progress.
*
* A running reset (see below on need_txbug_workaround) should never be
* done if the interface is closing down and several running resets
* should never be scheduled simultaneously.
*/
spinlock_t lock;
/* Whether a workaround is needed due to a bug in older hardware. In
* this case, the driver both tries to prevent the bug from being
* triggered and recovers, if the bug nevertheless happens, by doing a
* running reset. A running reset, resets the device and continues from
* where it were without being noticeable from outside the driver (apart
* from slight delays).
*/
bool need_txbug_workaround;
/* To trigger initization of running reset and to trigger running reset
* respectively in the case of a hanged device due to a txbug.
*/
struct timer_list hang_timer;
struct timer_list rr_timer;
/* To avoid waking up the netif queue and restarting timers
* when a reset is scheduled or when closing of the device is
* undergoing
*/
bool resetting;
bool closing;
};
/* Wait time for a short wait for ongoing to clear */
#define GRCAN_SHORTWAIT_USECS 10
/* Limit on the number of transmitted bits of an eff frame according to the CAN
* specification: 1 bit start of frame, 32 bits arbitration field, 6 bits
* control field, 8 bytes data field, 16 bits crc field, 2 bits ACK field and 7
* bits end of frame
*/
#define GRCAN_EFF_FRAME_MAX_BITS (1+32+6+8*8+16+2+7)
#if defined(__BIG_ENDIAN)
static inline u32 grcan_read_reg(u32 __iomem *reg)
{
return ioread32be(reg);
}
static inline void grcan_write_reg(u32 __iomem *reg, u32 val)
{
iowrite32be(val, reg);
}
#else
static inline u32 grcan_read_reg(u32 __iomem *reg)
{
return ioread32(reg);
}
static inline void grcan_write_reg(u32 __iomem *reg, u32 val)
{
iowrite32(val, reg);
}
#endif
static inline void grcan_clear_bits(u32 __iomem *reg, u32 mask)
{
grcan_write_reg(reg, grcan_read_reg(reg) & ~mask);
}
static inline void grcan_set_bits(u32 __iomem *reg, u32 mask)
{
grcan_write_reg(reg, grcan_read_reg(reg) | mask);
}
static inline u32 grcan_read_bits(u32 __iomem *reg, u32 mask)
{
return grcan_read_reg(reg) & mask;
}
static inline void grcan_write_bits(u32 __iomem *reg, u32 value, u32 mask)
{
u32 old = grcan_read_reg(reg);
grcan_write_reg(reg, (old & ~mask) | (value & mask));
}
/* a and b should both be in [0,size] and a == b == size should not hold */
static inline u32 grcan_ring_add(u32 a, u32 b, u32 size)
{
u32 sum = a + b;
if (sum < size)
return sum;
else
return sum - size;
}
/* a and b should both be in [0,size) */
static inline u32 grcan_ring_sub(u32 a, u32 b, u32 size)
{
return grcan_ring_add(a, size - b, size);
}
/* Available slots for new transmissions */
static inline u32 grcan_txspace(size_t txsize, u32 txwr, u32 eskbp)
{
u32 slots = txsize / GRCAN_MSG_SIZE - 1;
u32 used = grcan_ring_sub(txwr, eskbp, txsize) / GRCAN_MSG_SIZE;
return slots - used;
}
/* Configuration parameters that can be set via module parameters */
static struct grcan_device_config grcan_module_config =
GRCAN_DEFAULT_DEVICE_CONFIG;
static const struct can_bittiming_const grcan_bittiming_const = {
.name = DRV_NAME,
.tseg1_min = GRCAN_CONF_PS1_MIN + 1,
.tseg1_max = GRCAN_CONF_PS1_MAX + 1,
.tseg2_min = GRCAN_CONF_PS2_MIN,
.tseg2_max = GRCAN_CONF_PS2_MAX,
.sjw_max = GRCAN_CONF_RSJ_MAX,
.brp_min = GRCAN_CONF_SCALER_MIN + 1,
.brp_max = GRCAN_CONF_SCALER_MAX + 1,
.brp_inc = GRCAN_CONF_SCALER_INC,
};
static int grcan_set_bittiming(struct net_device *dev)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
struct can_bittiming *bt = &priv->can.bittiming;
u32 timing = 0;
int bpr, rsj, ps1, ps2, scaler;
/* Should never happen - function will not be called when
* device is up
*/
if (grcan_read_bits(®s->ctrl, GRCAN_CTRL_ENABLE))
return -EBUSY;
bpr = 0; /* Note bpr and brp are different concepts */
rsj = bt->sjw;
ps1 = (bt->prop_seg + bt->phase_seg1) - 1; /* tseg1 - 1 */
ps2 = bt->phase_seg2;
scaler = (bt->brp - 1);
netdev_dbg(dev, "Request for BPR=%d, RSJ=%d, PS1=%d, PS2=%d, SCALER=%d",
bpr, rsj, ps1, ps2, scaler);
if (!(ps1 > ps2)) {
netdev_err(dev, "PS1 > PS2 must hold: PS1=%d, PS2=%d\n",
ps1, ps2);
return -EINVAL;
}
if (!(ps2 >= rsj)) {
netdev_err(dev, "PS2 >= RSJ must hold: PS2=%d, RSJ=%d\n",
ps2, rsj);
return -EINVAL;
}
timing |= (bpr << GRCAN_CONF_BPR_BIT) & GRCAN_CONF_BPR;
timing |= (rsj << GRCAN_CONF_RSJ_BIT) & GRCAN_CONF_RSJ;
timing |= (ps1 << GRCAN_CONF_PS1_BIT) & GRCAN_CONF_PS1;
timing |= (ps2 << GRCAN_CONF_PS2_BIT) & GRCAN_CONF_PS2;
timing |= (scaler << GRCAN_CONF_SCALER_BIT) & GRCAN_CONF_SCALER;
netdev_info(dev, "setting timing=0x%x\n", timing);
grcan_write_bits(®s->conf, timing, GRCAN_CONF_TIMING);
return 0;
}
static int grcan_get_berr_counter(const struct net_device *dev,
struct can_berr_counter *bec)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
u32 status = grcan_read_reg(®s->stat);
bec->txerr = (status & GRCAN_STAT_TXERRCNT) >> GRCAN_STAT_TXERRCNT_BIT;
bec->rxerr = (status & GRCAN_STAT_RXERRCNT) >> GRCAN_STAT_RXERRCNT_BIT;
return 0;
}
static int grcan_poll(struct napi_struct *napi, int budget);
/* Reset device, but keep configuration information */
static void grcan_reset(struct net_device *dev)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
u32 config = grcan_read_reg(®s->conf);
grcan_set_bits(®s->ctrl, GRCAN_CTRL_RESET);
grcan_write_reg(®s->conf, config);
priv->eskbp = grcan_read_reg(®s->txrd);
priv->can.state = CAN_STATE_STOPPED;
/* Turn off hardware filtering - regs->rxcode set to 0 by reset */
grcan_write_reg(®s->rxmask, 0);
}
/* stop device without changing any configurations */
static void grcan_stop_hardware(struct net_device *dev)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
grcan_write_reg(®s->imr, GRCAN_IRQ_NONE);
grcan_clear_bits(®s->txctrl, GRCAN_TXCTRL_ENABLE);
grcan_clear_bits(®s->rxctrl, GRCAN_RXCTRL_ENABLE);
grcan_clear_bits(®s->ctrl, GRCAN_CTRL_ENABLE);
}
/* Let priv->eskbp catch up to regs->txrd and echo back the skbs if echo
* is true and free them otherwise.
*
* If budget is >= 0, stop after handling at most budget skbs. Otherwise,
* continue until priv->eskbp catches up to regs->txrd.
*
* priv->lock *must* be held when calling this function
*/
static int catch_up_echo_skb(struct net_device *dev, int budget, bool echo)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
struct grcan_dma *dma = &priv->dma;
struct net_device_stats *stats = &dev->stats;
int i, work_done;
/* Updates to priv->eskbp and wake-ups of the queue needs to
* be atomic towards the reads of priv->eskbp and shut-downs
* of the queue in grcan_start_xmit.
*/
u32 txrd = grcan_read_reg(®s->txrd);
for (work_done = 0; work_done < budget || budget < 0; work_done++) {
if (priv->eskbp == txrd)
break;
i = priv->eskbp / GRCAN_MSG_SIZE;
if (echo) {
/* Normal echo of messages */
stats->tx_packets++;
stats->tx_bytes += priv->txdlc[i];
priv->txdlc[i] = 0;
can_get_echo_skb(dev, i);
} else {
/* For cleanup of untransmitted messages */
can_free_echo_skb(dev, i);
}
priv->eskbp = grcan_ring_add(priv->eskbp, GRCAN_MSG_SIZE,
dma->tx.size);
txrd = grcan_read_reg(®s->txrd);
}
return work_done;
}
static void grcan_lost_one_shot_frame(struct net_device *dev)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
struct grcan_dma *dma = &priv->dma;
u32 txrd;
unsigned long flags;
spin_lock_irqsave(&priv->lock, flags);
catch_up_echo_skb(dev, -1, true);
if (unlikely(grcan_read_bits(®s->txctrl, GRCAN_TXCTRL_ENABLE))) {
/* Should never happen */
netdev_err(dev, "TXCTRL enabled at TXLOSS in one shot mode\n");
} else {
/* By the time an GRCAN_IRQ_TXLOSS is generated in
* one-shot mode there is no problem in writing
* to TXRD even in versions of the hardware in
* which GRCAN_TXCTRL_ONGOING is not cleared properly
* in one-shot mode.
*/
/* Skip message and discard echo-skb */
txrd = grcan_read_reg(®s->txrd);
txrd = grcan_ring_add(txrd, GRCAN_MSG_SIZE, dma->tx.size);
grcan_write_reg(®s->txrd, txrd);
catch_up_echo_skb(dev, -1, false);
if (!priv->resetting && !priv->closing &&
!(priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)) {
netif_wake_queue(dev);
grcan_set_bits(®s->txctrl, GRCAN_TXCTRL_ENABLE);
}
}
spin_unlock_irqrestore(&priv->lock, flags);
}
static void grcan_err(struct net_device *dev, u32 sources, u32 status)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
struct grcan_dma *dma = &priv->dma;
struct net_device_stats *stats = &dev->stats;
struct can_frame cf;
/* Zero potential error_frame */
memset(&cf, 0, sizeof(cf));
/* Message lost interrupt. This might be due to arbitration error, but
* is also triggered when there is no one else on the can bus or when
* there is a problem with the hardware interface or the bus itself. As
* arbitration errors can not be singled out, no error frames are
* generated reporting this event as an arbitration error.
*/
if (sources & GRCAN_IRQ_TXLOSS) {
/* Take care of failed one-shot transmit */
if (priv->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT)
grcan_lost_one_shot_frame(dev);
/* Stop printing as soon as error passive or bus off is in
* effect to limit the amount of txloss debug printouts.
*/
if (!(status & GRCAN_STAT_ERRCTR_RELATED)) {
netdev_dbg(dev, "tx message lost\n");
stats->tx_errors++;
}
}
/* Conditions dealing with the error counters. There is no interrupt for
* error warning, but there are interrupts for increases of the error
* counters.
*/
if ((sources & GRCAN_IRQ_ERRCTR_RELATED) ||
(status & GRCAN_STAT_ERRCTR_RELATED)) {
enum can_state state = priv->can.state;
enum can_state oldstate = state;
u32 txerr = (status & GRCAN_STAT_TXERRCNT)
>> GRCAN_STAT_TXERRCNT_BIT;
u32 rxerr = (status & GRCAN_STAT_RXERRCNT)
>> GRCAN_STAT_RXERRCNT_BIT;
/* Figure out current state */
if (status & GRCAN_STAT_OFF) {
state = CAN_STATE_BUS_OFF;
} else if (status & GRCAN_STAT_PASS) {
state = CAN_STATE_ERROR_PASSIVE;
} else if (txerr >= GRCAN_STAT_ERRCNT_WARNING_LIMIT ||
rxerr >= GRCAN_STAT_ERRCNT_WARNING_LIMIT) {
state = CAN_STATE_ERROR_WARNING;
} else {
state = CAN_STATE_ERROR_ACTIVE;
}
/* Handle and report state changes */
if (state != oldstate) {
switch (state) {
case CAN_STATE_BUS_OFF:
netdev_dbg(dev, "bus-off\n");
netif_carrier_off(dev);
priv->can.can_stats.bus_off++;
/* Prevent the hardware from recovering from bus
* off on its own if restart is disabled.
*/
if (!priv->can.restart_ms)
grcan_stop_hardware(dev);
cf.can_id |= CAN_ERR_BUSOFF;
break;
case CAN_STATE_ERROR_PASSIVE:
netdev_dbg(dev, "Error passive condition\n");
priv->can.can_stats.error_passive++;
cf.can_id |= CAN_ERR_CRTL;
if (txerr >= GRCAN_STAT_ERRCNT_PASSIVE_LIMIT)
cf.data[1] |= CAN_ERR_CRTL_TX_PASSIVE;
if (rxerr >= GRCAN_STAT_ERRCNT_PASSIVE_LIMIT)
cf.data[1] |= CAN_ERR_CRTL_RX_PASSIVE;
break;
case CAN_STATE_ERROR_WARNING:
netdev_dbg(dev, "Error warning condition\n");
priv->can.can_stats.error_warning++;
cf.can_id |= CAN_ERR_CRTL;
if (txerr >= GRCAN_STAT_ERRCNT_WARNING_LIMIT)
cf.data[1] |= CAN_ERR_CRTL_TX_WARNING;
if (rxerr >= GRCAN_STAT_ERRCNT_WARNING_LIMIT)
cf.data[1] |= CAN_ERR_CRTL_RX_WARNING;
break;
case CAN_STATE_ERROR_ACTIVE:
netdev_dbg(dev, "Error active condition\n");
cf.can_id |= CAN_ERR_CRTL;
break;
default:
/* There are no others at this point */
break;
}
cf.data[6] = txerr;
cf.data[7] = rxerr;
priv->can.state = state;
}
/* Report automatic restarts */
if (priv->can.restart_ms && oldstate == CAN_STATE_BUS_OFF) {
unsigned long flags;
cf.can_id |= CAN_ERR_RESTARTED;
netdev_dbg(dev, "restarted\n");
priv->can.can_stats.restarts++;
netif_carrier_on(dev);
spin_lock_irqsave(&priv->lock, flags);
if (!priv->resetting && !priv->closing) {
u32 txwr = grcan_read_reg(®s->txwr);
if (grcan_txspace(dma->tx.size, txwr,
priv->eskbp))
netif_wake_queue(dev);
}
spin_unlock_irqrestore(&priv->lock, flags);
}
}
/* Data overrun interrupt */
if ((sources & GRCAN_IRQ_OR) || (status & GRCAN_STAT_OR)) {
netdev_dbg(dev, "got data overrun interrupt\n");
stats->rx_over_errors++;
stats->rx_errors++;
cf.can_id |= CAN_ERR_CRTL;
cf.data[1] |= CAN_ERR_CRTL_RX_OVERFLOW;
}
/* AHB bus error interrupts (not CAN bus errors) - shut down the
* device.
*/
if (sources & (GRCAN_IRQ_TXAHBERR | GRCAN_IRQ_RXAHBERR) ||
(status & GRCAN_STAT_AHBERR)) {
char *txrx = "";
unsigned long flags;
if (sources & GRCAN_IRQ_TXAHBERR) {
txrx = "on tx ";
stats->tx_errors++;
} else if (sources & GRCAN_IRQ_RXAHBERR) {
txrx = "on rx ";
stats->rx_errors++;
}
netdev_err(dev, "Fatal AHB buss error %s- halting device\n",
txrx);
spin_lock_irqsave(&priv->lock, flags);
/* Prevent anything to be enabled again and halt device */
priv->closing = true;
netif_stop_queue(dev);
grcan_stop_hardware(dev);
priv->can.state = CAN_STATE_STOPPED;
spin_unlock_irqrestore(&priv->lock, flags);
}
/* Pass on error frame if something to report,
* i.e. id contains some information
*/
if (cf.can_id) {
struct can_frame *skb_cf;
struct sk_buff *skb = alloc_can_err_skb(dev, &skb_cf);
if (skb == NULL) {
netdev_dbg(dev, "could not allocate error frame\n");
return;
}
skb_cf->can_id |= cf.can_id;
memcpy(skb_cf->data, cf.data, sizeof(cf.data));
netif_rx(skb);
}
}
static irqreturn_t grcan_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
u32 sources, status;
/* Find out the source */
sources = grcan_read_reg(®s->pimsr);
if (!sources)
return IRQ_NONE;
grcan_write_reg(®s->picr, sources);
status = grcan_read_reg(®s->stat);
/* If we got TX progress, the device has not hanged,
* so disable the hang timer
*/
if (priv->need_txbug_workaround &&
(sources & (GRCAN_IRQ_TX | GRCAN_IRQ_TXLOSS))) {
del_timer(&priv->hang_timer);
}
/* Frame(s) received or transmitted */
if (sources & (GRCAN_IRQ_TX | GRCAN_IRQ_RX)) {
/* Disable tx/rx interrupts and schedule poll(). No need for
* locking as interference from a running reset at worst leads
* to an extra interrupt.
*/
grcan_clear_bits(®s->imr, GRCAN_IRQ_TX | GRCAN_IRQ_RX);
napi_schedule(&priv->napi);
}
/* (Potential) error conditions to take care of */
if (sources & GRCAN_IRQ_ERRORS)
grcan_err(dev, sources, status);
return IRQ_HANDLED;
}
/* Reset device and restart operations from where they were.
*
* This assumes that RXCTRL & RXCTRL is properly disabled and that RX
* is not ONGOING (TX might be stuck in ONGOING due to a harwrware bug
* for single shot)
*/
static void grcan_running_reset(unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
unsigned long flags;
/* This temporarily messes with eskbp, so we need to lock
* priv->lock
*/
spin_lock_irqsave(&priv->lock, flags);
priv->resetting = false;
del_timer(&priv->hang_timer);
del_timer(&priv->rr_timer);
if (!priv->closing) {
/* Save and reset - config register preserved by grcan_reset */
u32 imr = grcan_read_reg(®s->imr);
u32 txaddr = grcan_read_reg(®s->txaddr);
u32 txsize = grcan_read_reg(®s->txsize);
u32 txwr = grcan_read_reg(®s->txwr);
u32 txrd = grcan_read_reg(®s->txrd);
u32 eskbp = priv->eskbp;
u32 rxaddr = grcan_read_reg(®s->rxaddr);
u32 rxsize = grcan_read_reg(®s->rxsize);
u32 rxwr = grcan_read_reg(®s->rxwr);
u32 rxrd = grcan_read_reg(®s->rxrd);
grcan_reset(dev);
/* Restore */
grcan_write_reg(®s->txaddr, txaddr);
grcan_write_reg(®s->txsize, txsize);
grcan_write_reg(®s->txwr, txwr);
grcan_write_reg(®s->txrd, txrd);
priv->eskbp = eskbp;
grcan_write_reg(®s->rxaddr, rxaddr);
grcan_write_reg(®s->rxsize, rxsize);
grcan_write_reg(®s->rxwr, rxwr);
grcan_write_reg(®s->rxrd, rxrd);
/* Turn on device again */
grcan_write_reg(®s->imr, imr);
priv->can.state = CAN_STATE_ERROR_ACTIVE;
grcan_write_reg(®s->txctrl, GRCAN_TXCTRL_ENABLE
| (priv->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT
? GRCAN_TXCTRL_SINGLE : 0));
grcan_write_reg(®s->rxctrl, GRCAN_RXCTRL_ENABLE);
grcan_write_reg(®s->ctrl, GRCAN_CTRL_ENABLE);
/* Start queue if there is size and listen-onle mode is not
* enabled
*/
if (grcan_txspace(priv->dma.tx.size, txwr, priv->eskbp) &&
!(priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY))
netif_wake_queue(dev);
}
spin_unlock_irqrestore(&priv->lock, flags);
netdev_err(dev, "Device reset and restored\n");
}
/* Waiting time in usecs corresponding to the transmission of three maximum
* sized can frames in the given bitrate (in bits/sec). Waiting for this amount
* of time makes sure that the can controller have time to finish sending or
* receiving a frame with a good margin.
*
* usecs/sec * number of frames * bits/frame / bits/sec
*/
static inline u32 grcan_ongoing_wait_usecs(__u32 bitrate)
{
return 1000000 * 3 * GRCAN_EFF_FRAME_MAX_BITS / bitrate;
}
/* Set timer so that it will not fire until after a period in which the can
* controller have a good margin to finish transmitting a frame unless it has
* hanged
*/
static inline void grcan_reset_timer(struct timer_list *timer, __u32 bitrate)
{
u32 wait_jiffies = usecs_to_jiffies(grcan_ongoing_wait_usecs(bitrate));
mod_timer(timer, jiffies + wait_jiffies);
}
/* Disable channels and schedule a running reset */
static void grcan_initiate_running_reset(unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
unsigned long flags;
netdev_err(dev, "Device seems hanged - reset scheduled\n");
spin_lock_irqsave(&priv->lock, flags);
/* The main body of this function must never be executed again
* until after an execution of grcan_running_reset
*/
if (!priv->resetting && !priv->closing) {
priv->resetting = true;
netif_stop_queue(dev);
grcan_clear_bits(®s->txctrl, GRCAN_TXCTRL_ENABLE);
grcan_clear_bits(®s->rxctrl, GRCAN_RXCTRL_ENABLE);
grcan_reset_timer(&priv->rr_timer, priv->can.bittiming.bitrate);
}
spin_unlock_irqrestore(&priv->lock, flags);
}
static void grcan_free_dma_buffers(struct net_device *dev)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_dma *dma = &priv->dma;
dma_free_coherent(&dev->dev, dma->base_size, dma->base_buf,
dma->base_handle);
memset(dma, 0, sizeof(*dma));
}
static int grcan_allocate_dma_buffers(struct net_device *dev,
size_t tsize, size_t rsize)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_dma *dma = &priv->dma;
struct grcan_dma_buffer *large = rsize > tsize ? &dma->rx : &dma->tx;
struct grcan_dma_buffer *small = rsize > tsize ? &dma->tx : &dma->rx;
size_t shift;
/* Need a whole number of GRCAN_BUFFER_ALIGNMENT for the large,
* i.e. first buffer
*/
size_t maxs = max(tsize, rsize);
size_t lsize = ALIGN(maxs, GRCAN_BUFFER_ALIGNMENT);
/* Put the small buffer after that */
size_t ssize = min(tsize, rsize);
/* Extra GRCAN_BUFFER_ALIGNMENT to allow for alignment */
dma->base_size = lsize + ssize + GRCAN_BUFFER_ALIGNMENT;
dma->base_buf = dma_alloc_coherent(&dev->dev,
dma->base_size,
&dma->base_handle,
GFP_KERNEL);
if (!dma->base_buf)
return -ENOMEM;
dma->tx.size = tsize;
dma->rx.size = rsize;
large->handle = ALIGN(dma->base_handle, GRCAN_BUFFER_ALIGNMENT);
small->handle = large->handle + lsize;
shift = large->handle - dma->base_handle;
large->buf = dma->base_buf + shift;
small->buf = large->buf + lsize;
return 0;
}
/* priv->lock *must* be held when calling this function */
static int grcan_start(struct net_device *dev)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
u32 confop, txctrl;
grcan_reset(dev);
grcan_write_reg(®s->txaddr, priv->dma.tx.handle);
grcan_write_reg(®s->txsize, priv->dma.tx.size);
/* regs->txwr, regs->txrd and priv->eskbp already set to 0 by reset */
grcan_write_reg(®s->rxaddr, priv->dma.rx.handle);
grcan_write_reg(®s->rxsize, priv->dma.rx.size);
/* regs->rxwr and regs->rxrd already set to 0 by reset */
/* Enable interrupts */
grcan_read_reg(®s->pir);
grcan_write_reg(®s->imr, GRCAN_IRQ_DEFAULT);
/* Enable interfaces, channels and device */
confop = GRCAN_CONF_ABORT
| (priv->config.enable0 ? GRCAN_CONF_ENABLE0 : 0)
| (priv->config.enable1 ? GRCAN_CONF_ENABLE1 : 0)
| (priv->config.select ? GRCAN_CONF_SELECT : 0)
| (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY ?
GRCAN_CONF_SILENT : 0)
| (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES ?
GRCAN_CONF_SAM : 0);
grcan_write_bits(®s->conf, confop, GRCAN_CONF_OPERATION);
txctrl = GRCAN_TXCTRL_ENABLE
| (priv->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT
? GRCAN_TXCTRL_SINGLE : 0);
grcan_write_reg(®s->txctrl, txctrl);
grcan_write_reg(®s->rxctrl, GRCAN_RXCTRL_ENABLE);
grcan_write_reg(®s->ctrl, GRCAN_CTRL_ENABLE);
priv->can.state = CAN_STATE_ERROR_ACTIVE;
return 0;
}
static int grcan_set_mode(struct net_device *dev, enum can_mode mode)
{
struct grcan_priv *priv = netdev_priv(dev);
unsigned long flags;
int err = 0;
if (mode == CAN_MODE_START) {
/* This might be called to restart the device to recover from
* bus off errors
*/
spin_lock_irqsave(&priv->lock, flags);
if (priv->closing || priv->resetting) {
err = -EBUSY;
} else {
netdev_info(dev, "Restarting device\n");
grcan_start(dev);
if (!(priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY))
netif_wake_queue(dev);
}
spin_unlock_irqrestore(&priv->lock, flags);
return err;
}
return -EOPNOTSUPP;
}
static int grcan_open(struct net_device *dev)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_dma *dma = &priv->dma;
unsigned long flags;
int err;
/* Allocate memory */
err = grcan_allocate_dma_buffers(dev, priv->config.txsize,
priv->config.rxsize);
if (err) {
netdev_err(dev, "could not allocate DMA buffers\n");
return err;
}
priv->echo_skb = kzalloc(dma->tx.size * sizeof(*priv->echo_skb),
GFP_KERNEL);
if (!priv->echo_skb) {
err = -ENOMEM;
goto exit_free_dma_buffers;
}
priv->can.echo_skb_max = dma->tx.size;
priv->can.echo_skb = priv->echo_skb;
priv->txdlc = kzalloc(dma->tx.size * sizeof(*priv->txdlc), GFP_KERNEL);
if (!priv->txdlc) {
err = -ENOMEM;
goto exit_free_echo_skb;
}
/* Get can device up */
err = open_candev(dev);
if (err)
goto exit_free_txdlc;
err = request_irq(dev->irq, grcan_interrupt, IRQF_SHARED,
dev->name, dev);
if (err)
goto exit_close_candev;
spin_lock_irqsave(&priv->lock, flags);
napi_enable(&priv->napi);
grcan_start(dev);
if (!(priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY))
netif_start_queue(dev);
priv->resetting = false;
priv->closing = false;
spin_unlock_irqrestore(&priv->lock, flags);
return 0;
exit_close_candev:
close_candev(dev);
exit_free_txdlc:
kfree(priv->txdlc);
exit_free_echo_skb:
kfree(priv->echo_skb);
exit_free_dma_buffers:
grcan_free_dma_buffers(dev);
return err;
}
static int grcan_close(struct net_device *dev)
{
struct grcan_priv *priv = netdev_priv(dev);
unsigned long flags;
napi_disable(&priv->napi);
spin_lock_irqsave(&priv->lock, flags);
priv->closing = true;
if (priv->need_txbug_workaround) {
del_timer_sync(&priv->hang_timer);
del_timer_sync(&priv->rr_timer);
}
netif_stop_queue(dev);
grcan_stop_hardware(dev);
priv->can.state = CAN_STATE_STOPPED;
spin_unlock_irqrestore(&priv->lock, flags);
free_irq(dev->irq, dev);
close_candev(dev);
grcan_free_dma_buffers(dev);
priv->can.echo_skb_max = 0;
priv->can.echo_skb = NULL;
kfree(priv->echo_skb);
kfree(priv->txdlc);
return 0;
}
static int grcan_transmit_catch_up(struct net_device *dev, int budget)
{
struct grcan_priv *priv = netdev_priv(dev);
unsigned long flags;
int work_done;
spin_lock_irqsave(&priv->lock, flags);
work_done = catch_up_echo_skb(dev, budget, true);
if (work_done) {
if (!priv->resetting && !priv->closing &&
!(priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY))
netif_wake_queue(dev);
/* With napi we don't get TX interrupts for a while,
* so prevent a running reset while catching up
*/
if (priv->need_txbug_workaround)
del_timer(&priv->hang_timer);
}
spin_unlock_irqrestore(&priv->lock, flags);
return work_done;
}
static int grcan_receive(struct net_device *dev, int budget)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
struct grcan_dma *dma = &priv->dma;
struct net_device_stats *stats = &dev->stats;
struct can_frame *cf;
struct sk_buff *skb;
u32 wr, rd, startrd;
u32 *slot;
u32 i, rtr, eff, j, shift;
int work_done = 0;
rd = grcan_read_reg(®s->rxrd);
startrd = rd;
for (work_done = 0; work_done < budget; work_done++) {
/* Check for packet to receive */
wr = grcan_read_reg(®s->rxwr);
if (rd == wr)
break;
/* Take care of packet */
skb = alloc_can_skb(dev, &cf);
if (skb == NULL) {
netdev_err(dev,
"dropping frame: skb allocation failed\n");
stats->rx_dropped++;
continue;
}
slot = dma->rx.buf + rd;
eff = slot[0] & GRCAN_MSG_IDE;
rtr = slot[0] & GRCAN_MSG_RTR;
if (eff) {
cf->can_id = ((slot[0] & GRCAN_MSG_EID)
>> GRCAN_MSG_EID_BIT);
cf->can_id |= CAN_EFF_FLAG;
} else {
cf->can_id = ((slot[0] & GRCAN_MSG_BID)
>> GRCAN_MSG_BID_BIT);
}
cf->can_dlc = get_can_dlc((slot[1] & GRCAN_MSG_DLC)
>> GRCAN_MSG_DLC_BIT);
if (rtr) {
cf->can_id |= CAN_RTR_FLAG;
} else {
for (i = 0; i < cf->can_dlc; i++) {
j = GRCAN_MSG_DATA_SLOT_INDEX(i);
shift = GRCAN_MSG_DATA_SHIFT(i);
cf->data[i] = (u8)(slot[j] >> shift);
}
}
/* Update statistics and read pointer */
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
netif_receive_skb(skb);
rd = grcan_ring_add(rd, GRCAN_MSG_SIZE, dma->rx.size);
}
/* Make sure everything is read before allowing hardware to
* use the memory
*/
mb();
/* Update read pointer - no need to check for ongoing */
if (likely(rd != startrd))
grcan_write_reg(®s->rxrd, rd);
return work_done;
}
static int grcan_poll(struct napi_struct *napi, int budget)
{
struct grcan_priv *priv = container_of(napi, struct grcan_priv, napi);
struct net_device *dev = priv->dev;
struct grcan_registers __iomem *regs = priv->regs;
unsigned long flags;
int tx_work_done, rx_work_done;
int rx_budget = budget / 2;
int tx_budget = budget - rx_budget;
/* Half of the budget for receiveing messages */
rx_work_done = grcan_receive(dev, rx_budget);
/* Half of the budget for transmitting messages as that can trigger echo
* frames being received
*/
tx_work_done = grcan_transmit_catch_up(dev, tx_budget);
if (rx_work_done < rx_budget && tx_work_done < tx_budget) {
napi_complete(napi);
/* Guarantee no interference with a running reset that otherwise
* could turn off interrupts.
*/
spin_lock_irqsave(&priv->lock, flags);
/* Enable tx and rx interrupts again. No need to check
* priv->closing as napi_disable in grcan_close is waiting for
* scheduled napi calls to finish.
*/
grcan_set_bits(®s->imr, GRCAN_IRQ_TX | GRCAN_IRQ_RX);
spin_unlock_irqrestore(&priv->lock, flags);
}
return rx_work_done + tx_work_done;
}
/* Work tx bug by waiting while for the risky situation to clear. If that fails,
* drop a frame in one-shot mode or indicate a busy device otherwise.
*
* Returns 0 on successful wait. Otherwise it sets *netdev_tx_status to the
* value that should be returned by grcan_start_xmit when aborting the xmit.
*/
static int grcan_txbug_workaround(struct net_device *dev, struct sk_buff *skb,
u32 txwr, u32 oneshotmode,
netdev_tx_t *netdev_tx_status)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
struct grcan_dma *dma = &priv->dma;
int i;
unsigned long flags;
/* Wait a while for ongoing to be cleared or read pointer to catch up to
* write pointer. The latter is needed due to a bug in older versions of
* GRCAN in which ONGOING is not cleared properly one-shot mode when a
* transmission fails.
*/
for (i = 0; i < GRCAN_SHORTWAIT_USECS; i++) {
udelay(1);
if (!grcan_read_bits(®s->txctrl, GRCAN_TXCTRL_ONGOING) ||
grcan_read_reg(®s->txrd) == txwr) {
return 0;
}
}
/* Clean up, in case the situation was not resolved */
spin_lock_irqsave(&priv->lock, flags);
if (!priv->resetting && !priv->closing) {
/* Queue might have been stopped earlier in grcan_start_xmit */
if (grcan_txspace(dma->tx.size, txwr, priv->eskbp))
netif_wake_queue(dev);
/* Set a timer to resolve a hanged tx controller */
if (!timer_pending(&priv->hang_timer))
grcan_reset_timer(&priv->hang_timer,
priv->can.bittiming.bitrate);
}
spin_unlock_irqrestore(&priv->lock, flags);
if (oneshotmode) {
/* In one-shot mode we should never end up here because
* then the interrupt handler increases txrd on TXLOSS,
* but it is consistent with one-shot mode to drop the
* frame in this case.
*/
kfree_skb(skb);
*netdev_tx_status = NETDEV_TX_OK;
} else {
/* In normal mode the socket-can transmission queue get
* to keep the frame so that it can be retransmitted
* later
*/
*netdev_tx_status = NETDEV_TX_BUSY;
}
return -EBUSY;
}
/* Notes on the tx cyclic buffer handling:
*
* regs->txwr - the next slot for the driver to put data to be sent
* regs->txrd - the next slot for the device to read data
* priv->eskbp - the next slot for the driver to call can_put_echo_skb for
*
* grcan_start_xmit can enter more messages as long as regs->txwr does
* not reach priv->eskbp (within 1 message gap)
*
* The device sends messages until regs->txrd reaches regs->txwr
*
* The interrupt calls handler calls can_put_echo_skb until
* priv->eskbp reaches regs->txrd
*/
static netdev_tx_t grcan_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct grcan_priv *priv = netdev_priv(dev);
struct grcan_registers __iomem *regs = priv->regs;
struct grcan_dma *dma = &priv->dma;
struct can_frame *cf = (struct can_frame *)skb->data;
u32 id, txwr, txrd, space, txctrl;
int slotindex;
u32 *slot;
u32 i, rtr, eff, dlc, tmp, err;
int j, shift;
unsigned long flags;
u32 oneshotmode = priv->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT;
if (can_dropped_invalid_skb(dev, skb))
return NETDEV_TX_OK;
/* Trying to transmit in silent mode will generate error interrupts, but
* this should never happen - the queue should not have been started.
*/
if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
return NETDEV_TX_BUSY;
/* Reads of priv->eskbp and shut-downs of the queue needs to
* be atomic towards the updates to priv->eskbp and wake-ups
* of the queue in the interrupt handler.
*/
spin_lock_irqsave(&priv->lock, flags);
txwr = grcan_read_reg(®s->txwr);
space = grcan_txspace(dma->tx.size, txwr, priv->eskbp);
slotindex = txwr / GRCAN_MSG_SIZE;
slot = dma->tx.buf + txwr;
if (unlikely(space == 1))
netif_stop_queue(dev);
spin_unlock_irqrestore(&priv->lock, flags);
/* End of critical section*/
/* This should never happen. If circular buffer is full, the
* netif_stop_queue should have been stopped already.
*/
if (unlikely(!space)) {
netdev_err(dev, "No buffer space, but queue is non-stopped.\n");
return NETDEV_TX_BUSY;
}
/* Convert and write CAN message to DMA buffer */
eff = cf->can_id & CAN_EFF_FLAG;
rtr = cf->can_id & CAN_RTR_FLAG;
id = cf->can_id & (eff ? CAN_EFF_MASK : CAN_SFF_MASK);
dlc = cf->can_dlc;
if (eff)
tmp = (id << GRCAN_MSG_EID_BIT) & GRCAN_MSG_EID;
else
tmp = (id << GRCAN_MSG_BID_BIT) & GRCAN_MSG_BID;
slot[0] = (eff ? GRCAN_MSG_IDE : 0) | (rtr ? GRCAN_MSG_RTR : 0) | tmp;
slot[1] = ((dlc << GRCAN_MSG_DLC_BIT) & GRCAN_MSG_DLC);
slot[2] = 0;
slot[3] = 0;
for (i = 0; i < dlc; i++) {
j = GRCAN_MSG_DATA_SLOT_INDEX(i);
shift = GRCAN_MSG_DATA_SHIFT(i);
slot[j] |= cf->data[i] << shift;
}
/* Checking that channel has not been disabled. These cases
* should never happen
*/
txctrl = grcan_read_reg(®s->txctrl);
if (!(txctrl & GRCAN_TXCTRL_ENABLE))
netdev_err(dev, "tx channel spuriously disabled\n");
if (oneshotmode && !(txctrl & GRCAN_TXCTRL_SINGLE))
netdev_err(dev, "one-shot mode spuriously disabled\n");
/* Bug workaround for old version of grcan where updating txwr
* in the same clock cycle as the controller updates txrd to
* the current txwr could hang the can controller
*/
if (priv->need_txbug_workaround) {
txrd = grcan_read_reg(®s->txrd);
if (unlikely(grcan_ring_sub(txwr, txrd, dma->tx.size) == 1)) {
netdev_tx_t txstatus;
err = grcan_txbug_workaround(dev, skb, txwr,
oneshotmode, &txstatus);
if (err)
return txstatus;
}
}
/* Prepare skb for echoing. This must be after the bug workaround above
* as ownership of the skb is passed on by calling can_put_echo_skb.
* Returning NETDEV_TX_BUSY or accessing skb or cf after a call to
* can_put_echo_skb would be an error unless other measures are
* taken.
*/
priv->txdlc[slotindex] = cf->can_dlc; /* Store dlc for statistics */
can_put_echo_skb(skb, dev, slotindex);
/* Make sure everything is written before allowing hardware to
* read from the memory
*/
wmb();
/* Update write pointer to start transmission */
grcan_write_reg(®s->txwr,
grcan_ring_add(txwr, GRCAN_MSG_SIZE, dma->tx.size));
return NETDEV_TX_OK;
}
/* ========== Setting up sysfs interface and module parameters ========== */
#define GRCAN_NOT_BOOL(unsigned_val) ((unsigned_val) > 1)
#define GRCAN_MODULE_PARAM(name, mtype, valcheckf, desc) \
static void grcan_sanitize_##name(struct platform_device *pd) \
{ \
struct grcan_device_config grcan_default_config \
= GRCAN_DEFAULT_DEVICE_CONFIG; \
if (valcheckf(grcan_module_config.name)) { \
dev_err(&pd->dev, \
"Invalid module parameter value for " \
#name " - setting default\n"); \
grcan_module_config.name = \
grcan_default_config.name; \
} \
} \
module_param_named(name, grcan_module_config.name, \
mtype, S_IRUGO); \
MODULE_PARM_DESC(name, desc)
#define GRCAN_CONFIG_ATTR(name, desc) \
static ssize_t grcan_store_##name(struct device *sdev, \
struct device_attribute *att, \
const char *buf, \
size_t count) \
{ \
struct net_device *dev = to_net_dev(sdev); \
struct grcan_priv *priv = netdev_priv(dev); \
u8 val; \
int ret; \
if (dev->flags & IFF_UP) \
return -EBUSY; \
ret = kstrtou8(buf, 0, &val); \
if (ret < 0 || val > 1) \
return -EINVAL; \
priv->config.name = val; \
return count; \
} \
static ssize_t grcan_show_##name(struct device *sdev, \
struct device_attribute *att, \
char *buf) \
{ \
struct net_device *dev = to_net_dev(sdev); \
struct grcan_priv *priv = netdev_priv(dev); \
return sprintf(buf, "%d\n", priv->config.name); \
} \
static DEVICE_ATTR(name, S_IRUGO | S_IWUSR, \
grcan_show_##name, \
grcan_store_##name); \
GRCAN_MODULE_PARAM(name, ushort, GRCAN_NOT_BOOL, desc)
/* The following configuration options are made available both via module
* parameters and writable sysfs files. See the chapter about GRCAN in the
* documentation for the GRLIB VHDL library for further details.
*/
GRCAN_CONFIG_ATTR(enable0,
"Configuration of physical interface 0. Determines\n" \
"the \"Enable 0\" bit of the configuration register.\n" \
"Format: 0 | 1\nDefault: 0\n");
GRCAN_CONFIG_ATTR(enable1,
"Configuration of physical interface 1. Determines\n" \
"the \"Enable 1\" bit of the configuration register.\n" \
"Format: 0 | 1\nDefault: 0\n");
GRCAN_CONFIG_ATTR(select,
"Select which physical interface to use.\n" \
"Format: 0 | 1\nDefault: 0\n");
/* The tx and rx buffer size configuration options are only available via module
* parameters.
*/
GRCAN_MODULE_PARAM(txsize, uint, GRCAN_INVALID_BUFFER_SIZE,
"Sets the size of the tx buffer.\n" \
"Format: <unsigned int> where (txsize & ~0x1fffc0) == 0\n" \
"Default: 1024\n");
GRCAN_MODULE_PARAM(rxsize, uint, GRCAN_INVALID_BUFFER_SIZE,
"Sets the size of the rx buffer.\n" \
"Format: <unsigned int> where (size & ~0x1fffc0) == 0\n" \
"Default: 1024\n");
/* Function that makes sure that configuration done using
* module parameters are set to valid values
*/
static void grcan_sanitize_module_config(struct platform_device *ofdev)
{
grcan_sanitize_enable0(ofdev);
grcan_sanitize_enable1(ofdev);
grcan_sanitize_select(ofdev);
grcan_sanitize_txsize(ofdev);
grcan_sanitize_rxsize(ofdev);
}
static const struct attribute *const sysfs_grcan_attrs[] = {
/* Config attrs */
&dev_attr_enable0.attr,
&dev_attr_enable1.attr,
&dev_attr_select.attr,
NULL,
};
static const struct attribute_group sysfs_grcan_group = {
.name = "grcan",
.attrs = (struct attribute **)sysfs_grcan_attrs,
};
/* ========== Setting up the driver ========== */
static const struct net_device_ops grcan_netdev_ops = {
.ndo_open = grcan_open,
.ndo_stop = grcan_close,
.ndo_start_xmit = grcan_start_xmit,
.ndo_change_mtu = can_change_mtu,
};
static int grcan_setup_netdev(struct platform_device *ofdev,
void __iomem *base,
int irq, u32 ambafreq, bool txbug)
{
struct net_device *dev;
struct grcan_priv *priv;
struct grcan_registers __iomem *regs;
int err;
dev = alloc_candev(sizeof(struct grcan_priv), 0);
if (!dev)
return -ENOMEM;
dev->irq = irq;
dev->flags |= IFF_ECHO;
dev->netdev_ops = &grcan_netdev_ops;
dev->sysfs_groups[0] = &sysfs_grcan_group;
priv = netdev_priv(dev);
memcpy(&priv->config, &grcan_module_config,
sizeof(struct grcan_device_config));
priv->dev = dev;
priv->regs = base;
priv->can.bittiming_const = &grcan_bittiming_const;
priv->can.do_set_bittiming = grcan_set_bittiming;
priv->can.do_set_mode = grcan_set_mode;
priv->can.do_get_berr_counter = grcan_get_berr_counter;
priv->can.clock.freq = ambafreq;
priv->can.ctrlmode_supported =
CAN_CTRLMODE_LISTENONLY | CAN_CTRLMODE_ONE_SHOT;
priv->need_txbug_workaround = txbug;
/* Discover if triple sampling is supported by hardware */
regs = priv->regs;
grcan_set_bits(®s->ctrl, GRCAN_CTRL_RESET);
grcan_set_bits(®s->conf, GRCAN_CONF_SAM);
if (grcan_read_bits(®s->conf, GRCAN_CONF_SAM)) {
priv->can.ctrlmode_supported |= CAN_CTRLMODE_3_SAMPLES;
dev_dbg(&ofdev->dev, "Hardware supports triple-sampling\n");
}
spin_lock_init(&priv->lock);
if (priv->need_txbug_workaround) {
init_timer(&priv->rr_timer);
priv->rr_timer.function = grcan_running_reset;
priv->rr_timer.data = (unsigned long)dev;
init_timer(&priv->hang_timer);
priv->hang_timer.function = grcan_initiate_running_reset;
priv->hang_timer.data = (unsigned long)dev;
}
netif_napi_add(dev, &priv->napi, grcan_poll, GRCAN_NAPI_WEIGHT);
SET_NETDEV_DEV(dev, &ofdev->dev);
dev_info(&ofdev->dev, "regs=0x%p, irq=%d, clock=%d\n",
priv->regs, dev->irq, priv->can.clock.freq);
err = register_candev(dev);
if (err)
goto exit_free_candev;
platform_set_drvdata(ofdev, dev);
/* Reset device to allow bit-timing to be set. No need to call
* grcan_reset at this stage. That is done in grcan_open.
*/
grcan_write_reg(®s->ctrl, GRCAN_CTRL_RESET);
return 0;
exit_free_candev:
free_candev(dev);
return err;
}
static int grcan_probe(struct platform_device *ofdev)
{
struct device_node *np = ofdev->dev.of_node;
struct resource *res;
u32 sysid, ambafreq;
int irq, err;
void __iomem *base;
bool txbug = true;
/* Compare GRLIB version number with the first that does not
* have the tx bug (see start_xmit)
*/
err = of_property_read_u32(np, "systemid", &sysid);
if (!err && ((sysid & GRLIB_VERSION_MASK)
>= GRCAN_TXBUG_SAFE_GRLIB_VERSION))
txbug = false;
err = of_property_read_u32(np, "freq", &ambafreq);
if (err) {
dev_err(&ofdev->dev, "unable to fetch \"freq\" property\n");
goto exit_error;
}
res = platform_get_resource(ofdev, IORESOURCE_MEM, 0);
base = devm_ioremap_resource(&ofdev->dev, res);
if (IS_ERR(base)) {
err = PTR_ERR(base);
goto exit_error;
}
irq = irq_of_parse_and_map(np, GRCAN_IRQIX_IRQ);
if (!irq) {
dev_err(&ofdev->dev, "no irq found\n");
err = -ENODEV;
goto exit_error;
}
grcan_sanitize_module_config(ofdev);
err = grcan_setup_netdev(ofdev, base, irq, ambafreq, txbug);
if (err)
goto exit_dispose_irq;
return 0;
exit_dispose_irq:
irq_dispose_mapping(irq);
exit_error:
dev_err(&ofdev->dev,
"%s socket CAN driver initialization failed with error %d\n",
DRV_NAME, err);
return err;
}
static int grcan_remove(struct platform_device *ofdev)
{
struct net_device *dev = platform_get_drvdata(ofdev);
struct grcan_priv *priv = netdev_priv(dev);
unregister_candev(dev); /* Will in turn call grcan_close */
irq_dispose_mapping(dev->irq);
netif_napi_del(&priv->napi);
free_candev(dev);
return 0;
}
static const struct of_device_id grcan_match[] = {
{.name = "GAISLER_GRCAN"},
{.name = "01_03d"},
{.name = "GAISLER_GRHCAN"},
{.name = "01_034"},
{},
};
MODULE_DEVICE_TABLE(of, grcan_match);
static struct platform_driver grcan_driver = {
.driver = {
.name = DRV_NAME,
.of_match_table = grcan_match,
},
.probe = grcan_probe,
.remove = grcan_remove,
};
module_platform_driver(grcan_driver);
MODULE_AUTHOR("Aeroflex Gaisler AB.");
MODULE_DESCRIPTION("Socket CAN driver for Aeroflex Gaisler GRCAN");
MODULE_LICENSE("GPL");
| gpl-2.0 |
vm03/android_kernel_asus_P024 | drivers/pinctrl/core.c | 409 | 43657 | /*
* Core driver for the pin control subsystem
*
* Copyright (C) 2011-2012 ST-Ericsson SA
* Written on behalf of Linaro for ST-Ericsson
* Based on bits of regulator core, gpio core and clk core
*
* Author: Linus Walleij <linus.walleij@linaro.org>
*
* Copyright (C) 2012 NVIDIA CORPORATION. All rights reserved.
*
* License terms: GNU General Public License (GPL) version 2
*/
#define pr_fmt(fmt) "pinctrl core: " fmt
#include <linux/kernel.h>
#include <linux/kref.h>
#include <linux/export.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/list.h>
#include <linux/sysfs.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/pinctrl/consumer.h>
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/machine.h>
#ifdef CONFIG_GPIOLIB
#include <asm-generic/gpio.h>
#endif
#include "core.h"
#include "devicetree.h"
#include "pinmux.h"
#include "pinconf.h"
static bool pinctrl_dummy_state;
/* Mutex taken to protect pinctrl_list */
DEFINE_MUTEX(pinctrl_list_mutex);
/* Mutex taken to protect pinctrl_maps */
DEFINE_MUTEX(pinctrl_maps_mutex);
/* Mutex taken to protect pinctrldev_list */
DEFINE_MUTEX(pinctrldev_list_mutex);
/* Global list of pin control devices (struct pinctrl_dev) */
static LIST_HEAD(pinctrldev_list);
/* List of pin controller handles (struct pinctrl) */
static LIST_HEAD(pinctrl_list);
/* List of pinctrl maps (struct pinctrl_maps) */
LIST_HEAD(pinctrl_maps);
/**
* pinctrl_provide_dummies() - indicate if pinctrl provides dummy state support
*
* Usually this function is called by platforms without pinctrl driver support
* but run with some shared drivers using pinctrl APIs.
* After calling this function, the pinctrl core will return successfully
* with creating a dummy state for the driver to keep going smoothly.
*/
void pinctrl_provide_dummies(void)
{
pinctrl_dummy_state = true;
}
const char *pinctrl_dev_get_name(struct pinctrl_dev *pctldev)
{
/* We're not allowed to register devices without name */
return pctldev->desc->name;
}
EXPORT_SYMBOL_GPL(pinctrl_dev_get_name);
const char *pinctrl_dev_get_devname(struct pinctrl_dev *pctldev)
{
return dev_name(pctldev->dev);
}
EXPORT_SYMBOL_GPL(pinctrl_dev_get_devname);
void *pinctrl_dev_get_drvdata(struct pinctrl_dev *pctldev)
{
return pctldev->driver_data;
}
EXPORT_SYMBOL_GPL(pinctrl_dev_get_drvdata);
/**
* get_pinctrl_dev_from_devname() - look up pin controller device
* @devname: the name of a device instance, as returned by dev_name()
*
* Looks up a pin control device matching a certain device name or pure device
* pointer, the pure device pointer will take precedence.
*/
struct pinctrl_dev *get_pinctrl_dev_from_devname(const char *devname)
{
struct pinctrl_dev *pctldev = NULL;
bool found = false;
if (!devname)
return NULL;
list_for_each_entry(pctldev, &pinctrldev_list, node) {
if (!strcmp(dev_name(pctldev->dev), devname)) {
/* Matched on device name */
found = true;
break;
}
}
return found ? pctldev : NULL;
}
struct pinctrl_dev *get_pinctrl_dev_from_of_node(struct device_node *np)
{
struct pinctrl_dev *pctldev;
mutex_lock(&pinctrldev_list_mutex);
list_for_each_entry(pctldev, &pinctrldev_list, node)
if (pctldev->dev->of_node == np) {
mutex_unlock(&pinctrldev_list_mutex);
return pctldev;
}
mutex_unlock(&pinctrldev_list_mutex);
return NULL;
}
/**
* pin_get_from_name() - look up a pin number from a name
* @pctldev: the pin control device to lookup the pin on
* @name: the name of the pin to look up
*/
int pin_get_from_name(struct pinctrl_dev *pctldev, const char *name)
{
unsigned i, pin;
/* The pin number can be retrived from the pin controller descriptor */
for (i = 0; i < pctldev->desc->npins; i++) {
struct pin_desc *desc;
pin = pctldev->desc->pins[i].number;
desc = pin_desc_get(pctldev, pin);
/* Pin space may be sparse */
if (desc == NULL)
continue;
if (desc->name && !strcmp(name, desc->name))
return pin;
}
return -EINVAL;
}
/**
* pin_get_name_from_id() - look up a pin name from a pin id
* @pctldev: the pin control device to lookup the pin on
* @name: the name of the pin to look up
*/
const char *pin_get_name(struct pinctrl_dev *pctldev, const unsigned pin)
{
const struct pin_desc *desc;
desc = pin_desc_get(pctldev, pin);
if (desc == NULL) {
dev_err(pctldev->dev, "failed to get pin(%d) name\n",
pin);
return NULL;
}
return desc->name;
}
/**
* pin_is_valid() - check if pin exists on controller
* @pctldev: the pin control device to check the pin on
* @pin: pin to check, use the local pin controller index number
*
* This tells us whether a certain pin exist on a certain pin controller or
* not. Pin lists may be sparse, so some pins may not exist.
*/
bool pin_is_valid(struct pinctrl_dev *pctldev, int pin)
{
struct pin_desc *pindesc;
if (pin < 0)
return false;
mutex_lock(&pctldev->mutex);
pindesc = pin_desc_get(pctldev, pin);
mutex_unlock(&pctldev->mutex);
return pindesc != NULL;
}
EXPORT_SYMBOL_GPL(pin_is_valid);
/* Deletes a range of pin descriptors */
static void pinctrl_free_pindescs(struct pinctrl_dev *pctldev,
const struct pinctrl_pin_desc *pins,
unsigned num_pins)
{
int i;
for (i = 0; i < num_pins; i++) {
struct pin_desc *pindesc;
pindesc = radix_tree_lookup(&pctldev->pin_desc_tree,
pins[i].number);
if (pindesc != NULL) {
radix_tree_delete(&pctldev->pin_desc_tree,
pins[i].number);
if (pindesc->dynamic_name)
kfree(pindesc->name);
}
kfree(pindesc);
}
}
static int pinctrl_register_one_pin(struct pinctrl_dev *pctldev,
unsigned number, const char *name)
{
struct pin_desc *pindesc;
pindesc = pin_desc_get(pctldev, number);
if (pindesc != NULL) {
pr_err("pin %d already registered on %s\n", number,
pctldev->desc->name);
return -EINVAL;
}
pindesc = kzalloc(sizeof(*pindesc), GFP_KERNEL);
if (pindesc == NULL) {
dev_err(pctldev->dev, "failed to alloc struct pin_desc\n");
return -ENOMEM;
}
/* Set owner */
pindesc->pctldev = pctldev;
/* Copy basic pin info */
if (name) {
pindesc->name = name;
} else {
pindesc->name = kasprintf(GFP_KERNEL, "PIN%u", number);
if (pindesc->name == NULL) {
kfree(pindesc);
return -ENOMEM;
}
pindesc->dynamic_name = true;
}
radix_tree_insert(&pctldev->pin_desc_tree, number, pindesc);
pr_debug("registered pin %d (%s) on %s\n",
number, pindesc->name, pctldev->desc->name);
return 0;
}
static int pinctrl_register_pins(struct pinctrl_dev *pctldev,
struct pinctrl_pin_desc const *pins,
unsigned num_descs)
{
unsigned i;
int ret = 0;
for (i = 0; i < num_descs; i++) {
ret = pinctrl_register_one_pin(pctldev,
pins[i].number, pins[i].name);
if (ret)
return ret;
}
return 0;
}
/**
* pinctrl_match_gpio_range() - check if a certain GPIO pin is in range
* @pctldev: pin controller device to check
* @gpio: gpio pin to check taken from the global GPIO pin space
*
* Tries to match a GPIO pin number to the ranges handled by a certain pin
* controller, return the range or NULL
*/
static struct pinctrl_gpio_range *
pinctrl_match_gpio_range(struct pinctrl_dev *pctldev, unsigned gpio)
{
struct pinctrl_gpio_range *range = NULL;
mutex_lock(&pctldev->mutex);
/* Loop over the ranges */
list_for_each_entry(range, &pctldev->gpio_ranges, node) {
/* Check if we're in the valid range */
if (gpio >= range->base &&
gpio < range->base + range->npins) {
mutex_unlock(&pctldev->mutex);
return range;
}
}
mutex_unlock(&pctldev->mutex);
return NULL;
}
/**
* pinctrl_ready_for_gpio_range() - check if other GPIO pins of
* the same GPIO chip are in range
* @gpio: gpio pin to check taken from the global GPIO pin space
*
* This function is complement of pinctrl_match_gpio_range(). If the return
* value of pinctrl_match_gpio_range() is NULL, this function could be used
* to check whether pinctrl device is ready or not. Maybe some GPIO pins
* of the same GPIO chip don't have back-end pinctrl interface.
* If the return value is true, it means that pinctrl device is ready & the
* certain GPIO pin doesn't have back-end pinctrl device. If the return value
* is false, it means that pinctrl device may not be ready.
*/
#ifdef CONFIG_GPIOLIB
static bool pinctrl_ready_for_gpio_range(unsigned gpio)
{
struct pinctrl_dev *pctldev;
struct pinctrl_gpio_range *range = NULL;
struct gpio_chip *chip = gpio_to_chip(gpio);
/* Loop over the pin controllers */
list_for_each_entry(pctldev, &pinctrldev_list, node) {
/* Loop over the ranges */
list_for_each_entry(range, &pctldev->gpio_ranges, node) {
/* Check if any gpio range overlapped with gpio chip */
if (range->base + range->npins - 1 < chip->base ||
range->base > chip->base + chip->ngpio - 1)
continue;
return true;
}
}
return false;
}
#else
static bool pinctrl_ready_for_gpio_range(unsigned gpio) { return true; }
#endif
/**
* pinctrl_get_device_gpio_range() - find device for GPIO range
* @gpio: the pin to locate the pin controller for
* @outdev: the pin control device if found
* @outrange: the GPIO range if found
*
* Find the pin controller handling a certain GPIO pin from the pinspace of
* the GPIO subsystem, return the device and the matching GPIO range. Returns
* -EPROBE_DEFER if the GPIO range could not be found in any device since it
* may still have not been registered.
*/
static int pinctrl_get_device_gpio_range(unsigned gpio,
struct pinctrl_dev **outdev,
struct pinctrl_gpio_range **outrange)
{
struct pinctrl_dev *pctldev = NULL;
/* Loop over the pin controllers */
list_for_each_entry(pctldev, &pinctrldev_list, node) {
struct pinctrl_gpio_range *range;
range = pinctrl_match_gpio_range(pctldev, gpio);
if (range != NULL) {
*outdev = pctldev;
*outrange = range;
return 0;
}
}
return -EPROBE_DEFER;
}
/**
* pinctrl_add_gpio_range() - register a GPIO range for a controller
* @pctldev: pin controller device to add the range to
* @range: the GPIO range to add
*
* This adds a range of GPIOs to be handled by a certain pin controller. Call
* this to register handled ranges after registering your pin controller.
*/
void pinctrl_add_gpio_range(struct pinctrl_dev *pctldev,
struct pinctrl_gpio_range *range)
{
mutex_lock(&pctldev->mutex);
list_add_tail(&range->node, &pctldev->gpio_ranges);
mutex_unlock(&pctldev->mutex);
}
EXPORT_SYMBOL_GPL(pinctrl_add_gpio_range);
void pinctrl_add_gpio_ranges(struct pinctrl_dev *pctldev,
struct pinctrl_gpio_range *ranges,
unsigned nranges)
{
int i;
for (i = 0; i < nranges; i++)
pinctrl_add_gpio_range(pctldev, &ranges[i]);
}
EXPORT_SYMBOL_GPL(pinctrl_add_gpio_ranges);
struct pinctrl_dev *pinctrl_find_and_add_gpio_range(const char *devname,
struct pinctrl_gpio_range *range)
{
struct pinctrl_dev *pctldev;
mutex_lock(&pinctrldev_list_mutex);
pctldev = get_pinctrl_dev_from_devname(devname);
/*
* If we can't find this device, let's assume that is because
* it has not probed yet, so the driver trying to register this
* range need to defer probing.
*/
if (!pctldev) {
mutex_unlock(&pinctrldev_list_mutex);
return ERR_PTR(-EPROBE_DEFER);
}
pinctrl_add_gpio_range(pctldev, range);
mutex_unlock(&pinctrldev_list_mutex);
return pctldev;
}
EXPORT_SYMBOL_GPL(pinctrl_find_and_add_gpio_range);
/**
* pinctrl_find_gpio_range_from_pin() - locate the GPIO range for a pin
* @pctldev: the pin controller device to look in
* @pin: a controller-local number to find the range for
*/
struct pinctrl_gpio_range *
pinctrl_find_gpio_range_from_pin(struct pinctrl_dev *pctldev,
unsigned int pin)
{
struct pinctrl_gpio_range *range = NULL;
mutex_lock(&pctldev->mutex);
/* Loop over the ranges */
list_for_each_entry(range, &pctldev->gpio_ranges, node) {
/* Check if we're in the valid range */
if (pin >= range->pin_base &&
pin < range->pin_base + range->npins) {
mutex_unlock(&pctldev->mutex);
return range;
}
}
mutex_unlock(&pctldev->mutex);
return NULL;
}
EXPORT_SYMBOL_GPL(pinctrl_find_gpio_range_from_pin);
/**
* pinctrl_remove_gpio_range() - remove a range of GPIOs fro a pin controller
* @pctldev: pin controller device to remove the range from
* @range: the GPIO range to remove
*/
void pinctrl_remove_gpio_range(struct pinctrl_dev *pctldev,
struct pinctrl_gpio_range *range)
{
mutex_lock(&pctldev->mutex);
list_del(&range->node);
mutex_unlock(&pctldev->mutex);
}
EXPORT_SYMBOL_GPL(pinctrl_remove_gpio_range);
/**
* pinctrl_get_group_selector() - returns the group selector for a group
* @pctldev: the pin controller handling the group
* @pin_group: the pin group to look up
*/
int pinctrl_get_group_selector(struct pinctrl_dev *pctldev,
const char *pin_group)
{
const struct pinctrl_ops *pctlops = pctldev->desc->pctlops;
unsigned ngroups = pctlops->get_groups_count(pctldev);
unsigned group_selector = 0;
while (group_selector < ngroups) {
const char *gname = pctlops->get_group_name(pctldev,
group_selector);
if (!strcmp(gname, pin_group)) {
dev_dbg(pctldev->dev,
"found group selector %u for %s\n",
group_selector,
pin_group);
return group_selector;
}
group_selector++;
}
dev_err(pctldev->dev, "does not have pin group %s\n",
pin_group);
return -EINVAL;
}
/**
* pinctrl_request_gpio() - request a single pin to be used in as GPIO
* @gpio: the GPIO pin number from the GPIO subsystem number space
*
* This function should *ONLY* be used from gpiolib-based GPIO drivers,
* as part of their gpio_request() semantics, platforms and individual drivers
* shall *NOT* request GPIO pins to be muxed in.
*/
int pinctrl_request_gpio(unsigned gpio)
{
struct pinctrl_dev *pctldev;
struct pinctrl_gpio_range *range;
int ret;
int pin;
mutex_lock(&pinctrldev_list_mutex);
ret = pinctrl_get_device_gpio_range(gpio, &pctldev, &range);
if (ret) {
if (pinctrl_ready_for_gpio_range(gpio))
ret = 0;
mutex_unlock(&pinctrldev_list_mutex);
return ret;
}
/* Convert to the pin controllers number space */
pin = gpio - range->base + range->pin_base;
ret = pinmux_request_gpio(pctldev, range, pin, gpio);
mutex_unlock(&pinctrldev_list_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(pinctrl_request_gpio);
/**
* pinctrl_free_gpio() - free control on a single pin, currently used as GPIO
* @gpio: the GPIO pin number from the GPIO subsystem number space
*
* This function should *ONLY* be used from gpiolib-based GPIO drivers,
* as part of their gpio_free() semantics, platforms and individual drivers
* shall *NOT* request GPIO pins to be muxed out.
*/
void pinctrl_free_gpio(unsigned gpio)
{
struct pinctrl_dev *pctldev;
struct pinctrl_gpio_range *range;
int ret;
int pin;
mutex_lock(&pinctrldev_list_mutex);
ret = pinctrl_get_device_gpio_range(gpio, &pctldev, &range);
if (ret) {
mutex_unlock(&pinctrldev_list_mutex);
return;
}
mutex_lock(&pctldev->mutex);
/* Convert to the pin controllers number space */
pin = gpio - range->base + range->pin_base;
pinmux_free_gpio(pctldev, pin, range);
mutex_unlock(&pctldev->mutex);
mutex_unlock(&pinctrldev_list_mutex);
}
EXPORT_SYMBOL_GPL(pinctrl_free_gpio);
static int pinctrl_gpio_direction(unsigned gpio, bool input)
{
struct pinctrl_dev *pctldev;
struct pinctrl_gpio_range *range;
int ret;
int pin;
mutex_lock(&pinctrldev_list_mutex);
ret = pinctrl_get_device_gpio_range(gpio, &pctldev, &range);
if (ret) {
mutex_unlock(&pinctrldev_list_mutex);
return ret;
}
mutex_lock(&pctldev->mutex);
/* Convert to the pin controllers number space */
pin = gpio - range->base + range->pin_base;
ret = pinmux_gpio_direction(pctldev, range, pin, input);
mutex_unlock(&pctldev->mutex);
mutex_unlock(&pinctrldev_list_mutex);
return ret;
}
/**
* pinctrl_gpio_direction_input() - request a GPIO pin to go into input mode
* @gpio: the GPIO pin number from the GPIO subsystem number space
*
* This function should *ONLY* be used from gpiolib-based GPIO drivers,
* as part of their gpio_direction_input() semantics, platforms and individual
* drivers shall *NOT* touch pin control GPIO calls.
*/
int pinctrl_gpio_direction_input(unsigned gpio)
{
return pinctrl_gpio_direction(gpio, true);
}
EXPORT_SYMBOL_GPL(pinctrl_gpio_direction_input);
/**
* pinctrl_gpio_direction_output() - request a GPIO pin to go into output mode
* @gpio: the GPIO pin number from the GPIO subsystem number space
*
* This function should *ONLY* be used from gpiolib-based GPIO drivers,
* as part of their gpio_direction_output() semantics, platforms and individual
* drivers shall *NOT* touch pin control GPIO calls.
*/
int pinctrl_gpio_direction_output(unsigned gpio)
{
return pinctrl_gpio_direction(gpio, false);
}
EXPORT_SYMBOL_GPL(pinctrl_gpio_direction_output);
static struct pinctrl_state *find_state(struct pinctrl *p,
const char *name)
{
struct pinctrl_state *state;
list_for_each_entry(state, &p->states, node)
if (!strcmp(state->name, name))
return state;
return NULL;
}
static struct pinctrl_state *create_state(struct pinctrl *p,
const char *name)
{
struct pinctrl_state *state;
state = kzalloc(sizeof(*state), GFP_KERNEL);
if (state == NULL) {
dev_err(p->dev,
"failed to alloc struct pinctrl_state\n");
return ERR_PTR(-ENOMEM);
}
state->name = name;
INIT_LIST_HEAD(&state->settings);
list_add_tail(&state->node, &p->states);
return state;
}
static int add_setting(struct pinctrl *p, struct pinctrl_map const *map)
{
struct pinctrl_state *state;
struct pinctrl_setting *setting;
int ret;
state = find_state(p, map->name);
if (!state)
state = create_state(p, map->name);
if (IS_ERR(state))
return PTR_ERR(state);
if (map->type == PIN_MAP_TYPE_DUMMY_STATE)
return 0;
setting = kzalloc(sizeof(*setting), GFP_KERNEL);
if (setting == NULL) {
dev_err(p->dev,
"failed to alloc struct pinctrl_setting\n");
return -ENOMEM;
}
setting->type = map->type;
setting->pctldev = get_pinctrl_dev_from_devname(map->ctrl_dev_name);
if (setting->pctldev == NULL) {
kfree(setting);
/* Do not defer probing of hogs (circular loop) */
if (!strcmp(map->ctrl_dev_name, map->dev_name))
return -ENODEV;
/*
* OK let us guess that the driver is not there yet, and
* let's defer obtaining this pinctrl handle to later...
*/
dev_info(p->dev, "unknown pinctrl device %s in map entry, deferring probe",
map->ctrl_dev_name);
return -EPROBE_DEFER;
}
setting->dev_name = map->dev_name;
switch (map->type) {
case PIN_MAP_TYPE_MUX_GROUP:
ret = pinmux_map_to_setting(map, setting);
break;
case PIN_MAP_TYPE_CONFIGS_PIN:
case PIN_MAP_TYPE_CONFIGS_GROUP:
ret = pinconf_map_to_setting(map, setting);
break;
default:
ret = -EINVAL;
break;
}
if (ret < 0) {
kfree(setting);
return ret;
}
list_add_tail(&setting->node, &state->settings);
return 0;
}
static struct pinctrl *find_pinctrl(struct device *dev)
{
struct pinctrl *p;
mutex_lock(&pinctrl_list_mutex);
list_for_each_entry(p, &pinctrl_list, node)
if (p->dev == dev) {
mutex_unlock(&pinctrl_list_mutex);
return p;
}
mutex_unlock(&pinctrl_list_mutex);
return NULL;
}
static void pinctrl_free(struct pinctrl *p, bool inlist);
static struct pinctrl *create_pinctrl(struct device *dev)
{
struct pinctrl *p;
const char *devname;
struct pinctrl_maps *maps_node;
int i;
struct pinctrl_map const *map;
int ret;
/*
* create the state cookie holder struct pinctrl for each
* mapping, this is what consumers will get when requesting
* a pin control handle with pinctrl_get()
*/
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (p == NULL) {
dev_err(dev, "failed to alloc struct pinctrl\n");
return ERR_PTR(-ENOMEM);
}
p->dev = dev;
INIT_LIST_HEAD(&p->states);
INIT_LIST_HEAD(&p->dt_maps);
ret = pinctrl_dt_to_map(p);
if (ret < 0) {
kfree(p);
return ERR_PTR(ret);
}
devname = dev_name(dev);
mutex_lock(&pinctrl_maps_mutex);
/* Iterate over the pin control maps to locate the right ones */
for_each_maps(maps_node, i, map) {
/* Map must be for this device */
if (strcmp(map->dev_name, devname))
continue;
ret = add_setting(p, map);
/*
* At this point the adding of a setting may:
*
* - Defer, if the pinctrl device is not yet available
* - Fail, if the pinctrl device is not yet available,
* AND the setting is a hog. We cannot defer that, since
* the hog will kick in immediately after the device
* is registered.
*
* If the error returned was not -EPROBE_DEFER then we
* accumulate the errors to see if we end up with
* an -EPROBE_DEFER later, as that is the worst case.
*/
if (ret == -EPROBE_DEFER) {
pinctrl_free(p, false);
mutex_unlock(&pinctrl_maps_mutex);
return ERR_PTR(ret);
}
}
mutex_unlock(&pinctrl_maps_mutex);
if (ret < 0) {
/* If some other error than deferral occured, return here */
pinctrl_free(p, false);
return ERR_PTR(ret);
}
kref_init(&p->users);
/* Add the pinctrl handle to the global list */
mutex_lock(&pinctrl_list_mutex);
list_add_tail(&p->node, &pinctrl_list);
mutex_unlock(&pinctrl_list_mutex);
return p;
}
/**
* pinctrl_get() - retrieves the pinctrl handle for a device
* @dev: the device to obtain the handle for
*/
struct pinctrl *pinctrl_get(struct device *dev)
{
struct pinctrl *p;
if (WARN_ON(!dev))
return ERR_PTR(-EINVAL);
/*
* See if somebody else (such as the device core) has already
* obtained a handle to the pinctrl for this device. In that case,
* return another pointer to it.
*/
p = find_pinctrl(dev);
if (p != NULL) {
dev_dbg(dev, "obtain a copy of previously claimed pinctrl\n");
kref_get(&p->users);
return p;
}
return create_pinctrl(dev);
}
EXPORT_SYMBOL_GPL(pinctrl_get);
static void pinctrl_free_setting(bool disable_setting,
struct pinctrl_setting *setting)
{
switch (setting->type) {
case PIN_MAP_TYPE_MUX_GROUP:
if (disable_setting)
pinmux_disable_setting(setting);
pinmux_free_setting(setting);
break;
case PIN_MAP_TYPE_CONFIGS_PIN:
case PIN_MAP_TYPE_CONFIGS_GROUP:
pinconf_free_setting(setting);
break;
default:
break;
}
}
static void pinctrl_free(struct pinctrl *p, bool inlist)
{
struct pinctrl_state *state, *n1;
struct pinctrl_setting *setting, *n2;
mutex_lock(&pinctrl_list_mutex);
list_for_each_entry_safe(state, n1, &p->states, node) {
list_for_each_entry_safe(setting, n2, &state->settings, node) {
pinctrl_free_setting(state == p->state, setting);
list_del(&setting->node);
kfree(setting);
}
list_del(&state->node);
kfree(state);
}
pinctrl_dt_free_maps(p);
if (inlist)
list_del(&p->node);
kfree(p);
mutex_unlock(&pinctrl_list_mutex);
}
/**
* pinctrl_release() - release the pinctrl handle
* @kref: the kref in the pinctrl being released
*/
static void pinctrl_release(struct kref *kref)
{
struct pinctrl *p = container_of(kref, struct pinctrl, users);
pinctrl_free(p, true);
}
/**
* pinctrl_put() - decrease use count on a previously claimed pinctrl handle
* @p: the pinctrl handle to release
*/
void pinctrl_put(struct pinctrl *p)
{
kref_put(&p->users, pinctrl_release);
}
EXPORT_SYMBOL_GPL(pinctrl_put);
/**
* pinctrl_lookup_state() - retrieves a state handle from a pinctrl handle
* @p: the pinctrl handle to retrieve the state from
* @name: the state name to retrieve
*/
struct pinctrl_state *pinctrl_lookup_state(struct pinctrl *p,
const char *name)
{
struct pinctrl_state *state;
state = find_state(p, name);
if (!state) {
if (pinctrl_dummy_state) {
/* create dummy state */
dev_dbg(p->dev, "using pinctrl dummy state (%s)\n",
name);
state = create_state(p, name);
} else
state = ERR_PTR(-ENODEV);
}
return state;
}
EXPORT_SYMBOL_GPL(pinctrl_lookup_state);
/**
* pinctrl_select_state() - select/activate/program a pinctrl state to HW
* @p: the pinctrl handle for the device that requests configuration
* @state: the state handle to select/activate/program
*/
int pinctrl_select_state(struct pinctrl *p, struct pinctrl_state *state)
{
struct pinctrl_setting *setting, *setting2;
struct pinctrl_state *old_state = p->state;
int ret;
if (p->state == state)
return 0;
if (p->state) {
/*
* The set of groups with a mux configuration in the old state
* may not be identical to the set of groups with a mux setting
* in the new state. While this might be unusual, it's entirely
* possible for the "user"-supplied mapping table to be written
* that way. For each group that was configured in the old state
* but not in the new state, this code puts that group into a
* safe/disabled state.
*/
list_for_each_entry(setting, &p->state->settings, node) {
bool found = false;
if (setting->type != PIN_MAP_TYPE_MUX_GROUP)
continue;
list_for_each_entry(setting2, &state->settings, node) {
if (setting2->type != PIN_MAP_TYPE_MUX_GROUP)
continue;
if (setting2->data.mux.group ==
setting->data.mux.group) {
found = true;
break;
}
}
if (!found)
pinmux_disable_setting(setting);
}
}
p->state = NULL;
/* Apply all the settings for the new state */
list_for_each_entry(setting, &state->settings, node) {
switch (setting->type) {
case PIN_MAP_TYPE_MUX_GROUP:
ret = pinmux_enable_setting(setting);
break;
case PIN_MAP_TYPE_CONFIGS_PIN:
case PIN_MAP_TYPE_CONFIGS_GROUP:
ret = pinconf_apply_setting(setting);
break;
default:
ret = -EINVAL;
break;
}
if (ret < 0) {
goto unapply_new_state;
}
}
p->state = state;
return 0;
unapply_new_state:
dev_err(p->dev, "Error applying setting, reverse things back\n");
list_for_each_entry(setting2, &state->settings, node) {
if (&setting2->node == &setting->node)
break;
/*
* All we can do here is pinmux_disable_setting.
* That means that some pins are muxed differently now
* than they were before applying the setting (We can't
* "unmux a pin"!), but it's not a big deal since the pins
* are free to be muxed by another apply_setting.
*/
if (setting2->type == PIN_MAP_TYPE_MUX_GROUP)
pinmux_disable_setting(setting2);
}
/* There's no infinite recursive loop here because p->state is NULL */
if (old_state)
pinctrl_select_state(p, old_state);
return ret;
}
EXPORT_SYMBOL_GPL(pinctrl_select_state);
static void devm_pinctrl_release(struct device *dev, void *res)
{
pinctrl_put(*(struct pinctrl **)res);
}
/**
* struct devm_pinctrl_get() - Resource managed pinctrl_get()
* @dev: the device to obtain the handle for
*
* If there is a need to explicitly destroy the returned struct pinctrl,
* devm_pinctrl_put() should be used, rather than plain pinctrl_put().
*/
struct pinctrl *devm_pinctrl_get(struct device *dev)
{
struct pinctrl **ptr, *p;
ptr = devres_alloc(devm_pinctrl_release, sizeof(*ptr), GFP_KERNEL);
if (!ptr)
return ERR_PTR(-ENOMEM);
p = pinctrl_get(dev);
if (!IS_ERR(p)) {
*ptr = p;
devres_add(dev, ptr);
} else {
devres_free(ptr);
}
return p;
}
EXPORT_SYMBOL_GPL(devm_pinctrl_get);
static int devm_pinctrl_match(struct device *dev, void *res, void *data)
{
struct pinctrl **p = res;
return *p == data;
}
/**
* devm_pinctrl_put() - Resource managed pinctrl_put()
* @p: the pinctrl handle to release
*
* Deallocate a struct pinctrl obtained via devm_pinctrl_get(). Normally
* this function will not need to be called and the resource management
* code will ensure that the resource is freed.
*/
void devm_pinctrl_put(struct pinctrl *p)
{
WARN_ON(devres_release(p->dev, devm_pinctrl_release,
devm_pinctrl_match, p));
}
EXPORT_SYMBOL_GPL(devm_pinctrl_put);
int pinctrl_register_map(struct pinctrl_map const *maps, unsigned num_maps,
bool dup)
{
int i, ret;
struct pinctrl_maps *maps_node;
pr_debug("add %d pinmux maps\n", num_maps);
/* First sanity check the new mapping */
for (i = 0; i < num_maps; i++) {
if (!maps[i].dev_name) {
pr_err("failed to register map %s (%d): no device given\n",
maps[i].name, i);
return -EINVAL;
}
if (!maps[i].name) {
pr_err("failed to register map %d: no map name given\n",
i);
return -EINVAL;
}
if (maps[i].type != PIN_MAP_TYPE_DUMMY_STATE &&
!maps[i].ctrl_dev_name) {
pr_err("failed to register map %s (%d): no pin control device given\n",
maps[i].name, i);
return -EINVAL;
}
switch (maps[i].type) {
case PIN_MAP_TYPE_DUMMY_STATE:
break;
case PIN_MAP_TYPE_MUX_GROUP:
ret = pinmux_validate_map(&maps[i], i);
if (ret < 0)
return ret;
break;
case PIN_MAP_TYPE_CONFIGS_PIN:
case PIN_MAP_TYPE_CONFIGS_GROUP:
ret = pinconf_validate_map(&maps[i], i);
if (ret < 0)
return ret;
break;
default:
pr_err("failed to register map %s (%d): invalid type given\n",
maps[i].name, i);
return -EINVAL;
}
}
maps_node = kzalloc(sizeof(*maps_node), GFP_KERNEL);
if (!maps_node) {
pr_err("failed to alloc struct pinctrl_maps\n");
return -ENOMEM;
}
maps_node->num_maps = num_maps;
if (dup) {
maps_node->maps = kmemdup(maps, sizeof(*maps) * num_maps,
GFP_KERNEL);
if (!maps_node->maps) {
pr_err("failed to duplicate mapping table\n");
kfree(maps_node);
return -ENOMEM;
}
} else {
maps_node->maps = maps;
}
mutex_lock(&pinctrl_maps_mutex);
list_add_tail(&maps_node->node, &pinctrl_maps);
mutex_unlock(&pinctrl_maps_mutex);
return 0;
}
/**
* pinctrl_register_mappings() - register a set of pin controller mappings
* @maps: the pincontrol mappings table to register. This should probably be
* marked with __initdata so it can be discarded after boot. This
* function will perform a shallow copy for the mapping entries.
* @num_maps: the number of maps in the mapping table
*/
int pinctrl_register_mappings(struct pinctrl_map const *maps,
unsigned num_maps)
{
return pinctrl_register_map(maps, num_maps, true);
}
void pinctrl_unregister_map(struct pinctrl_map const *map)
{
struct pinctrl_maps *maps_node;
mutex_lock(&pinctrl_maps_mutex);
list_for_each_entry(maps_node, &pinctrl_maps, node) {
if (maps_node->maps == map) {
list_del(&maps_node->node);
kfree(maps_node);
mutex_unlock(&pinctrl_maps_mutex);
return;
}
}
mutex_unlock(&pinctrl_maps_mutex);
}
/**
* pinctrl_force_sleep() - turn a given controller device into sleep state
* @pctldev: pin controller device
*/
int pinctrl_force_sleep(struct pinctrl_dev *pctldev)
{
if (!IS_ERR(pctldev->p) && !IS_ERR(pctldev->hog_sleep))
return pinctrl_select_state(pctldev->p, pctldev->hog_sleep);
return 0;
}
EXPORT_SYMBOL_GPL(pinctrl_force_sleep);
/**
* pinctrl_force_default() - turn a given controller device into default state
* @pctldev: pin controller device
*/
int pinctrl_force_default(struct pinctrl_dev *pctldev)
{
if (!IS_ERR(pctldev->p) && !IS_ERR(pctldev->hog_default))
return pinctrl_select_state(pctldev->p, pctldev->hog_default);
return 0;
}
EXPORT_SYMBOL_GPL(pinctrl_force_default);
#ifdef CONFIG_DEBUG_FS
static int pinctrl_pins_show(struct seq_file *s, void *what)
{
struct pinctrl_dev *pctldev = s->private;
const struct pinctrl_ops *ops = pctldev->desc->pctlops;
unsigned i, pin;
seq_printf(s, "registered pins: %d\n", pctldev->desc->npins);
mutex_lock(&pctldev->mutex);
/* The pin number can be retrived from the pin controller descriptor */
for (i = 0; i < pctldev->desc->npins; i++) {
struct pin_desc *desc;
pin = pctldev->desc->pins[i].number;
desc = pin_desc_get(pctldev, pin);
/* Pin space may be sparse */
if (desc == NULL)
continue;
seq_printf(s, "pin %d (%s) ", pin,
desc->name ? desc->name : "unnamed");
/* Driver-specific info per pin */
if (ops->pin_dbg_show)
ops->pin_dbg_show(pctldev, s, pin);
seq_puts(s, "\n");
}
mutex_unlock(&pctldev->mutex);
return 0;
}
static int pinctrl_groups_show(struct seq_file *s, void *what)
{
struct pinctrl_dev *pctldev = s->private;
const struct pinctrl_ops *ops = pctldev->desc->pctlops;
unsigned ngroups, selector = 0;
mutex_lock(&pctldev->mutex);
ngroups = ops->get_groups_count(pctldev);
seq_puts(s, "registered pin groups:\n");
while (selector < ngroups) {
const unsigned *pins;
unsigned num_pins;
const char *gname = ops->get_group_name(pctldev, selector);
const char *pname;
int ret;
int i;
ret = ops->get_group_pins(pctldev, selector,
&pins, &num_pins);
if (ret)
seq_printf(s, "%s [ERROR GETTING PINS]\n",
gname);
else {
seq_printf(s, "group: %s\n", gname);
for (i = 0; i < num_pins; i++) {
pname = pin_get_name(pctldev, pins[i]);
if (WARN_ON(!pname)) {
mutex_unlock(&pctldev->mutex);
return -EINVAL;
}
seq_printf(s, "pin %d (%s)\n", pins[i], pname);
}
seq_puts(s, "\n");
}
selector++;
}
mutex_unlock(&pctldev->mutex);
return 0;
}
static int pinctrl_gpioranges_show(struct seq_file *s, void *what)
{
struct pinctrl_dev *pctldev = s->private;
struct pinctrl_gpio_range *range = NULL;
seq_puts(s, "GPIO ranges handled:\n");
mutex_lock(&pctldev->mutex);
/* Loop over the ranges */
list_for_each_entry(range, &pctldev->gpio_ranges, node) {
seq_printf(s, "%u: %s GPIOS [%u - %u] PINS [%u - %u]\n",
range->id, range->name,
range->base, (range->base + range->npins - 1),
range->pin_base,
(range->pin_base + range->npins - 1));
}
mutex_unlock(&pctldev->mutex);
return 0;
}
static int pinctrl_devices_show(struct seq_file *s, void *what)
{
struct pinctrl_dev *pctldev;
seq_puts(s, "name [pinmux] [pinconf]\n");
mutex_lock(&pinctrldev_list_mutex);
list_for_each_entry(pctldev, &pinctrldev_list, node) {
seq_printf(s, "%s ", pctldev->desc->name);
if (pctldev->desc->pmxops)
seq_puts(s, "yes ");
else
seq_puts(s, "no ");
if (pctldev->desc->confops)
seq_puts(s, "yes");
else
seq_puts(s, "no");
seq_puts(s, "\n");
}
mutex_unlock(&pinctrldev_list_mutex);
return 0;
}
static inline const char *map_type(enum pinctrl_map_type type)
{
static const char * const names[] = {
"INVALID",
"DUMMY_STATE",
"MUX_GROUP",
"CONFIGS_PIN",
"CONFIGS_GROUP",
};
if (type >= ARRAY_SIZE(names))
return "UNKNOWN";
return names[type];
}
static int pinctrl_maps_show(struct seq_file *s, void *what)
{
struct pinctrl_maps *maps_node;
int i;
struct pinctrl_map const *map;
seq_puts(s, "Pinctrl maps:\n");
mutex_lock(&pinctrl_maps_mutex);
for_each_maps(maps_node, i, map) {
seq_printf(s, "device %s\nstate %s\ntype %s (%d)\n",
map->dev_name, map->name, map_type(map->type),
map->type);
if (map->type != PIN_MAP_TYPE_DUMMY_STATE)
seq_printf(s, "controlling device %s\n",
map->ctrl_dev_name);
switch (map->type) {
case PIN_MAP_TYPE_MUX_GROUP:
pinmux_show_map(s, map);
break;
case PIN_MAP_TYPE_CONFIGS_PIN:
case PIN_MAP_TYPE_CONFIGS_GROUP:
pinconf_show_map(s, map);
break;
default:
break;
}
seq_printf(s, "\n");
}
mutex_unlock(&pinctrl_maps_mutex);
return 0;
}
static int pinctrl_show(struct seq_file *s, void *what)
{
struct pinctrl *p;
struct pinctrl_state *state;
struct pinctrl_setting *setting;
seq_puts(s, "Requested pin control handlers their pinmux maps:\n");
mutex_lock(&pinctrl_list_mutex);
list_for_each_entry(p, &pinctrl_list, node) {
seq_printf(s, "device: %s current state: %s\n",
dev_name(p->dev),
p->state ? p->state->name : "none");
list_for_each_entry(state, &p->states, node) {
seq_printf(s, " state: %s\n", state->name);
list_for_each_entry(setting, &state->settings, node) {
struct pinctrl_dev *pctldev = setting->pctldev;
seq_printf(s, " type: %s controller %s ",
map_type(setting->type),
pinctrl_dev_get_name(pctldev));
switch (setting->type) {
case PIN_MAP_TYPE_MUX_GROUP:
pinmux_show_setting(s, setting);
break;
case PIN_MAP_TYPE_CONFIGS_PIN:
case PIN_MAP_TYPE_CONFIGS_GROUP:
pinconf_show_setting(s, setting);
break;
default:
break;
}
}
}
}
mutex_unlock(&pinctrl_list_mutex);
return 0;
}
static int pinctrl_pins_open(struct inode *inode, struct file *file)
{
return single_open(file, pinctrl_pins_show, inode->i_private);
}
static int pinctrl_groups_open(struct inode *inode, struct file *file)
{
return single_open(file, pinctrl_groups_show, inode->i_private);
}
static int pinctrl_gpioranges_open(struct inode *inode, struct file *file)
{
return single_open(file, pinctrl_gpioranges_show, inode->i_private);
}
static int pinctrl_devices_open(struct inode *inode, struct file *file)
{
return single_open(file, pinctrl_devices_show, NULL);
}
static int pinctrl_maps_open(struct inode *inode, struct file *file)
{
return single_open(file, pinctrl_maps_show, NULL);
}
static int pinctrl_open(struct inode *inode, struct file *file)
{
return single_open(file, pinctrl_show, NULL);
}
static const struct file_operations pinctrl_pins_ops = {
.open = pinctrl_pins_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations pinctrl_groups_ops = {
.open = pinctrl_groups_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations pinctrl_gpioranges_ops = {
.open = pinctrl_gpioranges_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations pinctrl_devices_ops = {
.open = pinctrl_devices_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations pinctrl_maps_ops = {
.open = pinctrl_maps_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static const struct file_operations pinctrl_ops = {
.open = pinctrl_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static struct dentry *debugfs_root;
static void pinctrl_init_device_debugfs(struct pinctrl_dev *pctldev)
{
struct dentry *device_root;
device_root = debugfs_create_dir(dev_name(pctldev->dev),
debugfs_root);
pctldev->device_root = device_root;
if (IS_ERR(device_root) || !device_root) {
pr_warn("failed to create debugfs directory for %s\n",
dev_name(pctldev->dev));
return;
}
debugfs_create_file("pins", S_IFREG | S_IRUGO,
device_root, pctldev, &pinctrl_pins_ops);
debugfs_create_file("pingroups", S_IFREG | S_IRUGO,
device_root, pctldev, &pinctrl_groups_ops);
debugfs_create_file("gpio-ranges", S_IFREG | S_IRUGO,
device_root, pctldev, &pinctrl_gpioranges_ops);
pinmux_init_device_debugfs(device_root, pctldev);
pinconf_init_device_debugfs(device_root, pctldev);
}
static void pinctrl_remove_device_debugfs(struct pinctrl_dev *pctldev)
{
debugfs_remove_recursive(pctldev->device_root);
}
static void pinctrl_init_debugfs(void)
{
debugfs_root = debugfs_create_dir("pinctrl", NULL);
if (IS_ERR(debugfs_root) || !debugfs_root) {
pr_warn("failed to create debugfs directory\n");
debugfs_root = NULL;
return;
}
debugfs_create_file("pinctrl-devices", S_IFREG | S_IRUGO,
debugfs_root, NULL, &pinctrl_devices_ops);
debugfs_create_file("pinctrl-maps", S_IFREG | S_IRUGO,
debugfs_root, NULL, &pinctrl_maps_ops);
debugfs_create_file("pinctrl-handles", S_IFREG | S_IRUGO,
debugfs_root, NULL, &pinctrl_ops);
}
#else /* CONFIG_DEBUG_FS */
static void pinctrl_init_device_debugfs(struct pinctrl_dev *pctldev)
{
}
static void pinctrl_init_debugfs(void)
{
}
static void pinctrl_remove_device_debugfs(struct pinctrl_dev *pctldev)
{
}
#endif
static int pinctrl_check_ops(struct pinctrl_dev *pctldev)
{
const struct pinctrl_ops *ops = pctldev->desc->pctlops;
if (!ops ||
!ops->get_groups_count ||
!ops->get_group_name ||
!ops->get_group_pins)
return -EINVAL;
if (ops->dt_node_to_map && !ops->dt_free_map)
return -EINVAL;
return 0;
}
/**
* pinctrl_register() - register a pin controller device
* @pctldesc: descriptor for this pin controller
* @dev: parent device for this pin controller
* @driver_data: private pin controller data for this pin controller
*/
struct pinctrl_dev *pinctrl_register(struct pinctrl_desc *pctldesc,
struct device *dev, void *driver_data)
{
struct pinctrl_dev *pctldev;
int ret;
if (!pctldesc)
return NULL;
if (!pctldesc->name)
return NULL;
pctldev = kzalloc(sizeof(*pctldev), GFP_KERNEL);
if (pctldev == NULL) {
dev_err(dev, "failed to alloc struct pinctrl_dev\n");
return NULL;
}
/* Initialize pin control device struct */
pctldev->owner = pctldesc->owner;
pctldev->desc = pctldesc;
pctldev->driver_data = driver_data;
INIT_RADIX_TREE(&pctldev->pin_desc_tree, GFP_KERNEL);
INIT_LIST_HEAD(&pctldev->gpio_ranges);
pctldev->dev = dev;
mutex_init(&pctldev->mutex);
/* check core ops for sanity */
if (pinctrl_check_ops(pctldev)) {
dev_err(dev, "pinctrl ops lacks necessary functions\n");
goto out_err;
}
/* If we're implementing pinmuxing, check the ops for sanity */
if (pctldesc->pmxops) {
if (pinmux_check_ops(pctldev))
goto out_err;
}
/* If we're implementing pinconfig, check the ops for sanity */
if (pctldesc->confops) {
if (pinconf_check_ops(pctldev))
goto out_err;
}
/* Register all the pins */
dev_dbg(dev, "try to register %d pins ...\n", pctldesc->npins);
ret = pinctrl_register_pins(pctldev, pctldesc->pins, pctldesc->npins);
if (ret) {
dev_err(dev, "error during pin registration\n");
pinctrl_free_pindescs(pctldev, pctldesc->pins,
pctldesc->npins);
goto out_err;
}
mutex_lock(&pinctrldev_list_mutex);
list_add_tail(&pctldev->node, &pinctrldev_list);
mutex_unlock(&pinctrldev_list_mutex);
pctldev->p = pinctrl_get(pctldev->dev);
if (!IS_ERR(pctldev->p)) {
pctldev->hog_default =
pinctrl_lookup_state(pctldev->p, PINCTRL_STATE_DEFAULT);
if (IS_ERR(pctldev->hog_default)) {
dev_dbg(dev, "failed to lookup the default state\n");
} else {
if (pinctrl_select_state(pctldev->p,
pctldev->hog_default))
dev_err(dev,
"failed to select default state\n");
}
pctldev->hog_sleep =
pinctrl_lookup_state(pctldev->p,
PINCTRL_STATE_SLEEP);
if (IS_ERR(pctldev->hog_sleep))
dev_dbg(dev, "failed to lookup the sleep state\n");
}
pinctrl_init_device_debugfs(pctldev);
return pctldev;
out_err:
mutex_destroy(&pctldev->mutex);
kfree(pctldev);
return NULL;
}
EXPORT_SYMBOL_GPL(pinctrl_register);
/**
* pinctrl_unregister() - unregister pinmux
* @pctldev: pin controller to unregister
*
* Called by pinmux drivers to unregister a pinmux.
*/
void pinctrl_unregister(struct pinctrl_dev *pctldev)
{
struct pinctrl_gpio_range *range, *n;
if (pctldev == NULL)
return;
mutex_lock(&pinctrldev_list_mutex);
mutex_lock(&pctldev->mutex);
pinctrl_remove_device_debugfs(pctldev);
if (!IS_ERR(pctldev->p))
pinctrl_put(pctldev->p);
/* TODO: check that no pinmuxes are still active? */
list_del(&pctldev->node);
/* Destroy descriptor tree */
pinctrl_free_pindescs(pctldev, pctldev->desc->pins,
pctldev->desc->npins);
/* remove gpio ranges map */
list_for_each_entry_safe(range, n, &pctldev->gpio_ranges, node)
list_del(&range->node);
mutex_unlock(&pctldev->mutex);
mutex_destroy(&pctldev->mutex);
kfree(pctldev);
mutex_unlock(&pinctrldev_list_mutex);
}
EXPORT_SYMBOL_GPL(pinctrl_unregister);
static int __init pinctrl_init(void)
{
pr_info("initialized pinctrl subsystem\n");
pinctrl_init_debugfs();
return 0;
}
/* init early since many drivers really need to initialized pinmux early */
core_initcall(pinctrl_init);
| gpl-2.0 |
ktraghavendra/linux | arch/m68k/mm/hwtest.c | 1689 | 2584 | /* Tests for presence or absence of hardware registers.
* This code was originally in atari/config.c, but I noticed
* that it was also in drivers/nubus/nubus.c and I wanted to
* use it in hp300/config.c, so it seemed sensible to pull it
* out into its own file.
*
* The test is for use when trying to read a hardware register
* that isn't present would cause a bus error. We set up a
* temporary handler so that this doesn't kill the kernel.
*
* There is a test-by-reading and a test-by-writing; I present
* them here complete with the comments from the original atari
* config.c...
* -- PMM <pmaydell@chiark.greenend.org.uk>, 05/1998
*/
/* This function tests for the presence of an address, specially a
* hardware register address. It is called very early in the kernel
* initialization process, when the VBR register isn't set up yet. On
* an Atari, it still points to address 0, which is unmapped. So a bus
* error would cause another bus error while fetching the exception
* vector, and the CPU would do nothing at all. So we needed to set up
* a temporary VBR and a vector table for the duration of the test.
*/
#include <linux/module.h>
int hwreg_present(volatile void *regp)
{
int ret = 0;
unsigned long flags;
long save_sp, save_vbr;
long tmp_vectors[3];
local_irq_save(flags);
__asm__ __volatile__ (
"movec %/vbr,%2\n\t"
"movel #Lberr1,%4@(8)\n\t"
"movec %4,%/vbr\n\t"
"movel %/sp,%1\n\t"
"moveq #0,%0\n\t"
"tstb %3@\n\t"
"nop\n\t"
"moveq #1,%0\n"
"Lberr1:\n\t"
"movel %1,%/sp\n\t"
"movec %2,%/vbr"
: "=&d" (ret), "=&r" (save_sp), "=&r" (save_vbr)
: "a" (regp), "a" (tmp_vectors)
);
local_irq_restore(flags);
return ret;
}
EXPORT_SYMBOL(hwreg_present);
/* Basically the same, but writes a value into a word register, protected
* by a bus error handler. Returns 1 if successful, 0 otherwise.
*/
int hwreg_write(volatile void *regp, unsigned short val)
{
int ret;
unsigned long flags;
long save_sp, save_vbr;
long tmp_vectors[3];
local_irq_save(flags);
__asm__ __volatile__ (
"movec %/vbr,%2\n\t"
"movel #Lberr2,%4@(8)\n\t"
"movec %4,%/vbr\n\t"
"movel %/sp,%1\n\t"
"moveq #0,%0\n\t"
"movew %5,%3@\n\t"
"nop\n\t"
/*
* If this nop isn't present, 'ret' may already be loaded
* with 1 at the time the bus error happens!
*/
"moveq #1,%0\n"
"Lberr2:\n\t"
"movel %1,%/sp\n\t"
"movec %2,%/vbr"
: "=&d" (ret), "=&r" (save_sp), "=&r" (save_vbr)
: "a" (regp), "a" (tmp_vectors), "g" (val)
);
local_irq_restore(flags);
return ret;
}
EXPORT_SYMBOL(hwreg_write);
| gpl-2.0 |
jyizheng/net-next-nuse-old | drivers/hwmon/max16065.c | 1945 | 22285 | /*
* Driver for
* Maxim MAX16065/MAX16066 12-Channel/8-Channel, Flash-Configurable
* System Managers with Nonvolatile Fault Registers
* Maxim MAX16067/MAX16068 6-Channel, Flash-Configurable System Managers
* with Nonvolatile Fault Registers
* Maxim MAX16070/MAX16071 12-Channel/8-Channel, Flash-Configurable System
* Monitors with Nonvolatile Fault Registers
*
* Copyright (C) 2011 Ericsson AB.
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/jiffies.h>
enum chips { max16065, max16066, max16067, max16068, max16070, max16071 };
/*
* Registers
*/
#define MAX16065_ADC(x) ((x) * 2)
#define MAX16065_CURR_SENSE 0x18
#define MAX16065_CSP_ADC 0x19
#define MAX16065_FAULT(x) (0x1b + (x))
#define MAX16065_SCALE(x) (0x43 + (x))
#define MAX16065_CURR_CONTROL 0x47
#define MAX16065_LIMIT(l, x) (0x48 + (l) + (x) * 3) /*
* l: limit
* 0: min/max
* 1: crit
* 2: lcrit
* x: ADC index
*/
#define MAX16065_SW_ENABLE 0x73
#define MAX16065_WARNING_OV (1 << 3) /* Set if secondary threshold is OV
warning */
#define MAX16065_CURR_ENABLE (1 << 0)
#define MAX16065_NUM_LIMIT 3
#define MAX16065_NUM_ADC 12 /* maximum number of ADC channels */
static const int max16065_num_adc[] = {
[max16065] = 12,
[max16066] = 8,
[max16067] = 6,
[max16068] = 6,
[max16070] = 12,
[max16071] = 8,
};
static const bool max16065_have_secondary[] = {
[max16065] = true,
[max16066] = true,
[max16067] = false,
[max16068] = false,
[max16070] = true,
[max16071] = true,
};
static const bool max16065_have_current[] = {
[max16065] = true,
[max16066] = true,
[max16067] = false,
[max16068] = false,
[max16070] = true,
[max16071] = true,
};
struct max16065_data {
enum chips type;
struct i2c_client *client;
const struct attribute_group *groups[4];
struct mutex update_lock;
bool valid;
unsigned long last_updated; /* in jiffies */
int num_adc;
bool have_current;
int curr_gain;
/* limits are in mV */
int limit[MAX16065_NUM_LIMIT][MAX16065_NUM_ADC];
int range[MAX16065_NUM_ADC + 1];/* voltage range */
int adc[MAX16065_NUM_ADC + 1]; /* adc values (raw) including csp_adc */
int curr_sense;
int fault[2];
};
static const int max16065_adc_range[] = { 5560, 2780, 1390, 0 };
static const int max16065_csp_adc_range[] = { 7000, 14000 };
/* ADC registers have 10 bit resolution. */
static inline int ADC_TO_MV(int adc, int range)
{
return (adc * range) / 1024;
}
/*
* Limit registers have 8 bit resolution and match upper 8 bits of ADC
* registers.
*/
static inline int LIMIT_TO_MV(int limit, int range)
{
return limit * range / 256;
}
static inline int MV_TO_LIMIT(int mv, int range)
{
return clamp_val(DIV_ROUND_CLOSEST(mv * 256, range), 0, 255);
}
static inline int ADC_TO_CURR(int adc, int gain)
{
return adc * 1400000 / (gain * 255);
}
/*
* max16065_read_adc()
*
* Read 16 bit value from <reg>, <reg+1>.
* Upper 8 bits are in <reg>, lower 2 bits are in bits 7:6 of <reg+1>.
*/
static int max16065_read_adc(struct i2c_client *client, int reg)
{
int rv;
rv = i2c_smbus_read_word_swapped(client, reg);
if (unlikely(rv < 0))
return rv;
return rv >> 6;
}
static struct max16065_data *max16065_update_device(struct device *dev)
{
struct max16065_data *data = dev_get_drvdata(dev);
struct i2c_client *client = data->client;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ) || !data->valid) {
int i;
for (i = 0; i < data->num_adc; i++)
data->adc[i]
= max16065_read_adc(client, MAX16065_ADC(i));
if (data->have_current) {
data->adc[MAX16065_NUM_ADC]
= max16065_read_adc(client, MAX16065_CSP_ADC);
data->curr_sense
= i2c_smbus_read_byte_data(client,
MAX16065_CURR_SENSE);
}
for (i = 0; i < DIV_ROUND_UP(data->num_adc, 8); i++)
data->fault[i]
= i2c_smbus_read_byte_data(client, MAX16065_FAULT(i));
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t max16065_show_alarm(struct device *dev,
struct device_attribute *da, char *buf)
{
struct sensor_device_attribute_2 *attr2 = to_sensor_dev_attr_2(da);
struct max16065_data *data = max16065_update_device(dev);
int val = data->fault[attr2->nr];
if (val < 0)
return val;
val &= (1 << attr2->index);
if (val)
i2c_smbus_write_byte_data(data->client,
MAX16065_FAULT(attr2->nr), val);
return snprintf(buf, PAGE_SIZE, "%d\n", !!val);
}
static ssize_t max16065_show_input(struct device *dev,
struct device_attribute *da, char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
struct max16065_data *data = max16065_update_device(dev);
int adc = data->adc[attr->index];
if (unlikely(adc < 0))
return adc;
return snprintf(buf, PAGE_SIZE, "%d\n",
ADC_TO_MV(adc, data->range[attr->index]));
}
static ssize_t max16065_show_current(struct device *dev,
struct device_attribute *da, char *buf)
{
struct max16065_data *data = max16065_update_device(dev);
if (unlikely(data->curr_sense < 0))
return data->curr_sense;
return snprintf(buf, PAGE_SIZE, "%d\n",
ADC_TO_CURR(data->curr_sense, data->curr_gain));
}
static ssize_t max16065_set_limit(struct device *dev,
struct device_attribute *da,
const char *buf, size_t count)
{
struct sensor_device_attribute_2 *attr2 = to_sensor_dev_attr_2(da);
struct max16065_data *data = dev_get_drvdata(dev);
unsigned long val;
int err;
int limit;
err = kstrtoul(buf, 10, &val);
if (unlikely(err < 0))
return err;
limit = MV_TO_LIMIT(val, data->range[attr2->index]);
mutex_lock(&data->update_lock);
data->limit[attr2->nr][attr2->index]
= LIMIT_TO_MV(limit, data->range[attr2->index]);
i2c_smbus_write_byte_data(data->client,
MAX16065_LIMIT(attr2->nr, attr2->index),
limit);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t max16065_show_limit(struct device *dev,
struct device_attribute *da, char *buf)
{
struct sensor_device_attribute_2 *attr2 = to_sensor_dev_attr_2(da);
struct max16065_data *data = dev_get_drvdata(dev);
return snprintf(buf, PAGE_SIZE, "%d\n",
data->limit[attr2->nr][attr2->index]);
}
/* Construct a sensor_device_attribute structure for each register */
/* Input voltages */
static SENSOR_DEVICE_ATTR(in0_input, S_IRUGO, max16065_show_input, NULL, 0);
static SENSOR_DEVICE_ATTR(in1_input, S_IRUGO, max16065_show_input, NULL, 1);
static SENSOR_DEVICE_ATTR(in2_input, S_IRUGO, max16065_show_input, NULL, 2);
static SENSOR_DEVICE_ATTR(in3_input, S_IRUGO, max16065_show_input, NULL, 3);
static SENSOR_DEVICE_ATTR(in4_input, S_IRUGO, max16065_show_input, NULL, 4);
static SENSOR_DEVICE_ATTR(in5_input, S_IRUGO, max16065_show_input, NULL, 5);
static SENSOR_DEVICE_ATTR(in6_input, S_IRUGO, max16065_show_input, NULL, 6);
static SENSOR_DEVICE_ATTR(in7_input, S_IRUGO, max16065_show_input, NULL, 7);
static SENSOR_DEVICE_ATTR(in8_input, S_IRUGO, max16065_show_input, NULL, 8);
static SENSOR_DEVICE_ATTR(in9_input, S_IRUGO, max16065_show_input, NULL, 9);
static SENSOR_DEVICE_ATTR(in10_input, S_IRUGO, max16065_show_input, NULL, 10);
static SENSOR_DEVICE_ATTR(in11_input, S_IRUGO, max16065_show_input, NULL, 11);
static SENSOR_DEVICE_ATTR(in12_input, S_IRUGO, max16065_show_input, NULL, 12);
/* Input voltages lcrit */
static SENSOR_DEVICE_ATTR_2(in0_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 0);
static SENSOR_DEVICE_ATTR_2(in1_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 1);
static SENSOR_DEVICE_ATTR_2(in2_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 2);
static SENSOR_DEVICE_ATTR_2(in3_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 3);
static SENSOR_DEVICE_ATTR_2(in4_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 4);
static SENSOR_DEVICE_ATTR_2(in5_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 5);
static SENSOR_DEVICE_ATTR_2(in6_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 6);
static SENSOR_DEVICE_ATTR_2(in7_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 7);
static SENSOR_DEVICE_ATTR_2(in8_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 8);
static SENSOR_DEVICE_ATTR_2(in9_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 9);
static SENSOR_DEVICE_ATTR_2(in10_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 10);
static SENSOR_DEVICE_ATTR_2(in11_lcrit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 2, 11);
/* Input voltages crit */
static SENSOR_DEVICE_ATTR_2(in0_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 0);
static SENSOR_DEVICE_ATTR_2(in1_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 1);
static SENSOR_DEVICE_ATTR_2(in2_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 2);
static SENSOR_DEVICE_ATTR_2(in3_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 3);
static SENSOR_DEVICE_ATTR_2(in4_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 4);
static SENSOR_DEVICE_ATTR_2(in5_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 5);
static SENSOR_DEVICE_ATTR_2(in6_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 6);
static SENSOR_DEVICE_ATTR_2(in7_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 7);
static SENSOR_DEVICE_ATTR_2(in8_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 8);
static SENSOR_DEVICE_ATTR_2(in9_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 9);
static SENSOR_DEVICE_ATTR_2(in10_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 10);
static SENSOR_DEVICE_ATTR_2(in11_crit, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 1, 11);
/* Input voltages min */
static SENSOR_DEVICE_ATTR_2(in0_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 0);
static SENSOR_DEVICE_ATTR_2(in1_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 1);
static SENSOR_DEVICE_ATTR_2(in2_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 2);
static SENSOR_DEVICE_ATTR_2(in3_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 3);
static SENSOR_DEVICE_ATTR_2(in4_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 4);
static SENSOR_DEVICE_ATTR_2(in5_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 5);
static SENSOR_DEVICE_ATTR_2(in6_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 6);
static SENSOR_DEVICE_ATTR_2(in7_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 7);
static SENSOR_DEVICE_ATTR_2(in8_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 8);
static SENSOR_DEVICE_ATTR_2(in9_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 9);
static SENSOR_DEVICE_ATTR_2(in10_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 10);
static SENSOR_DEVICE_ATTR_2(in11_min, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 11);
/* Input voltages max */
static SENSOR_DEVICE_ATTR_2(in0_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 0);
static SENSOR_DEVICE_ATTR_2(in1_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 1);
static SENSOR_DEVICE_ATTR_2(in2_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 2);
static SENSOR_DEVICE_ATTR_2(in3_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 3);
static SENSOR_DEVICE_ATTR_2(in4_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 4);
static SENSOR_DEVICE_ATTR_2(in5_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 5);
static SENSOR_DEVICE_ATTR_2(in6_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 6);
static SENSOR_DEVICE_ATTR_2(in7_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 7);
static SENSOR_DEVICE_ATTR_2(in8_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 8);
static SENSOR_DEVICE_ATTR_2(in9_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 9);
static SENSOR_DEVICE_ATTR_2(in10_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 10);
static SENSOR_DEVICE_ATTR_2(in11_max, S_IWUSR | S_IRUGO, max16065_show_limit,
max16065_set_limit, 0, 11);
/* alarms */
static SENSOR_DEVICE_ATTR_2(in0_alarm, S_IRUGO, max16065_show_alarm, NULL,
0, 0);
static SENSOR_DEVICE_ATTR_2(in1_alarm, S_IRUGO, max16065_show_alarm, NULL,
0, 1);
static SENSOR_DEVICE_ATTR_2(in2_alarm, S_IRUGO, max16065_show_alarm, NULL,
0, 2);
static SENSOR_DEVICE_ATTR_2(in3_alarm, S_IRUGO, max16065_show_alarm, NULL,
0, 3);
static SENSOR_DEVICE_ATTR_2(in4_alarm, S_IRUGO, max16065_show_alarm, NULL,
0, 4);
static SENSOR_DEVICE_ATTR_2(in5_alarm, S_IRUGO, max16065_show_alarm, NULL,
0, 5);
static SENSOR_DEVICE_ATTR_2(in6_alarm, S_IRUGO, max16065_show_alarm, NULL,
0, 6);
static SENSOR_DEVICE_ATTR_2(in7_alarm, S_IRUGO, max16065_show_alarm, NULL,
0, 7);
static SENSOR_DEVICE_ATTR_2(in8_alarm, S_IRUGO, max16065_show_alarm, NULL,
1, 0);
static SENSOR_DEVICE_ATTR_2(in9_alarm, S_IRUGO, max16065_show_alarm, NULL,
1, 1);
static SENSOR_DEVICE_ATTR_2(in10_alarm, S_IRUGO, max16065_show_alarm, NULL,
1, 2);
static SENSOR_DEVICE_ATTR_2(in11_alarm, S_IRUGO, max16065_show_alarm, NULL,
1, 3);
/* Current and alarm */
static SENSOR_DEVICE_ATTR(curr1_input, S_IRUGO, max16065_show_current, NULL, 0);
static SENSOR_DEVICE_ATTR_2(curr1_alarm, S_IRUGO, max16065_show_alarm, NULL,
1, 4);
/*
* Finally, construct an array of pointers to members of the above objects,
* as required for sysfs_create_group()
*/
static struct attribute *max16065_basic_attributes[] = {
&sensor_dev_attr_in0_input.dev_attr.attr,
&sensor_dev_attr_in0_lcrit.dev_attr.attr,
&sensor_dev_attr_in0_crit.dev_attr.attr,
&sensor_dev_attr_in0_alarm.dev_attr.attr,
&sensor_dev_attr_in1_input.dev_attr.attr,
&sensor_dev_attr_in1_lcrit.dev_attr.attr,
&sensor_dev_attr_in1_crit.dev_attr.attr,
&sensor_dev_attr_in1_alarm.dev_attr.attr,
&sensor_dev_attr_in2_input.dev_attr.attr,
&sensor_dev_attr_in2_lcrit.dev_attr.attr,
&sensor_dev_attr_in2_crit.dev_attr.attr,
&sensor_dev_attr_in2_alarm.dev_attr.attr,
&sensor_dev_attr_in3_input.dev_attr.attr,
&sensor_dev_attr_in3_lcrit.dev_attr.attr,
&sensor_dev_attr_in3_crit.dev_attr.attr,
&sensor_dev_attr_in3_alarm.dev_attr.attr,
&sensor_dev_attr_in4_input.dev_attr.attr,
&sensor_dev_attr_in4_lcrit.dev_attr.attr,
&sensor_dev_attr_in4_crit.dev_attr.attr,
&sensor_dev_attr_in4_alarm.dev_attr.attr,
&sensor_dev_attr_in5_input.dev_attr.attr,
&sensor_dev_attr_in5_lcrit.dev_attr.attr,
&sensor_dev_attr_in5_crit.dev_attr.attr,
&sensor_dev_attr_in5_alarm.dev_attr.attr,
&sensor_dev_attr_in6_input.dev_attr.attr,
&sensor_dev_attr_in6_lcrit.dev_attr.attr,
&sensor_dev_attr_in6_crit.dev_attr.attr,
&sensor_dev_attr_in6_alarm.dev_attr.attr,
&sensor_dev_attr_in7_input.dev_attr.attr,
&sensor_dev_attr_in7_lcrit.dev_attr.attr,
&sensor_dev_attr_in7_crit.dev_attr.attr,
&sensor_dev_attr_in7_alarm.dev_attr.attr,
&sensor_dev_attr_in8_input.dev_attr.attr,
&sensor_dev_attr_in8_lcrit.dev_attr.attr,
&sensor_dev_attr_in8_crit.dev_attr.attr,
&sensor_dev_attr_in8_alarm.dev_attr.attr,
&sensor_dev_attr_in9_input.dev_attr.attr,
&sensor_dev_attr_in9_lcrit.dev_attr.attr,
&sensor_dev_attr_in9_crit.dev_attr.attr,
&sensor_dev_attr_in9_alarm.dev_attr.attr,
&sensor_dev_attr_in10_input.dev_attr.attr,
&sensor_dev_attr_in10_lcrit.dev_attr.attr,
&sensor_dev_attr_in10_crit.dev_attr.attr,
&sensor_dev_attr_in10_alarm.dev_attr.attr,
&sensor_dev_attr_in11_input.dev_attr.attr,
&sensor_dev_attr_in11_lcrit.dev_attr.attr,
&sensor_dev_attr_in11_crit.dev_attr.attr,
&sensor_dev_attr_in11_alarm.dev_attr.attr,
NULL
};
static struct attribute *max16065_current_attributes[] = {
&sensor_dev_attr_in12_input.dev_attr.attr,
&sensor_dev_attr_curr1_input.dev_attr.attr,
&sensor_dev_attr_curr1_alarm.dev_attr.attr,
NULL
};
static struct attribute *max16065_min_attributes[] = {
&sensor_dev_attr_in0_min.dev_attr.attr,
&sensor_dev_attr_in1_min.dev_attr.attr,
&sensor_dev_attr_in2_min.dev_attr.attr,
&sensor_dev_attr_in3_min.dev_attr.attr,
&sensor_dev_attr_in4_min.dev_attr.attr,
&sensor_dev_attr_in5_min.dev_attr.attr,
&sensor_dev_attr_in6_min.dev_attr.attr,
&sensor_dev_attr_in7_min.dev_attr.attr,
&sensor_dev_attr_in8_min.dev_attr.attr,
&sensor_dev_attr_in9_min.dev_attr.attr,
&sensor_dev_attr_in10_min.dev_attr.attr,
&sensor_dev_attr_in11_min.dev_attr.attr,
NULL
};
static struct attribute *max16065_max_attributes[] = {
&sensor_dev_attr_in0_max.dev_attr.attr,
&sensor_dev_attr_in1_max.dev_attr.attr,
&sensor_dev_attr_in2_max.dev_attr.attr,
&sensor_dev_attr_in3_max.dev_attr.attr,
&sensor_dev_attr_in4_max.dev_attr.attr,
&sensor_dev_attr_in5_max.dev_attr.attr,
&sensor_dev_attr_in6_max.dev_attr.attr,
&sensor_dev_attr_in7_max.dev_attr.attr,
&sensor_dev_attr_in8_max.dev_attr.attr,
&sensor_dev_attr_in9_max.dev_attr.attr,
&sensor_dev_attr_in10_max.dev_attr.attr,
&sensor_dev_attr_in11_max.dev_attr.attr,
NULL
};
static umode_t max16065_basic_is_visible(struct kobject *kobj,
struct attribute *a, int n)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct max16065_data *data = dev_get_drvdata(dev);
int index = n / 4;
if (index >= data->num_adc || !data->range[index])
return 0;
return a->mode;
}
static umode_t max16065_secondary_is_visible(struct kobject *kobj,
struct attribute *a, int index)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct max16065_data *data = dev_get_drvdata(dev);
if (index >= data->num_adc)
return 0;
return a->mode;
}
static const struct attribute_group max16065_basic_group = {
.attrs = max16065_basic_attributes,
.is_visible = max16065_basic_is_visible,
};
static const struct attribute_group max16065_current_group = {
.attrs = max16065_current_attributes,
};
static const struct attribute_group max16065_min_group = {
.attrs = max16065_min_attributes,
.is_visible = max16065_secondary_is_visible,
};
static const struct attribute_group max16065_max_group = {
.attrs = max16065_max_attributes,
.is_visible = max16065_secondary_is_visible,
};
static int max16065_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = client->adapter;
struct max16065_data *data;
struct device *dev = &client->dev;
struct device *hwmon_dev;
int i, j, val;
bool have_secondary; /* true if chip has secondary limits */
bool secondary_is_max = false; /* secondary limits reflect max */
int groups = 0;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA
| I2C_FUNC_SMBUS_READ_WORD_DATA))
return -ENODEV;
data = devm_kzalloc(dev, sizeof(*data), GFP_KERNEL);
if (unlikely(!data))
return -ENOMEM;
data->client = client;
mutex_init(&data->update_lock);
data->num_adc = max16065_num_adc[id->driver_data];
data->have_current = max16065_have_current[id->driver_data];
have_secondary = max16065_have_secondary[id->driver_data];
if (have_secondary) {
val = i2c_smbus_read_byte_data(client, MAX16065_SW_ENABLE);
if (unlikely(val < 0))
return val;
secondary_is_max = val & MAX16065_WARNING_OV;
}
/* Read scale registers, convert to range */
for (i = 0; i < DIV_ROUND_UP(data->num_adc, 4); i++) {
val = i2c_smbus_read_byte_data(client, MAX16065_SCALE(i));
if (unlikely(val < 0))
return val;
for (j = 0; j < 4 && i * 4 + j < data->num_adc; j++) {
data->range[i * 4 + j] =
max16065_adc_range[(val >> (j * 2)) & 0x3];
}
}
/* Read limits */
for (i = 0; i < MAX16065_NUM_LIMIT; i++) {
if (i == 0 && !have_secondary)
continue;
for (j = 0; j < data->num_adc; j++) {
val = i2c_smbus_read_byte_data(client,
MAX16065_LIMIT(i, j));
if (unlikely(val < 0))
return val;
data->limit[i][j] = LIMIT_TO_MV(val, data->range[j]);
}
}
/* sysfs hooks */
data->groups[groups++] = &max16065_basic_group;
if (have_secondary)
data->groups[groups++] = secondary_is_max ?
&max16065_max_group : &max16065_min_group;
if (data->have_current) {
val = i2c_smbus_read_byte_data(client, MAX16065_CURR_CONTROL);
if (unlikely(val < 0))
return val;
if (val & MAX16065_CURR_ENABLE) {
/*
* Current gain is 6, 12, 24, 48 based on values in
* bit 2,3.
*/
data->curr_gain = 6 << ((val >> 2) & 0x03);
data->range[MAX16065_NUM_ADC]
= max16065_csp_adc_range[(val >> 1) & 0x01];
data->groups[groups++] = &max16065_current_group;
} else {
data->have_current = false;
}
}
hwmon_dev = devm_hwmon_device_register_with_groups(dev, client->name,
data, data->groups);
return PTR_ERR_OR_ZERO(hwmon_dev);
}
static const struct i2c_device_id max16065_id[] = {
{ "max16065", max16065 },
{ "max16066", max16066 },
{ "max16067", max16067 },
{ "max16068", max16068 },
{ "max16070", max16070 },
{ "max16071", max16071 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max16065_id);
/* This is the driver that will be inserted */
static struct i2c_driver max16065_driver = {
.driver = {
.name = "max16065",
},
.probe = max16065_probe,
.id_table = max16065_id,
};
module_i2c_driver(max16065_driver);
MODULE_AUTHOR("Guenter Roeck <linux@roeck-us.net>");
MODULE_DESCRIPTION("MAX16065 driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
vic3t3chn0/kernel_ubuntu_togari | drivers/rtc/rtc-pcf8563.c | 3225 | 7407 | /*
* An I2C driver for the Philips PCF8563 RTC
* Copyright 2005-06 Tower Technologies
*
* Author: Alessandro Zummo <a.zummo@towertech.it>
* Maintainers: http://www.nslu2-linux.org/
*
* based on the other drivers in this same directory.
*
* http://www.semiconductors.philips.com/acrobat/datasheets/PCF8563-04.pdf
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/i2c.h>
#include <linux/bcd.h>
#include <linux/rtc.h>
#include <linux/slab.h>
#define DRV_VERSION "0.4.3"
#define PCF8563_REG_ST1 0x00 /* status */
#define PCF8563_REG_ST2 0x01
#define PCF8563_REG_SC 0x02 /* datetime */
#define PCF8563_REG_MN 0x03
#define PCF8563_REG_HR 0x04
#define PCF8563_REG_DM 0x05
#define PCF8563_REG_DW 0x06
#define PCF8563_REG_MO 0x07
#define PCF8563_REG_YR 0x08
#define PCF8563_REG_AMN 0x09 /* alarm */
#define PCF8563_REG_AHR 0x0A
#define PCF8563_REG_ADM 0x0B
#define PCF8563_REG_ADW 0x0C
#define PCF8563_REG_CLKO 0x0D /* clock out */
#define PCF8563_REG_TMRC 0x0E /* timer control */
#define PCF8563_REG_TMR 0x0F /* timer */
#define PCF8563_SC_LV 0x80 /* low voltage */
#define PCF8563_MO_C 0x80 /* century */
static struct i2c_driver pcf8563_driver;
struct pcf8563 {
struct rtc_device *rtc;
/*
* The meaning of MO_C bit varies by the chip type.
* From PCF8563 datasheet: this bit is toggled when the years
* register overflows from 99 to 00
* 0 indicates the century is 20xx
* 1 indicates the century is 19xx
* From RTC8564 datasheet: this bit indicates change of
* century. When the year digit data overflows from 99 to 00,
* this bit is set. By presetting it to 0 while still in the
* 20th century, it will be set in year 2000, ...
* There seems no reliable way to know how the system use this
* bit. So let's do it heuristically, assuming we are live in
* 1970...2069.
*/
int c_polarity; /* 0: MO_C=1 means 19xx, otherwise MO_C=1 means 20xx */
};
/*
* In the routines that deal directly with the pcf8563 hardware, we use
* rtc_time -- month 0-11, hour 0-23, yr = calendar year-epoch.
*/
static int pcf8563_get_datetime(struct i2c_client *client, struct rtc_time *tm)
{
struct pcf8563 *pcf8563 = i2c_get_clientdata(client);
unsigned char buf[13] = { PCF8563_REG_ST1 };
struct i2c_msg msgs[] = {
{ client->addr, 0, 1, buf }, /* setup read ptr */
{ client->addr, I2C_M_RD, 13, buf }, /* read status + date */
};
/* read registers */
if ((i2c_transfer(client->adapter, msgs, 2)) != 2) {
dev_err(&client->dev, "%s: read error\n", __func__);
return -EIO;
}
if (buf[PCF8563_REG_SC] & PCF8563_SC_LV)
dev_info(&client->dev,
"low voltage detected, date/time is not reliable.\n");
dev_dbg(&client->dev,
"%s: raw data is st1=%02x, st2=%02x, sec=%02x, min=%02x, hr=%02x, "
"mday=%02x, wday=%02x, mon=%02x, year=%02x\n",
__func__,
buf[0], buf[1], buf[2], buf[3],
buf[4], buf[5], buf[6], buf[7],
buf[8]);
tm->tm_sec = bcd2bin(buf[PCF8563_REG_SC] & 0x7F);
tm->tm_min = bcd2bin(buf[PCF8563_REG_MN] & 0x7F);
tm->tm_hour = bcd2bin(buf[PCF8563_REG_HR] & 0x3F); /* rtc hr 0-23 */
tm->tm_mday = bcd2bin(buf[PCF8563_REG_DM] & 0x3F);
tm->tm_wday = buf[PCF8563_REG_DW] & 0x07;
tm->tm_mon = bcd2bin(buf[PCF8563_REG_MO] & 0x1F) - 1; /* rtc mn 1-12 */
tm->tm_year = bcd2bin(buf[PCF8563_REG_YR]);
if (tm->tm_year < 70)
tm->tm_year += 100; /* assume we are in 1970...2069 */
/* detect the polarity heuristically. see note above. */
pcf8563->c_polarity = (buf[PCF8563_REG_MO] & PCF8563_MO_C) ?
(tm->tm_year >= 100) : (tm->tm_year < 100);
dev_dbg(&client->dev, "%s: tm is secs=%d, mins=%d, hours=%d, "
"mday=%d, mon=%d, year=%d, wday=%d\n",
__func__,
tm->tm_sec, tm->tm_min, tm->tm_hour,
tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday);
/* the clock can give out invalid datetime, but we cannot return
* -EINVAL otherwise hwclock will refuse to set the time on bootup.
*/
if (rtc_valid_tm(tm) < 0)
dev_err(&client->dev, "retrieved date/time is not valid.\n");
return 0;
}
static int pcf8563_set_datetime(struct i2c_client *client, struct rtc_time *tm)
{
struct pcf8563 *pcf8563 = i2c_get_clientdata(client);
int i, err;
unsigned char buf[9];
dev_dbg(&client->dev, "%s: secs=%d, mins=%d, hours=%d, "
"mday=%d, mon=%d, year=%d, wday=%d\n",
__func__,
tm->tm_sec, tm->tm_min, tm->tm_hour,
tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday);
/* hours, minutes and seconds */
buf[PCF8563_REG_SC] = bin2bcd(tm->tm_sec);
buf[PCF8563_REG_MN] = bin2bcd(tm->tm_min);
buf[PCF8563_REG_HR] = bin2bcd(tm->tm_hour);
buf[PCF8563_REG_DM] = bin2bcd(tm->tm_mday);
/* month, 1 - 12 */
buf[PCF8563_REG_MO] = bin2bcd(tm->tm_mon + 1);
/* year and century */
buf[PCF8563_REG_YR] = bin2bcd(tm->tm_year % 100);
if (pcf8563->c_polarity ? (tm->tm_year >= 100) : (tm->tm_year < 100))
buf[PCF8563_REG_MO] |= PCF8563_MO_C;
buf[PCF8563_REG_DW] = tm->tm_wday & 0x07;
/* write register's data */
for (i = 0; i < 7; i++) {
unsigned char data[2] = { PCF8563_REG_SC + i,
buf[PCF8563_REG_SC + i] };
err = i2c_master_send(client, data, sizeof(data));
if (err != sizeof(data)) {
dev_err(&client->dev,
"%s: err=%d addr=%02x, data=%02x\n",
__func__, err, data[0], data[1]);
return -EIO;
}
};
return 0;
}
static int pcf8563_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
return pcf8563_get_datetime(to_i2c_client(dev), tm);
}
static int pcf8563_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
return pcf8563_set_datetime(to_i2c_client(dev), tm);
}
static const struct rtc_class_ops pcf8563_rtc_ops = {
.read_time = pcf8563_rtc_read_time,
.set_time = pcf8563_rtc_set_time,
};
static int pcf8563_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pcf8563 *pcf8563;
int err = 0;
dev_dbg(&client->dev, "%s\n", __func__);
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
return -ENODEV;
pcf8563 = kzalloc(sizeof(struct pcf8563), GFP_KERNEL);
if (!pcf8563)
return -ENOMEM;
dev_info(&client->dev, "chip found, driver version " DRV_VERSION "\n");
i2c_set_clientdata(client, pcf8563);
pcf8563->rtc = rtc_device_register(pcf8563_driver.driver.name,
&client->dev, &pcf8563_rtc_ops, THIS_MODULE);
if (IS_ERR(pcf8563->rtc)) {
err = PTR_ERR(pcf8563->rtc);
goto exit_kfree;
}
return 0;
exit_kfree:
kfree(pcf8563);
return err;
}
static int pcf8563_remove(struct i2c_client *client)
{
struct pcf8563 *pcf8563 = i2c_get_clientdata(client);
if (pcf8563->rtc)
rtc_device_unregister(pcf8563->rtc);
kfree(pcf8563);
return 0;
}
static const struct i2c_device_id pcf8563_id[] = {
{ "pcf8563", 0 },
{ "rtc8564", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, pcf8563_id);
static struct i2c_driver pcf8563_driver = {
.driver = {
.name = "rtc-pcf8563",
},
.probe = pcf8563_probe,
.remove = pcf8563_remove,
.id_table = pcf8563_id,
};
static int __init pcf8563_init(void)
{
return i2c_add_driver(&pcf8563_driver);
}
static void __exit pcf8563_exit(void)
{
i2c_del_driver(&pcf8563_driver);
}
MODULE_AUTHOR("Alessandro Zummo <a.zummo@towertech.it>");
MODULE_DESCRIPTION("Philips PCF8563/Epson RTC8564 RTC driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
module_init(pcf8563_init);
module_exit(pcf8563_exit);
| gpl-2.0 |
ChronoMonochrome/Samsung_STE_Kernel | arch/frv/kernel/gdb-io.c | 3993 | 4990 | /* gdb-io.c: FR403 GDB stub I/O
*
* Copyright (C) 2003 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.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/string.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/serial_reg.h>
#include <asm/pgtable.h>
#include <asm/system.h>
#include <asm/irc-regs.h>
#include <asm/timer-regs.h>
#include <asm/gdb-stub.h>
#include "gdb-io.h"
#ifdef CONFIG_GDBSTUB_UART0
#define __UART(X) (*(volatile uint8_t *)(UART0_BASE + (UART_##X)))
#define __UART_IRR_NMI 0xff0f0000
#else /* CONFIG_GDBSTUB_UART1 */
#define __UART(X) (*(volatile uint8_t *)(UART1_BASE + (UART_##X)))
#define __UART_IRR_NMI 0xfff00000
#endif
#define LSR_WAIT_FOR(STATE) \
do { \
gdbstub_do_rx(); \
} while (!(__UART(LSR) & UART_LSR_##STATE))
#define FLOWCTL_QUERY(LINE) ({ __UART(MSR) & UART_MSR_##LINE; })
#define FLOWCTL_CLEAR(LINE) do { __UART(MCR) &= ~UART_MCR_##LINE; mb(); } while (0)
#define FLOWCTL_SET(LINE) do { __UART(MCR) |= UART_MCR_##LINE; mb(); } while (0)
#define FLOWCTL_WAIT_FOR(LINE) \
do { \
gdbstub_do_rx(); \
} while(!FLOWCTL_QUERY(LINE))
/*****************************************************************************/
/*
* initialise the GDB stub
* - called with PSR.ET==0, so can't incur external interrupts
*/
void gdbstub_io_init(void)
{
/* set up the serial port */
__UART(LCR) = UART_LCR_WLEN8; /* 1N8 */
__UART(FCR) =
UART_FCR_ENABLE_FIFO |
UART_FCR_CLEAR_RCVR |
UART_FCR_CLEAR_XMIT |
UART_FCR_TRIGGER_1;
FLOWCTL_CLEAR(DTR);
FLOWCTL_SET(RTS);
// gdbstub_set_baud(115200);
/* we want to get serial receive interrupts */
__UART(IER) = UART_IER_RDI | UART_IER_RLSI;
mb();
__set_IRR(6, __UART_IRR_NMI); /* map ERRs and UARTx to NMI */
} /* end gdbstub_io_init() */
/*****************************************************************************/
/*
* set up the GDB stub serial port baud rate timers
*/
void gdbstub_set_baud(unsigned baud)
{
unsigned value, high, low;
u8 lcr;
/* work out the divisor to give us the nearest higher baud rate */
value = __serial_clock_speed_HZ / 16 / baud;
/* determine the baud rate range */
high = __serial_clock_speed_HZ / 16 / value;
low = __serial_clock_speed_HZ / 16 / (value + 1);
/* pick the nearest bound */
if (low + (high - low) / 2 > baud)
value++;
lcr = __UART(LCR);
__UART(LCR) |= UART_LCR_DLAB;
mb();
__UART(DLL) = value & 0xff;
__UART(DLM) = (value >> 8) & 0xff;
mb();
__UART(LCR) = lcr;
mb();
} /* end gdbstub_set_baud() */
/*****************************************************************************/
/*
* receive characters into the receive FIFO
*/
void gdbstub_do_rx(void)
{
unsigned ix, nix;
ix = gdbstub_rx_inp;
while (__UART(LSR) & UART_LSR_DR) {
nix = (ix + 2) & 0xfff;
if (nix == gdbstub_rx_outp)
break;
gdbstub_rx_buffer[ix++] = __UART(LSR);
gdbstub_rx_buffer[ix++] = __UART(RX);
ix = nix;
}
gdbstub_rx_inp = ix;
__clr_RC(15);
__clr_IRL();
} /* end gdbstub_do_rx() */
/*****************************************************************************/
/*
* wait for a character to come from the debugger
*/
int gdbstub_rx_char(unsigned char *_ch, int nonblock)
{
unsigned ix;
u8 ch, st;
*_ch = 0xff;
if (gdbstub_rx_unget) {
*_ch = gdbstub_rx_unget;
gdbstub_rx_unget = 0;
return 0;
}
try_again:
gdbstub_do_rx();
/* pull chars out of the buffer */
ix = gdbstub_rx_outp;
if (ix == gdbstub_rx_inp) {
if (nonblock)
return -EAGAIN;
//watchdog_alert_counter = 0;
goto try_again;
}
st = gdbstub_rx_buffer[ix++];
ch = gdbstub_rx_buffer[ix++];
gdbstub_rx_outp = ix & 0x00000fff;
if (st & UART_LSR_BI) {
gdbstub_proto("### GDB Rx Break Detected ###\n");
return -EINTR;
}
else if (st & (UART_LSR_FE|UART_LSR_OE|UART_LSR_PE)) {
gdbstub_io("### GDB Rx Error (st=%02x) ###\n",st);
return -EIO;
}
else {
gdbstub_io("### GDB Rx %02x (st=%02x) ###\n",ch,st);
*_ch = ch & 0x7f;
return 0;
}
} /* end gdbstub_rx_char() */
/*****************************************************************************/
/*
* send a character to the debugger
*/
void gdbstub_tx_char(unsigned char ch)
{
FLOWCTL_SET(DTR);
LSR_WAIT_FOR(THRE);
// FLOWCTL_WAIT_FOR(CTS);
if (ch == 0x0a) {
__UART(TX) = 0x0d;
mb();
LSR_WAIT_FOR(THRE);
// FLOWCTL_WAIT_FOR(CTS);
}
__UART(TX) = ch;
mb();
FLOWCTL_CLEAR(DTR);
} /* end gdbstub_tx_char() */
/*****************************************************************************/
/*
* send a character to the debugger
*/
void gdbstub_tx_flush(void)
{
LSR_WAIT_FOR(TEMT);
LSR_WAIT_FOR(THRE);
FLOWCTL_CLEAR(DTR);
} /* end gdbstub_tx_flush() */
| gpl-2.0 |
csolg/hi35xx-buildroot | linux/linux-3.4.y/arch/arm/mach-msm/irq-vic.c | 5785 | 10910 | /*
* Copyright (C) 2007 Google, Inc.
* Copyright (c) 2009, Code Aurora Forum. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/ptrace.h>
#include <linux/timer.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <asm/cacheflush.h>
#include <mach/hardware.h>
#include <mach/msm_iomap.h>
#include "smd_private.h"
enum {
IRQ_DEBUG_SLEEP_INT_TRIGGER = 1U << 0,
IRQ_DEBUG_SLEEP_INT = 1U << 1,
IRQ_DEBUG_SLEEP_ABORT = 1U << 2,
IRQ_DEBUG_SLEEP = 1U << 3,
IRQ_DEBUG_SLEEP_REQUEST = 1U << 4,
};
static int msm_irq_debug_mask;
module_param_named(debug_mask, msm_irq_debug_mask, int,
S_IRUGO | S_IWUSR | S_IWGRP);
#define VIC_REG(off) (MSM_VIC_BASE + (off))
#define VIC_INT_TO_REG_ADDR(base, irq) (base + (irq / 32) * 4)
#define VIC_INT_TO_REG_INDEX(irq) ((irq >> 5) & 3)
#define VIC_INT_SELECT0 VIC_REG(0x0000) /* 1: FIQ, 0: IRQ */
#define VIC_INT_SELECT1 VIC_REG(0x0004) /* 1: FIQ, 0: IRQ */
#define VIC_INT_SELECT2 VIC_REG(0x0008) /* 1: FIQ, 0: IRQ */
#define VIC_INT_SELECT3 VIC_REG(0x000C) /* 1: FIQ, 0: IRQ */
#define VIC_INT_EN0 VIC_REG(0x0010)
#define VIC_INT_EN1 VIC_REG(0x0014)
#define VIC_INT_EN2 VIC_REG(0x0018)
#define VIC_INT_EN3 VIC_REG(0x001C)
#define VIC_INT_ENCLEAR0 VIC_REG(0x0020)
#define VIC_INT_ENCLEAR1 VIC_REG(0x0024)
#define VIC_INT_ENCLEAR2 VIC_REG(0x0028)
#define VIC_INT_ENCLEAR3 VIC_REG(0x002C)
#define VIC_INT_ENSET0 VIC_REG(0x0030)
#define VIC_INT_ENSET1 VIC_REG(0x0034)
#define VIC_INT_ENSET2 VIC_REG(0x0038)
#define VIC_INT_ENSET3 VIC_REG(0x003C)
#define VIC_INT_TYPE0 VIC_REG(0x0040) /* 1: EDGE, 0: LEVEL */
#define VIC_INT_TYPE1 VIC_REG(0x0044) /* 1: EDGE, 0: LEVEL */
#define VIC_INT_TYPE2 VIC_REG(0x0048) /* 1: EDGE, 0: LEVEL */
#define VIC_INT_TYPE3 VIC_REG(0x004C) /* 1: EDGE, 0: LEVEL */
#define VIC_INT_POLARITY0 VIC_REG(0x0050) /* 1: NEG, 0: POS */
#define VIC_INT_POLARITY1 VIC_REG(0x0054) /* 1: NEG, 0: POS */
#define VIC_INT_POLARITY2 VIC_REG(0x0058) /* 1: NEG, 0: POS */
#define VIC_INT_POLARITY3 VIC_REG(0x005C) /* 1: NEG, 0: POS */
#define VIC_NO_PEND_VAL VIC_REG(0x0060)
#if defined(CONFIG_ARCH_MSM_SCORPION)
#define VIC_NO_PEND_VAL_FIQ VIC_REG(0x0064)
#define VIC_INT_MASTEREN VIC_REG(0x0068) /* 1: IRQ, 2: FIQ */
#define VIC_CONFIG VIC_REG(0x006C) /* 1: USE SC VIC */
#else
#define VIC_INT_MASTEREN VIC_REG(0x0064) /* 1: IRQ, 2: FIQ */
#define VIC_PROTECTION VIC_REG(0x006C) /* 1: ENABLE */
#define VIC_CONFIG VIC_REG(0x0068) /* 1: USE ARM1136 VIC */
#endif
#define VIC_IRQ_STATUS0 VIC_REG(0x0080)
#define VIC_IRQ_STATUS1 VIC_REG(0x0084)
#define VIC_IRQ_STATUS2 VIC_REG(0x0088)
#define VIC_IRQ_STATUS3 VIC_REG(0x008C)
#define VIC_FIQ_STATUS0 VIC_REG(0x0090)
#define VIC_FIQ_STATUS1 VIC_REG(0x0094)
#define VIC_FIQ_STATUS2 VIC_REG(0x0098)
#define VIC_FIQ_STATUS3 VIC_REG(0x009C)
#define VIC_RAW_STATUS0 VIC_REG(0x00A0)
#define VIC_RAW_STATUS1 VIC_REG(0x00A4)
#define VIC_RAW_STATUS2 VIC_REG(0x00A8)
#define VIC_RAW_STATUS3 VIC_REG(0x00AC)
#define VIC_INT_CLEAR0 VIC_REG(0x00B0)
#define VIC_INT_CLEAR1 VIC_REG(0x00B4)
#define VIC_INT_CLEAR2 VIC_REG(0x00B8)
#define VIC_INT_CLEAR3 VIC_REG(0x00BC)
#define VIC_SOFTINT0 VIC_REG(0x00C0)
#define VIC_SOFTINT1 VIC_REG(0x00C4)
#define VIC_SOFTINT2 VIC_REG(0x00C8)
#define VIC_SOFTINT3 VIC_REG(0x00CC)
#define VIC_IRQ_VEC_RD VIC_REG(0x00D0) /* pending int # */
#define VIC_IRQ_VEC_PEND_RD VIC_REG(0x00D4) /* pending vector addr */
#define VIC_IRQ_VEC_WR VIC_REG(0x00D8)
#if defined(CONFIG_ARCH_MSM_SCORPION)
#define VIC_FIQ_VEC_RD VIC_REG(0x00DC)
#define VIC_FIQ_VEC_PEND_RD VIC_REG(0x00E0)
#define VIC_FIQ_VEC_WR VIC_REG(0x00E4)
#define VIC_IRQ_IN_SERVICE VIC_REG(0x00E8)
#define VIC_IRQ_IN_STACK VIC_REG(0x00EC)
#define VIC_FIQ_IN_SERVICE VIC_REG(0x00F0)
#define VIC_FIQ_IN_STACK VIC_REG(0x00F4)
#define VIC_TEST_BUS_SEL VIC_REG(0x00F8)
#define VIC_IRQ_CTRL_CONFIG VIC_REG(0x00FC)
#else
#define VIC_IRQ_IN_SERVICE VIC_REG(0x00E0)
#define VIC_IRQ_IN_STACK VIC_REG(0x00E4)
#define VIC_TEST_BUS_SEL VIC_REG(0x00E8)
#endif
#define VIC_VECTPRIORITY(n) VIC_REG(0x0200+((n) * 4))
#define VIC_VECTADDR(n) VIC_REG(0x0400+((n) * 4))
#if defined(CONFIG_ARCH_MSM7X30)
#define VIC_NUM_REGS 4
#else
#define VIC_NUM_REGS 2
#endif
#if VIC_NUM_REGS == 2
#define DPRINT_REGS(base_reg, format, ...) \
printk(KERN_INFO format " %x %x\n", ##__VA_ARGS__, \
readl(base_reg ## 0), readl(base_reg ## 1))
#define DPRINT_ARRAY(array, format, ...) \
printk(KERN_INFO format " %x %x\n", ##__VA_ARGS__, \
array[0], array[1])
#elif VIC_NUM_REGS == 4
#define DPRINT_REGS(base_reg, format, ...) \
printk(KERN_INFO format " %x %x %x %x\n", ##__VA_ARGS__, \
readl(base_reg ## 0), readl(base_reg ## 1), \
readl(base_reg ## 2), readl(base_reg ## 3))
#define DPRINT_ARRAY(array, format, ...) \
printk(KERN_INFO format " %x %x %x %x\n", ##__VA_ARGS__, \
array[0], array[1], \
array[2], array[3])
#else
#error "VIC_NUM_REGS set to illegal value"
#endif
static uint32_t msm_irq_smsm_wake_enable[2];
static struct {
uint32_t int_en[2];
uint32_t int_type;
uint32_t int_polarity;
uint32_t int_select;
} msm_irq_shadow_reg[VIC_NUM_REGS];
static uint32_t msm_irq_idle_disable[VIC_NUM_REGS];
#define SMSM_FAKE_IRQ (0xff)
static uint8_t msm_irq_to_smsm[NR_IRQS] = {
[INT_MDDI_EXT] = 1,
[INT_MDDI_PRI] = 2,
[INT_MDDI_CLIENT] = 3,
[INT_USB_OTG] = 4,
[INT_PWB_I2C] = 5,
[INT_SDC1_0] = 6,
[INT_SDC1_1] = 7,
[INT_SDC2_0] = 8,
[INT_SDC2_1] = 9,
[INT_ADSP_A9_A11] = 10,
[INT_UART1] = 11,
[INT_UART2] = 12,
[INT_UART3] = 13,
[INT_UART1_RX] = 14,
[INT_UART2_RX] = 15,
[INT_UART3_RX] = 16,
[INT_UART1DM_IRQ] = 17,
[INT_UART1DM_RX] = 18,
[INT_KEYSENSE] = 19,
#if !defined(CONFIG_ARCH_MSM7X30)
[INT_AD_HSSD] = 20,
#endif
[INT_NAND_WR_ER_DONE] = 21,
[INT_NAND_OP_DONE] = 22,
[INT_TCHSCRN1] = 23,
[INT_TCHSCRN2] = 24,
[INT_TCHSCRN_SSBI] = 25,
[INT_USB_HS] = 26,
[INT_UART2DM_RX] = 27,
[INT_UART2DM_IRQ] = 28,
[INT_SDC4_1] = 29,
[INT_SDC4_0] = 30,
[INT_SDC3_1] = 31,
[INT_SDC3_0] = 32,
/* fake wakeup interrupts */
[INT_GPIO_GROUP1] = SMSM_FAKE_IRQ,
[INT_GPIO_GROUP2] = SMSM_FAKE_IRQ,
[INT_A9_M2A_0] = SMSM_FAKE_IRQ,
[INT_A9_M2A_1] = SMSM_FAKE_IRQ,
[INT_A9_M2A_5] = SMSM_FAKE_IRQ,
[INT_GP_TIMER_EXP] = SMSM_FAKE_IRQ,
[INT_DEBUG_TIMER_EXP] = SMSM_FAKE_IRQ,
[INT_ADSP_A11] = SMSM_FAKE_IRQ,
#ifdef CONFIG_ARCH_QSD8X50
[INT_SIRC_0] = SMSM_FAKE_IRQ,
[INT_SIRC_1] = SMSM_FAKE_IRQ,
#endif
};
static inline void msm_irq_write_all_regs(void __iomem *base, unsigned int val)
{
int i;
for (i = 0; i < VIC_NUM_REGS; i++)
writel(val, base + (i * 4));
}
static void msm_irq_ack(struct irq_data *d)
{
void __iomem *reg = VIC_INT_TO_REG_ADDR(VIC_INT_CLEAR0, d->irq);
writel(1 << (d->irq & 31), reg);
}
static void msm_irq_mask(struct irq_data *d)
{
void __iomem *reg = VIC_INT_TO_REG_ADDR(VIC_INT_ENCLEAR0, d->irq);
unsigned index = VIC_INT_TO_REG_INDEX(d->irq);
uint32_t mask = 1UL << (d->irq & 31);
int smsm_irq = msm_irq_to_smsm[d->irq];
msm_irq_shadow_reg[index].int_en[0] &= ~mask;
writel(mask, reg);
if (smsm_irq == 0)
msm_irq_idle_disable[index] &= ~mask;
else {
mask = 1UL << (smsm_irq - 1);
msm_irq_smsm_wake_enable[0] &= ~mask;
}
}
static void msm_irq_unmask(struct irq_data *d)
{
void __iomem *reg = VIC_INT_TO_REG_ADDR(VIC_INT_ENSET0, d->irq);
unsigned index = VIC_INT_TO_REG_INDEX(d->irq);
uint32_t mask = 1UL << (d->irq & 31);
int smsm_irq = msm_irq_to_smsm[d->irq];
msm_irq_shadow_reg[index].int_en[0] |= mask;
writel(mask, reg);
if (smsm_irq == 0)
msm_irq_idle_disable[index] |= mask;
else {
mask = 1UL << (smsm_irq - 1);
msm_irq_smsm_wake_enable[0] |= mask;
}
}
static int msm_irq_set_wake(struct irq_data *d, unsigned int on)
{
unsigned index = VIC_INT_TO_REG_INDEX(d->irq);
uint32_t mask = 1UL << (d->irq & 31);
int smsm_irq = msm_irq_to_smsm[d->irq];
if (smsm_irq == 0) {
printk(KERN_ERR "msm_irq_set_wake: bad wakeup irq %d\n", d->irq);
return -EINVAL;
}
if (on)
msm_irq_shadow_reg[index].int_en[1] |= mask;
else
msm_irq_shadow_reg[index].int_en[1] &= ~mask;
if (smsm_irq == SMSM_FAKE_IRQ)
return 0;
mask = 1UL << (smsm_irq - 1);
if (on)
msm_irq_smsm_wake_enable[1] |= mask;
else
msm_irq_smsm_wake_enable[1] &= ~mask;
return 0;
}
static int msm_irq_set_type(struct irq_data *d, unsigned int flow_type)
{
void __iomem *treg = VIC_INT_TO_REG_ADDR(VIC_INT_TYPE0, d->irq);
void __iomem *preg = VIC_INT_TO_REG_ADDR(VIC_INT_POLARITY0, d->irq);
unsigned index = VIC_INT_TO_REG_INDEX(d->irq);
int b = 1 << (d->irq & 31);
uint32_t polarity;
uint32_t type;
polarity = msm_irq_shadow_reg[index].int_polarity;
if (flow_type & (IRQF_TRIGGER_FALLING | IRQF_TRIGGER_LOW))
polarity |= b;
if (flow_type & (IRQF_TRIGGER_RISING | IRQF_TRIGGER_HIGH))
polarity &= ~b;
writel(polarity, preg);
msm_irq_shadow_reg[index].int_polarity = polarity;
type = msm_irq_shadow_reg[index].int_type;
if (flow_type & (IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING)) {
type |= b;
__irq_set_handler_locked(d->irq, handle_edge_irq);
}
if (flow_type & (IRQF_TRIGGER_HIGH | IRQF_TRIGGER_LOW)) {
type &= ~b;
__irq_set_handler_locked(d->irq, handle_level_irq);
}
writel(type, treg);
msm_irq_shadow_reg[index].int_type = type;
return 0;
}
static struct irq_chip msm_irq_chip = {
.name = "msm",
.irq_disable = msm_irq_mask,
.irq_ack = msm_irq_ack,
.irq_mask = msm_irq_mask,
.irq_unmask = msm_irq_unmask,
.irq_set_wake = msm_irq_set_wake,
.irq_set_type = msm_irq_set_type,
};
void __init msm_init_irq(void)
{
unsigned n;
/* select level interrupts */
msm_irq_write_all_regs(VIC_INT_TYPE0, 0);
/* select highlevel interrupts */
msm_irq_write_all_regs(VIC_INT_POLARITY0, 0);
/* select IRQ for all INTs */
msm_irq_write_all_regs(VIC_INT_SELECT0, 0);
/* disable all INTs */
msm_irq_write_all_regs(VIC_INT_EN0, 0);
/* don't use vic */
writel(0, VIC_CONFIG);
/* enable interrupt controller */
writel(3, VIC_INT_MASTEREN);
for (n = 0; n < NR_MSM_IRQS; n++) {
irq_set_chip_and_handler(n, &msm_irq_chip, handle_level_irq);
set_irq_flags(n, IRQF_VALID);
}
}
| gpl-2.0 |
ali-filth/android_kernel_samsung_msm8226 | arch/sh/kernel/kprobes.c | 7833 | 15267 | /*
* Kernel probes (kprobes) for SuperH
*
* Copyright (C) 2007 Chris Smith <chris.smith@st.com>
* Copyright (C) 2006 Lineo Solutions, Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/kprobes.h>
#include <linux/module.h>
#include <linux/ptrace.h>
#include <linux/preempt.h>
#include <linux/kdebug.h>
#include <linux/slab.h>
#include <asm/cacheflush.h>
#include <asm/uaccess.h>
DEFINE_PER_CPU(struct kprobe *, current_kprobe) = NULL;
DEFINE_PER_CPU(struct kprobe_ctlblk, kprobe_ctlblk);
static DEFINE_PER_CPU(struct kprobe, saved_current_opcode);
static DEFINE_PER_CPU(struct kprobe, saved_next_opcode);
static DEFINE_PER_CPU(struct kprobe, saved_next_opcode2);
#define OPCODE_JMP(x) (((x) & 0xF0FF) == 0x402b)
#define OPCODE_JSR(x) (((x) & 0xF0FF) == 0x400b)
#define OPCODE_BRA(x) (((x) & 0xF000) == 0xa000)
#define OPCODE_BRAF(x) (((x) & 0xF0FF) == 0x0023)
#define OPCODE_BSR(x) (((x) & 0xF000) == 0xb000)
#define OPCODE_BSRF(x) (((x) & 0xF0FF) == 0x0003)
#define OPCODE_BF_S(x) (((x) & 0xFF00) == 0x8f00)
#define OPCODE_BT_S(x) (((x) & 0xFF00) == 0x8d00)
#define OPCODE_BF(x) (((x) & 0xFF00) == 0x8b00)
#define OPCODE_BT(x) (((x) & 0xFF00) == 0x8900)
#define OPCODE_RTS(x) (((x) & 0x000F) == 0x000b)
#define OPCODE_RTE(x) (((x) & 0xFFFF) == 0x002b)
int __kprobes arch_prepare_kprobe(struct kprobe *p)
{
kprobe_opcode_t opcode = *(kprobe_opcode_t *) (p->addr);
if (OPCODE_RTE(opcode))
return -EFAULT; /* Bad breakpoint */
p->opcode = opcode;
return 0;
}
void __kprobes arch_copy_kprobe(struct kprobe *p)
{
memcpy(p->ainsn.insn, p->addr, MAX_INSN_SIZE * sizeof(kprobe_opcode_t));
p->opcode = *p->addr;
}
void __kprobes arch_arm_kprobe(struct kprobe *p)
{
*p->addr = BREAKPOINT_INSTRUCTION;
flush_icache_range((unsigned long)p->addr,
(unsigned long)p->addr + sizeof(kprobe_opcode_t));
}
void __kprobes arch_disarm_kprobe(struct kprobe *p)
{
*p->addr = p->opcode;
flush_icache_range((unsigned long)p->addr,
(unsigned long)p->addr + sizeof(kprobe_opcode_t));
}
int __kprobes arch_trampoline_kprobe(struct kprobe *p)
{
if (*p->addr == BREAKPOINT_INSTRUCTION)
return 1;
return 0;
}
/**
* If an illegal slot instruction exception occurs for an address
* containing a kprobe, remove the probe.
*
* Returns 0 if the exception was handled successfully, 1 otherwise.
*/
int __kprobes kprobe_handle_illslot(unsigned long pc)
{
struct kprobe *p = get_kprobe((kprobe_opcode_t *) pc + 1);
if (p != NULL) {
printk("Warning: removing kprobe from delay slot: 0x%.8x\n",
(unsigned int)pc + 2);
unregister_kprobe(p);
return 0;
}
return 1;
}
void __kprobes arch_remove_kprobe(struct kprobe *p)
{
struct kprobe *saved = &__get_cpu_var(saved_next_opcode);
if (saved->addr) {
arch_disarm_kprobe(p);
arch_disarm_kprobe(saved);
saved->addr = NULL;
saved->opcode = 0;
saved = &__get_cpu_var(saved_next_opcode2);
if (saved->addr) {
arch_disarm_kprobe(saved);
saved->addr = NULL;
saved->opcode = 0;
}
}
}
static void __kprobes save_previous_kprobe(struct kprobe_ctlblk *kcb)
{
kcb->prev_kprobe.kp = kprobe_running();
kcb->prev_kprobe.status = kcb->kprobe_status;
}
static void __kprobes restore_previous_kprobe(struct kprobe_ctlblk *kcb)
{
__get_cpu_var(current_kprobe) = kcb->prev_kprobe.kp;
kcb->kprobe_status = kcb->prev_kprobe.status;
}
static void __kprobes set_current_kprobe(struct kprobe *p, struct pt_regs *regs,
struct kprobe_ctlblk *kcb)
{
__get_cpu_var(current_kprobe) = p;
}
/*
* Singlestep is implemented by disabling the current kprobe and setting one
* on the next instruction, following branches. Two probes are set if the
* branch is conditional.
*/
static void __kprobes prepare_singlestep(struct kprobe *p, struct pt_regs *regs)
{
__get_cpu_var(saved_current_opcode).addr = (kprobe_opcode_t *)regs->pc;
if (p != NULL) {
struct kprobe *op1, *op2;
arch_disarm_kprobe(p);
op1 = &__get_cpu_var(saved_next_opcode);
op2 = &__get_cpu_var(saved_next_opcode2);
if (OPCODE_JSR(p->opcode) || OPCODE_JMP(p->opcode)) {
unsigned int reg_nr = ((p->opcode >> 8) & 0x000F);
op1->addr = (kprobe_opcode_t *) regs->regs[reg_nr];
} else if (OPCODE_BRA(p->opcode) || OPCODE_BSR(p->opcode)) {
unsigned long disp = (p->opcode & 0x0FFF);
op1->addr =
(kprobe_opcode_t *) (regs->pc + 4 + disp * 2);
} else if (OPCODE_BRAF(p->opcode) || OPCODE_BSRF(p->opcode)) {
unsigned int reg_nr = ((p->opcode >> 8) & 0x000F);
op1->addr =
(kprobe_opcode_t *) (regs->pc + 4 +
regs->regs[reg_nr]);
} else if (OPCODE_RTS(p->opcode)) {
op1->addr = (kprobe_opcode_t *) regs->pr;
} else if (OPCODE_BF(p->opcode) || OPCODE_BT(p->opcode)) {
unsigned long disp = (p->opcode & 0x00FF);
/* case 1 */
op1->addr = p->addr + 1;
/* case 2 */
op2->addr =
(kprobe_opcode_t *) (regs->pc + 4 + disp * 2);
op2->opcode = *(op2->addr);
arch_arm_kprobe(op2);
} else if (OPCODE_BF_S(p->opcode) || OPCODE_BT_S(p->opcode)) {
unsigned long disp = (p->opcode & 0x00FF);
/* case 1 */
op1->addr = p->addr + 2;
/* case 2 */
op2->addr =
(kprobe_opcode_t *) (regs->pc + 4 + disp * 2);
op2->opcode = *(op2->addr);
arch_arm_kprobe(op2);
} else {
op1->addr = p->addr + 1;
}
op1->opcode = *(op1->addr);
arch_arm_kprobe(op1);
}
}
/* Called with kretprobe_lock held */
void __kprobes arch_prepare_kretprobe(struct kretprobe_instance *ri,
struct pt_regs *regs)
{
ri->ret_addr = (kprobe_opcode_t *) regs->pr;
/* Replace the return addr with trampoline addr */
regs->pr = (unsigned long)kretprobe_trampoline;
}
static int __kprobes kprobe_handler(struct pt_regs *regs)
{
struct kprobe *p;
int ret = 0;
kprobe_opcode_t *addr = NULL;
struct kprobe_ctlblk *kcb;
/*
* We don't want to be preempted for the entire
* duration of kprobe processing
*/
preempt_disable();
kcb = get_kprobe_ctlblk();
addr = (kprobe_opcode_t *) (regs->pc);
/* Check we're not actually recursing */
if (kprobe_running()) {
p = get_kprobe(addr);
if (p) {
if (kcb->kprobe_status == KPROBE_HIT_SS &&
*p->ainsn.insn == BREAKPOINT_INSTRUCTION) {
goto no_kprobe;
}
/* We have reentered the kprobe_handler(), since
* another probe was hit while within the handler.
* We here save the original kprobes variables and
* just single step on the instruction of the new probe
* without calling any user handlers.
*/
save_previous_kprobe(kcb);
set_current_kprobe(p, regs, kcb);
kprobes_inc_nmissed_count(p);
prepare_singlestep(p, regs);
kcb->kprobe_status = KPROBE_REENTER;
return 1;
} else {
p = __get_cpu_var(current_kprobe);
if (p->break_handler && p->break_handler(p, regs)) {
goto ss_probe;
}
}
goto no_kprobe;
}
p = get_kprobe(addr);
if (!p) {
/* Not one of ours: let kernel handle it */
if (*(kprobe_opcode_t *)addr != BREAKPOINT_INSTRUCTION) {
/*
* The breakpoint instruction was removed right
* after we hit it. Another cpu has removed
* either a probepoint or a debugger breakpoint
* at this address. In either case, no further
* handling of this interrupt is appropriate.
*/
ret = 1;
}
goto no_kprobe;
}
set_current_kprobe(p, regs, kcb);
kcb->kprobe_status = KPROBE_HIT_ACTIVE;
if (p->pre_handler && p->pre_handler(p, regs))
/* handler has already set things up, so skip ss setup */
return 1;
ss_probe:
prepare_singlestep(p, regs);
kcb->kprobe_status = KPROBE_HIT_SS;
return 1;
no_kprobe:
preempt_enable_no_resched();
return ret;
}
/*
* For function-return probes, init_kprobes() establishes a probepoint
* here. When a retprobed function returns, this probe is hit and
* trampoline_probe_handler() runs, calling the kretprobe's handler.
*/
static void __used kretprobe_trampoline_holder(void)
{
asm volatile (".globl kretprobe_trampoline\n"
"kretprobe_trampoline:\n\t"
"nop\n");
}
/*
* Called when we hit the probe point at kretprobe_trampoline
*/
int __kprobes trampoline_probe_handler(struct kprobe *p, struct pt_regs *regs)
{
struct kretprobe_instance *ri = NULL;
struct hlist_head *head, empty_rp;
struct hlist_node *node, *tmp;
unsigned long flags, orig_ret_address = 0;
unsigned long trampoline_address = (unsigned long)&kretprobe_trampoline;
INIT_HLIST_HEAD(&empty_rp);
kretprobe_hash_lock(current, &head, &flags);
/*
* It is possible to have multiple instances associated with a given
* task either because an multiple functions in the call path
* have a return probe installed on them, and/or more then one return
* return probe was registered for a target function.
*
* We can handle this because:
* - instances are always inserted at the head of the list
* - when multiple return probes are registered for the same
* function, the first instance's ret_addr will point to the
* real return address, and all the rest will point to
* kretprobe_trampoline
*/
hlist_for_each_entry_safe(ri, node, tmp, head, hlist) {
if (ri->task != current)
/* another task is sharing our hash bucket */
continue;
if (ri->rp && ri->rp->handler) {
__get_cpu_var(current_kprobe) = &ri->rp->kp;
ri->rp->handler(ri, regs);
__get_cpu_var(current_kprobe) = NULL;
}
orig_ret_address = (unsigned long)ri->ret_addr;
recycle_rp_inst(ri, &empty_rp);
if (orig_ret_address != trampoline_address)
/*
* This is the real return address. Any other
* instances associated with this task are for
* other calls deeper on the call stack
*/
break;
}
kretprobe_assert(ri, orig_ret_address, trampoline_address);
regs->pc = orig_ret_address;
kretprobe_hash_unlock(current, &flags);
preempt_enable_no_resched();
hlist_for_each_entry_safe(ri, node, tmp, &empty_rp, hlist) {
hlist_del(&ri->hlist);
kfree(ri);
}
return orig_ret_address;
}
static int __kprobes post_kprobe_handler(struct pt_regs *regs)
{
struct kprobe *cur = kprobe_running();
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
kprobe_opcode_t *addr = NULL;
struct kprobe *p = NULL;
if (!cur)
return 0;
if ((kcb->kprobe_status != KPROBE_REENTER) && cur->post_handler) {
kcb->kprobe_status = KPROBE_HIT_SSDONE;
cur->post_handler(cur, regs, 0);
}
p = &__get_cpu_var(saved_next_opcode);
if (p->addr) {
arch_disarm_kprobe(p);
p->addr = NULL;
p->opcode = 0;
addr = __get_cpu_var(saved_current_opcode).addr;
__get_cpu_var(saved_current_opcode).addr = NULL;
p = get_kprobe(addr);
arch_arm_kprobe(p);
p = &__get_cpu_var(saved_next_opcode2);
if (p->addr) {
arch_disarm_kprobe(p);
p->addr = NULL;
p->opcode = 0;
}
}
/* Restore back the original saved kprobes variables and continue. */
if (kcb->kprobe_status == KPROBE_REENTER) {
restore_previous_kprobe(kcb);
goto out;
}
reset_current_kprobe();
out:
preempt_enable_no_resched();
return 1;
}
int __kprobes kprobe_fault_handler(struct pt_regs *regs, int trapnr)
{
struct kprobe *cur = kprobe_running();
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
const struct exception_table_entry *entry;
switch (kcb->kprobe_status) {
case KPROBE_HIT_SS:
case KPROBE_REENTER:
/*
* We are here because the instruction being single
* stepped caused a page fault. We reset the current
* kprobe, point the pc back to the probe address
* and allow the page fault handler to continue as a
* normal page fault.
*/
regs->pc = (unsigned long)cur->addr;
if (kcb->kprobe_status == KPROBE_REENTER)
restore_previous_kprobe(kcb);
else
reset_current_kprobe();
preempt_enable_no_resched();
break;
case KPROBE_HIT_ACTIVE:
case KPROBE_HIT_SSDONE:
/*
* We increment the nmissed count for accounting,
* we can also use npre/npostfault count for accounting
* these specific fault cases.
*/
kprobes_inc_nmissed_count(cur);
/*
* We come here because instructions in the pre/post
* handler caused the page_fault, this could happen
* if handler tries to access user space by
* copy_from_user(), get_user() etc. Let the
* user-specified handler try to fix it first.
*/
if (cur->fault_handler && cur->fault_handler(cur, regs, trapnr))
return 1;
/*
* In case the user-specified fault handler returned
* zero, try to fix up.
*/
if ((entry = search_exception_tables(regs->pc)) != NULL) {
regs->pc = entry->fixup;
return 1;
}
/*
* fixup_exception() could not handle it,
* Let do_page_fault() fix it.
*/
break;
default:
break;
}
return 0;
}
/*
* Wrapper routine to for handling exceptions.
*/
int __kprobes kprobe_exceptions_notify(struct notifier_block *self,
unsigned long val, void *data)
{
struct kprobe *p = NULL;
struct die_args *args = (struct die_args *)data;
int ret = NOTIFY_DONE;
kprobe_opcode_t *addr = NULL;
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
addr = (kprobe_opcode_t *) (args->regs->pc);
if (val == DIE_TRAP) {
if (!kprobe_running()) {
if (kprobe_handler(args->regs)) {
ret = NOTIFY_STOP;
} else {
/* Not a kprobe trap */
ret = NOTIFY_DONE;
}
} else {
p = get_kprobe(addr);
if ((kcb->kprobe_status == KPROBE_HIT_SS) ||
(kcb->kprobe_status == KPROBE_REENTER)) {
if (post_kprobe_handler(args->regs))
ret = NOTIFY_STOP;
} else {
if (kprobe_handler(args->regs)) {
ret = NOTIFY_STOP;
} else {
p = __get_cpu_var(current_kprobe);
if (p->break_handler &&
p->break_handler(p, args->regs))
ret = NOTIFY_STOP;
}
}
}
}
return ret;
}
int __kprobes setjmp_pre_handler(struct kprobe *p, struct pt_regs *regs)
{
struct jprobe *jp = container_of(p, struct jprobe, kp);
unsigned long addr;
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
kcb->jprobe_saved_regs = *regs;
kcb->jprobe_saved_r15 = regs->regs[15];
addr = kcb->jprobe_saved_r15;
/*
* TBD: As Linus pointed out, gcc assumes that the callee
* owns the argument space and could overwrite it, e.g.
* tailcall optimization. So, to be absolutely safe
* we also save and restore enough stack bytes to cover
* the argument area.
*/
memcpy(kcb->jprobes_stack, (kprobe_opcode_t *) addr,
MIN_STACK_SIZE(addr));
regs->pc = (unsigned long)(jp->entry);
return 1;
}
void __kprobes jprobe_return(void)
{
asm volatile ("trapa #0x3a\n\t" "jprobe_return_end:\n\t" "nop\n\t");
}
int __kprobes longjmp_break_handler(struct kprobe *p, struct pt_regs *regs)
{
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
unsigned long stack_addr = kcb->jprobe_saved_r15;
u8 *addr = (u8 *)regs->pc;
if ((addr >= (u8 *)jprobe_return) &&
(addr <= (u8 *)jprobe_return_end)) {
*regs = kcb->jprobe_saved_regs;
memcpy((kprobe_opcode_t *)stack_addr, kcb->jprobes_stack,
MIN_STACK_SIZE(stack_addr));
kcb->kprobe_status = KPROBE_HIT_SS;
preempt_enable_no_resched();
return 1;
}
return 0;
}
static struct kprobe trampoline_p = {
.addr = (kprobe_opcode_t *)&kretprobe_trampoline,
.pre_handler = trampoline_probe_handler
};
int __init arch_init_kprobes(void)
{
return register_kprobe(&trampoline_p);
}
| gpl-2.0 |
MattCrystal/oneXL | drivers/sh/intc/handle.c | 10393 | 7013 | /*
* Shared interrupt handling code for IPR and INTC2 types of IRQs.
*
* Copyright (C) 2007, 2008 Magnus Damm
* Copyright (C) 2009, 2010 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/spinlock.h>
#include "internals.h"
static unsigned long ack_handle[INTC_NR_IRQS];
static intc_enum __init intc_grp_id(struct intc_desc *desc,
intc_enum enum_id)
{
struct intc_group *g = desc->hw.groups;
unsigned int i, j;
for (i = 0; g && enum_id && i < desc->hw.nr_groups; i++) {
g = desc->hw.groups + i;
for (j = 0; g->enum_ids[j]; j++) {
if (g->enum_ids[j] != enum_id)
continue;
return g->enum_id;
}
}
return 0;
}
static unsigned int __init _intc_mask_data(struct intc_desc *desc,
struct intc_desc_int *d,
intc_enum enum_id,
unsigned int *reg_idx,
unsigned int *fld_idx)
{
struct intc_mask_reg *mr = desc->hw.mask_regs;
unsigned int fn, mode;
unsigned long reg_e, reg_d;
while (mr && enum_id && *reg_idx < desc->hw.nr_mask_regs) {
mr = desc->hw.mask_regs + *reg_idx;
for (; *fld_idx < ARRAY_SIZE(mr->enum_ids); (*fld_idx)++) {
if (mr->enum_ids[*fld_idx] != enum_id)
continue;
if (mr->set_reg && mr->clr_reg) {
fn = REG_FN_WRITE_BASE;
mode = MODE_DUAL_REG;
reg_e = mr->clr_reg;
reg_d = mr->set_reg;
} else {
fn = REG_FN_MODIFY_BASE;
if (mr->set_reg) {
mode = MODE_ENABLE_REG;
reg_e = mr->set_reg;
reg_d = mr->set_reg;
} else {
mode = MODE_MASK_REG;
reg_e = mr->clr_reg;
reg_d = mr->clr_reg;
}
}
fn += (mr->reg_width >> 3) - 1;
return _INTC_MK(fn, mode,
intc_get_reg(d, reg_e),
intc_get_reg(d, reg_d),
1,
(mr->reg_width - 1) - *fld_idx);
}
*fld_idx = 0;
(*reg_idx)++;
}
return 0;
}
unsigned int __init
intc_get_mask_handle(struct intc_desc *desc, struct intc_desc_int *d,
intc_enum enum_id, int do_grps)
{
unsigned int i = 0;
unsigned int j = 0;
unsigned int ret;
ret = _intc_mask_data(desc, d, enum_id, &i, &j);
if (ret)
return ret;
if (do_grps)
return intc_get_mask_handle(desc, d, intc_grp_id(desc, enum_id), 0);
return 0;
}
static unsigned int __init _intc_prio_data(struct intc_desc *desc,
struct intc_desc_int *d,
intc_enum enum_id,
unsigned int *reg_idx,
unsigned int *fld_idx)
{
struct intc_prio_reg *pr = desc->hw.prio_regs;
unsigned int fn, n, mode, bit;
unsigned long reg_e, reg_d;
while (pr && enum_id && *reg_idx < desc->hw.nr_prio_regs) {
pr = desc->hw.prio_regs + *reg_idx;
for (; *fld_idx < ARRAY_SIZE(pr->enum_ids); (*fld_idx)++) {
if (pr->enum_ids[*fld_idx] != enum_id)
continue;
if (pr->set_reg && pr->clr_reg) {
fn = REG_FN_WRITE_BASE;
mode = MODE_PCLR_REG;
reg_e = pr->set_reg;
reg_d = pr->clr_reg;
} else {
fn = REG_FN_MODIFY_BASE;
mode = MODE_PRIO_REG;
if (!pr->set_reg)
BUG();
reg_e = pr->set_reg;
reg_d = pr->set_reg;
}
fn += (pr->reg_width >> 3) - 1;
n = *fld_idx + 1;
BUG_ON(n * pr->field_width > pr->reg_width);
bit = pr->reg_width - (n * pr->field_width);
return _INTC_MK(fn, mode,
intc_get_reg(d, reg_e),
intc_get_reg(d, reg_d),
pr->field_width, bit);
}
*fld_idx = 0;
(*reg_idx)++;
}
return 0;
}
unsigned int __init
intc_get_prio_handle(struct intc_desc *desc, struct intc_desc_int *d,
intc_enum enum_id, int do_grps)
{
unsigned int i = 0;
unsigned int j = 0;
unsigned int ret;
ret = _intc_prio_data(desc, d, enum_id, &i, &j);
if (ret)
return ret;
if (do_grps)
return intc_get_prio_handle(desc, d, intc_grp_id(desc, enum_id), 0);
return 0;
}
static unsigned int intc_ack_data(struct intc_desc *desc,
struct intc_desc_int *d, intc_enum enum_id)
{
struct intc_mask_reg *mr = desc->hw.ack_regs;
unsigned int i, j, fn, mode;
unsigned long reg_e, reg_d;
for (i = 0; mr && enum_id && i < desc->hw.nr_ack_regs; i++) {
mr = desc->hw.ack_regs + i;
for (j = 0; j < ARRAY_SIZE(mr->enum_ids); j++) {
if (mr->enum_ids[j] != enum_id)
continue;
fn = REG_FN_MODIFY_BASE;
mode = MODE_ENABLE_REG;
reg_e = mr->set_reg;
reg_d = mr->set_reg;
fn += (mr->reg_width >> 3) - 1;
return _INTC_MK(fn, mode,
intc_get_reg(d, reg_e),
intc_get_reg(d, reg_d),
1,
(mr->reg_width - 1) - j);
}
}
return 0;
}
static void intc_enable_disable(struct intc_desc_int *d,
unsigned long handle, int do_enable)
{
unsigned long addr;
unsigned int cpu;
unsigned long (*fn)(unsigned long, unsigned long,
unsigned long (*)(unsigned long, unsigned long,
unsigned long),
unsigned int);
if (do_enable) {
for (cpu = 0; cpu < SMP_NR(d, _INTC_ADDR_E(handle)); cpu++) {
addr = INTC_REG(d, _INTC_ADDR_E(handle), cpu);
fn = intc_enable_noprio_fns[_INTC_MODE(handle)];
fn(addr, handle, intc_reg_fns[_INTC_FN(handle)], 0);
}
} else {
for (cpu = 0; cpu < SMP_NR(d, _INTC_ADDR_D(handle)); cpu++) {
addr = INTC_REG(d, _INTC_ADDR_D(handle), cpu);
fn = intc_disable_fns[_INTC_MODE(handle)];
fn(addr, handle, intc_reg_fns[_INTC_FN(handle)], 0);
}
}
}
void __init intc_enable_disable_enum(struct intc_desc *desc,
struct intc_desc_int *d,
intc_enum enum_id, int enable)
{
unsigned int i, j, data;
/* go through and enable/disable all mask bits */
i = j = 0;
do {
data = _intc_mask_data(desc, d, enum_id, &i, &j);
if (data)
intc_enable_disable(d, data, enable);
j++;
} while (data);
/* go through and enable/disable all priority fields */
i = j = 0;
do {
data = _intc_prio_data(desc, d, enum_id, &i, &j);
if (data)
intc_enable_disable(d, data, enable);
j++;
} while (data);
}
unsigned int __init
intc_get_sense_handle(struct intc_desc *desc, struct intc_desc_int *d,
intc_enum enum_id)
{
struct intc_sense_reg *sr = desc->hw.sense_regs;
unsigned int i, j, fn, bit;
for (i = 0; sr && enum_id && i < desc->hw.nr_sense_regs; i++) {
sr = desc->hw.sense_regs + i;
for (j = 0; j < ARRAY_SIZE(sr->enum_ids); j++) {
if (sr->enum_ids[j] != enum_id)
continue;
fn = REG_FN_MODIFY_BASE;
fn += (sr->reg_width >> 3) - 1;
BUG_ON((j + 1) * sr->field_width > sr->reg_width);
bit = sr->reg_width - ((j + 1) * sr->field_width);
return _INTC_MK(fn, 0, intc_get_reg(d, sr->reg),
0, sr->field_width, bit);
}
}
return 0;
}
void intc_set_ack_handle(unsigned int irq, struct intc_desc *desc,
struct intc_desc_int *d, intc_enum id)
{
unsigned long flags;
/*
* Nothing to do for this IRQ.
*/
if (!desc->hw.ack_regs)
return;
raw_spin_lock_irqsave(&intc_big_lock, flags);
ack_handle[irq] = intc_ack_data(desc, d, id);
raw_spin_unlock_irqrestore(&intc_big_lock, flags);
}
unsigned long intc_get_ack_handle(unsigned int irq)
{
return ack_handle[irq];
}
| gpl-2.0 |
EPDCenterSpain/kernel_odys_genio | sound/pcmcia/pdaudiocf/pdaudiocf_pcm.c | 12185 | 7818 | /*
* Driver for Sound Core PDAudioCF soundcards
*
* PCM part
*
* Copyright (c) 2003 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/delay.h>
#include <sound/core.h>
#include <sound/asoundef.h>
#include "pdaudiocf.h"
/*
* clear the SRAM contents
*/
static int pdacf_pcm_clear_sram(struct snd_pdacf *chip)
{
int max_loop = 64 * 1024;
while (inw(chip->port + PDAUDIOCF_REG_RDP) != inw(chip->port + PDAUDIOCF_REG_WDP)) {
if (max_loop-- < 0)
return -EIO;
inw(chip->port + PDAUDIOCF_REG_MD);
}
return 0;
}
/*
* pdacf_pcm_trigger - trigger callback for capture
*/
static int pdacf_pcm_trigger(struct snd_pcm_substream *subs, int cmd)
{
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
struct snd_pcm_runtime *runtime = subs->runtime;
int inc, ret = 0, rate;
unsigned short mask, val, tmp;
if (chip->chip_status & PDAUDIOCF_STAT_IS_STALE)
return -EBUSY;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
chip->pcm_hwptr = 0;
chip->pcm_tdone = 0;
/* fall thru */
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
mask = 0;
val = PDAUDIOCF_RECORD;
inc = 1;
rate = snd_ak4117_check_rate_and_errors(chip->ak4117, AK4117_CHECK_NO_STAT|AK4117_CHECK_NO_RATE);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
mask = PDAUDIOCF_RECORD;
val = 0;
inc = -1;
rate = 0;
break;
default:
return -EINVAL;
}
spin_lock(&chip->reg_lock);
chip->pcm_running += inc;
tmp = pdacf_reg_read(chip, PDAUDIOCF_REG_SCR);
if (chip->pcm_running) {
if ((chip->ak4117->rcs0 & AK4117_UNLCK) || runtime->rate != rate) {
chip->pcm_running -= inc;
ret = -EIO;
goto __end;
}
}
tmp &= ~mask;
tmp |= val;
pdacf_reg_write(chip, PDAUDIOCF_REG_SCR, tmp);
__end:
spin_unlock(&chip->reg_lock);
snd_ak4117_check_rate_and_errors(chip->ak4117, AK4117_CHECK_NO_RATE);
return ret;
}
/*
* pdacf_pcm_hw_params - hw_params callback for playback and capture
*/
static int pdacf_pcm_hw_params(struct snd_pcm_substream *subs,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_alloc_vmalloc_32_buffer
(subs, params_buffer_bytes(hw_params));
}
/*
* pdacf_pcm_hw_free - hw_free callback for playback and capture
*/
static int pdacf_pcm_hw_free(struct snd_pcm_substream *subs)
{
return snd_pcm_lib_free_vmalloc_buffer(subs);
}
/*
* pdacf_pcm_prepare - prepare callback for playback and capture
*/
static int pdacf_pcm_prepare(struct snd_pcm_substream *subs)
{
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
struct snd_pcm_runtime *runtime = subs->runtime;
u16 val, nval, aval;
if (chip->chip_status & PDAUDIOCF_STAT_IS_STALE)
return -EBUSY;
chip->pcm_channels = runtime->channels;
chip->pcm_little = snd_pcm_format_little_endian(runtime->format) > 0;
#ifdef SNDRV_LITTLE_ENDIAN
chip->pcm_swab = snd_pcm_format_big_endian(runtime->format) > 0;
#else
chip->pcm_swab = chip->pcm_little;
#endif
if (snd_pcm_format_unsigned(runtime->format))
chip->pcm_xor = 0x80008000;
if (pdacf_pcm_clear_sram(chip) < 0)
return -EIO;
val = nval = pdacf_reg_read(chip, PDAUDIOCF_REG_SCR);
nval &= ~(PDAUDIOCF_DATAFMT0|PDAUDIOCF_DATAFMT1);
switch (runtime->format) {
case SNDRV_PCM_FORMAT_S16_LE:
case SNDRV_PCM_FORMAT_S16_BE:
break;
default: /* 24-bit */
nval |= PDAUDIOCF_DATAFMT0 | PDAUDIOCF_DATAFMT1;
break;
}
aval = 0;
chip->pcm_sample = 4;
switch (runtime->format) {
case SNDRV_PCM_FORMAT_S16_LE:
case SNDRV_PCM_FORMAT_S16_BE:
aval = AK4117_DIF_16R;
chip->pcm_frame = 2;
chip->pcm_sample = 2;
break;
case SNDRV_PCM_FORMAT_S24_3LE:
case SNDRV_PCM_FORMAT_S24_3BE:
chip->pcm_sample = 3;
/* fall through */
default: /* 24-bit */
aval = AK4117_DIF_24R;
chip->pcm_frame = 3;
chip->pcm_xor &= 0xffff0000;
break;
}
if (val != nval) {
snd_ak4117_reg_write(chip->ak4117, AK4117_REG_IO, AK4117_DIF2|AK4117_DIF1|AK4117_DIF0, aval);
pdacf_reg_write(chip, PDAUDIOCF_REG_SCR, nval);
}
val = pdacf_reg_read(chip, PDAUDIOCF_REG_IER);
val &= ~(PDAUDIOCF_IRQLVLEN1);
val |= PDAUDIOCF_IRQLVLEN0;
pdacf_reg_write(chip, PDAUDIOCF_REG_IER, val);
chip->pcm_size = runtime->buffer_size;
chip->pcm_period = runtime->period_size;
chip->pcm_area = runtime->dma_area;
return 0;
}
/*
* capture hw information
*/
static struct snd_pcm_hardware pdacf_pcm_capture_hw = {
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BATCH),
.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE |
SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S24_3BE |
SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE,
.rates = SNDRV_PCM_RATE_32000 |
SNDRV_PCM_RATE_44100 |
SNDRV_PCM_RATE_48000 |
SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000 |
SNDRV_PCM_RATE_176400 |
SNDRV_PCM_RATE_192000,
.rate_min = 32000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (512*1024),
.period_bytes_min = 8*1024,
.period_bytes_max = (64*1024),
.periods_min = 2,
.periods_max = 128,
.fifo_size = 0,
};
/*
* pdacf_pcm_capture_open - open callback for capture
*/
static int pdacf_pcm_capture_open(struct snd_pcm_substream *subs)
{
struct snd_pcm_runtime *runtime = subs->runtime;
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
if (chip->chip_status & PDAUDIOCF_STAT_IS_STALE)
return -EBUSY;
runtime->hw = pdacf_pcm_capture_hw;
runtime->private_data = chip;
chip->pcm_substream = subs;
return 0;
}
/*
* pdacf_pcm_capture_close - close callback for capture
*/
static int pdacf_pcm_capture_close(struct snd_pcm_substream *subs)
{
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
if (!chip)
return -EINVAL;
pdacf_reinit(chip, 0);
chip->pcm_substream = NULL;
return 0;
}
/*
* pdacf_pcm_capture_pointer - pointer callback for capture
*/
static snd_pcm_uframes_t pdacf_pcm_capture_pointer(struct snd_pcm_substream *subs)
{
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
return chip->pcm_hwptr;
}
/*
* operators for PCM capture
*/
static struct snd_pcm_ops pdacf_pcm_capture_ops = {
.open = pdacf_pcm_capture_open,
.close = pdacf_pcm_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = pdacf_pcm_hw_params,
.hw_free = pdacf_pcm_hw_free,
.prepare = pdacf_pcm_prepare,
.trigger = pdacf_pcm_trigger,
.pointer = pdacf_pcm_capture_pointer,
.page = snd_pcm_lib_get_vmalloc_page,
.mmap = snd_pcm_lib_mmap_vmalloc,
};
/*
* snd_pdacf_pcm_new - create and initialize a pcm
*/
int snd_pdacf_pcm_new(struct snd_pdacf *chip)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(chip->card, "PDAudioCF", 0, 0, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &pdacf_pcm_capture_ops);
pcm->private_data = chip;
pcm->info_flags = 0;
strcpy(pcm->name, chip->card->shortname);
chip->pcm = pcm;
err = snd_ak4117_build(chip->ak4117, pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream);
if (err < 0)
return err;
return 0;
}
| gpl-2.0 |
garwynn/L900_LJC_Kernel | sound/pcmcia/pdaudiocf/pdaudiocf_pcm.c | 12185 | 7818 | /*
* Driver for Sound Core PDAudioCF soundcards
*
* PCM part
*
* Copyright (c) 2003 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/delay.h>
#include <sound/core.h>
#include <sound/asoundef.h>
#include "pdaudiocf.h"
/*
* clear the SRAM contents
*/
static int pdacf_pcm_clear_sram(struct snd_pdacf *chip)
{
int max_loop = 64 * 1024;
while (inw(chip->port + PDAUDIOCF_REG_RDP) != inw(chip->port + PDAUDIOCF_REG_WDP)) {
if (max_loop-- < 0)
return -EIO;
inw(chip->port + PDAUDIOCF_REG_MD);
}
return 0;
}
/*
* pdacf_pcm_trigger - trigger callback for capture
*/
static int pdacf_pcm_trigger(struct snd_pcm_substream *subs, int cmd)
{
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
struct snd_pcm_runtime *runtime = subs->runtime;
int inc, ret = 0, rate;
unsigned short mask, val, tmp;
if (chip->chip_status & PDAUDIOCF_STAT_IS_STALE)
return -EBUSY;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
chip->pcm_hwptr = 0;
chip->pcm_tdone = 0;
/* fall thru */
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
mask = 0;
val = PDAUDIOCF_RECORD;
inc = 1;
rate = snd_ak4117_check_rate_and_errors(chip->ak4117, AK4117_CHECK_NO_STAT|AK4117_CHECK_NO_RATE);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
mask = PDAUDIOCF_RECORD;
val = 0;
inc = -1;
rate = 0;
break;
default:
return -EINVAL;
}
spin_lock(&chip->reg_lock);
chip->pcm_running += inc;
tmp = pdacf_reg_read(chip, PDAUDIOCF_REG_SCR);
if (chip->pcm_running) {
if ((chip->ak4117->rcs0 & AK4117_UNLCK) || runtime->rate != rate) {
chip->pcm_running -= inc;
ret = -EIO;
goto __end;
}
}
tmp &= ~mask;
tmp |= val;
pdacf_reg_write(chip, PDAUDIOCF_REG_SCR, tmp);
__end:
spin_unlock(&chip->reg_lock);
snd_ak4117_check_rate_and_errors(chip->ak4117, AK4117_CHECK_NO_RATE);
return ret;
}
/*
* pdacf_pcm_hw_params - hw_params callback for playback and capture
*/
static int pdacf_pcm_hw_params(struct snd_pcm_substream *subs,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_alloc_vmalloc_32_buffer
(subs, params_buffer_bytes(hw_params));
}
/*
* pdacf_pcm_hw_free - hw_free callback for playback and capture
*/
static int pdacf_pcm_hw_free(struct snd_pcm_substream *subs)
{
return snd_pcm_lib_free_vmalloc_buffer(subs);
}
/*
* pdacf_pcm_prepare - prepare callback for playback and capture
*/
static int pdacf_pcm_prepare(struct snd_pcm_substream *subs)
{
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
struct snd_pcm_runtime *runtime = subs->runtime;
u16 val, nval, aval;
if (chip->chip_status & PDAUDIOCF_STAT_IS_STALE)
return -EBUSY;
chip->pcm_channels = runtime->channels;
chip->pcm_little = snd_pcm_format_little_endian(runtime->format) > 0;
#ifdef SNDRV_LITTLE_ENDIAN
chip->pcm_swab = snd_pcm_format_big_endian(runtime->format) > 0;
#else
chip->pcm_swab = chip->pcm_little;
#endif
if (snd_pcm_format_unsigned(runtime->format))
chip->pcm_xor = 0x80008000;
if (pdacf_pcm_clear_sram(chip) < 0)
return -EIO;
val = nval = pdacf_reg_read(chip, PDAUDIOCF_REG_SCR);
nval &= ~(PDAUDIOCF_DATAFMT0|PDAUDIOCF_DATAFMT1);
switch (runtime->format) {
case SNDRV_PCM_FORMAT_S16_LE:
case SNDRV_PCM_FORMAT_S16_BE:
break;
default: /* 24-bit */
nval |= PDAUDIOCF_DATAFMT0 | PDAUDIOCF_DATAFMT1;
break;
}
aval = 0;
chip->pcm_sample = 4;
switch (runtime->format) {
case SNDRV_PCM_FORMAT_S16_LE:
case SNDRV_PCM_FORMAT_S16_BE:
aval = AK4117_DIF_16R;
chip->pcm_frame = 2;
chip->pcm_sample = 2;
break;
case SNDRV_PCM_FORMAT_S24_3LE:
case SNDRV_PCM_FORMAT_S24_3BE:
chip->pcm_sample = 3;
/* fall through */
default: /* 24-bit */
aval = AK4117_DIF_24R;
chip->pcm_frame = 3;
chip->pcm_xor &= 0xffff0000;
break;
}
if (val != nval) {
snd_ak4117_reg_write(chip->ak4117, AK4117_REG_IO, AK4117_DIF2|AK4117_DIF1|AK4117_DIF0, aval);
pdacf_reg_write(chip, PDAUDIOCF_REG_SCR, nval);
}
val = pdacf_reg_read(chip, PDAUDIOCF_REG_IER);
val &= ~(PDAUDIOCF_IRQLVLEN1);
val |= PDAUDIOCF_IRQLVLEN0;
pdacf_reg_write(chip, PDAUDIOCF_REG_IER, val);
chip->pcm_size = runtime->buffer_size;
chip->pcm_period = runtime->period_size;
chip->pcm_area = runtime->dma_area;
return 0;
}
/*
* capture hw information
*/
static struct snd_pcm_hardware pdacf_pcm_capture_hw = {
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BATCH),
.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S16_BE |
SNDRV_PCM_FMTBIT_S24_3LE | SNDRV_PCM_FMTBIT_S24_3BE |
SNDRV_PCM_FMTBIT_S32_LE | SNDRV_PCM_FMTBIT_S32_BE,
.rates = SNDRV_PCM_RATE_32000 |
SNDRV_PCM_RATE_44100 |
SNDRV_PCM_RATE_48000 |
SNDRV_PCM_RATE_88200 |
SNDRV_PCM_RATE_96000 |
SNDRV_PCM_RATE_176400 |
SNDRV_PCM_RATE_192000,
.rate_min = 32000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = (512*1024),
.period_bytes_min = 8*1024,
.period_bytes_max = (64*1024),
.periods_min = 2,
.periods_max = 128,
.fifo_size = 0,
};
/*
* pdacf_pcm_capture_open - open callback for capture
*/
static int pdacf_pcm_capture_open(struct snd_pcm_substream *subs)
{
struct snd_pcm_runtime *runtime = subs->runtime;
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
if (chip->chip_status & PDAUDIOCF_STAT_IS_STALE)
return -EBUSY;
runtime->hw = pdacf_pcm_capture_hw;
runtime->private_data = chip;
chip->pcm_substream = subs;
return 0;
}
/*
* pdacf_pcm_capture_close - close callback for capture
*/
static int pdacf_pcm_capture_close(struct snd_pcm_substream *subs)
{
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
if (!chip)
return -EINVAL;
pdacf_reinit(chip, 0);
chip->pcm_substream = NULL;
return 0;
}
/*
* pdacf_pcm_capture_pointer - pointer callback for capture
*/
static snd_pcm_uframes_t pdacf_pcm_capture_pointer(struct snd_pcm_substream *subs)
{
struct snd_pdacf *chip = snd_pcm_substream_chip(subs);
return chip->pcm_hwptr;
}
/*
* operators for PCM capture
*/
static struct snd_pcm_ops pdacf_pcm_capture_ops = {
.open = pdacf_pcm_capture_open,
.close = pdacf_pcm_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = pdacf_pcm_hw_params,
.hw_free = pdacf_pcm_hw_free,
.prepare = pdacf_pcm_prepare,
.trigger = pdacf_pcm_trigger,
.pointer = pdacf_pcm_capture_pointer,
.page = snd_pcm_lib_get_vmalloc_page,
.mmap = snd_pcm_lib_mmap_vmalloc,
};
/*
* snd_pdacf_pcm_new - create and initialize a pcm
*/
int snd_pdacf_pcm_new(struct snd_pdacf *chip)
{
struct snd_pcm *pcm;
int err;
err = snd_pcm_new(chip->card, "PDAudioCF", 0, 0, 1, &pcm);
if (err < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &pdacf_pcm_capture_ops);
pcm->private_data = chip;
pcm->info_flags = 0;
strcpy(pcm->name, chip->card->shortname);
chip->pcm = pcm;
err = snd_ak4117_build(chip->ak4117, pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream);
if (err < 0)
return err;
return 0;
}
| gpl-2.0 |
Split-Screen/android_kernel_motorola_otus | drivers/mtd/maps/pmcmsp-flash.c | 12185 | 6243 | /*
* Mapping of a custom board with both AMD CFI and JEDEC flash in partitions.
* Config with both CFI and JEDEC device support.
*
* Basically physmap.c with the addition of partitions and
* an array of mapping info to accommodate more than one flash type per board.
*
* Copyright 2005-2007 PMC-Sierra, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
#include <asm/io.h>
#include <msp_prom.h>
#include <msp_regs.h>
static struct mtd_info **msp_flash;
static struct mtd_partition **msp_parts;
static struct map_info *msp_maps;
static int fcnt;
#define DEBUG_MARKER printk(KERN_NOTICE "%s[%d]\n", __func__, __LINE__)
static int __init init_msp_flash(void)
{
int i, j, ret = -ENOMEM;
int offset, coff;
char *env;
int pcnt;
char flash_name[] = "flash0";
char part_name[] = "flash0_0";
unsigned addr, size;
/* If ELB is disabled by "ful-mux" mode, we can't get at flash */
if ((*DEV_ID_REG & DEV_ID_SINGLE_PC) &&
(*ELB_1PC_EN_REG & SINGLE_PCCARD)) {
printk(KERN_NOTICE "Single PC Card mode: no flash access\n");
return -ENXIO;
}
/* examine the prom environment for flash devices */
for (fcnt = 0; (env = prom_getenv(flash_name)); fcnt++)
flash_name[5] = '0' + fcnt + 1;
if (fcnt < 1)
return -ENXIO;
printk(KERN_NOTICE "Found %d PMC flash devices\n", fcnt);
msp_flash = kmalloc(fcnt * sizeof(struct map_info *), GFP_KERNEL);
if (!msp_flash)
return -ENOMEM;
msp_parts = kmalloc(fcnt * sizeof(struct mtd_partition *), GFP_KERNEL);
if (!msp_parts)
goto free_msp_flash;
msp_maps = kcalloc(fcnt, sizeof(struct mtd_info), GFP_KERNEL);
if (!msp_maps)
goto free_msp_parts;
/* loop over the flash devices, initializing each */
for (i = 0; i < fcnt; i++) {
/* examine the prom environment for flash partititions */
part_name[5] = '0' + i;
part_name[7] = '0';
for (pcnt = 0; (env = prom_getenv(part_name)); pcnt++)
part_name[7] = '0' + pcnt + 1;
if (pcnt == 0) {
printk(KERN_NOTICE "Skipping flash device %d "
"(no partitions defined)\n", i);
continue;
}
msp_parts[i] = kcalloc(pcnt, sizeof(struct mtd_partition),
GFP_KERNEL);
if (!msp_parts[i])
goto cleanup_loop;
/* now initialize the devices proper */
flash_name[5] = '0' + i;
env = prom_getenv(flash_name);
if (sscanf(env, "%x:%x", &addr, &size) < 2) {
ret = -ENXIO;
kfree(msp_parts[i]);
goto cleanup_loop;
}
addr = CPHYSADDR(addr);
printk(KERN_NOTICE
"MSP flash device \"%s\": 0x%08x at 0x%08x\n",
flash_name, size, addr);
/* This must matchs the actual size of the flash chip */
msp_maps[i].size = size;
msp_maps[i].phys = addr;
/*
* Platforms have a specific limit of the size of memory
* which may be mapped for flash:
*/
if (size > CONFIG_MSP_FLASH_MAP_LIMIT)
size = CONFIG_MSP_FLASH_MAP_LIMIT;
msp_maps[i].virt = ioremap(addr, size);
if (msp_maps[i].virt == NULL) {
ret = -ENXIO;
kfree(msp_parts[i]);
goto cleanup_loop;
}
msp_maps[i].bankwidth = 1;
msp_maps[i].name = kmalloc(7, GFP_KERNEL);
if (!msp_maps[i].name) {
iounmap(msp_maps[i].virt);
kfree(msp_parts[i]);
goto cleanup_loop;
}
msp_maps[i].name = strncpy(msp_maps[i].name, flash_name, 7);
for (j = 0; j < pcnt; j++) {
part_name[5] = '0' + i;
part_name[7] = '0' + j;
env = prom_getenv(part_name);
if (sscanf(env, "%x:%x:%n", &offset, &size,
&coff) < 2) {
ret = -ENXIO;
kfree(msp_maps[i].name);
iounmap(msp_maps[i].virt);
kfree(msp_parts[i]);
goto cleanup_loop;
}
msp_parts[i][j].size = size;
msp_parts[i][j].offset = offset;
msp_parts[i][j].name = env + coff;
}
/* now probe and add the device */
simple_map_init(&msp_maps[i]);
msp_flash[i] = do_map_probe("cfi_probe", &msp_maps[i]);
if (msp_flash[i]) {
msp_flash[i]->owner = THIS_MODULE;
mtd_device_register(msp_flash[i], msp_parts[i], pcnt);
} else {
printk(KERN_ERR "map probe failed for flash\n");
ret = -ENXIO;
kfree(msp_maps[i].name);
iounmap(msp_maps[i].virt);
kfree(msp_parts[i]);
goto cleanup_loop;
}
}
return 0;
cleanup_loop:
while (i--) {
mtd_device_unregister(msp_flash[i]);
map_destroy(msp_flash[i]);
kfree(msp_maps[i].name);
iounmap(msp_maps[i].virt);
kfree(msp_parts[i]);
}
kfree(msp_maps);
free_msp_parts:
kfree(msp_parts);
free_msp_flash:
kfree(msp_flash);
return ret;
}
static void __exit cleanup_msp_flash(void)
{
int i;
for (i = 0; i < fcnt; i++) {
mtd_device_unregister(msp_flash[i]);
map_destroy(msp_flash[i]);
iounmap((void *)msp_maps[i].virt);
/* free the memory */
kfree(msp_maps[i].name);
kfree(msp_parts[i]);
}
kfree(msp_flash);
kfree(msp_parts);
kfree(msp_maps);
}
MODULE_AUTHOR("PMC-Sierra, Inc");
MODULE_DESCRIPTION("MTD map driver for PMC-Sierra MSP boards");
MODULE_LICENSE("GPL");
module_init(init_msp_flash);
module_exit(cleanup_msp_flash);
| gpl-2.0 |
prakhya/linux_sai | arch/ia64/kernel/perfmon_default_smpl.c | 12185 | 7512 | /*
* Copyright (C) 2002-2003 Hewlett-Packard Co
* Stephane Eranian <eranian@hpl.hp.com>
*
* This file implements the default sampling buffer format
* for the Linux/ia64 perfmon-2 subsystem.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/init.h>
#include <asm/delay.h>
#include <linux/smp.h>
#include <asm/perfmon.h>
#include <asm/perfmon_default_smpl.h>
MODULE_AUTHOR("Stephane Eranian <eranian@hpl.hp.com>");
MODULE_DESCRIPTION("perfmon default sampling format");
MODULE_LICENSE("GPL");
#define DEFAULT_DEBUG 1
#ifdef DEFAULT_DEBUG
#define DPRINT(a) \
do { \
if (unlikely(pfm_sysctl.debug >0)) { printk("%s.%d: CPU%d ", __func__, __LINE__, smp_processor_id()); printk a; } \
} while (0)
#define DPRINT_ovfl(a) \
do { \
if (unlikely(pfm_sysctl.debug > 0 && pfm_sysctl.debug_ovfl >0)) { printk("%s.%d: CPU%d ", __func__, __LINE__, smp_processor_id()); printk a; } \
} while (0)
#else
#define DPRINT(a)
#define DPRINT_ovfl(a)
#endif
static int
default_validate(struct task_struct *task, unsigned int flags, int cpu, void *data)
{
pfm_default_smpl_arg_t *arg = (pfm_default_smpl_arg_t*)data;
int ret = 0;
if (data == NULL) {
DPRINT(("[%d] no argument passed\n", task_pid_nr(task)));
return -EINVAL;
}
DPRINT(("[%d] validate flags=0x%x CPU%d\n", task_pid_nr(task), flags, cpu));
/*
* must hold at least the buffer header + one minimally sized entry
*/
if (arg->buf_size < PFM_DEFAULT_SMPL_MIN_BUF_SIZE) return -EINVAL;
DPRINT(("buf_size=%lu\n", arg->buf_size));
return ret;
}
static int
default_get_size(struct task_struct *task, unsigned int flags, int cpu, void *data, unsigned long *size)
{
pfm_default_smpl_arg_t *arg = (pfm_default_smpl_arg_t *)data;
/*
* size has been validated in default_validate
*/
*size = arg->buf_size;
return 0;
}
static int
default_init(struct task_struct *task, void *buf, unsigned int flags, int cpu, void *data)
{
pfm_default_smpl_hdr_t *hdr;
pfm_default_smpl_arg_t *arg = (pfm_default_smpl_arg_t *)data;
hdr = (pfm_default_smpl_hdr_t *)buf;
hdr->hdr_version = PFM_DEFAULT_SMPL_VERSION;
hdr->hdr_buf_size = arg->buf_size;
hdr->hdr_cur_offs = sizeof(*hdr);
hdr->hdr_overflows = 0UL;
hdr->hdr_count = 0UL;
DPRINT(("[%d] buffer=%p buf_size=%lu hdr_size=%lu hdr_version=%u cur_offs=%lu\n",
task_pid_nr(task),
buf,
hdr->hdr_buf_size,
sizeof(*hdr),
hdr->hdr_version,
hdr->hdr_cur_offs));
return 0;
}
static int
default_handler(struct task_struct *task, void *buf, pfm_ovfl_arg_t *arg, struct pt_regs *regs, unsigned long stamp)
{
pfm_default_smpl_hdr_t *hdr;
pfm_default_smpl_entry_t *ent;
void *cur, *last;
unsigned long *e, entry_size;
unsigned int npmds, i;
unsigned char ovfl_pmd;
unsigned char ovfl_notify;
if (unlikely(buf == NULL || arg == NULL|| regs == NULL || task == NULL)) {
DPRINT(("[%d] invalid arguments buf=%p arg=%p\n", task->pid, buf, arg));
return -EINVAL;
}
hdr = (pfm_default_smpl_hdr_t *)buf;
cur = buf+hdr->hdr_cur_offs;
last = buf+hdr->hdr_buf_size;
ovfl_pmd = arg->ovfl_pmd;
ovfl_notify = arg->ovfl_notify;
/*
* precheck for sanity
*/
if ((last - cur) < PFM_DEFAULT_MAX_ENTRY_SIZE) goto full;
npmds = hweight64(arg->smpl_pmds[0]);
ent = (pfm_default_smpl_entry_t *)cur;
prefetch(arg->smpl_pmds_values);
entry_size = sizeof(*ent) + (npmds << 3);
/* position for first pmd */
e = (unsigned long *)(ent+1);
hdr->hdr_count++;
DPRINT_ovfl(("[%d] count=%lu cur=%p last=%p free_bytes=%lu ovfl_pmd=%d ovfl_notify=%d npmds=%u\n",
task->pid,
hdr->hdr_count,
cur, last,
last-cur,
ovfl_pmd,
ovfl_notify, npmds));
/*
* current = task running at the time of the overflow.
*
* per-task mode:
* - this is usually the task being monitored.
* Under certain conditions, it might be a different task
*
* system-wide:
* - this is not necessarily the task controlling the session
*/
ent->pid = current->pid;
ent->ovfl_pmd = ovfl_pmd;
ent->last_reset_val = arg->pmd_last_reset; //pmd[0].reg_last_reset_val;
/*
* where did the fault happen (includes slot number)
*/
ent->ip = regs->cr_iip | ((regs->cr_ipsr >> 41) & 0x3);
ent->tstamp = stamp;
ent->cpu = smp_processor_id();
ent->set = arg->active_set;
ent->tgid = current->tgid;
/*
* selectively store PMDs in increasing index number
*/
if (npmds) {
unsigned long *val = arg->smpl_pmds_values;
for(i=0; i < npmds; i++) {
*e++ = *val++;
}
}
/*
* update position for next entry
*/
hdr->hdr_cur_offs += entry_size;
cur += entry_size;
/*
* post check to avoid losing the last sample
*/
if ((last - cur) < PFM_DEFAULT_MAX_ENTRY_SIZE) goto full;
/*
* keep same ovfl_pmds, ovfl_notify
*/
arg->ovfl_ctrl.bits.notify_user = 0;
arg->ovfl_ctrl.bits.block_task = 0;
arg->ovfl_ctrl.bits.mask_monitoring = 0;
arg->ovfl_ctrl.bits.reset_ovfl_pmds = 1; /* reset before returning from interrupt handler */
return 0;
full:
DPRINT_ovfl(("sampling buffer full free=%lu, count=%lu, ovfl_notify=%d\n", last-cur, hdr->hdr_count, ovfl_notify));
/*
* increment number of buffer overflow.
* important to detect duplicate set of samples.
*/
hdr->hdr_overflows++;
/*
* if no notification requested, then we saturate the buffer
*/
if (ovfl_notify == 0) {
arg->ovfl_ctrl.bits.notify_user = 0;
arg->ovfl_ctrl.bits.block_task = 0;
arg->ovfl_ctrl.bits.mask_monitoring = 1;
arg->ovfl_ctrl.bits.reset_ovfl_pmds = 0;
} else {
arg->ovfl_ctrl.bits.notify_user = 1;
arg->ovfl_ctrl.bits.block_task = 1; /* ignored for non-blocking context */
arg->ovfl_ctrl.bits.mask_monitoring = 1;
arg->ovfl_ctrl.bits.reset_ovfl_pmds = 0; /* no reset now */
}
return -1; /* we are full, sorry */
}
static int
default_restart(struct task_struct *task, pfm_ovfl_ctrl_t *ctrl, void *buf, struct pt_regs *regs)
{
pfm_default_smpl_hdr_t *hdr;
hdr = (pfm_default_smpl_hdr_t *)buf;
hdr->hdr_count = 0UL;
hdr->hdr_cur_offs = sizeof(*hdr);
ctrl->bits.mask_monitoring = 0;
ctrl->bits.reset_ovfl_pmds = 1; /* uses long-reset values */
return 0;
}
static int
default_exit(struct task_struct *task, void *buf, struct pt_regs *regs)
{
DPRINT(("[%d] exit(%p)\n", task_pid_nr(task), buf));
return 0;
}
static pfm_buffer_fmt_t default_fmt={
.fmt_name = "default_format",
.fmt_uuid = PFM_DEFAULT_SMPL_UUID,
.fmt_arg_size = sizeof(pfm_default_smpl_arg_t),
.fmt_validate = default_validate,
.fmt_getsize = default_get_size,
.fmt_init = default_init,
.fmt_handler = default_handler,
.fmt_restart = default_restart,
.fmt_restart_active = default_restart,
.fmt_exit = default_exit,
};
static int __init
pfm_default_smpl_init_module(void)
{
int ret;
ret = pfm_register_buffer_fmt(&default_fmt);
if (ret == 0) {
printk("perfmon_default_smpl: %s v%u.%u registered\n",
default_fmt.fmt_name,
PFM_DEFAULT_SMPL_VERSION_MAJ,
PFM_DEFAULT_SMPL_VERSION_MIN);
} else {
printk("perfmon_default_smpl: %s cannot register ret=%d\n",
default_fmt.fmt_name,
ret);
}
return ret;
}
static void __exit
pfm_default_smpl_cleanup_module(void)
{
int ret;
ret = pfm_unregister_buffer_fmt(default_fmt.fmt_uuid);
printk("perfmon_default_smpl: unregister %s=%d\n", default_fmt.fmt_name, ret);
}
module_init(pfm_default_smpl_init_module);
module_exit(pfm_default_smpl_cleanup_module);
| gpl-2.0 |
Ezekeel/GLaDOS-nexus-s | arch/m32r/kernel/setup.c | 12953 | 10349 | /*
* linux/arch/m32r/kernel/setup.c
*
* Setup routines for Renesas M32R
*
* Copyright (c) 2001, 2002 Hiroyuki Kondo, Hirokazu Takata,
* Hitoshi Yamamoto
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/stddef.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/ioport.h>
#include <linux/mm.h>
#include <linux/bootmem.h>
#include <linux/console.h>
#include <linux/initrd.h>
#include <linux/major.h>
#include <linux/root_dev.h>
#include <linux/seq_file.h>
#include <linux/timex.h>
#include <linux/screen_info.h>
#include <linux/cpu.h>
#include <linux/nodemask.h>
#include <linux/pfn.h>
#include <asm/processor.h>
#include <asm/pgtable.h>
#include <asm/io.h>
#include <asm/mmu_context.h>
#include <asm/m32r.h>
#include <asm/setup.h>
#include <asm/sections.h>
#ifdef CONFIG_MMU
extern void init_mmu(void);
#endif
extern char _end[];
/*
* Machine setup..
*/
struct cpuinfo_m32r boot_cpu_data;
#ifdef CONFIG_BLK_DEV_RAM
extern int rd_doload; /* 1 = load ramdisk, 0 = don't load */
extern int rd_prompt; /* 1 = prompt for ramdisk, 0 = don't prompt */
extern int rd_image_start; /* starting block # of image */
#endif
#if defined(CONFIG_VGA_CONSOLE)
struct screen_info screen_info = {
.orig_video_lines = 25,
.orig_video_cols = 80,
.orig_video_mode = 0,
.orig_video_ega_bx = 0,
.orig_video_isVGA = 1,
.orig_video_points = 8
};
#endif
extern int root_mountflags;
static char __initdata command_line[COMMAND_LINE_SIZE];
static struct resource data_resource = {
.name = "Kernel data",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
static struct resource code_resource = {
.name = "Kernel code",
.start = 0,
.end = 0,
.flags = IORESOURCE_BUSY | IORESOURCE_MEM
};
unsigned long memory_start;
unsigned long memory_end;
void __init setup_arch(char **);
int get_cpuinfo(char *);
static __inline__ void parse_mem_cmdline(char ** cmdline_p)
{
char c = ' ';
char *to = command_line;
char *from = COMMAND_LINE;
int len = 0;
int usermem = 0;
/* Save unparsed command line copy for /proc/cmdline */
memcpy(boot_command_line, COMMAND_LINE, COMMAND_LINE_SIZE);
boot_command_line[COMMAND_LINE_SIZE-1] = '\0';
memory_start = (unsigned long)CONFIG_MEMORY_START+PAGE_OFFSET;
memory_end = memory_start+(unsigned long)CONFIG_MEMORY_SIZE;
for ( ; ; ) {
if (c == ' ' && !memcmp(from, "mem=", 4)) {
if (to != command_line)
to--;
{
unsigned long mem_size;
usermem = 1;
mem_size = memparse(from+4, &from);
memory_end = memory_start + mem_size;
}
}
c = *(from++);
if (!c)
break;
if (COMMAND_LINE_SIZE <= ++len)
break;
*(to++) = c;
}
*to = '\0';
*cmdline_p = command_line;
if (usermem)
printk(KERN_INFO "user-defined physical RAM map:\n");
}
#ifndef CONFIG_DISCONTIGMEM
static unsigned long __init setup_memory(void)
{
unsigned long start_pfn, max_low_pfn, bootmap_size;
start_pfn = PFN_UP( __pa(_end) );
max_low_pfn = PFN_DOWN( __pa(memory_end) );
/*
* Initialize the boot-time allocator (with low memory only):
*/
bootmap_size = init_bootmem_node(NODE_DATA(0), start_pfn,
CONFIG_MEMORY_START>>PAGE_SHIFT, max_low_pfn);
/*
* Register fully available low RAM pages with the bootmem allocator.
*/
{
unsigned long curr_pfn;
unsigned long last_pfn;
unsigned long pages;
/*
* We are rounding up the start address of usable memory:
*/
curr_pfn = PFN_UP(__pa(memory_start));
/*
* ... and at the end of the usable range downwards:
*/
last_pfn = PFN_DOWN(__pa(memory_end));
if (last_pfn > max_low_pfn)
last_pfn = max_low_pfn;
pages = last_pfn - curr_pfn;
free_bootmem(PFN_PHYS(curr_pfn), PFN_PHYS(pages));
}
/*
* Reserve the kernel text and
* Reserve the bootmem bitmap. We do this in two steps (first step
* was init_bootmem()), because this catches the (definitely buggy)
* case of us accidentally initializing the bootmem allocator with
* an invalid RAM area.
*/
reserve_bootmem(CONFIG_MEMORY_START + PAGE_SIZE,
(PFN_PHYS(start_pfn) + bootmap_size + PAGE_SIZE - 1)
- CONFIG_MEMORY_START,
BOOTMEM_DEFAULT);
/*
* reserve physical page 0 - it's a special BIOS page on many boxes,
* enabling clean reboots, SMP operation, laptop functions.
*/
reserve_bootmem(CONFIG_MEMORY_START, PAGE_SIZE, BOOTMEM_DEFAULT);
/*
* reserve memory hole
*/
#ifdef CONFIG_MEMHOLE
reserve_bootmem(CONFIG_MEMHOLE_START, CONFIG_MEMHOLE_SIZE,
BOOTMEM_DEFAULT);
#endif
#ifdef CONFIG_BLK_DEV_INITRD
if (LOADER_TYPE && INITRD_START) {
if (INITRD_START + INITRD_SIZE <= (max_low_pfn << PAGE_SHIFT)) {
reserve_bootmem(INITRD_START, INITRD_SIZE,
BOOTMEM_DEFAULT);
initrd_start = INITRD_START + PAGE_OFFSET;
initrd_end = initrd_start + INITRD_SIZE;
printk("initrd:start[%08lx],size[%08lx]\n",
initrd_start, INITRD_SIZE);
} else {
printk("initrd extends beyond end of memory "
"(0x%08lx > 0x%08lx)\ndisabling initrd\n",
INITRD_START + INITRD_SIZE,
max_low_pfn << PAGE_SHIFT);
initrd_start = 0;
}
}
#endif
return max_low_pfn;
}
#else /* CONFIG_DISCONTIGMEM */
extern unsigned long setup_memory(void);
#endif /* CONFIG_DISCONTIGMEM */
void __init setup_arch(char **cmdline_p)
{
ROOT_DEV = old_decode_dev(ORIG_ROOT_DEV);
boot_cpu_data.cpu_clock = M32R_CPUCLK;
boot_cpu_data.bus_clock = M32R_BUSCLK;
boot_cpu_data.timer_divide = M32R_TIMER_DIVIDE;
#ifdef CONFIG_BLK_DEV_RAM
rd_image_start = RAMDISK_FLAGS & RAMDISK_IMAGE_START_MASK;
rd_prompt = ((RAMDISK_FLAGS & RAMDISK_PROMPT_FLAG) != 0);
rd_doload = ((RAMDISK_FLAGS & RAMDISK_LOAD_FLAG) != 0);
#endif
if (!MOUNT_ROOT_RDONLY)
root_mountflags &= ~MS_RDONLY;
#ifdef CONFIG_VT
#if defined(CONFIG_VGA_CONSOLE)
conswitchp = &vga_con;
#elif defined(CONFIG_DUMMY_CONSOLE)
conswitchp = &dummy_con;
#endif
#endif
#ifdef CONFIG_DISCONTIGMEM
nodes_clear(node_online_map);
node_set_online(0);
node_set_online(1);
#endif /* CONFIG_DISCONTIGMEM */
init_mm.start_code = (unsigned long) _text;
init_mm.end_code = (unsigned long) _etext;
init_mm.end_data = (unsigned long) _edata;
init_mm.brk = (unsigned long) _end;
code_resource.start = virt_to_phys(_text);
code_resource.end = virt_to_phys(_etext)-1;
data_resource.start = virt_to_phys(_etext);
data_resource.end = virt_to_phys(_edata)-1;
parse_mem_cmdline(cmdline_p);
setup_memory();
paging_init();
}
static struct cpu cpu_devices[NR_CPUS];
static int __init topology_init(void)
{
int i;
for_each_present_cpu(i)
register_cpu(&cpu_devices[i], i);
return 0;
}
subsys_initcall(topology_init);
#ifdef CONFIG_PROC_FS
/*
* Get CPU information for use by the procfs.
*/
static int show_cpuinfo(struct seq_file *m, void *v)
{
struct cpuinfo_m32r *c = v;
unsigned long cpu = c - cpu_data;
#ifdef CONFIG_SMP
if (!cpu_online(cpu))
return 0;
#endif /* CONFIG_SMP */
seq_printf(m, "processor\t: %ld\n", cpu);
#if defined(CONFIG_CHIP_VDEC2)
seq_printf(m, "cpu family\t: VDEC2\n"
"cache size\t: Unknown\n");
#elif defined(CONFIG_CHIP_M32700)
seq_printf(m,"cpu family\t: M32700\n"
"cache size\t: I-8KB/D-8KB\n");
#elif defined(CONFIG_CHIP_M32102)
seq_printf(m,"cpu family\t: M32102\n"
"cache size\t: I-8KB\n");
#elif defined(CONFIG_CHIP_OPSP)
seq_printf(m,"cpu family\t: OPSP\n"
"cache size\t: I-8KB/D-8KB\n");
#elif defined(CONFIG_CHIP_MP)
seq_printf(m, "cpu family\t: M32R-MP\n"
"cache size\t: I-xxKB/D-xxKB\n");
#elif defined(CONFIG_CHIP_M32104)
seq_printf(m,"cpu family\t: M32104\n"
"cache size\t: I-8KB/D-8KB\n");
#else
seq_printf(m, "cpu family\t: Unknown\n");
#endif
seq_printf(m, "bogomips\t: %lu.%02lu\n",
c->loops_per_jiffy/(500000/HZ),
(c->loops_per_jiffy/(5000/HZ)) % 100);
#if defined(CONFIG_PLAT_MAPPI)
seq_printf(m, "Machine\t\t: Mappi Evaluation board\n");
#elif defined(CONFIG_PLAT_MAPPI2)
seq_printf(m, "Machine\t\t: Mappi-II Evaluation board\n");
#elif defined(CONFIG_PLAT_MAPPI3)
seq_printf(m, "Machine\t\t: Mappi-III Evaluation board\n");
#elif defined(CONFIG_PLAT_M32700UT)
seq_printf(m, "Machine\t\t: M32700UT Evaluation board\n");
#elif defined(CONFIG_PLAT_OPSPUT)
seq_printf(m, "Machine\t\t: OPSPUT Evaluation board\n");
#elif defined(CONFIG_PLAT_USRV)
seq_printf(m, "Machine\t\t: uServer\n");
#elif defined(CONFIG_PLAT_OAKS32R)
seq_printf(m, "Machine\t\t: OAKS32R\n");
#elif defined(CONFIG_PLAT_M32104UT)
seq_printf(m, "Machine\t\t: M3T-M32104UT uT Engine board\n");
#else
seq_printf(m, "Machine\t\t: Unknown\n");
#endif
#define PRINT_CLOCK(name, value) \
seq_printf(m, name " clock\t: %d.%02dMHz\n", \
((value) / 1000000), ((value) % 1000000)/10000)
PRINT_CLOCK("CPU", (int)c->cpu_clock);
PRINT_CLOCK("Bus", (int)c->bus_clock);
seq_printf(m, "\n");
return 0;
}
static void *c_start(struct seq_file *m, loff_t *pos)
{
return *pos < NR_CPUS ? cpu_data + *pos : NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return c_start(m, pos);
}
static void c_stop(struct seq_file *m, void *v)
{
}
const struct seq_operations cpuinfo_op = {
.start = c_start,
.next = c_next,
.stop = c_stop,
.show = show_cpuinfo,
};
#endif /* CONFIG_PROC_FS */
unsigned long cpu_initialized __initdata = 0;
/*
* cpu_init() initializes state that is per-CPU. Some data is already
* initialized (naturally) in the bootstrap process.
* We reload them nevertheless, this function acts as a
* 'CPU state barrier', nothing should get across.
*/
#if defined(CONFIG_CHIP_VDEC2) || defined(CONFIG_CHIP_XNUX2) \
|| defined(CONFIG_CHIP_M32700) || defined(CONFIG_CHIP_M32102) \
|| defined(CONFIG_CHIP_OPSP) || defined(CONFIG_CHIP_M32104)
void __init cpu_init (void)
{
int cpu_id = smp_processor_id();
if (test_and_set_bit(cpu_id, &cpu_initialized)) {
printk(KERN_WARNING "CPU#%d already initialized!\n", cpu_id);
for ( ; ; )
local_irq_enable();
}
printk(KERN_INFO "Initializing CPU#%d\n", cpu_id);
/* Set up and load the per-CPU TSS and LDT */
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
if (current->mm)
BUG();
/* Force FPU initialization */
current_thread_info()->status = 0;
clear_used_math();
#ifdef CONFIG_MMU
/* Set up MMU */
init_mmu();
#endif
/* Set up ICUIMASK */
outl(0x00070000, M32R_ICU_IMASK_PORTL); /* imask=111 */
}
#endif /* defined(CONFIG_CHIP_VDEC2) ... */
| gpl-2.0 |
mdalexca/marlin | drivers/net/wimax/i2400m/op-rfkill.c | 12953 | 6534 | /*
* Intel Wireless WiMAX Connection 2400m
* Implement backend for the WiMAX stack rfkill support
*
*
* Copyright (C) 2007-2008 Intel Corporation <linux-wimax@intel.com>
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.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 Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*
* The WiMAX kernel stack integrates into RF-Kill and keeps the
* switches's status. We just need to:
*
* - report changes in the HW RF Kill switch [with
* wimax_rfkill_{sw,hw}_report(), which happens when we detect those
* indications coming through hardware reports]. We also do it on
* initialization to let the stack know the initial HW state.
*
* - implement indications from the stack to change the SW RF Kill
* switch (coming from sysfs, the wimax stack or user space).
*/
#include "i2400m.h"
#include <linux/wimax/i2400m.h>
#include <linux/slab.h>
#define D_SUBMODULE rfkill
#include "debug-levels.h"
/*
* Return true if the i2400m radio is in the requested wimax_rf_state state
*
*/
static
int i2400m_radio_is(struct i2400m *i2400m, enum wimax_rf_state state)
{
if (state == WIMAX_RF_OFF)
return i2400m->state == I2400M_SS_RF_OFF
|| i2400m->state == I2400M_SS_RF_SHUTDOWN;
else if (state == WIMAX_RF_ON)
/* state == WIMAX_RF_ON */
return i2400m->state != I2400M_SS_RF_OFF
&& i2400m->state != I2400M_SS_RF_SHUTDOWN;
else {
BUG();
return -EINVAL; /* shut gcc warnings on certain arches */
}
}
/*
* WiMAX stack operation: implement SW RFKill toggling
*
* @wimax_dev: device descriptor
* @skb: skb where the message has been received; skb->data is
* expected to point to the message payload.
* @genl_info: passed by the generic netlink layer
*
* Generic Netlink will call this function when a message is sent from
* userspace to change the software RF-Kill switch status.
*
* This function will set the device's software RF-Kill switch state to
* match what is requested.
*
* NOTE: the i2400m has a strict state machine; we can only set the
* RF-Kill switch when it is on, the HW RF-Kill is on and the
* device is initialized. So we ignore errors steaming from not
* being in the right state (-EILSEQ).
*/
int i2400m_op_rfkill_sw_toggle(struct wimax_dev *wimax_dev,
enum wimax_rf_state state)
{
int result;
struct i2400m *i2400m = wimax_dev_to_i2400m(wimax_dev);
struct device *dev = i2400m_dev(i2400m);
struct sk_buff *ack_skb;
struct {
struct i2400m_l3l4_hdr hdr;
struct i2400m_tlv_rf_operation sw_rf;
} __packed *cmd;
char strerr[32];
d_fnstart(4, dev, "(wimax_dev %p state %d)\n", wimax_dev, state);
result = -ENOMEM;
cmd = kzalloc(sizeof(*cmd), GFP_KERNEL);
if (cmd == NULL)
goto error_alloc;
cmd->hdr.type = cpu_to_le16(I2400M_MT_CMD_RF_CONTROL);
cmd->hdr.length = sizeof(cmd->sw_rf);
cmd->hdr.version = cpu_to_le16(I2400M_L3L4_VERSION);
cmd->sw_rf.hdr.type = cpu_to_le16(I2400M_TLV_RF_OPERATION);
cmd->sw_rf.hdr.length = cpu_to_le16(sizeof(cmd->sw_rf.status));
switch (state) {
case WIMAX_RF_OFF: /* RFKILL ON, radio OFF */
cmd->sw_rf.status = cpu_to_le32(2);
break;
case WIMAX_RF_ON: /* RFKILL OFF, radio ON */
cmd->sw_rf.status = cpu_to_le32(1);
break;
default:
BUG();
}
ack_skb = i2400m_msg_to_dev(i2400m, cmd, sizeof(*cmd));
result = PTR_ERR(ack_skb);
if (IS_ERR(ack_skb)) {
dev_err(dev, "Failed to issue 'RF Control' command: %d\n",
result);
goto error_msg_to_dev;
}
result = i2400m_msg_check_status(wimax_msg_data(ack_skb),
strerr, sizeof(strerr));
if (result < 0) {
dev_err(dev, "'RF Control' (0x%04x) command failed: %d - %s\n",
I2400M_MT_CMD_RF_CONTROL, result, strerr);
goto error_cmd;
}
/* Now we wait for the state to change to RADIO_OFF or RADIO_ON */
result = wait_event_timeout(
i2400m->state_wq, i2400m_radio_is(i2400m, state),
5 * HZ);
if (result == 0)
result = -ETIMEDOUT;
if (result < 0)
dev_err(dev, "Error waiting for device to toggle RF state: "
"%d\n", result);
result = 0;
error_cmd:
kfree_skb(ack_skb);
error_msg_to_dev:
error_alloc:
d_fnend(4, dev, "(wimax_dev %p state %d) = %d\n",
wimax_dev, state, result);
return result;
}
/*
* Inform the WiMAX stack of changes in the RF Kill switches reported
* by the device
*
* @i2400m: device descriptor
* @rfss: TLV for RF Switches status; already validated
*
* NOTE: the reports on RF switch status cannot be trusted
* or used until the device is in a state of RADIO_OFF
* or greater.
*/
void i2400m_report_tlv_rf_switches_status(
struct i2400m *i2400m,
const struct i2400m_tlv_rf_switches_status *rfss)
{
struct device *dev = i2400m_dev(i2400m);
enum i2400m_rf_switch_status hw, sw;
enum wimax_st wimax_state;
sw = le32_to_cpu(rfss->sw_rf_switch);
hw = le32_to_cpu(rfss->hw_rf_switch);
d_fnstart(3, dev, "(i2400m %p rfss %p [hw %u sw %u])\n",
i2400m, rfss, hw, sw);
/* We only process rw switch evens when the device has been
* fully initialized */
wimax_state = wimax_state_get(&i2400m->wimax_dev);
if (wimax_state < WIMAX_ST_RADIO_OFF) {
d_printf(3, dev, "ignoring RF switches report, state %u\n",
wimax_state);
goto out;
}
switch (sw) {
case I2400M_RF_SWITCH_ON: /* RF Kill disabled (radio on) */
wimax_report_rfkill_sw(&i2400m->wimax_dev, WIMAX_RF_ON);
break;
case I2400M_RF_SWITCH_OFF: /* RF Kill enabled (radio off) */
wimax_report_rfkill_sw(&i2400m->wimax_dev, WIMAX_RF_OFF);
break;
default:
dev_err(dev, "HW BUG? Unknown RF SW state 0x%x\n", sw);
}
switch (hw) {
case I2400M_RF_SWITCH_ON: /* RF Kill disabled (radio on) */
wimax_report_rfkill_hw(&i2400m->wimax_dev, WIMAX_RF_ON);
break;
case I2400M_RF_SWITCH_OFF: /* RF Kill enabled (radio off) */
wimax_report_rfkill_hw(&i2400m->wimax_dev, WIMAX_RF_OFF);
break;
default:
dev_err(dev, "HW BUG? Unknown RF HW state 0x%x\n", hw);
}
out:
d_fnend(3, dev, "(i2400m %p rfss %p [hw %u sw %u]) = void\n",
i2400m, rfss, hw, sw);
}
| gpl-2.0 |
nks15/nks_kernel_j7xeltektt | drivers/net/wireless/b43/main.c | 154 | 155679 | /*
Broadcom B43 wireless driver
Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>
Copyright (c) 2005 Stefano Brivio <stefano.brivio@polimi.it>
Copyright (c) 2005-2009 Michael Buesch <m@bues.ch>
Copyright (c) 2005 Danny van Dyk <kugelfang@gentoo.org>
Copyright (c) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch>
Copyright (c) 2010-2011 Rafał Miłecki <zajec5@gmail.com>
SDIO support
Copyright (c) 2009 Albert Herranz <albert_herranz@yahoo.es>
Some parts of the code in this file are derived from the ipw2200
driver Copyright(c) 2003 - 2004 Intel Corporation.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/if_arp.h>
#include <linux/etherdevice.h>
#include <linux/firmware.h>
#include <linux/workqueue.h>
#include <linux/skbuff.h>
#include <linux/io.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#include "b43.h"
#include "main.h"
#include "debugfs.h"
#include "phy_common.h"
#include "phy_g.h"
#include "phy_n.h"
#include "dma.h"
#include "pio.h"
#include "sysfs.h"
#include "xmit.h"
#include "lo.h"
#include "pcmcia.h"
#include "sdio.h"
#include <linux/mmc/sdio_func.h>
MODULE_DESCRIPTION("Broadcom B43 wireless driver");
MODULE_AUTHOR("Martin Langer");
MODULE_AUTHOR("Stefano Brivio");
MODULE_AUTHOR("Michael Buesch");
MODULE_AUTHOR("Gábor Stefanik");
MODULE_AUTHOR("Rafał Miłecki");
MODULE_LICENSE("GPL");
MODULE_FIRMWARE("b43/ucode11.fw");
MODULE_FIRMWARE("b43/ucode13.fw");
MODULE_FIRMWARE("b43/ucode14.fw");
MODULE_FIRMWARE("b43/ucode15.fw");
MODULE_FIRMWARE("b43/ucode16_mimo.fw");
MODULE_FIRMWARE("b43/ucode5.fw");
MODULE_FIRMWARE("b43/ucode9.fw");
static int modparam_bad_frames_preempt;
module_param_named(bad_frames_preempt, modparam_bad_frames_preempt, int, 0444);
MODULE_PARM_DESC(bad_frames_preempt,
"enable(1) / disable(0) Bad Frames Preemption");
static char modparam_fwpostfix[16];
module_param_string(fwpostfix, modparam_fwpostfix, 16, 0444);
MODULE_PARM_DESC(fwpostfix, "Postfix for the .fw files to load.");
static int modparam_hwpctl;
module_param_named(hwpctl, modparam_hwpctl, int, 0444);
MODULE_PARM_DESC(hwpctl, "Enable hardware-side power control (default off)");
static int modparam_nohwcrypt;
module_param_named(nohwcrypt, modparam_nohwcrypt, int, 0444);
MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption.");
static int modparam_hwtkip;
module_param_named(hwtkip, modparam_hwtkip, int, 0444);
MODULE_PARM_DESC(hwtkip, "Enable hardware tkip.");
static int modparam_qos = 1;
module_param_named(qos, modparam_qos, int, 0444);
MODULE_PARM_DESC(qos, "Enable QOS support (default on)");
static int modparam_btcoex = 1;
module_param_named(btcoex, modparam_btcoex, int, 0444);
MODULE_PARM_DESC(btcoex, "Enable Bluetooth coexistence (default on)");
int b43_modparam_verbose = B43_VERBOSITY_DEFAULT;
module_param_named(verbose, b43_modparam_verbose, int, 0644);
MODULE_PARM_DESC(verbose, "Log message verbosity: 0=error, 1=warn, 2=info(default), 3=debug");
static int b43_modparam_pio = 0;
module_param_named(pio, b43_modparam_pio, int, 0644);
MODULE_PARM_DESC(pio, "Use PIO accesses by default: 0=DMA, 1=PIO");
static int modparam_allhwsupport = !IS_ENABLED(CONFIG_BRCMSMAC);
module_param_named(allhwsupport, modparam_allhwsupport, int, 0444);
MODULE_PARM_DESC(allhwsupport, "Enable support for all hardware (even it if overlaps with the brcmsmac driver)");
#ifdef CONFIG_B43_BCMA
static const struct bcma_device_id b43_bcma_tbl[] = {
BCMA_CORE(BCMA_MANUF_BCM, BCMA_CORE_80211, 0x11, BCMA_ANY_CLASS),
BCMA_CORE(BCMA_MANUF_BCM, BCMA_CORE_80211, 0x17, BCMA_ANY_CLASS),
BCMA_CORE(BCMA_MANUF_BCM, BCMA_CORE_80211, 0x18, BCMA_ANY_CLASS),
BCMA_CORE(BCMA_MANUF_BCM, BCMA_CORE_80211, 0x1C, BCMA_ANY_CLASS),
BCMA_CORE(BCMA_MANUF_BCM, BCMA_CORE_80211, 0x1D, BCMA_ANY_CLASS),
BCMA_CORE(BCMA_MANUF_BCM, BCMA_CORE_80211, 0x1E, BCMA_ANY_CLASS),
BCMA_CORE(BCMA_MANUF_BCM, BCMA_CORE_80211, 0x28, BCMA_ANY_CLASS),
BCMA_CORE(BCMA_MANUF_BCM, BCMA_CORE_80211, 0x2A, BCMA_ANY_CLASS),
BCMA_CORETABLE_END
};
MODULE_DEVICE_TABLE(bcma, b43_bcma_tbl);
#endif
#ifdef CONFIG_B43_SSB
static const struct ssb_device_id b43_ssb_tbl[] = {
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 5),
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 6),
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 7),
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 9),
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 10),
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 11),
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 12),
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 13),
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 15),
SSB_DEVICE(SSB_VENDOR_BROADCOM, SSB_DEV_80211, 16),
SSB_DEVTABLE_END
};
MODULE_DEVICE_TABLE(ssb, b43_ssb_tbl);
#endif
/* Channel and ratetables are shared for all devices.
* They can't be const, because ieee80211 puts some precalculated
* data in there. This data is the same for all devices, so we don't
* get concurrency issues */
#define RATETAB_ENT(_rateid, _flags) \
{ \
.bitrate = B43_RATE_TO_BASE100KBPS(_rateid), \
.hw_value = (_rateid), \
.flags = (_flags), \
}
/*
* NOTE: When changing this, sync with xmit.c's
* b43_plcp_get_bitrate_idx_* functions!
*/
static struct ieee80211_rate __b43_ratetable[] = {
RATETAB_ENT(B43_CCK_RATE_1MB, 0),
RATETAB_ENT(B43_CCK_RATE_2MB, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(B43_CCK_RATE_5MB, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(B43_CCK_RATE_11MB, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(B43_OFDM_RATE_6MB, 0),
RATETAB_ENT(B43_OFDM_RATE_9MB, 0),
RATETAB_ENT(B43_OFDM_RATE_12MB, 0),
RATETAB_ENT(B43_OFDM_RATE_18MB, 0),
RATETAB_ENT(B43_OFDM_RATE_24MB, 0),
RATETAB_ENT(B43_OFDM_RATE_36MB, 0),
RATETAB_ENT(B43_OFDM_RATE_48MB, 0),
RATETAB_ENT(B43_OFDM_RATE_54MB, 0),
};
#define b43_a_ratetable (__b43_ratetable + 4)
#define b43_a_ratetable_size 8
#define b43_b_ratetable (__b43_ratetable + 0)
#define b43_b_ratetable_size 4
#define b43_g_ratetable (__b43_ratetable + 0)
#define b43_g_ratetable_size 12
#define CHAN2G(_channel, _freq, _flags) { \
.band = IEEE80211_BAND_2GHZ, \
.center_freq = (_freq), \
.hw_value = (_channel), \
.flags = (_flags), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
static struct ieee80211_channel b43_2ghz_chantable[] = {
CHAN2G(1, 2412, 0),
CHAN2G(2, 2417, 0),
CHAN2G(3, 2422, 0),
CHAN2G(4, 2427, 0),
CHAN2G(5, 2432, 0),
CHAN2G(6, 2437, 0),
CHAN2G(7, 2442, 0),
CHAN2G(8, 2447, 0),
CHAN2G(9, 2452, 0),
CHAN2G(10, 2457, 0),
CHAN2G(11, 2462, 0),
CHAN2G(12, 2467, 0),
CHAN2G(13, 2472, 0),
CHAN2G(14, 2484, 0),
};
/* No support for the last 3 channels (12, 13, 14) */
#define b43_2ghz_chantable_limited_size 11
#undef CHAN2G
#define CHAN4G(_channel, _flags) { \
.band = IEEE80211_BAND_5GHZ, \
.center_freq = 4000 + (5 * (_channel)), \
.hw_value = (_channel), \
.flags = (_flags), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
#define CHAN5G(_channel, _flags) { \
.band = IEEE80211_BAND_5GHZ, \
.center_freq = 5000 + (5 * (_channel)), \
.hw_value = (_channel), \
.flags = (_flags), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
static struct ieee80211_channel b43_5ghz_nphy_chantable[] = {
CHAN4G(184, 0), CHAN4G(186, 0),
CHAN4G(188, 0), CHAN4G(190, 0),
CHAN4G(192, 0), CHAN4G(194, 0),
CHAN4G(196, 0), CHAN4G(198, 0),
CHAN4G(200, 0), CHAN4G(202, 0),
CHAN4G(204, 0), CHAN4G(206, 0),
CHAN4G(208, 0), CHAN4G(210, 0),
CHAN4G(212, 0), CHAN4G(214, 0),
CHAN4G(216, 0), CHAN4G(218, 0),
CHAN4G(220, 0), CHAN4G(222, 0),
CHAN4G(224, 0), CHAN4G(226, 0),
CHAN4G(228, 0),
CHAN5G(32, 0), CHAN5G(34, 0),
CHAN5G(36, 0), CHAN5G(38, 0),
CHAN5G(40, 0), CHAN5G(42, 0),
CHAN5G(44, 0), CHAN5G(46, 0),
CHAN5G(48, 0), CHAN5G(50, 0),
CHAN5G(52, 0), CHAN5G(54, 0),
CHAN5G(56, 0), CHAN5G(58, 0),
CHAN5G(60, 0), CHAN5G(62, 0),
CHAN5G(64, 0), CHAN5G(66, 0),
CHAN5G(68, 0), CHAN5G(70, 0),
CHAN5G(72, 0), CHAN5G(74, 0),
CHAN5G(76, 0), CHAN5G(78, 0),
CHAN5G(80, 0), CHAN5G(82, 0),
CHAN5G(84, 0), CHAN5G(86, 0),
CHAN5G(88, 0), CHAN5G(90, 0),
CHAN5G(92, 0), CHAN5G(94, 0),
CHAN5G(96, 0), CHAN5G(98, 0),
CHAN5G(100, 0), CHAN5G(102, 0),
CHAN5G(104, 0), CHAN5G(106, 0),
CHAN5G(108, 0), CHAN5G(110, 0),
CHAN5G(112, 0), CHAN5G(114, 0),
CHAN5G(116, 0), CHAN5G(118, 0),
CHAN5G(120, 0), CHAN5G(122, 0),
CHAN5G(124, 0), CHAN5G(126, 0),
CHAN5G(128, 0), CHAN5G(130, 0),
CHAN5G(132, 0), CHAN5G(134, 0),
CHAN5G(136, 0), CHAN5G(138, 0),
CHAN5G(140, 0), CHAN5G(142, 0),
CHAN5G(144, 0), CHAN5G(145, 0),
CHAN5G(146, 0), CHAN5G(147, 0),
CHAN5G(148, 0), CHAN5G(149, 0),
CHAN5G(150, 0), CHAN5G(151, 0),
CHAN5G(152, 0), CHAN5G(153, 0),
CHAN5G(154, 0), CHAN5G(155, 0),
CHAN5G(156, 0), CHAN5G(157, 0),
CHAN5G(158, 0), CHAN5G(159, 0),
CHAN5G(160, 0), CHAN5G(161, 0),
CHAN5G(162, 0), CHAN5G(163, 0),
CHAN5G(164, 0), CHAN5G(165, 0),
CHAN5G(166, 0), CHAN5G(168, 0),
CHAN5G(170, 0), CHAN5G(172, 0),
CHAN5G(174, 0), CHAN5G(176, 0),
CHAN5G(178, 0), CHAN5G(180, 0),
CHAN5G(182, 0),
};
static struct ieee80211_channel b43_5ghz_nphy_chantable_limited[] = {
CHAN5G(36, 0), CHAN5G(40, 0),
CHAN5G(44, 0), CHAN5G(48, 0),
CHAN5G(149, 0), CHAN5G(153, 0),
CHAN5G(157, 0), CHAN5G(161, 0),
CHAN5G(165, 0),
};
static struct ieee80211_channel b43_5ghz_aphy_chantable[] = {
CHAN5G(34, 0), CHAN5G(36, 0),
CHAN5G(38, 0), CHAN5G(40, 0),
CHAN5G(42, 0), CHAN5G(44, 0),
CHAN5G(46, 0), CHAN5G(48, 0),
CHAN5G(52, 0), CHAN5G(56, 0),
CHAN5G(60, 0), CHAN5G(64, 0),
CHAN5G(100, 0), CHAN5G(104, 0),
CHAN5G(108, 0), CHAN5G(112, 0),
CHAN5G(116, 0), CHAN5G(120, 0),
CHAN5G(124, 0), CHAN5G(128, 0),
CHAN5G(132, 0), CHAN5G(136, 0),
CHAN5G(140, 0), CHAN5G(149, 0),
CHAN5G(153, 0), CHAN5G(157, 0),
CHAN5G(161, 0), CHAN5G(165, 0),
CHAN5G(184, 0), CHAN5G(188, 0),
CHAN5G(192, 0), CHAN5G(196, 0),
CHAN5G(200, 0), CHAN5G(204, 0),
CHAN5G(208, 0), CHAN5G(212, 0),
CHAN5G(216, 0),
};
#undef CHAN4G
#undef CHAN5G
static struct ieee80211_supported_band b43_band_5GHz_nphy = {
.band = IEEE80211_BAND_5GHZ,
.channels = b43_5ghz_nphy_chantable,
.n_channels = ARRAY_SIZE(b43_5ghz_nphy_chantable),
.bitrates = b43_a_ratetable,
.n_bitrates = b43_a_ratetable_size,
};
static struct ieee80211_supported_band b43_band_5GHz_nphy_limited = {
.band = IEEE80211_BAND_5GHZ,
.channels = b43_5ghz_nphy_chantable_limited,
.n_channels = ARRAY_SIZE(b43_5ghz_nphy_chantable_limited),
.bitrates = b43_a_ratetable,
.n_bitrates = b43_a_ratetable_size,
};
static struct ieee80211_supported_band b43_band_5GHz_aphy = {
.band = IEEE80211_BAND_5GHZ,
.channels = b43_5ghz_aphy_chantable,
.n_channels = ARRAY_SIZE(b43_5ghz_aphy_chantable),
.bitrates = b43_a_ratetable,
.n_bitrates = b43_a_ratetable_size,
};
static struct ieee80211_supported_band b43_band_2GHz = {
.band = IEEE80211_BAND_2GHZ,
.channels = b43_2ghz_chantable,
.n_channels = ARRAY_SIZE(b43_2ghz_chantable),
.bitrates = b43_g_ratetable,
.n_bitrates = b43_g_ratetable_size,
};
static struct ieee80211_supported_band b43_band_2ghz_limited = {
.band = IEEE80211_BAND_2GHZ,
.channels = b43_2ghz_chantable,
.n_channels = b43_2ghz_chantable_limited_size,
.bitrates = b43_g_ratetable,
.n_bitrates = b43_g_ratetable_size,
};
static void b43_wireless_core_exit(struct b43_wldev *dev);
static int b43_wireless_core_init(struct b43_wldev *dev);
static struct b43_wldev * b43_wireless_core_stop(struct b43_wldev *dev);
static int b43_wireless_core_start(struct b43_wldev *dev);
static void b43_op_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *conf,
u32 changed);
static int b43_ratelimit(struct b43_wl *wl)
{
if (!wl || !wl->current_dev)
return 1;
if (b43_status(wl->current_dev) < B43_STAT_STARTED)
return 1;
/* We are up and running.
* Ratelimit the messages to avoid DoS over the net. */
return net_ratelimit();
}
void b43info(struct b43_wl *wl, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (b43_modparam_verbose < B43_VERBOSITY_INFO)
return;
if (!b43_ratelimit(wl))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_INFO "b43-%s: %pV",
(wl && wl->hw) ? wiphy_name(wl->hw->wiphy) : "wlan", &vaf);
va_end(args);
}
void b43err(struct b43_wl *wl, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (b43_modparam_verbose < B43_VERBOSITY_ERROR)
return;
if (!b43_ratelimit(wl))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_ERR "b43-%s ERROR: %pV",
(wl && wl->hw) ? wiphy_name(wl->hw->wiphy) : "wlan", &vaf);
va_end(args);
}
void b43warn(struct b43_wl *wl, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (b43_modparam_verbose < B43_VERBOSITY_WARN)
return;
if (!b43_ratelimit(wl))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "b43-%s warning: %pV",
(wl && wl->hw) ? wiphy_name(wl->hw->wiphy) : "wlan", &vaf);
va_end(args);
}
void b43dbg(struct b43_wl *wl, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (b43_modparam_verbose < B43_VERBOSITY_DEBUG)
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_DEBUG "b43-%s debug: %pV",
(wl && wl->hw) ? wiphy_name(wl->hw->wiphy) : "wlan", &vaf);
va_end(args);
}
static void b43_ram_write(struct b43_wldev *dev, u16 offset, u32 val)
{
u32 macctl;
B43_WARN_ON(offset % 4 != 0);
macctl = b43_read32(dev, B43_MMIO_MACCTL);
if (macctl & B43_MACCTL_BE)
val = swab32(val);
b43_write32(dev, B43_MMIO_RAM_CONTROL, offset);
mmiowb();
b43_write32(dev, B43_MMIO_RAM_DATA, val);
}
static inline void b43_shm_control_word(struct b43_wldev *dev,
u16 routing, u16 offset)
{
u32 control;
/* "offset" is the WORD offset. */
control = routing;
control <<= 16;
control |= offset;
b43_write32(dev, B43_MMIO_SHM_CONTROL, control);
}
u32 b43_shm_read32(struct b43_wldev *dev, u16 routing, u16 offset)
{
u32 ret;
if (routing == B43_SHM_SHARED) {
B43_WARN_ON(offset & 0x0001);
if (offset & 0x0003) {
/* Unaligned access */
b43_shm_control_word(dev, routing, offset >> 2);
ret = b43_read16(dev, B43_MMIO_SHM_DATA_UNALIGNED);
b43_shm_control_word(dev, routing, (offset >> 2) + 1);
ret |= ((u32)b43_read16(dev, B43_MMIO_SHM_DATA)) << 16;
goto out;
}
offset >>= 2;
}
b43_shm_control_word(dev, routing, offset);
ret = b43_read32(dev, B43_MMIO_SHM_DATA);
out:
return ret;
}
u16 b43_shm_read16(struct b43_wldev *dev, u16 routing, u16 offset)
{
u16 ret;
if (routing == B43_SHM_SHARED) {
B43_WARN_ON(offset & 0x0001);
if (offset & 0x0003) {
/* Unaligned access */
b43_shm_control_word(dev, routing, offset >> 2);
ret = b43_read16(dev, B43_MMIO_SHM_DATA_UNALIGNED);
goto out;
}
offset >>= 2;
}
b43_shm_control_word(dev, routing, offset);
ret = b43_read16(dev, B43_MMIO_SHM_DATA);
out:
return ret;
}
void b43_shm_write32(struct b43_wldev *dev, u16 routing, u16 offset, u32 value)
{
if (routing == B43_SHM_SHARED) {
B43_WARN_ON(offset & 0x0001);
if (offset & 0x0003) {
/* Unaligned access */
b43_shm_control_word(dev, routing, offset >> 2);
b43_write16(dev, B43_MMIO_SHM_DATA_UNALIGNED,
value & 0xFFFF);
b43_shm_control_word(dev, routing, (offset >> 2) + 1);
b43_write16(dev, B43_MMIO_SHM_DATA,
(value >> 16) & 0xFFFF);
return;
}
offset >>= 2;
}
b43_shm_control_word(dev, routing, offset);
b43_write32(dev, B43_MMIO_SHM_DATA, value);
}
void b43_shm_write16(struct b43_wldev *dev, u16 routing, u16 offset, u16 value)
{
if (routing == B43_SHM_SHARED) {
B43_WARN_ON(offset & 0x0001);
if (offset & 0x0003) {
/* Unaligned access */
b43_shm_control_word(dev, routing, offset >> 2);
b43_write16(dev, B43_MMIO_SHM_DATA_UNALIGNED, value);
return;
}
offset >>= 2;
}
b43_shm_control_word(dev, routing, offset);
b43_write16(dev, B43_MMIO_SHM_DATA, value);
}
/* Read HostFlags */
u64 b43_hf_read(struct b43_wldev *dev)
{
u64 ret;
ret = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_HOSTF3);
ret <<= 16;
ret |= b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_HOSTF2);
ret <<= 16;
ret |= b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_HOSTF1);
return ret;
}
/* Write HostFlags */
void b43_hf_write(struct b43_wldev *dev, u64 value)
{
u16 lo, mi, hi;
lo = (value & 0x00000000FFFFULL);
mi = (value & 0x0000FFFF0000ULL) >> 16;
hi = (value & 0xFFFF00000000ULL) >> 32;
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_HOSTF1, lo);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_HOSTF2, mi);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_HOSTF3, hi);
}
/* Read the firmware capabilities bitmask (Opensource firmware only) */
static u16 b43_fwcapa_read(struct b43_wldev *dev)
{
B43_WARN_ON(!dev->fw.opensource);
return b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_FWCAPA);
}
void b43_tsf_read(struct b43_wldev *dev, u64 *tsf)
{
u32 low, high;
B43_WARN_ON(dev->dev->core_rev < 3);
/* The hardware guarantees us an atomic read, if we
* read the low register first. */
low = b43_read32(dev, B43_MMIO_REV3PLUS_TSF_LOW);
high = b43_read32(dev, B43_MMIO_REV3PLUS_TSF_HIGH);
*tsf = high;
*tsf <<= 32;
*tsf |= low;
}
static void b43_time_lock(struct b43_wldev *dev)
{
b43_maskset32(dev, B43_MMIO_MACCTL, ~0, B43_MACCTL_TBTTHOLD);
/* Commit the write */
b43_read32(dev, B43_MMIO_MACCTL);
}
static void b43_time_unlock(struct b43_wldev *dev)
{
b43_maskset32(dev, B43_MMIO_MACCTL, ~B43_MACCTL_TBTTHOLD, 0);
/* Commit the write */
b43_read32(dev, B43_MMIO_MACCTL);
}
static void b43_tsf_write_locked(struct b43_wldev *dev, u64 tsf)
{
u32 low, high;
B43_WARN_ON(dev->dev->core_rev < 3);
low = tsf;
high = (tsf >> 32);
/* The hardware guarantees us an atomic write, if we
* write the low register first. */
b43_write32(dev, B43_MMIO_REV3PLUS_TSF_LOW, low);
mmiowb();
b43_write32(dev, B43_MMIO_REV3PLUS_TSF_HIGH, high);
mmiowb();
}
void b43_tsf_write(struct b43_wldev *dev, u64 tsf)
{
b43_time_lock(dev);
b43_tsf_write_locked(dev, tsf);
b43_time_unlock(dev);
}
static
void b43_macfilter_set(struct b43_wldev *dev, u16 offset, const u8 *mac)
{
static const u8 zero_addr[ETH_ALEN] = { 0 };
u16 data;
if (!mac)
mac = zero_addr;
offset |= 0x0020;
b43_write16(dev, B43_MMIO_MACFILTER_CONTROL, offset);
data = mac[0];
data |= mac[1] << 8;
b43_write16(dev, B43_MMIO_MACFILTER_DATA, data);
data = mac[2];
data |= mac[3] << 8;
b43_write16(dev, B43_MMIO_MACFILTER_DATA, data);
data = mac[4];
data |= mac[5] << 8;
b43_write16(dev, B43_MMIO_MACFILTER_DATA, data);
}
static void b43_write_mac_bssid_templates(struct b43_wldev *dev)
{
const u8 *mac;
const u8 *bssid;
u8 mac_bssid[ETH_ALEN * 2];
int i;
u32 tmp;
bssid = dev->wl->bssid;
mac = dev->wl->mac_addr;
b43_macfilter_set(dev, B43_MACFILTER_BSSID, bssid);
memcpy(mac_bssid, mac, ETH_ALEN);
memcpy(mac_bssid + ETH_ALEN, bssid, ETH_ALEN);
/* Write our MAC address and BSSID to template ram */
for (i = 0; i < ARRAY_SIZE(mac_bssid); i += sizeof(u32)) {
tmp = (u32) (mac_bssid[i + 0]);
tmp |= (u32) (mac_bssid[i + 1]) << 8;
tmp |= (u32) (mac_bssid[i + 2]) << 16;
tmp |= (u32) (mac_bssid[i + 3]) << 24;
b43_ram_write(dev, 0x20 + i, tmp);
}
}
static void b43_upload_card_macaddress(struct b43_wldev *dev)
{
b43_write_mac_bssid_templates(dev);
b43_macfilter_set(dev, B43_MACFILTER_SELF, dev->wl->mac_addr);
}
static void b43_set_slot_time(struct b43_wldev *dev, u16 slot_time)
{
/* slot_time is in usec. */
/* This test used to exit for all but a G PHY. */
if (b43_current_band(dev->wl) == IEEE80211_BAND_5GHZ)
return;
b43_write16(dev, B43_MMIO_IFSSLOT, 510 + slot_time);
/* Shared memory location 0x0010 is the slot time and should be
* set to slot_time; however, this register is initially 0 and changing
* the value adversely affects the transmit rate for BCM4311
* devices. Until this behavior is unterstood, delete this step
*
* b43_shm_write16(dev, B43_SHM_SHARED, 0x0010, slot_time);
*/
}
static void b43_short_slot_timing_enable(struct b43_wldev *dev)
{
b43_set_slot_time(dev, 9);
}
static void b43_short_slot_timing_disable(struct b43_wldev *dev)
{
b43_set_slot_time(dev, 20);
}
/* DummyTransmission function, as documented on
* http://bcm-v4.sipsolutions.net/802.11/DummyTransmission
*/
void b43_dummy_transmission(struct b43_wldev *dev, bool ofdm, bool pa_on)
{
struct b43_phy *phy = &dev->phy;
unsigned int i, max_loop;
u16 value;
u32 buffer[5] = {
0x00000000,
0x00D40000,
0x00000000,
0x01000000,
0x00000000,
};
if (ofdm) {
max_loop = 0x1E;
buffer[0] = 0x000201CC;
} else {
max_loop = 0xFA;
buffer[0] = 0x000B846E;
}
for (i = 0; i < 5; i++)
b43_ram_write(dev, i * 4, buffer[i]);
b43_write16(dev, B43_MMIO_XMTSEL, 0x0000);
if (dev->dev->core_rev < 11)
b43_write16(dev, B43_MMIO_WEPCTL, 0x0000);
else
b43_write16(dev, B43_MMIO_WEPCTL, 0x0100);
value = (ofdm ? 0x41 : 0x40);
b43_write16(dev, B43_MMIO_TXE0_PHYCTL, value);
if (phy->type == B43_PHYTYPE_N || phy->type == B43_PHYTYPE_LP ||
phy->type == B43_PHYTYPE_LCN)
b43_write16(dev, B43_MMIO_TXE0_PHYCTL1, 0x1A02);
b43_write16(dev, B43_MMIO_TXE0_WM_0, 0x0000);
b43_write16(dev, B43_MMIO_TXE0_WM_1, 0x0000);
b43_write16(dev, B43_MMIO_XMTTPLATETXPTR, 0x0000);
b43_write16(dev, B43_MMIO_XMTTXCNT, 0x0014);
b43_write16(dev, B43_MMIO_XMTSEL, 0x0826);
b43_write16(dev, B43_MMIO_TXE0_CTL, 0x0000);
if (!pa_on && phy->type == B43_PHYTYPE_N)
; /*b43_nphy_pa_override(dev, false) */
switch (phy->type) {
case B43_PHYTYPE_N:
case B43_PHYTYPE_LCN:
b43_write16(dev, B43_MMIO_TXE0_AUX, 0x00D0);
break;
case B43_PHYTYPE_LP:
b43_write16(dev, B43_MMIO_TXE0_AUX, 0x0050);
break;
default:
b43_write16(dev, B43_MMIO_TXE0_AUX, 0x0030);
}
b43_read16(dev, B43_MMIO_TXE0_AUX);
if (phy->radio_ver == 0x2050 && phy->radio_rev <= 0x5)
b43_radio_write16(dev, 0x0051, 0x0017);
for (i = 0x00; i < max_loop; i++) {
value = b43_read16(dev, B43_MMIO_TXE0_STATUS);
if (value & 0x0080)
break;
udelay(10);
}
for (i = 0x00; i < 0x0A; i++) {
value = b43_read16(dev, B43_MMIO_TXE0_STATUS);
if (value & 0x0400)
break;
udelay(10);
}
for (i = 0x00; i < 0x19; i++) {
value = b43_read16(dev, B43_MMIO_IFSSTAT);
if (!(value & 0x0100))
break;
udelay(10);
}
if (phy->radio_ver == 0x2050 && phy->radio_rev <= 0x5)
b43_radio_write16(dev, 0x0051, 0x0037);
}
static void key_write(struct b43_wldev *dev,
u8 index, u8 algorithm, const u8 *key)
{
unsigned int i;
u32 offset;
u16 value;
u16 kidx;
/* Key index/algo block */
kidx = b43_kidx_to_fw(dev, index);
value = ((kidx << 4) | algorithm);
b43_shm_write16(dev, B43_SHM_SHARED,
B43_SHM_SH_KEYIDXBLOCK + (kidx * 2), value);
/* Write the key to the Key Table Pointer offset */
offset = dev->ktp + (index * B43_SEC_KEYSIZE);
for (i = 0; i < B43_SEC_KEYSIZE; i += 2) {
value = key[i];
value |= (u16) (key[i + 1]) << 8;
b43_shm_write16(dev, B43_SHM_SHARED, offset + i, value);
}
}
static void keymac_write(struct b43_wldev *dev, u8 index, const u8 *addr)
{
u32 addrtmp[2] = { 0, 0, };
u8 pairwise_keys_start = B43_NR_GROUP_KEYS * 2;
if (b43_new_kidx_api(dev))
pairwise_keys_start = B43_NR_GROUP_KEYS;
B43_WARN_ON(index < pairwise_keys_start);
/* We have four default TX keys and possibly four default RX keys.
* Physical mac 0 is mapped to physical key 4 or 8, depending
* on the firmware version.
* So we must adjust the index here.
*/
index -= pairwise_keys_start;
B43_WARN_ON(index >= B43_NR_PAIRWISE_KEYS);
if (addr) {
addrtmp[0] = addr[0];
addrtmp[0] |= ((u32) (addr[1]) << 8);
addrtmp[0] |= ((u32) (addr[2]) << 16);
addrtmp[0] |= ((u32) (addr[3]) << 24);
addrtmp[1] = addr[4];
addrtmp[1] |= ((u32) (addr[5]) << 8);
}
/* Receive match transmitter address (RCMTA) mechanism */
b43_shm_write32(dev, B43_SHM_RCMTA,
(index * 2) + 0, addrtmp[0]);
b43_shm_write16(dev, B43_SHM_RCMTA,
(index * 2) + 1, addrtmp[1]);
}
/* The ucode will use phase1 key with TEK key to decrypt rx packets.
* When a packet is received, the iv32 is checked.
* - if it doesn't the packet is returned without modification (and software
* decryption can be done). That's what happen when iv16 wrap.
* - if it does, the rc4 key is computed, and decryption is tried.
* Either it will success and B43_RX_MAC_DEC is returned,
* either it fails and B43_RX_MAC_DEC|B43_RX_MAC_DECERR is returned
* and the packet is not usable (it got modified by the ucode).
* So in order to never have B43_RX_MAC_DECERR, we should provide
* a iv32 and phase1key that match. Because we drop packets in case of
* B43_RX_MAC_DECERR, if we have a correct iv32 but a wrong phase1key, all
* packets will be lost without higher layer knowing (ie no resync possible
* until next wrap).
*
* NOTE : this should support 50 key like RCMTA because
* (B43_SHM_SH_KEYIDXBLOCK - B43_SHM_SH_TKIPTSCTTAK)/14 = 50
*/
static void rx_tkip_phase1_write(struct b43_wldev *dev, u8 index, u32 iv32,
u16 *phase1key)
{
unsigned int i;
u32 offset;
u8 pairwise_keys_start = B43_NR_GROUP_KEYS * 2;
if (!modparam_hwtkip)
return;
if (b43_new_kidx_api(dev))
pairwise_keys_start = B43_NR_GROUP_KEYS;
B43_WARN_ON(index < pairwise_keys_start);
/* We have four default TX keys and possibly four default RX keys.
* Physical mac 0 is mapped to physical key 4 or 8, depending
* on the firmware version.
* So we must adjust the index here.
*/
index -= pairwise_keys_start;
B43_WARN_ON(index >= B43_NR_PAIRWISE_KEYS);
if (b43_debug(dev, B43_DBG_KEYS)) {
b43dbg(dev->wl, "rx_tkip_phase1_write : idx 0x%x, iv32 0x%x\n",
index, iv32);
}
/* Write the key to the RX tkip shared mem */
offset = B43_SHM_SH_TKIPTSCTTAK + index * (10 + 4);
for (i = 0; i < 10; i += 2) {
b43_shm_write16(dev, B43_SHM_SHARED, offset + i,
phase1key ? phase1key[i / 2] : 0);
}
b43_shm_write16(dev, B43_SHM_SHARED, offset + i, iv32);
b43_shm_write16(dev, B43_SHM_SHARED, offset + i + 2, iv32 >> 16);
}
static void b43_op_update_tkip_key(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_key_conf *keyconf,
struct ieee80211_sta *sta,
u32 iv32, u16 *phase1key)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
int index = keyconf->hw_key_idx;
if (B43_WARN_ON(!modparam_hwtkip))
return;
/* This is only called from the RX path through mac80211, where
* our mutex is already locked. */
B43_WARN_ON(!mutex_is_locked(&wl->mutex));
dev = wl->current_dev;
B43_WARN_ON(!dev || b43_status(dev) < B43_STAT_INITIALIZED);
keymac_write(dev, index, NULL); /* First zero out mac to avoid race */
rx_tkip_phase1_write(dev, index, iv32, phase1key);
/* only pairwise TKIP keys are supported right now */
if (WARN_ON(!sta))
return;
keymac_write(dev, index, sta->addr);
}
static void do_key_write(struct b43_wldev *dev,
u8 index, u8 algorithm,
const u8 *key, size_t key_len, const u8 *mac_addr)
{
u8 buf[B43_SEC_KEYSIZE] = { 0, };
u8 pairwise_keys_start = B43_NR_GROUP_KEYS * 2;
if (b43_new_kidx_api(dev))
pairwise_keys_start = B43_NR_GROUP_KEYS;
B43_WARN_ON(index >= ARRAY_SIZE(dev->key));
B43_WARN_ON(key_len > B43_SEC_KEYSIZE);
if (index >= pairwise_keys_start)
keymac_write(dev, index, NULL); /* First zero out mac. */
if (algorithm == B43_SEC_ALGO_TKIP) {
/*
* We should provide an initial iv32, phase1key pair.
* We could start with iv32=0 and compute the corresponding
* phase1key, but this means calling ieee80211_get_tkip_key
* with a fake skb (or export other tkip function).
* Because we are lazy we hope iv32 won't start with
* 0xffffffff and let's b43_op_update_tkip_key provide a
* correct pair.
*/
rx_tkip_phase1_write(dev, index, 0xffffffff, (u16*)buf);
} else if (index >= pairwise_keys_start) /* clear it */
rx_tkip_phase1_write(dev, index, 0, NULL);
if (key)
memcpy(buf, key, key_len);
key_write(dev, index, algorithm, buf);
if (index >= pairwise_keys_start)
keymac_write(dev, index, mac_addr);
dev->key[index].algorithm = algorithm;
}
static int b43_key_write(struct b43_wldev *dev,
int index, u8 algorithm,
const u8 *key, size_t key_len,
const u8 *mac_addr,
struct ieee80211_key_conf *keyconf)
{
int i;
int pairwise_keys_start;
/* For ALG_TKIP the key is encoded as a 256-bit (32 byte) data block:
* - Temporal Encryption Key (128 bits)
* - Temporal Authenticator Tx MIC Key (64 bits)
* - Temporal Authenticator Rx MIC Key (64 bits)
*
* Hardware only store TEK
*/
if (algorithm == B43_SEC_ALGO_TKIP && key_len == 32)
key_len = 16;
if (key_len > B43_SEC_KEYSIZE)
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(dev->key); i++) {
/* Check that we don't already have this key. */
B43_WARN_ON(dev->key[i].keyconf == keyconf);
}
if (index < 0) {
/* Pairwise key. Get an empty slot for the key. */
if (b43_new_kidx_api(dev))
pairwise_keys_start = B43_NR_GROUP_KEYS;
else
pairwise_keys_start = B43_NR_GROUP_KEYS * 2;
for (i = pairwise_keys_start;
i < pairwise_keys_start + B43_NR_PAIRWISE_KEYS;
i++) {
B43_WARN_ON(i >= ARRAY_SIZE(dev->key));
if (!dev->key[i].keyconf) {
/* found empty */
index = i;
break;
}
}
if (index < 0) {
b43warn(dev->wl, "Out of hardware key memory\n");
return -ENOSPC;
}
} else
B43_WARN_ON(index > 3);
do_key_write(dev, index, algorithm, key, key_len, mac_addr);
if ((index <= 3) && !b43_new_kidx_api(dev)) {
/* Default RX key */
B43_WARN_ON(mac_addr);
do_key_write(dev, index + 4, algorithm, key, key_len, NULL);
}
keyconf->hw_key_idx = index;
dev->key[index].keyconf = keyconf;
return 0;
}
static int b43_key_clear(struct b43_wldev *dev, int index)
{
if (B43_WARN_ON((index < 0) || (index >= ARRAY_SIZE(dev->key))))
return -EINVAL;
do_key_write(dev, index, B43_SEC_ALGO_NONE,
NULL, B43_SEC_KEYSIZE, NULL);
if ((index <= 3) && !b43_new_kidx_api(dev)) {
do_key_write(dev, index + 4, B43_SEC_ALGO_NONE,
NULL, B43_SEC_KEYSIZE, NULL);
}
dev->key[index].keyconf = NULL;
return 0;
}
static void b43_clear_keys(struct b43_wldev *dev)
{
int i, count;
if (b43_new_kidx_api(dev))
count = B43_NR_GROUP_KEYS + B43_NR_PAIRWISE_KEYS;
else
count = B43_NR_GROUP_KEYS * 2 + B43_NR_PAIRWISE_KEYS;
for (i = 0; i < count; i++)
b43_key_clear(dev, i);
}
static void b43_dump_keymemory(struct b43_wldev *dev)
{
unsigned int i, index, count, offset, pairwise_keys_start;
u8 mac[ETH_ALEN];
u16 algo;
u32 rcmta0;
u16 rcmta1;
u64 hf;
struct b43_key *key;
if (!b43_debug(dev, B43_DBG_KEYS))
return;
hf = b43_hf_read(dev);
b43dbg(dev->wl, "Hardware key memory dump: USEDEFKEYS=%u\n",
!!(hf & B43_HF_USEDEFKEYS));
if (b43_new_kidx_api(dev)) {
pairwise_keys_start = B43_NR_GROUP_KEYS;
count = B43_NR_GROUP_KEYS + B43_NR_PAIRWISE_KEYS;
} else {
pairwise_keys_start = B43_NR_GROUP_KEYS * 2;
count = B43_NR_GROUP_KEYS * 2 + B43_NR_PAIRWISE_KEYS;
}
for (index = 0; index < count; index++) {
key = &(dev->key[index]);
printk(KERN_DEBUG "Key slot %02u: %s",
index, (key->keyconf == NULL) ? " " : "*");
offset = dev->ktp + (index * B43_SEC_KEYSIZE);
for (i = 0; i < B43_SEC_KEYSIZE; i += 2) {
u16 tmp = b43_shm_read16(dev, B43_SHM_SHARED, offset + i);
printk("%02X%02X", (tmp & 0xFF), ((tmp >> 8) & 0xFF));
}
algo = b43_shm_read16(dev, B43_SHM_SHARED,
B43_SHM_SH_KEYIDXBLOCK + (index * 2));
printk(" Algo: %04X/%02X", algo, key->algorithm);
if (index >= pairwise_keys_start) {
if (key->algorithm == B43_SEC_ALGO_TKIP) {
printk(" TKIP: ");
offset = B43_SHM_SH_TKIPTSCTTAK + (index - 4) * (10 + 4);
for (i = 0; i < 14; i += 2) {
u16 tmp = b43_shm_read16(dev, B43_SHM_SHARED, offset + i);
printk("%02X%02X", (tmp & 0xFF), ((tmp >> 8) & 0xFF));
}
}
rcmta0 = b43_shm_read32(dev, B43_SHM_RCMTA,
((index - pairwise_keys_start) * 2) + 0);
rcmta1 = b43_shm_read16(dev, B43_SHM_RCMTA,
((index - pairwise_keys_start) * 2) + 1);
*((__le32 *)(&mac[0])) = cpu_to_le32(rcmta0);
*((__le16 *)(&mac[4])) = cpu_to_le16(rcmta1);
printk(" MAC: %pM", mac);
} else
printk(" DEFAULT KEY");
printk("\n");
}
}
void b43_power_saving_ctl_bits(struct b43_wldev *dev, unsigned int ps_flags)
{
u32 macctl;
u16 ucstat;
bool hwps;
bool awake;
int i;
B43_WARN_ON((ps_flags & B43_PS_ENABLED) &&
(ps_flags & B43_PS_DISABLED));
B43_WARN_ON((ps_flags & B43_PS_AWAKE) && (ps_flags & B43_PS_ASLEEP));
if (ps_flags & B43_PS_ENABLED) {
hwps = true;
} else if (ps_flags & B43_PS_DISABLED) {
hwps = false;
} else {
//TODO: If powersave is not off and FIXME is not set and we are not in adhoc
// and thus is not an AP and we are associated, set bit 25
}
if (ps_flags & B43_PS_AWAKE) {
awake = true;
} else if (ps_flags & B43_PS_ASLEEP) {
awake = false;
} else {
//TODO: If the device is awake or this is an AP, or we are scanning, or FIXME,
// or we are associated, or FIXME, or the latest PS-Poll packet sent was
// successful, set bit26
}
/* FIXME: For now we force awake-on and hwps-off */
hwps = false;
awake = true;
macctl = b43_read32(dev, B43_MMIO_MACCTL);
if (hwps)
macctl |= B43_MACCTL_HWPS;
else
macctl &= ~B43_MACCTL_HWPS;
if (awake)
macctl |= B43_MACCTL_AWAKE;
else
macctl &= ~B43_MACCTL_AWAKE;
b43_write32(dev, B43_MMIO_MACCTL, macctl);
/* Commit write */
b43_read32(dev, B43_MMIO_MACCTL);
if (awake && dev->dev->core_rev >= 5) {
/* Wait for the microcode to wake up. */
for (i = 0; i < 100; i++) {
ucstat = b43_shm_read16(dev, B43_SHM_SHARED,
B43_SHM_SH_UCODESTAT);
if (ucstat != B43_SHM_SH_UCODESTAT_SLEEP)
break;
udelay(10);
}
}
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/BmacCorePllReset */
void b43_wireless_core_phy_pll_reset(struct b43_wldev *dev)
{
struct bcma_drv_cc *bcma_cc __maybe_unused;
struct ssb_chipcommon *ssb_cc __maybe_unused;
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
bcma_cc = &dev->dev->bdev->bus->drv_cc;
bcma_cc_write32(bcma_cc, BCMA_CC_CHIPCTL_ADDR, 0);
bcma_cc_mask32(bcma_cc, BCMA_CC_CHIPCTL_DATA, ~0x4);
bcma_cc_set32(bcma_cc, BCMA_CC_CHIPCTL_DATA, 0x4);
bcma_cc_mask32(bcma_cc, BCMA_CC_CHIPCTL_DATA, ~0x4);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
ssb_cc = &dev->dev->sdev->bus->chipco;
chipco_write32(ssb_cc, SSB_CHIPCO_CHIPCTL_ADDR, 0);
chipco_mask32(ssb_cc, SSB_CHIPCO_CHIPCTL_DATA, ~0x4);
chipco_set32(ssb_cc, SSB_CHIPCO_CHIPCTL_DATA, 0x4);
chipco_mask32(ssb_cc, SSB_CHIPCO_CHIPCTL_DATA, ~0x4);
break;
#endif
}
}
#ifdef CONFIG_B43_BCMA
static void b43_bcma_phy_reset(struct b43_wldev *dev)
{
u32 flags;
/* Put PHY into reset */
flags = bcma_aread32(dev->dev->bdev, BCMA_IOCTL);
flags |= B43_BCMA_IOCTL_PHY_RESET;
flags |= B43_BCMA_IOCTL_PHY_BW_20MHZ; /* Make 20 MHz def */
bcma_awrite32(dev->dev->bdev, BCMA_IOCTL, flags);
udelay(2);
b43_phy_take_out_of_reset(dev);
}
static void b43_bcma_wireless_core_reset(struct b43_wldev *dev, bool gmode)
{
u32 req = B43_BCMA_CLKCTLST_80211_PLL_REQ |
B43_BCMA_CLKCTLST_PHY_PLL_REQ;
u32 status = B43_BCMA_CLKCTLST_80211_PLL_ST |
B43_BCMA_CLKCTLST_PHY_PLL_ST;
u32 flags;
flags = B43_BCMA_IOCTL_PHY_CLKEN;
if (gmode)
flags |= B43_BCMA_IOCTL_GMODE;
b43_device_enable(dev, flags);
bcma_core_set_clockmode(dev->dev->bdev, BCMA_CLKMODE_FAST);
b43_bcma_phy_reset(dev);
bcma_core_pll_ctl(dev->dev->bdev, req, status, true);
}
#endif
#ifdef CONFIG_B43_SSB
static void b43_ssb_wireless_core_reset(struct b43_wldev *dev, bool gmode)
{
u32 flags = 0;
if (gmode)
flags |= B43_TMSLOW_GMODE;
flags |= B43_TMSLOW_PHYCLKEN;
flags |= B43_TMSLOW_PHYRESET;
if (dev->phy.type == B43_PHYTYPE_N)
flags |= B43_TMSLOW_PHY_BANDWIDTH_20MHZ; /* Make 20 MHz def */
b43_device_enable(dev, flags);
msleep(2); /* Wait for the PLL to turn on. */
b43_phy_take_out_of_reset(dev);
}
#endif
void b43_wireless_core_reset(struct b43_wldev *dev, bool gmode)
{
u32 macctl;
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
b43_bcma_wireless_core_reset(dev, gmode);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
b43_ssb_wireless_core_reset(dev, gmode);
break;
#endif
}
/* Turn Analog ON, but only if we already know the PHY-type.
* This protects against very early setup where we don't know the
* PHY-type, yet. wireless_core_reset will be called once again later,
* when we know the PHY-type. */
if (dev->phy.ops)
dev->phy.ops->switch_analog(dev, 1);
macctl = b43_read32(dev, B43_MMIO_MACCTL);
macctl &= ~B43_MACCTL_GMODE;
if (gmode)
macctl |= B43_MACCTL_GMODE;
macctl |= B43_MACCTL_IHR_ENABLED;
b43_write32(dev, B43_MMIO_MACCTL, macctl);
}
static void handle_irq_transmit_status(struct b43_wldev *dev)
{
u32 v0, v1;
u16 tmp;
struct b43_txstatus stat;
while (1) {
v0 = b43_read32(dev, B43_MMIO_XMITSTAT_0);
if (!(v0 & 0x00000001))
break;
v1 = b43_read32(dev, B43_MMIO_XMITSTAT_1);
stat.cookie = (v0 >> 16);
stat.seq = (v1 & 0x0000FFFF);
stat.phy_stat = ((v1 & 0x00FF0000) >> 16);
tmp = (v0 & 0x0000FFFF);
stat.frame_count = ((tmp & 0xF000) >> 12);
stat.rts_count = ((tmp & 0x0F00) >> 8);
stat.supp_reason = ((tmp & 0x001C) >> 2);
stat.pm_indicated = !!(tmp & 0x0080);
stat.intermediate = !!(tmp & 0x0040);
stat.for_ampdu = !!(tmp & 0x0020);
stat.acked = !!(tmp & 0x0002);
b43_handle_txstatus(dev, &stat);
}
}
static void drain_txstatus_queue(struct b43_wldev *dev)
{
u32 dummy;
if (dev->dev->core_rev < 5)
return;
/* Read all entries from the microcode TXstatus FIFO
* and throw them away.
*/
while (1) {
dummy = b43_read32(dev, B43_MMIO_XMITSTAT_0);
if (!(dummy & 0x00000001))
break;
dummy = b43_read32(dev, B43_MMIO_XMITSTAT_1);
}
}
static u32 b43_jssi_read(struct b43_wldev *dev)
{
u32 val = 0;
val = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_JSSI1);
val <<= 16;
val |= b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_JSSI0);
return val;
}
static void b43_jssi_write(struct b43_wldev *dev, u32 jssi)
{
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_JSSI0,
(jssi & 0x0000FFFF));
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_JSSI1,
(jssi & 0xFFFF0000) >> 16);
}
static void b43_generate_noise_sample(struct b43_wldev *dev)
{
b43_jssi_write(dev, 0x7F7F7F7F);
b43_write32(dev, B43_MMIO_MACCMD,
b43_read32(dev, B43_MMIO_MACCMD) | B43_MACCMD_BGNOISE);
}
static void b43_calculate_link_quality(struct b43_wldev *dev)
{
/* Top half of Link Quality calculation. */
if (dev->phy.type != B43_PHYTYPE_G)
return;
if (dev->noisecalc.calculation_running)
return;
dev->noisecalc.calculation_running = true;
dev->noisecalc.nr_samples = 0;
b43_generate_noise_sample(dev);
}
static void handle_irq_noise(struct b43_wldev *dev)
{
struct b43_phy_g *phy = dev->phy.g;
u16 tmp;
u8 noise[4];
u8 i, j;
s32 average;
/* Bottom half of Link Quality calculation. */
if (dev->phy.type != B43_PHYTYPE_G)
return;
/* Possible race condition: It might be possible that the user
* changed to a different channel in the meantime since we
* started the calculation. We ignore that fact, since it's
* not really that much of a problem. The background noise is
* an estimation only anyway. Slightly wrong results will get damped
* by the averaging of the 8 sample rounds. Additionally the
* value is shortlived. So it will be replaced by the next noise
* calculation round soon. */
B43_WARN_ON(!dev->noisecalc.calculation_running);
*((__le32 *)noise) = cpu_to_le32(b43_jssi_read(dev));
if (noise[0] == 0x7F || noise[1] == 0x7F ||
noise[2] == 0x7F || noise[3] == 0x7F)
goto generate_new;
/* Get the noise samples. */
B43_WARN_ON(dev->noisecalc.nr_samples >= 8);
i = dev->noisecalc.nr_samples;
noise[0] = clamp_val(noise[0], 0, ARRAY_SIZE(phy->nrssi_lt) - 1);
noise[1] = clamp_val(noise[1], 0, ARRAY_SIZE(phy->nrssi_lt) - 1);
noise[2] = clamp_val(noise[2], 0, ARRAY_SIZE(phy->nrssi_lt) - 1);
noise[3] = clamp_val(noise[3], 0, ARRAY_SIZE(phy->nrssi_lt) - 1);
dev->noisecalc.samples[i][0] = phy->nrssi_lt[noise[0]];
dev->noisecalc.samples[i][1] = phy->nrssi_lt[noise[1]];
dev->noisecalc.samples[i][2] = phy->nrssi_lt[noise[2]];
dev->noisecalc.samples[i][3] = phy->nrssi_lt[noise[3]];
dev->noisecalc.nr_samples++;
if (dev->noisecalc.nr_samples == 8) {
/* Calculate the Link Quality by the noise samples. */
average = 0;
for (i = 0; i < 8; i++) {
for (j = 0; j < 4; j++)
average += dev->noisecalc.samples[i][j];
}
average /= (8 * 4);
average *= 125;
average += 64;
average /= 128;
tmp = b43_shm_read16(dev, B43_SHM_SHARED, 0x40C);
tmp = (tmp / 128) & 0x1F;
if (tmp >= 8)
average += 2;
else
average -= 25;
if (tmp == 8)
average -= 72;
else
average -= 48;
dev->stats.link_noise = average;
dev->noisecalc.calculation_running = false;
return;
}
generate_new:
b43_generate_noise_sample(dev);
}
static void handle_irq_tbtt_indication(struct b43_wldev *dev)
{
if (b43_is_mode(dev->wl, NL80211_IFTYPE_AP)) {
///TODO: PS TBTT
} else {
if (1 /*FIXME: the last PSpoll frame was sent successfully */ )
b43_power_saving_ctl_bits(dev, 0);
}
if (b43_is_mode(dev->wl, NL80211_IFTYPE_ADHOC))
dev->dfq_valid = true;
}
static void handle_irq_atim_end(struct b43_wldev *dev)
{
if (dev->dfq_valid) {
b43_write32(dev, B43_MMIO_MACCMD,
b43_read32(dev, B43_MMIO_MACCMD)
| B43_MACCMD_DFQ_VALID);
dev->dfq_valid = false;
}
}
static void handle_irq_pmq(struct b43_wldev *dev)
{
u32 tmp;
//TODO: AP mode.
while (1) {
tmp = b43_read32(dev, B43_MMIO_PS_STATUS);
if (!(tmp & 0x00000008))
break;
}
/* 16bit write is odd, but correct. */
b43_write16(dev, B43_MMIO_PS_STATUS, 0x0002);
}
static void b43_write_template_common(struct b43_wldev *dev,
const u8 *data, u16 size,
u16 ram_offset,
u16 shm_size_offset, u8 rate)
{
u32 i, tmp;
struct b43_plcp_hdr4 plcp;
plcp.data = 0;
b43_generate_plcp_hdr(&plcp, size + FCS_LEN, rate);
b43_ram_write(dev, ram_offset, le32_to_cpu(plcp.data));
ram_offset += sizeof(u32);
/* The PLCP is 6 bytes long, but we only wrote 4 bytes, yet.
* So leave the first two bytes of the next write blank.
*/
tmp = (u32) (data[0]) << 16;
tmp |= (u32) (data[1]) << 24;
b43_ram_write(dev, ram_offset, tmp);
ram_offset += sizeof(u32);
for (i = 2; i < size; i += sizeof(u32)) {
tmp = (u32) (data[i + 0]);
if (i + 1 < size)
tmp |= (u32) (data[i + 1]) << 8;
if (i + 2 < size)
tmp |= (u32) (data[i + 2]) << 16;
if (i + 3 < size)
tmp |= (u32) (data[i + 3]) << 24;
b43_ram_write(dev, ram_offset + i - 2, tmp);
}
b43_shm_write16(dev, B43_SHM_SHARED, shm_size_offset,
size + sizeof(struct b43_plcp_hdr6));
}
/* Check if the use of the antenna that ieee80211 told us to
* use is possible. This will fall back to DEFAULT.
* "antenna_nr" is the antenna identifier we got from ieee80211. */
u8 b43_ieee80211_antenna_sanitize(struct b43_wldev *dev,
u8 antenna_nr)
{
u8 antenna_mask;
if (antenna_nr == 0) {
/* Zero means "use default antenna". That's always OK. */
return 0;
}
/* Get the mask of available antennas. */
if (dev->phy.gmode)
antenna_mask = dev->dev->bus_sprom->ant_available_bg;
else
antenna_mask = dev->dev->bus_sprom->ant_available_a;
if (!(antenna_mask & (1 << (antenna_nr - 1)))) {
/* This antenna is not available. Fall back to default. */
return 0;
}
return antenna_nr;
}
/* Convert a b43 antenna number value to the PHY TX control value. */
static u16 b43_antenna_to_phyctl(int antenna)
{
switch (antenna) {
case B43_ANTENNA0:
return B43_TXH_PHY_ANT0;
case B43_ANTENNA1:
return B43_TXH_PHY_ANT1;
case B43_ANTENNA2:
return B43_TXH_PHY_ANT2;
case B43_ANTENNA3:
return B43_TXH_PHY_ANT3;
case B43_ANTENNA_AUTO0:
case B43_ANTENNA_AUTO1:
return B43_TXH_PHY_ANT01AUTO;
}
B43_WARN_ON(1);
return 0;
}
static void b43_write_beacon_template(struct b43_wldev *dev,
u16 ram_offset,
u16 shm_size_offset)
{
unsigned int i, len, variable_len;
const struct ieee80211_mgmt *bcn;
const u8 *ie;
bool tim_found = false;
unsigned int rate;
u16 ctl;
int antenna;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(dev->wl->current_beacon);
bcn = (const struct ieee80211_mgmt *)(dev->wl->current_beacon->data);
len = min_t(size_t, dev->wl->current_beacon->len,
0x200 - sizeof(struct b43_plcp_hdr6));
rate = ieee80211_get_tx_rate(dev->wl->hw, info)->hw_value;
b43_write_template_common(dev, (const u8 *)bcn,
len, ram_offset, shm_size_offset, rate);
/* Write the PHY TX control parameters. */
antenna = B43_ANTENNA_DEFAULT;
antenna = b43_antenna_to_phyctl(antenna);
ctl = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_BEACPHYCTL);
/* We can't send beacons with short preamble. Would get PHY errors. */
ctl &= ~B43_TXH_PHY_SHORTPRMBL;
ctl &= ~B43_TXH_PHY_ANT;
ctl &= ~B43_TXH_PHY_ENC;
ctl |= antenna;
if (b43_is_cck_rate(rate))
ctl |= B43_TXH_PHY_ENC_CCK;
else
ctl |= B43_TXH_PHY_ENC_OFDM;
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_BEACPHYCTL, ctl);
/* Find the position of the TIM and the DTIM_period value
* and write them to SHM. */
ie = bcn->u.beacon.variable;
variable_len = len - offsetof(struct ieee80211_mgmt, u.beacon.variable);
for (i = 0; i < variable_len - 2; ) {
uint8_t ie_id, ie_len;
ie_id = ie[i];
ie_len = ie[i + 1];
if (ie_id == 5) {
u16 tim_position;
u16 dtim_period;
/* This is the TIM Information Element */
/* Check whether the ie_len is in the beacon data range. */
if (variable_len < ie_len + 2 + i)
break;
/* A valid TIM is at least 4 bytes long. */
if (ie_len < 4)
break;
tim_found = true;
tim_position = sizeof(struct b43_plcp_hdr6);
tim_position += offsetof(struct ieee80211_mgmt, u.beacon.variable);
tim_position += i;
dtim_period = ie[i + 3];
b43_shm_write16(dev, B43_SHM_SHARED,
B43_SHM_SH_TIMBPOS, tim_position);
b43_shm_write16(dev, B43_SHM_SHARED,
B43_SHM_SH_DTIMPER, dtim_period);
break;
}
i += ie_len + 2;
}
if (!tim_found) {
/*
* If ucode wants to modify TIM do it behind the beacon, this
* will happen, for example, when doing mesh networking.
*/
b43_shm_write16(dev, B43_SHM_SHARED,
B43_SHM_SH_TIMBPOS,
len + sizeof(struct b43_plcp_hdr6));
b43_shm_write16(dev, B43_SHM_SHARED,
B43_SHM_SH_DTIMPER, 0);
}
b43dbg(dev->wl, "Updated beacon template at 0x%x\n", ram_offset);
}
static void b43_upload_beacon0(struct b43_wldev *dev)
{
struct b43_wl *wl = dev->wl;
if (wl->beacon0_uploaded)
return;
b43_write_beacon_template(dev, B43_SHM_SH_BT_BASE0, B43_SHM_SH_BTL0);
wl->beacon0_uploaded = true;
}
static void b43_upload_beacon1(struct b43_wldev *dev)
{
struct b43_wl *wl = dev->wl;
if (wl->beacon1_uploaded)
return;
b43_write_beacon_template(dev, B43_SHM_SH_BT_BASE1, B43_SHM_SH_BTL1);
wl->beacon1_uploaded = true;
}
static void handle_irq_beacon(struct b43_wldev *dev)
{
struct b43_wl *wl = dev->wl;
u32 cmd, beacon0_valid, beacon1_valid;
if (!b43_is_mode(wl, NL80211_IFTYPE_AP) &&
!b43_is_mode(wl, NL80211_IFTYPE_MESH_POINT) &&
!b43_is_mode(wl, NL80211_IFTYPE_ADHOC))
return;
/* This is the bottom half of the asynchronous beacon update. */
/* Ignore interrupt in the future. */
dev->irq_mask &= ~B43_IRQ_BEACON;
cmd = b43_read32(dev, B43_MMIO_MACCMD);
beacon0_valid = (cmd & B43_MACCMD_BEACON0_VALID);
beacon1_valid = (cmd & B43_MACCMD_BEACON1_VALID);
/* Schedule interrupt manually, if busy. */
if (beacon0_valid && beacon1_valid) {
b43_write32(dev, B43_MMIO_GEN_IRQ_REASON, B43_IRQ_BEACON);
dev->irq_mask |= B43_IRQ_BEACON;
return;
}
if (unlikely(wl->beacon_templates_virgin)) {
/* We never uploaded a beacon before.
* Upload both templates now, but only mark one valid. */
wl->beacon_templates_virgin = false;
b43_upload_beacon0(dev);
b43_upload_beacon1(dev);
cmd = b43_read32(dev, B43_MMIO_MACCMD);
cmd |= B43_MACCMD_BEACON0_VALID;
b43_write32(dev, B43_MMIO_MACCMD, cmd);
} else {
if (!beacon0_valid) {
b43_upload_beacon0(dev);
cmd = b43_read32(dev, B43_MMIO_MACCMD);
cmd |= B43_MACCMD_BEACON0_VALID;
b43_write32(dev, B43_MMIO_MACCMD, cmd);
} else if (!beacon1_valid) {
b43_upload_beacon1(dev);
cmd = b43_read32(dev, B43_MMIO_MACCMD);
cmd |= B43_MACCMD_BEACON1_VALID;
b43_write32(dev, B43_MMIO_MACCMD, cmd);
}
}
}
static void b43_do_beacon_update_trigger_work(struct b43_wldev *dev)
{
u32 old_irq_mask = dev->irq_mask;
/* update beacon right away or defer to irq */
handle_irq_beacon(dev);
if (old_irq_mask != dev->irq_mask) {
/* The handler updated the IRQ mask. */
B43_WARN_ON(!dev->irq_mask);
if (b43_read32(dev, B43_MMIO_GEN_IRQ_MASK)) {
b43_write32(dev, B43_MMIO_GEN_IRQ_MASK, dev->irq_mask);
} else {
/* Device interrupts are currently disabled. That means
* we just ran the hardirq handler and scheduled the
* IRQ thread. The thread will write the IRQ mask when
* it finished, so there's nothing to do here. Writing
* the mask _here_ would incorrectly re-enable IRQs. */
}
}
}
static void b43_beacon_update_trigger_work(struct work_struct *work)
{
struct b43_wl *wl = container_of(work, struct b43_wl,
beacon_update_trigger);
struct b43_wldev *dev;
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (likely(dev && (b43_status(dev) >= B43_STAT_INITIALIZED))) {
if (b43_bus_host_is_sdio(dev->dev)) {
/* wl->mutex is enough. */
b43_do_beacon_update_trigger_work(dev);
mmiowb();
} else {
spin_lock_irq(&wl->hardirq_lock);
b43_do_beacon_update_trigger_work(dev);
mmiowb();
spin_unlock_irq(&wl->hardirq_lock);
}
}
mutex_unlock(&wl->mutex);
}
/* Asynchronously update the packet templates in template RAM.
* Locking: Requires wl->mutex to be locked. */
static void b43_update_templates(struct b43_wl *wl)
{
struct sk_buff *beacon;
/* This is the top half of the ansynchronous beacon update.
* The bottom half is the beacon IRQ.
* Beacon update must be asynchronous to avoid sending an
* invalid beacon. This can happen for example, if the firmware
* transmits a beacon while we are updating it. */
/* We could modify the existing beacon and set the aid bit in
* the TIM field, but that would probably require resizing and
* moving of data within the beacon template.
* Simply request a new beacon and let mac80211 do the hard work. */
beacon = ieee80211_beacon_get(wl->hw, wl->vif);
if (unlikely(!beacon))
return;
if (wl->current_beacon)
dev_kfree_skb_any(wl->current_beacon);
wl->current_beacon = beacon;
wl->beacon0_uploaded = false;
wl->beacon1_uploaded = false;
ieee80211_queue_work(wl->hw, &wl->beacon_update_trigger);
}
static void b43_set_beacon_int(struct b43_wldev *dev, u16 beacon_int)
{
b43_time_lock(dev);
if (dev->dev->core_rev >= 3) {
b43_write32(dev, B43_MMIO_TSF_CFP_REP, (beacon_int << 16));
b43_write32(dev, B43_MMIO_TSF_CFP_START, (beacon_int << 10));
} else {
b43_write16(dev, 0x606, (beacon_int >> 6));
b43_write16(dev, 0x610, beacon_int);
}
b43_time_unlock(dev);
b43dbg(dev->wl, "Set beacon interval to %u\n", beacon_int);
}
static void b43_handle_firmware_panic(struct b43_wldev *dev)
{
u16 reason;
/* Read the register that contains the reason code for the panic. */
reason = b43_shm_read16(dev, B43_SHM_SCRATCH, B43_FWPANIC_REASON_REG);
b43err(dev->wl, "Whoopsy, firmware panic! Reason: %u\n", reason);
switch (reason) {
default:
b43dbg(dev->wl, "The panic reason is unknown.\n");
/* fallthrough */
case B43_FWPANIC_DIE:
/* Do not restart the controller or firmware.
* The device is nonfunctional from now on.
* Restarting would result in this panic to trigger again,
* so we avoid that recursion. */
break;
case B43_FWPANIC_RESTART:
b43_controller_restart(dev, "Microcode panic");
break;
}
}
static void handle_irq_ucode_debug(struct b43_wldev *dev)
{
unsigned int i, cnt;
u16 reason, marker_id, marker_line;
__le16 *buf;
/* The proprietary firmware doesn't have this IRQ. */
if (!dev->fw.opensource)
return;
/* Read the register that contains the reason code for this IRQ. */
reason = b43_shm_read16(dev, B43_SHM_SCRATCH, B43_DEBUGIRQ_REASON_REG);
switch (reason) {
case B43_DEBUGIRQ_PANIC:
b43_handle_firmware_panic(dev);
break;
case B43_DEBUGIRQ_DUMP_SHM:
if (!B43_DEBUG)
break; /* Only with driver debugging enabled. */
buf = kmalloc(4096, GFP_ATOMIC);
if (!buf) {
b43dbg(dev->wl, "SHM-dump: Failed to allocate memory\n");
goto out;
}
for (i = 0; i < 4096; i += 2) {
u16 tmp = b43_shm_read16(dev, B43_SHM_SHARED, i);
buf[i / 2] = cpu_to_le16(tmp);
}
b43info(dev->wl, "Shared memory dump:\n");
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_OFFSET,
16, 2, buf, 4096, 1);
kfree(buf);
break;
case B43_DEBUGIRQ_DUMP_REGS:
if (!B43_DEBUG)
break; /* Only with driver debugging enabled. */
b43info(dev->wl, "Microcode register dump:\n");
for (i = 0, cnt = 0; i < 64; i++) {
u16 tmp = b43_shm_read16(dev, B43_SHM_SCRATCH, i);
if (cnt == 0)
printk(KERN_INFO);
printk("r%02u: 0x%04X ", i, tmp);
cnt++;
if (cnt == 6) {
printk("\n");
cnt = 0;
}
}
printk("\n");
break;
case B43_DEBUGIRQ_MARKER:
if (!B43_DEBUG)
break; /* Only with driver debugging enabled. */
marker_id = b43_shm_read16(dev, B43_SHM_SCRATCH,
B43_MARKER_ID_REG);
marker_line = b43_shm_read16(dev, B43_SHM_SCRATCH,
B43_MARKER_LINE_REG);
b43info(dev->wl, "The firmware just executed the MARKER(%u) "
"at line number %u\n",
marker_id, marker_line);
break;
default:
b43dbg(dev->wl, "Debug-IRQ triggered for unknown reason: %u\n",
reason);
}
out:
/* Acknowledge the debug-IRQ, so the firmware can continue. */
b43_shm_write16(dev, B43_SHM_SCRATCH,
B43_DEBUGIRQ_REASON_REG, B43_DEBUGIRQ_ACK);
}
static void b43_do_interrupt_thread(struct b43_wldev *dev)
{
u32 reason;
u32 dma_reason[ARRAY_SIZE(dev->dma_reason)];
u32 merged_dma_reason = 0;
int i;
if (unlikely(b43_status(dev) != B43_STAT_STARTED))
return;
reason = dev->irq_reason;
for (i = 0; i < ARRAY_SIZE(dma_reason); i++) {
dma_reason[i] = dev->dma_reason[i];
merged_dma_reason |= dma_reason[i];
}
if (unlikely(reason & B43_IRQ_MAC_TXERR))
b43err(dev->wl, "MAC transmission error\n");
if (unlikely(reason & B43_IRQ_PHY_TXERR)) {
b43err(dev->wl, "PHY transmission error\n");
rmb();
if (unlikely(atomic_dec_and_test(&dev->phy.txerr_cnt))) {
atomic_set(&dev->phy.txerr_cnt,
B43_PHY_TX_BADNESS_LIMIT);
b43err(dev->wl, "Too many PHY TX errors, "
"restarting the controller\n");
b43_controller_restart(dev, "PHY TX errors");
}
}
if (unlikely(merged_dma_reason & (B43_DMAIRQ_FATALMASK))) {
b43err(dev->wl,
"Fatal DMA error: 0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X, 0x%08X\n",
dma_reason[0], dma_reason[1],
dma_reason[2], dma_reason[3],
dma_reason[4], dma_reason[5]);
b43err(dev->wl, "This device does not support DMA "
"on your system. It will now be switched to PIO.\n");
/* Fall back to PIO transfers if we get fatal DMA errors! */
dev->use_pio = true;
b43_controller_restart(dev, "DMA error");
return;
}
if (unlikely(reason & B43_IRQ_UCODE_DEBUG))
handle_irq_ucode_debug(dev);
if (reason & B43_IRQ_TBTT_INDI)
handle_irq_tbtt_indication(dev);
if (reason & B43_IRQ_ATIM_END)
handle_irq_atim_end(dev);
if (reason & B43_IRQ_BEACON)
handle_irq_beacon(dev);
if (reason & B43_IRQ_PMQ)
handle_irq_pmq(dev);
if (reason & B43_IRQ_TXFIFO_FLUSH_OK)
;/* TODO */
if (reason & B43_IRQ_NOISESAMPLE_OK)
handle_irq_noise(dev);
/* Check the DMA reason registers for received data. */
if (dma_reason[0] & B43_DMAIRQ_RDESC_UFLOW) {
if (B43_DEBUG)
b43warn(dev->wl, "RX descriptor underrun\n");
b43_dma_handle_rx_overflow(dev->dma.rx_ring);
}
if (dma_reason[0] & B43_DMAIRQ_RX_DONE) {
if (b43_using_pio_transfers(dev))
b43_pio_rx(dev->pio.rx_queue);
else
b43_dma_rx(dev->dma.rx_ring);
}
B43_WARN_ON(dma_reason[1] & B43_DMAIRQ_RX_DONE);
B43_WARN_ON(dma_reason[2] & B43_DMAIRQ_RX_DONE);
B43_WARN_ON(dma_reason[3] & B43_DMAIRQ_RX_DONE);
B43_WARN_ON(dma_reason[4] & B43_DMAIRQ_RX_DONE);
B43_WARN_ON(dma_reason[5] & B43_DMAIRQ_RX_DONE);
if (reason & B43_IRQ_TX_OK)
handle_irq_transmit_status(dev);
/* Re-enable interrupts on the device by restoring the current interrupt mask. */
b43_write32(dev, B43_MMIO_GEN_IRQ_MASK, dev->irq_mask);
#if B43_DEBUG
if (b43_debug(dev, B43_DBG_VERBOSESTATS)) {
dev->irq_count++;
for (i = 0; i < ARRAY_SIZE(dev->irq_bit_count); i++) {
if (reason & (1 << i))
dev->irq_bit_count[i]++;
}
}
#endif
}
/* Interrupt thread handler. Handles device interrupts in thread context. */
static irqreturn_t b43_interrupt_thread_handler(int irq, void *dev_id)
{
struct b43_wldev *dev = dev_id;
mutex_lock(&dev->wl->mutex);
b43_do_interrupt_thread(dev);
mmiowb();
mutex_unlock(&dev->wl->mutex);
return IRQ_HANDLED;
}
static irqreturn_t b43_do_interrupt(struct b43_wldev *dev)
{
u32 reason;
/* This code runs under wl->hardirq_lock, but _only_ on non-SDIO busses.
* On SDIO, this runs under wl->mutex. */
reason = b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
if (reason == 0xffffffff) /* shared IRQ */
return IRQ_NONE;
reason &= dev->irq_mask;
if (!reason)
return IRQ_NONE;
dev->dma_reason[0] = b43_read32(dev, B43_MMIO_DMA0_REASON)
& 0x0001FC00;
dev->dma_reason[1] = b43_read32(dev, B43_MMIO_DMA1_REASON)
& 0x0000DC00;
dev->dma_reason[2] = b43_read32(dev, B43_MMIO_DMA2_REASON)
& 0x0000DC00;
dev->dma_reason[3] = b43_read32(dev, B43_MMIO_DMA3_REASON)
& 0x0001DC00;
dev->dma_reason[4] = b43_read32(dev, B43_MMIO_DMA4_REASON)
& 0x0000DC00;
/* Unused ring
dev->dma_reason[5] = b43_read32(dev, B43_MMIO_DMA5_REASON)
& 0x0000DC00;
*/
/* ACK the interrupt. */
b43_write32(dev, B43_MMIO_GEN_IRQ_REASON, reason);
b43_write32(dev, B43_MMIO_DMA0_REASON, dev->dma_reason[0]);
b43_write32(dev, B43_MMIO_DMA1_REASON, dev->dma_reason[1]);
b43_write32(dev, B43_MMIO_DMA2_REASON, dev->dma_reason[2]);
b43_write32(dev, B43_MMIO_DMA3_REASON, dev->dma_reason[3]);
b43_write32(dev, B43_MMIO_DMA4_REASON, dev->dma_reason[4]);
/* Unused ring
b43_write32(dev, B43_MMIO_DMA5_REASON, dev->dma_reason[5]);
*/
/* Disable IRQs on the device. The IRQ thread handler will re-enable them. */
b43_write32(dev, B43_MMIO_GEN_IRQ_MASK, 0);
/* Save the reason bitmasks for the IRQ thread handler. */
dev->irq_reason = reason;
return IRQ_WAKE_THREAD;
}
/* Interrupt handler top-half. This runs with interrupts disabled. */
static irqreturn_t b43_interrupt_handler(int irq, void *dev_id)
{
struct b43_wldev *dev = dev_id;
irqreturn_t ret;
if (unlikely(b43_status(dev) < B43_STAT_STARTED))
return IRQ_NONE;
spin_lock(&dev->wl->hardirq_lock);
ret = b43_do_interrupt(dev);
mmiowb();
spin_unlock(&dev->wl->hardirq_lock);
return ret;
}
/* SDIO interrupt handler. This runs in process context. */
static void b43_sdio_interrupt_handler(struct b43_wldev *dev)
{
struct b43_wl *wl = dev->wl;
irqreturn_t ret;
mutex_lock(&wl->mutex);
ret = b43_do_interrupt(dev);
if (ret == IRQ_WAKE_THREAD)
b43_do_interrupt_thread(dev);
mutex_unlock(&wl->mutex);
}
void b43_do_release_fw(struct b43_firmware_file *fw)
{
release_firmware(fw->data);
fw->data = NULL;
fw->filename = NULL;
}
static void b43_release_firmware(struct b43_wldev *dev)
{
complete(&dev->fw_load_complete);
b43_do_release_fw(&dev->fw.ucode);
b43_do_release_fw(&dev->fw.pcm);
b43_do_release_fw(&dev->fw.initvals);
b43_do_release_fw(&dev->fw.initvals_band);
}
static void b43_print_fw_helptext(struct b43_wl *wl, bool error)
{
const char text[] =
"You must go to " \
"http://wireless.kernel.org/en/users/Drivers/b43#devicefirmware " \
"and download the correct firmware for this driver version. " \
"Please carefully read all instructions on this website.\n";
if (error)
b43err(wl, text);
else
b43warn(wl, text);
}
static void b43_fw_cb(const struct firmware *firmware, void *context)
{
struct b43_request_fw_context *ctx = context;
ctx->blob = firmware;
complete(&ctx->dev->fw_load_complete);
}
int b43_do_request_fw(struct b43_request_fw_context *ctx,
const char *name,
struct b43_firmware_file *fw, bool async)
{
struct b43_fw_header *hdr;
u32 size;
int err;
if (!name) {
/* Don't fetch anything. Free possibly cached firmware. */
/* FIXME: We should probably keep it anyway, to save some headache
* on suspend/resume with multiband devices. */
b43_do_release_fw(fw);
return 0;
}
if (fw->filename) {
if ((fw->type == ctx->req_type) &&
(strcmp(fw->filename, name) == 0))
return 0; /* Already have this fw. */
/* Free the cached firmware first. */
/* FIXME: We should probably do this later after we successfully
* got the new fw. This could reduce headache with multiband devices.
* We could also redesign this to cache the firmware for all possible
* bands all the time. */
b43_do_release_fw(fw);
}
switch (ctx->req_type) {
case B43_FWTYPE_PROPRIETARY:
snprintf(ctx->fwname, sizeof(ctx->fwname),
"b43%s/%s.fw",
modparam_fwpostfix, name);
break;
case B43_FWTYPE_OPENSOURCE:
snprintf(ctx->fwname, sizeof(ctx->fwname),
"b43-open%s/%s.fw",
modparam_fwpostfix, name);
break;
default:
B43_WARN_ON(1);
return -ENOSYS;
}
if (async) {
/* do this part asynchronously */
init_completion(&ctx->dev->fw_load_complete);
err = request_firmware_nowait(THIS_MODULE, 1, ctx->fwname,
ctx->dev->dev->dev, GFP_KERNEL,
ctx, b43_fw_cb);
if (err < 0) {
pr_err("Unable to load firmware\n");
return err;
}
wait_for_completion(&ctx->dev->fw_load_complete);
if (ctx->blob)
goto fw_ready;
/* On some ARM systems, the async request will fail, but the next sync
* request works. For this reason, we fall through here
*/
}
err = request_firmware(&ctx->blob, ctx->fwname,
ctx->dev->dev->dev);
if (err == -ENOENT) {
snprintf(ctx->errors[ctx->req_type],
sizeof(ctx->errors[ctx->req_type]),
"Firmware file \"%s\" not found\n",
ctx->fwname);
return err;
} else if (err) {
snprintf(ctx->errors[ctx->req_type],
sizeof(ctx->errors[ctx->req_type]),
"Firmware file \"%s\" request failed (err=%d)\n",
ctx->fwname, err);
return err;
}
fw_ready:
if (ctx->blob->size < sizeof(struct b43_fw_header))
goto err_format;
hdr = (struct b43_fw_header *)(ctx->blob->data);
switch (hdr->type) {
case B43_FW_TYPE_UCODE:
case B43_FW_TYPE_PCM:
size = be32_to_cpu(hdr->size);
if (size != ctx->blob->size - sizeof(struct b43_fw_header))
goto err_format;
/* fallthrough */
case B43_FW_TYPE_IV:
if (hdr->ver != 1)
goto err_format;
break;
default:
goto err_format;
}
fw->data = ctx->blob;
fw->filename = name;
fw->type = ctx->req_type;
return 0;
err_format:
snprintf(ctx->errors[ctx->req_type],
sizeof(ctx->errors[ctx->req_type]),
"Firmware file \"%s\" format error.\n", ctx->fwname);
release_firmware(ctx->blob);
return -EPROTO;
}
/* http://bcm-v4.sipsolutions.net/802.11/Init/Firmware */
static int b43_try_request_fw(struct b43_request_fw_context *ctx)
{
struct b43_wldev *dev = ctx->dev;
struct b43_firmware *fw = &ctx->dev->fw;
struct b43_phy *phy = &dev->phy;
const u8 rev = ctx->dev->dev->core_rev;
const char *filename;
int err;
/* Get microcode */
filename = NULL;
switch (rev) {
case 42:
if (phy->type == B43_PHYTYPE_AC)
filename = "ucode42";
break;
case 40:
if (phy->type == B43_PHYTYPE_AC)
filename = "ucode40";
break;
case 33:
if (phy->type == B43_PHYTYPE_LCN40)
filename = "ucode33_lcn40";
break;
case 30:
if (phy->type == B43_PHYTYPE_N)
filename = "ucode30_mimo";
break;
case 29:
if (phy->type == B43_PHYTYPE_HT)
filename = "ucode29_mimo";
break;
case 26:
if (phy->type == B43_PHYTYPE_HT)
filename = "ucode26_mimo";
break;
case 28:
case 25:
if (phy->type == B43_PHYTYPE_N)
filename = "ucode25_mimo";
else if (phy->type == B43_PHYTYPE_LCN)
filename = "ucode25_lcn";
break;
case 24:
if (phy->type == B43_PHYTYPE_LCN)
filename = "ucode24_lcn";
break;
case 23:
if (phy->type == B43_PHYTYPE_N)
filename = "ucode16_mimo";
break;
case 16 ... 19:
if (phy->type == B43_PHYTYPE_N)
filename = "ucode16_mimo";
else if (phy->type == B43_PHYTYPE_LP)
filename = "ucode16_lp";
break;
case 15:
filename = "ucode15";
break;
case 14:
filename = "ucode14";
break;
case 13:
filename = "ucode13";
break;
case 11 ... 12:
filename = "ucode11";
break;
case 5 ... 10:
filename = "ucode5";
break;
}
if (!filename)
goto err_no_ucode;
err = b43_do_request_fw(ctx, filename, &fw->ucode, true);
if (err)
goto err_load;
/* Get PCM code */
if ((rev >= 5) && (rev <= 10))
filename = "pcm5";
else if (rev >= 11)
filename = NULL;
else
goto err_no_pcm;
fw->pcm_request_failed = false;
err = b43_do_request_fw(ctx, filename, &fw->pcm, false);
if (err == -ENOENT) {
/* We did not find a PCM file? Not fatal, but
* core rev <= 10 must do without hwcrypto then. */
fw->pcm_request_failed = true;
} else if (err)
goto err_load;
/* Get initvals */
filename = NULL;
switch (dev->phy.type) {
case B43_PHYTYPE_G:
if (rev == 13)
filename = "b0g0initvals13";
else if (rev >= 5 && rev <= 10)
filename = "b0g0initvals5";
break;
case B43_PHYTYPE_N:
if (rev == 30)
filename = "n16initvals30";
else if (rev == 28 || rev == 25)
filename = "n0initvals25";
else if (rev == 24)
filename = "n0initvals24";
else if (rev == 23)
filename = "n0initvals16"; /* What about n0initvals22? */
else if (rev >= 16 && rev <= 18)
filename = "n0initvals16";
else if (rev >= 11 && rev <= 12)
filename = "n0initvals11";
break;
case B43_PHYTYPE_LP:
if (rev >= 16 && rev <= 18)
filename = "lp0initvals16";
else if (rev == 15)
filename = "lp0initvals15";
else if (rev == 14)
filename = "lp0initvals14";
else if (rev == 13)
filename = "lp0initvals13";
break;
case B43_PHYTYPE_HT:
if (rev == 29)
filename = "ht0initvals29";
else if (rev == 26)
filename = "ht0initvals26";
break;
case B43_PHYTYPE_LCN:
if (rev == 24)
filename = "lcn0initvals24";
break;
case B43_PHYTYPE_LCN40:
if (rev == 33)
filename = "lcn400initvals33";
break;
case B43_PHYTYPE_AC:
if (rev == 42)
filename = "ac1initvals42";
else if (rev == 40)
filename = "ac0initvals40";
break;
}
if (!filename)
goto err_no_initvals;
err = b43_do_request_fw(ctx, filename, &fw->initvals, false);
if (err)
goto err_load;
/* Get bandswitch initvals */
filename = NULL;
switch (dev->phy.type) {
case B43_PHYTYPE_G:
if (rev == 13)
filename = "b0g0bsinitvals13";
else if (rev >= 5 && rev <= 10)
filename = "b0g0bsinitvals5";
break;
case B43_PHYTYPE_N:
if (rev == 30)
filename = "n16bsinitvals30";
else if (rev == 28 || rev == 25)
filename = "n0bsinitvals25";
else if (rev == 24)
filename = "n0bsinitvals24";
else if (rev == 23)
filename = "n0bsinitvals16"; /* What about n0bsinitvals22? */
else if (rev >= 16 && rev <= 18)
filename = "n0bsinitvals16";
else if (rev >= 11 && rev <= 12)
filename = "n0bsinitvals11";
break;
case B43_PHYTYPE_LP:
if (rev >= 16 && rev <= 18)
filename = "lp0bsinitvals16";
else if (rev == 15)
filename = "lp0bsinitvals15";
else if (rev == 14)
filename = "lp0bsinitvals14";
else if (rev == 13)
filename = "lp0bsinitvals13";
break;
case B43_PHYTYPE_HT:
if (rev == 29)
filename = "ht0bsinitvals29";
else if (rev == 26)
filename = "ht0bsinitvals26";
break;
case B43_PHYTYPE_LCN:
if (rev == 24)
filename = "lcn0bsinitvals24";
break;
case B43_PHYTYPE_LCN40:
if (rev == 33)
filename = "lcn400bsinitvals33";
break;
case B43_PHYTYPE_AC:
if (rev == 42)
filename = "ac1bsinitvals42";
else if (rev == 40)
filename = "ac0bsinitvals40";
break;
}
if (!filename)
goto err_no_initvals;
err = b43_do_request_fw(ctx, filename, &fw->initvals_band, false);
if (err)
goto err_load;
fw->opensource = (ctx->req_type == B43_FWTYPE_OPENSOURCE);
return 0;
err_no_ucode:
err = ctx->fatal_failure = -EOPNOTSUPP;
b43err(dev->wl, "The driver does not know which firmware (ucode) "
"is required for your device (wl-core rev %u)\n", rev);
goto error;
err_no_pcm:
err = ctx->fatal_failure = -EOPNOTSUPP;
b43err(dev->wl, "The driver does not know which firmware (PCM) "
"is required for your device (wl-core rev %u)\n", rev);
goto error;
err_no_initvals:
err = ctx->fatal_failure = -EOPNOTSUPP;
b43err(dev->wl, "The driver does not know which firmware (initvals) "
"is required for your device (wl-core rev %u)\n", rev);
goto error;
err_load:
/* We failed to load this firmware image. The error message
* already is in ctx->errors. Return and let our caller decide
* what to do. */
goto error;
error:
b43_release_firmware(dev);
return err;
}
static int b43_one_core_attach(struct b43_bus_dev *dev, struct b43_wl *wl);
static void b43_one_core_detach(struct b43_bus_dev *dev);
static int b43_rng_init(struct b43_wl *wl);
static void b43_request_firmware(struct work_struct *work)
{
struct b43_wl *wl = container_of(work,
struct b43_wl, firmware_load);
struct b43_wldev *dev = wl->current_dev;
struct b43_request_fw_context *ctx;
unsigned int i;
int err;
const char *errmsg;
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return;
ctx->dev = dev;
ctx->req_type = B43_FWTYPE_PROPRIETARY;
err = b43_try_request_fw(ctx);
if (!err)
goto start_ieee80211; /* Successfully loaded it. */
/* Was fw version known? */
if (ctx->fatal_failure)
goto out;
/* proprietary fw not found, try open source */
ctx->req_type = B43_FWTYPE_OPENSOURCE;
err = b43_try_request_fw(ctx);
if (!err)
goto start_ieee80211; /* Successfully loaded it. */
if(ctx->fatal_failure)
goto out;
/* Could not find a usable firmware. Print the errors. */
for (i = 0; i < B43_NR_FWTYPES; i++) {
errmsg = ctx->errors[i];
if (strlen(errmsg))
b43err(dev->wl, "%s", errmsg);
}
b43_print_fw_helptext(dev->wl, 1);
goto out;
start_ieee80211:
wl->hw->queues = B43_QOS_QUEUE_NUM;
if (!modparam_qos || dev->fw.opensource)
wl->hw->queues = 1;
err = ieee80211_register_hw(wl->hw);
if (err)
goto err_one_core_detach;
wl->hw_registred = true;
b43_leds_register(wl->current_dev);
/* Register HW RNG driver */
b43_rng_init(wl);
goto out;
err_one_core_detach:
b43_one_core_detach(dev->dev);
out:
kfree(ctx);
}
static int b43_upload_microcode(struct b43_wldev *dev)
{
struct wiphy *wiphy = dev->wl->hw->wiphy;
const size_t hdr_len = sizeof(struct b43_fw_header);
const __be32 *data;
unsigned int i, len;
u16 fwrev, fwpatch, fwdate, fwtime;
u32 tmp, macctl;
int err = 0;
/* Jump the microcode PSM to offset 0 */
macctl = b43_read32(dev, B43_MMIO_MACCTL);
B43_WARN_ON(macctl & B43_MACCTL_PSM_RUN);
macctl |= B43_MACCTL_PSM_JMP0;
b43_write32(dev, B43_MMIO_MACCTL, macctl);
/* Zero out all microcode PSM registers and shared memory. */
for (i = 0; i < 64; i++)
b43_shm_write16(dev, B43_SHM_SCRATCH, i, 0);
for (i = 0; i < 4096; i += 2)
b43_shm_write16(dev, B43_SHM_SHARED, i, 0);
/* Upload Microcode. */
data = (__be32 *) (dev->fw.ucode.data->data + hdr_len);
len = (dev->fw.ucode.data->size - hdr_len) / sizeof(__be32);
b43_shm_control_word(dev, B43_SHM_UCODE | B43_SHM_AUTOINC_W, 0x0000);
for (i = 0; i < len; i++) {
b43_write32(dev, B43_MMIO_SHM_DATA, be32_to_cpu(data[i]));
udelay(10);
}
if (dev->fw.pcm.data) {
/* Upload PCM data. */
data = (__be32 *) (dev->fw.pcm.data->data + hdr_len);
len = (dev->fw.pcm.data->size - hdr_len) / sizeof(__be32);
b43_shm_control_word(dev, B43_SHM_HW, 0x01EA);
b43_write32(dev, B43_MMIO_SHM_DATA, 0x00004000);
/* No need for autoinc bit in SHM_HW */
b43_shm_control_word(dev, B43_SHM_HW, 0x01EB);
for (i = 0; i < len; i++) {
b43_write32(dev, B43_MMIO_SHM_DATA, be32_to_cpu(data[i]));
udelay(10);
}
}
b43_write32(dev, B43_MMIO_GEN_IRQ_REASON, B43_IRQ_ALL);
/* Start the microcode PSM */
b43_maskset32(dev, B43_MMIO_MACCTL, ~B43_MACCTL_PSM_JMP0,
B43_MACCTL_PSM_RUN);
/* Wait for the microcode to load and respond */
i = 0;
while (1) {
tmp = b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
if (tmp == B43_IRQ_MAC_SUSPENDED)
break;
i++;
if (i >= 20) {
b43err(dev->wl, "Microcode not responding\n");
b43_print_fw_helptext(dev->wl, 1);
err = -ENODEV;
goto error;
}
msleep(50);
}
b43_read32(dev, B43_MMIO_GEN_IRQ_REASON); /* dummy read */
/* Get and check the revisions. */
fwrev = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_UCODEREV);
fwpatch = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_UCODEPATCH);
fwdate = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_UCODEDATE);
fwtime = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_UCODETIME);
if (fwrev <= 0x128) {
b43err(dev->wl, "YOUR FIRMWARE IS TOO OLD. Firmware from "
"binary drivers older than version 4.x is unsupported. "
"You must upgrade your firmware files.\n");
b43_print_fw_helptext(dev->wl, 1);
err = -EOPNOTSUPP;
goto error;
}
dev->fw.rev = fwrev;
dev->fw.patch = fwpatch;
if (dev->fw.rev >= 598)
dev->fw.hdr_format = B43_FW_HDR_598;
else if (dev->fw.rev >= 410)
dev->fw.hdr_format = B43_FW_HDR_410;
else
dev->fw.hdr_format = B43_FW_HDR_351;
WARN_ON(dev->fw.opensource != (fwdate == 0xFFFF));
dev->qos_enabled = dev->wl->hw->queues > 1;
/* Default to firmware/hardware crypto acceleration. */
dev->hwcrypto_enabled = true;
if (dev->fw.opensource) {
u16 fwcapa;
/* Patchlevel info is encoded in the "time" field. */
dev->fw.patch = fwtime;
b43info(dev->wl, "Loading OpenSource firmware version %u.%u\n",
dev->fw.rev, dev->fw.patch);
fwcapa = b43_fwcapa_read(dev);
if (!(fwcapa & B43_FWCAPA_HWCRYPTO) || dev->fw.pcm_request_failed) {
b43info(dev->wl, "Hardware crypto acceleration not supported by firmware\n");
/* Disable hardware crypto and fall back to software crypto. */
dev->hwcrypto_enabled = false;
}
/* adding QoS support should use an offline discovery mechanism */
WARN(fwcapa & B43_FWCAPA_QOS, "QoS in OpenFW not supported\n");
} else {
b43info(dev->wl, "Loading firmware version %u.%u "
"(20%.2i-%.2i-%.2i %.2i:%.2i:%.2i)\n",
fwrev, fwpatch,
(fwdate >> 12) & 0xF, (fwdate >> 8) & 0xF, fwdate & 0xFF,
(fwtime >> 11) & 0x1F, (fwtime >> 5) & 0x3F, fwtime & 0x1F);
if (dev->fw.pcm_request_failed) {
b43warn(dev->wl, "No \"pcm5.fw\" firmware file found. "
"Hardware accelerated cryptography is disabled.\n");
b43_print_fw_helptext(dev->wl, 0);
}
}
snprintf(wiphy->fw_version, sizeof(wiphy->fw_version), "%u.%u",
dev->fw.rev, dev->fw.patch);
wiphy->hw_version = dev->dev->core_id;
if (dev->fw.hdr_format == B43_FW_HDR_351) {
/* We're over the deadline, but we keep support for old fw
* until it turns out to be in major conflict with something new. */
b43warn(dev->wl, "You are using an old firmware image. "
"Support for old firmware will be removed soon "
"(official deadline was July 2008).\n");
b43_print_fw_helptext(dev->wl, 0);
}
return 0;
error:
/* Stop the microcode PSM. */
b43_maskset32(dev, B43_MMIO_MACCTL, ~B43_MACCTL_PSM_RUN,
B43_MACCTL_PSM_JMP0);
return err;
}
static int b43_write_initvals(struct b43_wldev *dev,
const struct b43_iv *ivals,
size_t count,
size_t array_size)
{
const struct b43_iv *iv;
u16 offset;
size_t i;
bool bit32;
BUILD_BUG_ON(sizeof(struct b43_iv) != 6);
iv = ivals;
for (i = 0; i < count; i++) {
if (array_size < sizeof(iv->offset_size))
goto err_format;
array_size -= sizeof(iv->offset_size);
offset = be16_to_cpu(iv->offset_size);
bit32 = !!(offset & B43_IV_32BIT);
offset &= B43_IV_OFFSET_MASK;
if (offset >= 0x1000)
goto err_format;
if (bit32) {
u32 value;
if (array_size < sizeof(iv->data.d32))
goto err_format;
array_size -= sizeof(iv->data.d32);
value = get_unaligned_be32(&iv->data.d32);
b43_write32(dev, offset, value);
iv = (const struct b43_iv *)((const uint8_t *)iv +
sizeof(__be16) +
sizeof(__be32));
} else {
u16 value;
if (array_size < sizeof(iv->data.d16))
goto err_format;
array_size -= sizeof(iv->data.d16);
value = be16_to_cpu(iv->data.d16);
b43_write16(dev, offset, value);
iv = (const struct b43_iv *)((const uint8_t *)iv +
sizeof(__be16) +
sizeof(__be16));
}
}
if (array_size)
goto err_format;
return 0;
err_format:
b43err(dev->wl, "Initial Values Firmware file-format error.\n");
b43_print_fw_helptext(dev->wl, 1);
return -EPROTO;
}
static int b43_upload_initvals(struct b43_wldev *dev)
{
const size_t hdr_len = sizeof(struct b43_fw_header);
const struct b43_fw_header *hdr;
struct b43_firmware *fw = &dev->fw;
const struct b43_iv *ivals;
size_t count;
hdr = (const struct b43_fw_header *)(fw->initvals.data->data);
ivals = (const struct b43_iv *)(fw->initvals.data->data + hdr_len);
count = be32_to_cpu(hdr->size);
return b43_write_initvals(dev, ivals, count,
fw->initvals.data->size - hdr_len);
}
static int b43_upload_initvals_band(struct b43_wldev *dev)
{
const size_t hdr_len = sizeof(struct b43_fw_header);
const struct b43_fw_header *hdr;
struct b43_firmware *fw = &dev->fw;
const struct b43_iv *ivals;
size_t count;
if (!fw->initvals_band.data)
return 0;
hdr = (const struct b43_fw_header *)(fw->initvals_band.data->data);
ivals = (const struct b43_iv *)(fw->initvals_band.data->data + hdr_len);
count = be32_to_cpu(hdr->size);
return b43_write_initvals(dev, ivals, count,
fw->initvals_band.data->size - hdr_len);
}
/* Initialize the GPIOs
* http://bcm-specs.sipsolutions.net/GPIO
*/
#ifdef CONFIG_B43_SSB
static struct ssb_device *b43_ssb_gpio_dev(struct b43_wldev *dev)
{
struct ssb_bus *bus = dev->dev->sdev->bus;
#ifdef CONFIG_SSB_DRIVER_PCICORE
return (bus->chipco.dev ? bus->chipco.dev : bus->pcicore.dev);
#else
return bus->chipco.dev;
#endif
}
#endif
static int b43_gpio_init(struct b43_wldev *dev)
{
#ifdef CONFIG_B43_SSB
struct ssb_device *gpiodev;
#endif
u32 mask, set;
b43_maskset32(dev, B43_MMIO_MACCTL, ~B43_MACCTL_GPOUTSMSK, 0);
b43_maskset16(dev, B43_MMIO_GPIO_MASK, ~0, 0xF);
mask = 0x0000001F;
set = 0x0000000F;
if (dev->dev->chip_id == 0x4301) {
mask |= 0x0060;
set |= 0x0060;
} else if (dev->dev->chip_id == 0x5354) {
/* Don't allow overtaking buttons GPIOs */
set &= 0x2; /* 0x2 is LED GPIO on BCM5354 */
}
if (0 /* FIXME: conditional unknown */ ) {
b43_write16(dev, B43_MMIO_GPIO_MASK,
b43_read16(dev, B43_MMIO_GPIO_MASK)
| 0x0100);
/* BT Coexistance Input */
mask |= 0x0080;
set |= 0x0080;
/* BT Coexistance Out */
mask |= 0x0100;
set |= 0x0100;
}
if (dev->dev->bus_sprom->boardflags_lo & B43_BFL_PACTRL) {
/* PA is controlled by gpio 9, let ucode handle it */
b43_write16(dev, B43_MMIO_GPIO_MASK,
b43_read16(dev, B43_MMIO_GPIO_MASK)
| 0x0200);
mask |= 0x0200;
set |= 0x0200;
}
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
bcma_chipco_gpio_control(&dev->dev->bdev->bus->drv_cc, mask, set);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
gpiodev = b43_ssb_gpio_dev(dev);
if (gpiodev)
ssb_write32(gpiodev, B43_GPIO_CONTROL,
(ssb_read32(gpiodev, B43_GPIO_CONTROL)
& ~mask) | set);
break;
#endif
}
return 0;
}
/* Turn off all GPIO stuff. Call this on module unload, for example. */
static void b43_gpio_cleanup(struct b43_wldev *dev)
{
#ifdef CONFIG_B43_SSB
struct ssb_device *gpiodev;
#endif
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
bcma_chipco_gpio_control(&dev->dev->bdev->bus->drv_cc, ~0, 0);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
gpiodev = b43_ssb_gpio_dev(dev);
if (gpiodev)
ssb_write32(gpiodev, B43_GPIO_CONTROL, 0);
break;
#endif
}
}
/* http://bcm-specs.sipsolutions.net/EnableMac */
void b43_mac_enable(struct b43_wldev *dev)
{
if (b43_debug(dev, B43_DBG_FIRMWARE)) {
u16 fwstate;
fwstate = b43_shm_read16(dev, B43_SHM_SHARED,
B43_SHM_SH_UCODESTAT);
if ((fwstate != B43_SHM_SH_UCODESTAT_SUSP) &&
(fwstate != B43_SHM_SH_UCODESTAT_SLEEP)) {
b43err(dev->wl, "b43_mac_enable(): The firmware "
"should be suspended, but current state is %u\n",
fwstate);
}
}
dev->mac_suspended--;
B43_WARN_ON(dev->mac_suspended < 0);
if (dev->mac_suspended == 0) {
b43_maskset32(dev, B43_MMIO_MACCTL, ~0, B43_MACCTL_ENABLED);
b43_write32(dev, B43_MMIO_GEN_IRQ_REASON,
B43_IRQ_MAC_SUSPENDED);
/* Commit writes */
b43_read32(dev, B43_MMIO_MACCTL);
b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
b43_power_saving_ctl_bits(dev, 0);
}
}
/* http://bcm-specs.sipsolutions.net/SuspendMAC */
void b43_mac_suspend(struct b43_wldev *dev)
{
int i;
u32 tmp;
might_sleep();
B43_WARN_ON(dev->mac_suspended < 0);
if (dev->mac_suspended == 0) {
b43_power_saving_ctl_bits(dev, B43_PS_AWAKE);
b43_maskset32(dev, B43_MMIO_MACCTL, ~B43_MACCTL_ENABLED, 0);
/* force pci to flush the write */
b43_read32(dev, B43_MMIO_MACCTL);
for (i = 35; i; i--) {
tmp = b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
if (tmp & B43_IRQ_MAC_SUSPENDED)
goto out;
udelay(10);
}
/* Hm, it seems this will take some time. Use msleep(). */
for (i = 40; i; i--) {
tmp = b43_read32(dev, B43_MMIO_GEN_IRQ_REASON);
if (tmp & B43_IRQ_MAC_SUSPENDED)
goto out;
msleep(1);
}
b43err(dev->wl, "MAC suspend failed\n");
}
out:
dev->mac_suspended++;
}
/* http://bcm-v4.sipsolutions.net/802.11/PHY/N/MacPhyClkSet */
void b43_mac_phy_clock_set(struct b43_wldev *dev, bool on)
{
u32 tmp;
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
tmp = bcma_aread32(dev->dev->bdev, BCMA_IOCTL);
if (on)
tmp |= B43_BCMA_IOCTL_MACPHYCLKEN;
else
tmp &= ~B43_BCMA_IOCTL_MACPHYCLKEN;
bcma_awrite32(dev->dev->bdev, BCMA_IOCTL, tmp);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
tmp = ssb_read32(dev->dev->sdev, SSB_TMSLOW);
if (on)
tmp |= B43_TMSLOW_MACPHYCLKEN;
else
tmp &= ~B43_TMSLOW_MACPHYCLKEN;
ssb_write32(dev->dev->sdev, SSB_TMSLOW, tmp);
break;
#endif
}
}
/* brcms_b_switch_macfreq */
void b43_mac_switch_freq(struct b43_wldev *dev, u8 spurmode)
{
u16 chip_id = dev->dev->chip_id;
if (chip_id == BCMA_CHIP_ID_BCM4331) {
switch (spurmode) {
case 2: /* 168 Mhz: 2^26/168 = 0x61862 */
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_LOW, 0x1862);
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_HIGH, 0x6);
break;
case 1: /* 164 Mhz: 2^26/164 = 0x63e70 */
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_LOW, 0x3e70);
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_HIGH, 0x6);
break;
default: /* 160 Mhz: 2^26/160 = 0x66666 */
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_LOW, 0x6666);
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_HIGH, 0x6);
break;
}
} else if (chip_id == BCMA_CHIP_ID_BCM43131 ||
chip_id == BCMA_CHIP_ID_BCM43217 ||
chip_id == BCMA_CHIP_ID_BCM43222 ||
chip_id == BCMA_CHIP_ID_BCM43224 ||
chip_id == BCMA_CHIP_ID_BCM43225 ||
chip_id == BCMA_CHIP_ID_BCM43227 ||
chip_id == BCMA_CHIP_ID_BCM43228) {
switch (spurmode) {
case 2: /* 126 Mhz */
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_LOW, 0x2082);
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_HIGH, 0x8);
break;
case 1: /* 123 Mhz */
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_LOW, 0x5341);
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_HIGH, 0x8);
break;
default: /* 120 Mhz */
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_LOW, 0x8889);
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_HIGH, 0x8);
break;
}
} else if (dev->phy.type == B43_PHYTYPE_LCN) {
switch (spurmode) {
case 1: /* 82 Mhz */
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_LOW, 0x7CE0);
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_HIGH, 0xC);
break;
default: /* 80 Mhz */
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_LOW, 0xCCCD);
b43_write16(dev, B43_MMIO_TSF_CLK_FRAC_HIGH, 0xC);
break;
}
}
}
static void b43_adjust_opmode(struct b43_wldev *dev)
{
struct b43_wl *wl = dev->wl;
u32 ctl;
u16 cfp_pretbtt;
ctl = b43_read32(dev, B43_MMIO_MACCTL);
/* Reset status to STA infrastructure mode. */
ctl &= ~B43_MACCTL_AP;
ctl &= ~B43_MACCTL_KEEP_CTL;
ctl &= ~B43_MACCTL_KEEP_BADPLCP;
ctl &= ~B43_MACCTL_KEEP_BAD;
ctl &= ~B43_MACCTL_PROMISC;
ctl &= ~B43_MACCTL_BEACPROMISC;
ctl |= B43_MACCTL_INFRA;
if (b43_is_mode(wl, NL80211_IFTYPE_AP) ||
b43_is_mode(wl, NL80211_IFTYPE_MESH_POINT))
ctl |= B43_MACCTL_AP;
else if (b43_is_mode(wl, NL80211_IFTYPE_ADHOC))
ctl &= ~B43_MACCTL_INFRA;
if (wl->filter_flags & FIF_CONTROL)
ctl |= B43_MACCTL_KEEP_CTL;
if (wl->filter_flags & FIF_FCSFAIL)
ctl |= B43_MACCTL_KEEP_BAD;
if (wl->filter_flags & FIF_PLCPFAIL)
ctl |= B43_MACCTL_KEEP_BADPLCP;
if (wl->filter_flags & FIF_PROMISC_IN_BSS)
ctl |= B43_MACCTL_PROMISC;
if (wl->filter_flags & FIF_BCN_PRBRESP_PROMISC)
ctl |= B43_MACCTL_BEACPROMISC;
/* Workaround: On old hardware the HW-MAC-address-filter
* doesn't work properly, so always run promisc in filter
* it in software. */
if (dev->dev->core_rev <= 4)
ctl |= B43_MACCTL_PROMISC;
b43_write32(dev, B43_MMIO_MACCTL, ctl);
cfp_pretbtt = 2;
if ((ctl & B43_MACCTL_INFRA) && !(ctl & B43_MACCTL_AP)) {
if (dev->dev->chip_id == 0x4306 &&
dev->dev->chip_rev == 3)
cfp_pretbtt = 100;
else
cfp_pretbtt = 50;
}
b43_write16(dev, 0x612, cfp_pretbtt);
/* FIXME: We don't currently implement the PMQ mechanism,
* so always disable it. If we want to implement PMQ,
* we need to enable it here (clear DISCPMQ) in AP mode.
*/
if (0 /* ctl & B43_MACCTL_AP */)
b43_maskset32(dev, B43_MMIO_MACCTL, ~B43_MACCTL_DISCPMQ, 0);
else
b43_maskset32(dev, B43_MMIO_MACCTL, ~0, B43_MACCTL_DISCPMQ);
}
static void b43_rate_memory_write(struct b43_wldev *dev, u16 rate, int is_ofdm)
{
u16 offset;
if (is_ofdm) {
offset = 0x480;
offset += (b43_plcp_get_ratecode_ofdm(rate) & 0x000F) * 2;
} else {
offset = 0x4C0;
offset += (b43_plcp_get_ratecode_cck(rate) & 0x000F) * 2;
}
b43_shm_write16(dev, B43_SHM_SHARED, offset + 0x20,
b43_shm_read16(dev, B43_SHM_SHARED, offset));
}
static void b43_rate_memory_init(struct b43_wldev *dev)
{
switch (dev->phy.type) {
case B43_PHYTYPE_A:
case B43_PHYTYPE_G:
case B43_PHYTYPE_N:
case B43_PHYTYPE_LP:
case B43_PHYTYPE_HT:
case B43_PHYTYPE_LCN:
b43_rate_memory_write(dev, B43_OFDM_RATE_6MB, 1);
b43_rate_memory_write(dev, B43_OFDM_RATE_9MB, 1);
b43_rate_memory_write(dev, B43_OFDM_RATE_12MB, 1);
b43_rate_memory_write(dev, B43_OFDM_RATE_18MB, 1);
b43_rate_memory_write(dev, B43_OFDM_RATE_24MB, 1);
b43_rate_memory_write(dev, B43_OFDM_RATE_36MB, 1);
b43_rate_memory_write(dev, B43_OFDM_RATE_48MB, 1);
b43_rate_memory_write(dev, B43_OFDM_RATE_54MB, 1);
if (dev->phy.type == B43_PHYTYPE_A)
break;
/* fallthrough */
case B43_PHYTYPE_B:
b43_rate_memory_write(dev, B43_CCK_RATE_1MB, 0);
b43_rate_memory_write(dev, B43_CCK_RATE_2MB, 0);
b43_rate_memory_write(dev, B43_CCK_RATE_5MB, 0);
b43_rate_memory_write(dev, B43_CCK_RATE_11MB, 0);
break;
default:
B43_WARN_ON(1);
}
}
/* Set the default values for the PHY TX Control Words. */
static void b43_set_phytxctl_defaults(struct b43_wldev *dev)
{
u16 ctl = 0;
ctl |= B43_TXH_PHY_ENC_CCK;
ctl |= B43_TXH_PHY_ANT01AUTO;
ctl |= B43_TXH_PHY_TXPWR;
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_BEACPHYCTL, ctl);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_ACKCTSPHYCTL, ctl);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_PRPHYCTL, ctl);
}
/* Set the TX-Antenna for management frames sent by firmware. */
static void b43_mgmtframe_txantenna(struct b43_wldev *dev, int antenna)
{
u16 ant;
u16 tmp;
ant = b43_antenna_to_phyctl(antenna);
/* For ACK/CTS */
tmp = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_ACKCTSPHYCTL);
tmp = (tmp & ~B43_TXH_PHY_ANT) | ant;
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_ACKCTSPHYCTL, tmp);
/* For Probe Resposes */
tmp = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_PRPHYCTL);
tmp = (tmp & ~B43_TXH_PHY_ANT) | ant;
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_PRPHYCTL, tmp);
}
/* This is the opposite of b43_chip_init() */
static void b43_chip_exit(struct b43_wldev *dev)
{
b43_phy_exit(dev);
b43_gpio_cleanup(dev);
/* firmware is released later */
}
/* Initialize the chip
* http://bcm-specs.sipsolutions.net/ChipInit
*/
static int b43_chip_init(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
int err;
u32 macctl;
u16 value16;
/* Initialize the MAC control */
macctl = B43_MACCTL_IHR_ENABLED | B43_MACCTL_SHM_ENABLED;
if (dev->phy.gmode)
macctl |= B43_MACCTL_GMODE;
macctl |= B43_MACCTL_INFRA;
b43_write32(dev, B43_MMIO_MACCTL, macctl);
err = b43_upload_microcode(dev);
if (err)
goto out; /* firmware is released later */
err = b43_gpio_init(dev);
if (err)
goto out; /* firmware is released later */
err = b43_upload_initvals(dev);
if (err)
goto err_gpio_clean;
err = b43_upload_initvals_band(dev);
if (err)
goto err_gpio_clean;
/* Turn the Analog on and initialize the PHY. */
phy->ops->switch_analog(dev, 1);
err = b43_phy_init(dev);
if (err)
goto err_gpio_clean;
/* Disable Interference Mitigation. */
if (phy->ops->interf_mitigation)
phy->ops->interf_mitigation(dev, B43_INTERFMODE_NONE);
/* Select the antennae */
if (phy->ops->set_rx_antenna)
phy->ops->set_rx_antenna(dev, B43_ANTENNA_DEFAULT);
b43_mgmtframe_txantenna(dev, B43_ANTENNA_DEFAULT);
if (phy->type == B43_PHYTYPE_B) {
value16 = b43_read16(dev, 0x005E);
value16 |= 0x0004;
b43_write16(dev, 0x005E, value16);
}
b43_write32(dev, 0x0100, 0x01000000);
if (dev->dev->core_rev < 5)
b43_write32(dev, 0x010C, 0x01000000);
b43_maskset32(dev, B43_MMIO_MACCTL, ~B43_MACCTL_INFRA, 0);
b43_maskset32(dev, B43_MMIO_MACCTL, ~0, B43_MACCTL_INFRA);
/* Probe Response Timeout value */
/* FIXME: Default to 0, has to be set by ioctl probably... :-/ */
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_PRMAXTIME, 0);
/* Initially set the wireless operation mode. */
b43_adjust_opmode(dev);
if (dev->dev->core_rev < 3) {
b43_write16(dev, 0x060E, 0x0000);
b43_write16(dev, 0x0610, 0x8000);
b43_write16(dev, 0x0604, 0x0000);
b43_write16(dev, 0x0606, 0x0200);
} else {
b43_write32(dev, 0x0188, 0x80000000);
b43_write32(dev, 0x018C, 0x02000000);
}
b43_write32(dev, B43_MMIO_GEN_IRQ_REASON, 0x00004000);
b43_write32(dev, B43_MMIO_DMA0_IRQ_MASK, 0x0001FC00);
b43_write32(dev, B43_MMIO_DMA1_IRQ_MASK, 0x0000DC00);
b43_write32(dev, B43_MMIO_DMA2_IRQ_MASK, 0x0000DC00);
b43_write32(dev, B43_MMIO_DMA3_IRQ_MASK, 0x0001DC00);
b43_write32(dev, B43_MMIO_DMA4_IRQ_MASK, 0x0000DC00);
b43_write32(dev, B43_MMIO_DMA5_IRQ_MASK, 0x0000DC00);
b43_mac_phy_clock_set(dev, true);
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
/* FIXME: 0xE74 is quite common, but should be read from CC */
b43_write16(dev, B43_MMIO_POWERUP_DELAY, 0xE74);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
b43_write16(dev, B43_MMIO_POWERUP_DELAY,
dev->dev->sdev->bus->chipco.fast_pwrup_delay);
break;
#endif
}
err = 0;
b43dbg(dev->wl, "Chip initialized\n");
out:
return err;
err_gpio_clean:
b43_gpio_cleanup(dev);
return err;
}
static void b43_periodic_every60sec(struct b43_wldev *dev)
{
const struct b43_phy_operations *ops = dev->phy.ops;
if (ops->pwork_60sec)
ops->pwork_60sec(dev);
/* Force check the TX power emission now. */
b43_phy_txpower_check(dev, B43_TXPWR_IGNORE_TIME);
}
static void b43_periodic_every30sec(struct b43_wldev *dev)
{
/* Update device statistics. */
b43_calculate_link_quality(dev);
}
static void b43_periodic_every15sec(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
u16 wdr;
if (dev->fw.opensource) {
/* Check if the firmware is still alive.
* It will reset the watchdog counter to 0 in its idle loop. */
wdr = b43_shm_read16(dev, B43_SHM_SCRATCH, B43_WATCHDOG_REG);
if (unlikely(wdr)) {
b43err(dev->wl, "Firmware watchdog: The firmware died!\n");
b43_controller_restart(dev, "Firmware watchdog");
return;
} else {
b43_shm_write16(dev, B43_SHM_SCRATCH,
B43_WATCHDOG_REG, 1);
}
}
if (phy->ops->pwork_15sec)
phy->ops->pwork_15sec(dev);
atomic_set(&phy->txerr_cnt, B43_PHY_TX_BADNESS_LIMIT);
wmb();
#if B43_DEBUG
if (b43_debug(dev, B43_DBG_VERBOSESTATS)) {
unsigned int i;
b43dbg(dev->wl, "Stats: %7u IRQs/sec, %7u TX/sec, %7u RX/sec\n",
dev->irq_count / 15,
dev->tx_count / 15,
dev->rx_count / 15);
dev->irq_count = 0;
dev->tx_count = 0;
dev->rx_count = 0;
for (i = 0; i < ARRAY_SIZE(dev->irq_bit_count); i++) {
if (dev->irq_bit_count[i]) {
b43dbg(dev->wl, "Stats: %7u IRQ-%02u/sec (0x%08X)\n",
dev->irq_bit_count[i] / 15, i, (1 << i));
dev->irq_bit_count[i] = 0;
}
}
}
#endif
}
static void do_periodic_work(struct b43_wldev *dev)
{
unsigned int state;
state = dev->periodic_state;
if (state % 4 == 0)
b43_periodic_every60sec(dev);
if (state % 2 == 0)
b43_periodic_every30sec(dev);
b43_periodic_every15sec(dev);
}
/* Periodic work locking policy:
* The whole periodic work handler is protected by
* wl->mutex. If another lock is needed somewhere in the
* pwork callchain, it's acquired in-place, where it's needed.
*/
static void b43_periodic_work_handler(struct work_struct *work)
{
struct b43_wldev *dev = container_of(work, struct b43_wldev,
periodic_work.work);
struct b43_wl *wl = dev->wl;
unsigned long delay;
mutex_lock(&wl->mutex);
if (unlikely(b43_status(dev) != B43_STAT_STARTED))
goto out;
if (b43_debug(dev, B43_DBG_PWORK_STOP))
goto out_requeue;
do_periodic_work(dev);
dev->periodic_state++;
out_requeue:
if (b43_debug(dev, B43_DBG_PWORK_FAST))
delay = msecs_to_jiffies(50);
else
delay = round_jiffies_relative(HZ * 15);
ieee80211_queue_delayed_work(wl->hw, &dev->periodic_work, delay);
out:
mutex_unlock(&wl->mutex);
}
static void b43_periodic_tasks_setup(struct b43_wldev *dev)
{
struct delayed_work *work = &dev->periodic_work;
dev->periodic_state = 0;
INIT_DELAYED_WORK(work, b43_periodic_work_handler);
ieee80211_queue_delayed_work(dev->wl->hw, work, 0);
}
/* Check if communication with the device works correctly. */
static int b43_validate_chipaccess(struct b43_wldev *dev)
{
u32 v, backup0, backup4;
backup0 = b43_shm_read32(dev, B43_SHM_SHARED, 0);
backup4 = b43_shm_read32(dev, B43_SHM_SHARED, 4);
/* Check for read/write and endianness problems. */
b43_shm_write32(dev, B43_SHM_SHARED, 0, 0x55AAAA55);
if (b43_shm_read32(dev, B43_SHM_SHARED, 0) != 0x55AAAA55)
goto error;
b43_shm_write32(dev, B43_SHM_SHARED, 0, 0xAA5555AA);
if (b43_shm_read32(dev, B43_SHM_SHARED, 0) != 0xAA5555AA)
goto error;
/* Check if unaligned 32bit SHM_SHARED access works properly.
* However, don't bail out on failure, because it's noncritical. */
b43_shm_write16(dev, B43_SHM_SHARED, 0, 0x1122);
b43_shm_write16(dev, B43_SHM_SHARED, 2, 0x3344);
b43_shm_write16(dev, B43_SHM_SHARED, 4, 0x5566);
b43_shm_write16(dev, B43_SHM_SHARED, 6, 0x7788);
if (b43_shm_read32(dev, B43_SHM_SHARED, 2) != 0x55663344)
b43warn(dev->wl, "Unaligned 32bit SHM read access is broken\n");
b43_shm_write32(dev, B43_SHM_SHARED, 2, 0xAABBCCDD);
if (b43_shm_read16(dev, B43_SHM_SHARED, 0) != 0x1122 ||
b43_shm_read16(dev, B43_SHM_SHARED, 2) != 0xCCDD ||
b43_shm_read16(dev, B43_SHM_SHARED, 4) != 0xAABB ||
b43_shm_read16(dev, B43_SHM_SHARED, 6) != 0x7788)
b43warn(dev->wl, "Unaligned 32bit SHM write access is broken\n");
b43_shm_write32(dev, B43_SHM_SHARED, 0, backup0);
b43_shm_write32(dev, B43_SHM_SHARED, 4, backup4);
if ((dev->dev->core_rev >= 3) && (dev->dev->core_rev <= 10)) {
/* The 32bit register shadows the two 16bit registers
* with update sideeffects. Validate this. */
b43_write16(dev, B43_MMIO_TSF_CFP_START, 0xAAAA);
b43_write32(dev, B43_MMIO_TSF_CFP_START, 0xCCCCBBBB);
if (b43_read16(dev, B43_MMIO_TSF_CFP_START_LOW) != 0xBBBB)
goto error;
if (b43_read16(dev, B43_MMIO_TSF_CFP_START_HIGH) != 0xCCCC)
goto error;
}
b43_write32(dev, B43_MMIO_TSF_CFP_START, 0);
v = b43_read32(dev, B43_MMIO_MACCTL);
v |= B43_MACCTL_GMODE;
if (v != (B43_MACCTL_GMODE | B43_MACCTL_IHR_ENABLED))
goto error;
return 0;
error:
b43err(dev->wl, "Failed to validate the chipaccess\n");
return -ENODEV;
}
static void b43_security_init(struct b43_wldev *dev)
{
dev->ktp = b43_shm_read16(dev, B43_SHM_SHARED, B43_SHM_SH_KTP);
/* KTP is a word address, but we address SHM bytewise.
* So multiply by two.
*/
dev->ktp *= 2;
/* Number of RCMTA address slots */
b43_write16(dev, B43_MMIO_RCMTA_COUNT, B43_NR_PAIRWISE_KEYS);
/* Clear the key memory. */
b43_clear_keys(dev);
}
#ifdef CONFIG_B43_HWRNG
static int b43_rng_read(struct hwrng *rng, u32 *data)
{
struct b43_wl *wl = (struct b43_wl *)rng->priv;
struct b43_wldev *dev;
int count = -ENODEV;
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (likely(dev && b43_status(dev) >= B43_STAT_INITIALIZED)) {
*data = b43_read16(dev, B43_MMIO_RNG);
count = sizeof(u16);
}
mutex_unlock(&wl->mutex);
return count;
}
#endif /* CONFIG_B43_HWRNG */
static void b43_rng_exit(struct b43_wl *wl)
{
#ifdef CONFIG_B43_HWRNG
if (wl->rng_initialized)
hwrng_unregister(&wl->rng);
#endif /* CONFIG_B43_HWRNG */
}
static int b43_rng_init(struct b43_wl *wl)
{
int err = 0;
#ifdef CONFIG_B43_HWRNG
snprintf(wl->rng_name, ARRAY_SIZE(wl->rng_name),
"%s_%s", KBUILD_MODNAME, wiphy_name(wl->hw->wiphy));
wl->rng.name = wl->rng_name;
wl->rng.data_read = b43_rng_read;
wl->rng.priv = (unsigned long)wl;
wl->rng_initialized = true;
err = hwrng_register(&wl->rng);
if (err) {
wl->rng_initialized = false;
b43err(wl, "Failed to register the random "
"number generator (%d)\n", err);
}
#endif /* CONFIG_B43_HWRNG */
return err;
}
static void b43_tx_work(struct work_struct *work)
{
struct b43_wl *wl = container_of(work, struct b43_wl, tx_work);
struct b43_wldev *dev;
struct sk_buff *skb;
int queue_num;
int err = 0;
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (unlikely(!dev || b43_status(dev) < B43_STAT_STARTED)) {
mutex_unlock(&wl->mutex);
return;
}
for (queue_num = 0; queue_num < B43_QOS_QUEUE_NUM; queue_num++) {
while (skb_queue_len(&wl->tx_queue[queue_num])) {
skb = skb_dequeue(&wl->tx_queue[queue_num]);
if (b43_using_pio_transfers(dev))
err = b43_pio_tx(dev, skb);
else
err = b43_dma_tx(dev, skb);
if (err == -ENOSPC) {
wl->tx_queue_stopped[queue_num] = 1;
ieee80211_stop_queue(wl->hw, queue_num);
skb_queue_head(&wl->tx_queue[queue_num], skb);
break;
}
if (unlikely(err))
ieee80211_free_txskb(wl->hw, skb);
err = 0;
}
if (!err)
wl->tx_queue_stopped[queue_num] = 0;
}
#if B43_DEBUG
dev->tx_count++;
#endif
mutex_unlock(&wl->mutex);
}
static void b43_op_tx(struct ieee80211_hw *hw,
struct ieee80211_tx_control *control,
struct sk_buff *skb)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
if (unlikely(skb->len < 2 + 2 + 6)) {
/* Too short, this can't be a valid frame. */
ieee80211_free_txskb(hw, skb);
return;
}
B43_WARN_ON(skb_shinfo(skb)->nr_frags);
skb_queue_tail(&wl->tx_queue[skb->queue_mapping], skb);
if (!wl->tx_queue_stopped[skb->queue_mapping]) {
ieee80211_queue_work(wl->hw, &wl->tx_work);
} else {
ieee80211_stop_queue(wl->hw, skb->queue_mapping);
}
}
static void b43_qos_params_upload(struct b43_wldev *dev,
const struct ieee80211_tx_queue_params *p,
u16 shm_offset)
{
u16 params[B43_NR_QOSPARAMS];
int bslots, tmp;
unsigned int i;
if (!dev->qos_enabled)
return;
bslots = b43_read16(dev, B43_MMIO_RNG) & p->cw_min;
memset(¶ms, 0, sizeof(params));
params[B43_QOSPARAM_TXOP] = p->txop * 32;
params[B43_QOSPARAM_CWMIN] = p->cw_min;
params[B43_QOSPARAM_CWMAX] = p->cw_max;
params[B43_QOSPARAM_CWCUR] = p->cw_min;
params[B43_QOSPARAM_AIFS] = p->aifs;
params[B43_QOSPARAM_BSLOTS] = bslots;
params[B43_QOSPARAM_REGGAP] = bslots + p->aifs;
for (i = 0; i < ARRAY_SIZE(params); i++) {
if (i == B43_QOSPARAM_STATUS) {
tmp = b43_shm_read16(dev, B43_SHM_SHARED,
shm_offset + (i * 2));
/* Mark the parameters as updated. */
tmp |= 0x100;
b43_shm_write16(dev, B43_SHM_SHARED,
shm_offset + (i * 2),
tmp);
} else {
b43_shm_write16(dev, B43_SHM_SHARED,
shm_offset + (i * 2),
params[i]);
}
}
}
/* Mapping of mac80211 queue numbers to b43 QoS SHM offsets. */
static const u16 b43_qos_shm_offsets[] = {
/* [mac80211-queue-nr] = SHM_OFFSET, */
[0] = B43_QOS_VOICE,
[1] = B43_QOS_VIDEO,
[2] = B43_QOS_BESTEFFORT,
[3] = B43_QOS_BACKGROUND,
};
/* Update all QOS parameters in hardware. */
static void b43_qos_upload_all(struct b43_wldev *dev)
{
struct b43_wl *wl = dev->wl;
struct b43_qos_params *params;
unsigned int i;
if (!dev->qos_enabled)
return;
BUILD_BUG_ON(ARRAY_SIZE(b43_qos_shm_offsets) !=
ARRAY_SIZE(wl->qos_params));
b43_mac_suspend(dev);
for (i = 0; i < ARRAY_SIZE(wl->qos_params); i++) {
params = &(wl->qos_params[i]);
b43_qos_params_upload(dev, &(params->p),
b43_qos_shm_offsets[i]);
}
b43_mac_enable(dev);
}
static void b43_qos_clear(struct b43_wl *wl)
{
struct b43_qos_params *params;
unsigned int i;
/* Initialize QoS parameters to sane defaults. */
BUILD_BUG_ON(ARRAY_SIZE(b43_qos_shm_offsets) !=
ARRAY_SIZE(wl->qos_params));
for (i = 0; i < ARRAY_SIZE(wl->qos_params); i++) {
params = &(wl->qos_params[i]);
switch (b43_qos_shm_offsets[i]) {
case B43_QOS_VOICE:
params->p.txop = 0;
params->p.aifs = 2;
params->p.cw_min = 0x0001;
params->p.cw_max = 0x0001;
break;
case B43_QOS_VIDEO:
params->p.txop = 0;
params->p.aifs = 2;
params->p.cw_min = 0x0001;
params->p.cw_max = 0x0001;
break;
case B43_QOS_BESTEFFORT:
params->p.txop = 0;
params->p.aifs = 3;
params->p.cw_min = 0x0001;
params->p.cw_max = 0x03FF;
break;
case B43_QOS_BACKGROUND:
params->p.txop = 0;
params->p.aifs = 7;
params->p.cw_min = 0x0001;
params->p.cw_max = 0x03FF;
break;
default:
B43_WARN_ON(1);
}
}
}
/* Initialize the core's QOS capabilities */
static void b43_qos_init(struct b43_wldev *dev)
{
if (!dev->qos_enabled) {
/* Disable QOS support. */
b43_hf_write(dev, b43_hf_read(dev) & ~B43_HF_EDCF);
b43_write16(dev, B43_MMIO_IFSCTL,
b43_read16(dev, B43_MMIO_IFSCTL)
& ~B43_MMIO_IFSCTL_USE_EDCF);
b43dbg(dev->wl, "QoS disabled\n");
return;
}
/* Upload the current QOS parameters. */
b43_qos_upload_all(dev);
/* Enable QOS support. */
b43_hf_write(dev, b43_hf_read(dev) | B43_HF_EDCF);
b43_write16(dev, B43_MMIO_IFSCTL,
b43_read16(dev, B43_MMIO_IFSCTL)
| B43_MMIO_IFSCTL_USE_EDCF);
b43dbg(dev->wl, "QoS enabled\n");
}
static int b43_op_conf_tx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u16 _queue,
const struct ieee80211_tx_queue_params *params)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
unsigned int queue = (unsigned int)_queue;
int err = -ENODEV;
if (queue >= ARRAY_SIZE(wl->qos_params)) {
/* Queue not available or don't support setting
* params on this queue. Return success to not
* confuse mac80211. */
return 0;
}
BUILD_BUG_ON(ARRAY_SIZE(b43_qos_shm_offsets) !=
ARRAY_SIZE(wl->qos_params));
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (unlikely(!dev || (b43_status(dev) < B43_STAT_INITIALIZED)))
goto out_unlock;
memcpy(&(wl->qos_params[queue].p), params, sizeof(*params));
b43_mac_suspend(dev);
b43_qos_params_upload(dev, &(wl->qos_params[queue].p),
b43_qos_shm_offsets[queue]);
b43_mac_enable(dev);
err = 0;
out_unlock:
mutex_unlock(&wl->mutex);
return err;
}
static int b43_op_get_stats(struct ieee80211_hw *hw,
struct ieee80211_low_level_stats *stats)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
mutex_lock(&wl->mutex);
memcpy(stats, &wl->ieee_stats, sizeof(*stats));
mutex_unlock(&wl->mutex);
return 0;
}
static u64 b43_op_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
u64 tsf;
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (dev && (b43_status(dev) >= B43_STAT_INITIALIZED))
b43_tsf_read(dev, &tsf);
else
tsf = 0;
mutex_unlock(&wl->mutex);
return tsf;
}
static void b43_op_set_tsf(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u64 tsf)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (dev && (b43_status(dev) >= B43_STAT_INITIALIZED))
b43_tsf_write(dev, tsf);
mutex_unlock(&wl->mutex);
}
static const char *band_to_string(enum ieee80211_band band)
{
switch (band) {
case IEEE80211_BAND_5GHZ:
return "5";
case IEEE80211_BAND_2GHZ:
return "2.4";
default:
break;
}
B43_WARN_ON(1);
return "";
}
/* Expects wl->mutex locked */
static int b43_switch_band(struct b43_wldev *dev,
struct ieee80211_channel *chan)
{
struct b43_phy *phy = &dev->phy;
bool gmode;
u32 tmp;
switch (chan->band) {
case IEEE80211_BAND_5GHZ:
gmode = false;
break;
case IEEE80211_BAND_2GHZ:
gmode = true;
break;
default:
B43_WARN_ON(1);
return -EINVAL;
}
if (!((gmode && phy->supports_2ghz) ||
(!gmode && phy->supports_5ghz))) {
b43err(dev->wl, "This device doesn't support %s-GHz band\n",
band_to_string(chan->band));
return -ENODEV;
}
if (!!phy->gmode == !!gmode) {
/* This device is already running. */
return 0;
}
b43dbg(dev->wl, "Switching to %s GHz band\n",
band_to_string(chan->band));
/* Some new devices don't need disabling radio for band switching */
if (!(phy->type == B43_PHYTYPE_N && phy->rev >= 3))
b43_software_rfkill(dev, true);
phy->gmode = gmode;
b43_phy_put_into_reset(dev);
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
tmp = bcma_aread32(dev->dev->bdev, BCMA_IOCTL);
if (gmode)
tmp |= B43_BCMA_IOCTL_GMODE;
else
tmp &= ~B43_BCMA_IOCTL_GMODE;
bcma_awrite32(dev->dev->bdev, BCMA_IOCTL, tmp);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
tmp = ssb_read32(dev->dev->sdev, SSB_TMSLOW);
if (gmode)
tmp |= B43_TMSLOW_GMODE;
else
tmp &= ~B43_TMSLOW_GMODE;
ssb_write32(dev->dev->sdev, SSB_TMSLOW, tmp);
break;
#endif
}
b43_phy_take_out_of_reset(dev);
b43_upload_initvals_band(dev);
b43_phy_init(dev);
return 0;
}
static void b43_set_beacon_listen_interval(struct b43_wldev *dev, u16 interval)
{
interval = min_t(u16, interval, (u16)0xFF);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_BCN_LI, interval);
}
/* Write the short and long frame retry limit values. */
static void b43_set_retry_limits(struct b43_wldev *dev,
unsigned int short_retry,
unsigned int long_retry)
{
/* The retry limit is a 4-bit counter. Enforce this to avoid overflowing
* the chip-internal counter. */
short_retry = min(short_retry, (unsigned int)0xF);
long_retry = min(long_retry, (unsigned int)0xF);
b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_SRLIMIT,
short_retry);
b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_LRLIMIT,
long_retry);
}
static int b43_op_config(struct ieee80211_hw *hw, u32 changed)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev = wl->current_dev;
struct b43_phy *phy = &dev->phy;
struct ieee80211_conf *conf = &hw->conf;
int antenna;
int err = 0;
mutex_lock(&wl->mutex);
b43_mac_suspend(dev);
if (changed & IEEE80211_CONF_CHANGE_LISTEN_INTERVAL)
b43_set_beacon_listen_interval(dev, conf->listen_interval);
if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
phy->chandef = &conf->chandef;
phy->channel = conf->chandef.chan->hw_value;
/* Switch the band (if necessary). */
err = b43_switch_band(dev, conf->chandef.chan);
if (err)
goto out_mac_enable;
/* Switch to the requested channel.
* The firmware takes care of races with the TX handler.
*/
b43_switch_channel(dev, phy->channel);
}
if (changed & IEEE80211_CONF_CHANGE_RETRY_LIMITS)
b43_set_retry_limits(dev, conf->short_frame_max_tx_count,
conf->long_frame_max_tx_count);
changed &= ~IEEE80211_CONF_CHANGE_RETRY_LIMITS;
if (!changed)
goto out_mac_enable;
dev->wl->radiotap_enabled = !!(conf->flags & IEEE80211_CONF_MONITOR);
/* Adjust the desired TX power level. */
if (conf->power_level != 0) {
if (conf->power_level != phy->desired_txpower) {
phy->desired_txpower = conf->power_level;
b43_phy_txpower_check(dev, B43_TXPWR_IGNORE_TIME |
B43_TXPWR_IGNORE_TSSI);
}
}
/* Antennas for RX and management frame TX. */
antenna = B43_ANTENNA_DEFAULT;
b43_mgmtframe_txantenna(dev, antenna);
antenna = B43_ANTENNA_DEFAULT;
if (phy->ops->set_rx_antenna)
phy->ops->set_rx_antenna(dev, antenna);
if (wl->radio_enabled != phy->radio_on) {
if (wl->radio_enabled) {
b43_software_rfkill(dev, false);
b43info(dev->wl, "Radio turned on by software\n");
if (!dev->radio_hw_enable) {
b43info(dev->wl, "The hardware RF-kill button "
"still turns the radio physically off. "
"Press the button to turn it on.\n");
}
} else {
b43_software_rfkill(dev, true);
b43info(dev->wl, "Radio turned off by software\n");
}
}
out_mac_enable:
b43_mac_enable(dev);
mutex_unlock(&wl->mutex);
return err;
}
static void b43_update_basic_rates(struct b43_wldev *dev, u32 brates)
{
struct ieee80211_supported_band *sband =
dev->wl->hw->wiphy->bands[b43_current_band(dev->wl)];
struct ieee80211_rate *rate;
int i;
u16 basic, direct, offset, basic_offset, rateptr;
for (i = 0; i < sband->n_bitrates; i++) {
rate = &sband->bitrates[i];
if (b43_is_cck_rate(rate->hw_value)) {
direct = B43_SHM_SH_CCKDIRECT;
basic = B43_SHM_SH_CCKBASIC;
offset = b43_plcp_get_ratecode_cck(rate->hw_value);
offset &= 0xF;
} else {
direct = B43_SHM_SH_OFDMDIRECT;
basic = B43_SHM_SH_OFDMBASIC;
offset = b43_plcp_get_ratecode_ofdm(rate->hw_value);
offset &= 0xF;
}
rate = ieee80211_get_response_rate(sband, brates, rate->bitrate);
if (b43_is_cck_rate(rate->hw_value)) {
basic_offset = b43_plcp_get_ratecode_cck(rate->hw_value);
basic_offset &= 0xF;
} else {
basic_offset = b43_plcp_get_ratecode_ofdm(rate->hw_value);
basic_offset &= 0xF;
}
/*
* Get the pointer that we need to point to
* from the direct map
*/
rateptr = b43_shm_read16(dev, B43_SHM_SHARED,
direct + 2 * basic_offset);
/* and write it to the basic map */
b43_shm_write16(dev, B43_SHM_SHARED, basic + 2 * offset,
rateptr);
}
}
static void b43_op_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *conf,
u32 changed)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (!dev || b43_status(dev) < B43_STAT_STARTED)
goto out_unlock_mutex;
B43_WARN_ON(wl->vif != vif);
if (changed & BSS_CHANGED_BSSID) {
if (conf->bssid)
memcpy(wl->bssid, conf->bssid, ETH_ALEN);
else
memset(wl->bssid, 0, ETH_ALEN);
}
if (b43_status(dev) >= B43_STAT_INITIALIZED) {
if (changed & BSS_CHANGED_BEACON &&
(b43_is_mode(wl, NL80211_IFTYPE_AP) ||
b43_is_mode(wl, NL80211_IFTYPE_MESH_POINT) ||
b43_is_mode(wl, NL80211_IFTYPE_ADHOC)))
b43_update_templates(wl);
if (changed & BSS_CHANGED_BSSID)
b43_write_mac_bssid_templates(dev);
}
b43_mac_suspend(dev);
/* Update templates for AP/mesh mode. */
if (changed & BSS_CHANGED_BEACON_INT &&
(b43_is_mode(wl, NL80211_IFTYPE_AP) ||
b43_is_mode(wl, NL80211_IFTYPE_MESH_POINT) ||
b43_is_mode(wl, NL80211_IFTYPE_ADHOC)) &&
conf->beacon_int)
b43_set_beacon_int(dev, conf->beacon_int);
if (changed & BSS_CHANGED_BASIC_RATES)
b43_update_basic_rates(dev, conf->basic_rates);
if (changed & BSS_CHANGED_ERP_SLOT) {
if (conf->use_short_slot)
b43_short_slot_timing_enable(dev);
else
b43_short_slot_timing_disable(dev);
}
b43_mac_enable(dev);
out_unlock_mutex:
mutex_unlock(&wl->mutex);
}
static int b43_op_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif, struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
u8 algorithm;
u8 index;
int err;
static const u8 bcast_addr[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
if (modparam_nohwcrypt)
return -ENOSPC; /* User disabled HW-crypto */
if ((vif->type == NL80211_IFTYPE_ADHOC ||
vif->type == NL80211_IFTYPE_MESH_POINT) &&
(key->cipher == WLAN_CIPHER_SUITE_TKIP ||
key->cipher == WLAN_CIPHER_SUITE_CCMP) &&
!(key->flags & IEEE80211_KEY_FLAG_PAIRWISE)) {
/*
* For now, disable hw crypto for the RSN IBSS group keys. This
* could be optimized in the future, but until that gets
* implemented, use of software crypto for group addressed
* frames is a acceptable to allow RSN IBSS to be used.
*/
return -EOPNOTSUPP;
}
mutex_lock(&wl->mutex);
dev = wl->current_dev;
err = -ENODEV;
if (!dev || b43_status(dev) < B43_STAT_INITIALIZED)
goto out_unlock;
if (dev->fw.pcm_request_failed || !dev->hwcrypto_enabled) {
/* We don't have firmware for the crypto engine.
* Must use software-crypto. */
err = -EOPNOTSUPP;
goto out_unlock;
}
err = -EINVAL;
switch (key->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
algorithm = B43_SEC_ALGO_WEP40;
break;
case WLAN_CIPHER_SUITE_WEP104:
algorithm = B43_SEC_ALGO_WEP104;
break;
case WLAN_CIPHER_SUITE_TKIP:
algorithm = B43_SEC_ALGO_TKIP;
break;
case WLAN_CIPHER_SUITE_CCMP:
algorithm = B43_SEC_ALGO_AES;
break;
default:
B43_WARN_ON(1);
goto out_unlock;
}
index = (u8) (key->keyidx);
if (index > 3)
goto out_unlock;
switch (cmd) {
case SET_KEY:
if (algorithm == B43_SEC_ALGO_TKIP &&
(!(key->flags & IEEE80211_KEY_FLAG_PAIRWISE) ||
!modparam_hwtkip)) {
/* We support only pairwise key */
err = -EOPNOTSUPP;
goto out_unlock;
}
if (key->flags & IEEE80211_KEY_FLAG_PAIRWISE) {
if (WARN_ON(!sta)) {
err = -EOPNOTSUPP;
goto out_unlock;
}
/* Pairwise key with an assigned MAC address. */
err = b43_key_write(dev, -1, algorithm,
key->key, key->keylen,
sta->addr, key);
} else {
/* Group key */
err = b43_key_write(dev, index, algorithm,
key->key, key->keylen, NULL, key);
}
if (err)
goto out_unlock;
if (algorithm == B43_SEC_ALGO_WEP40 ||
algorithm == B43_SEC_ALGO_WEP104) {
b43_hf_write(dev, b43_hf_read(dev) | B43_HF_USEDEFKEYS);
} else {
b43_hf_write(dev,
b43_hf_read(dev) & ~B43_HF_USEDEFKEYS);
}
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
if (algorithm == B43_SEC_ALGO_TKIP)
key->flags |= IEEE80211_KEY_FLAG_GENERATE_MMIC;
break;
case DISABLE_KEY: {
err = b43_key_clear(dev, key->hw_key_idx);
if (err)
goto out_unlock;
break;
}
default:
B43_WARN_ON(1);
}
out_unlock:
if (!err) {
b43dbg(wl, "%s hardware based encryption for keyidx: %d, "
"mac: %pM\n",
cmd == SET_KEY ? "Using" : "Disabling", key->keyidx,
sta ? sta->addr : bcast_addr);
b43_dump_keymemory(dev);
}
mutex_unlock(&wl->mutex);
return err;
}
static void b43_op_configure_filter(struct ieee80211_hw *hw,
unsigned int changed, unsigned int *fflags,
u64 multicast)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (!dev) {
*fflags = 0;
goto out_unlock;
}
*fflags &= FIF_PROMISC_IN_BSS |
FIF_ALLMULTI |
FIF_FCSFAIL |
FIF_PLCPFAIL |
FIF_CONTROL |
FIF_OTHER_BSS |
FIF_BCN_PRBRESP_PROMISC;
changed &= FIF_PROMISC_IN_BSS |
FIF_ALLMULTI |
FIF_FCSFAIL |
FIF_PLCPFAIL |
FIF_CONTROL |
FIF_OTHER_BSS |
FIF_BCN_PRBRESP_PROMISC;
wl->filter_flags = *fflags;
if (changed && b43_status(dev) >= B43_STAT_INITIALIZED)
b43_adjust_opmode(dev);
out_unlock:
mutex_unlock(&wl->mutex);
}
/* Locking: wl->mutex
* Returns the current dev. This might be different from the passed in dev,
* because the core might be gone away while we unlocked the mutex. */
static struct b43_wldev * b43_wireless_core_stop(struct b43_wldev *dev)
{
struct b43_wl *wl;
struct b43_wldev *orig_dev;
u32 mask;
int queue_num;
if (!dev)
return NULL;
wl = dev->wl;
redo:
if (!dev || b43_status(dev) < B43_STAT_STARTED)
return dev;
/* Cancel work. Unlock to avoid deadlocks. */
mutex_unlock(&wl->mutex);
cancel_delayed_work_sync(&dev->periodic_work);
cancel_work_sync(&wl->tx_work);
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (!dev || b43_status(dev) < B43_STAT_STARTED) {
/* Whoops, aliens ate up the device while we were unlocked. */
return dev;
}
/* Disable interrupts on the device. */
b43_set_status(dev, B43_STAT_INITIALIZED);
if (b43_bus_host_is_sdio(dev->dev)) {
/* wl->mutex is locked. That is enough. */
b43_write32(dev, B43_MMIO_GEN_IRQ_MASK, 0);
b43_read32(dev, B43_MMIO_GEN_IRQ_MASK); /* Flush */
} else {
spin_lock_irq(&wl->hardirq_lock);
b43_write32(dev, B43_MMIO_GEN_IRQ_MASK, 0);
b43_read32(dev, B43_MMIO_GEN_IRQ_MASK); /* Flush */
spin_unlock_irq(&wl->hardirq_lock);
}
/* Synchronize and free the interrupt handlers. Unlock to avoid deadlocks. */
orig_dev = dev;
mutex_unlock(&wl->mutex);
if (b43_bus_host_is_sdio(dev->dev)) {
b43_sdio_free_irq(dev);
} else {
synchronize_irq(dev->dev->irq);
free_irq(dev->dev->irq, dev);
}
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (!dev)
return dev;
if (dev != orig_dev) {
if (b43_status(dev) >= B43_STAT_STARTED)
goto redo;
return dev;
}
mask = b43_read32(dev, B43_MMIO_GEN_IRQ_MASK);
B43_WARN_ON(mask != 0xFFFFFFFF && mask);
/* Drain all TX queues. */
for (queue_num = 0; queue_num < B43_QOS_QUEUE_NUM; queue_num++) {
while (skb_queue_len(&wl->tx_queue[queue_num])) {
struct sk_buff *skb;
skb = skb_dequeue(&wl->tx_queue[queue_num]);
ieee80211_free_txskb(wl->hw, skb);
}
}
b43_mac_suspend(dev);
b43_leds_exit(dev);
b43dbg(wl, "Wireless interface stopped\n");
return dev;
}
/* Locking: wl->mutex */
static int b43_wireless_core_start(struct b43_wldev *dev)
{
int err;
B43_WARN_ON(b43_status(dev) != B43_STAT_INITIALIZED);
drain_txstatus_queue(dev);
if (b43_bus_host_is_sdio(dev->dev)) {
err = b43_sdio_request_irq(dev, b43_sdio_interrupt_handler);
if (err) {
b43err(dev->wl, "Cannot request SDIO IRQ\n");
goto out;
}
} else {
err = request_threaded_irq(dev->dev->irq, b43_interrupt_handler,
b43_interrupt_thread_handler,
IRQF_SHARED, KBUILD_MODNAME, dev);
if (err) {
b43err(dev->wl, "Cannot request IRQ-%d\n",
dev->dev->irq);
goto out;
}
}
/* We are ready to run. */
ieee80211_wake_queues(dev->wl->hw);
b43_set_status(dev, B43_STAT_STARTED);
/* Start data flow (TX/RX). */
b43_mac_enable(dev);
b43_write32(dev, B43_MMIO_GEN_IRQ_MASK, dev->irq_mask);
/* Start maintenance work */
b43_periodic_tasks_setup(dev);
b43_leds_init(dev);
b43dbg(dev->wl, "Wireless interface started\n");
out:
return err;
}
static char *b43_phy_name(struct b43_wldev *dev, u8 phy_type)
{
switch (phy_type) {
case B43_PHYTYPE_A:
return "A";
case B43_PHYTYPE_B:
return "B";
case B43_PHYTYPE_G:
return "G";
case B43_PHYTYPE_N:
return "N";
case B43_PHYTYPE_LP:
return "LP";
case B43_PHYTYPE_SSLPN:
return "SSLPN";
case B43_PHYTYPE_HT:
return "HT";
case B43_PHYTYPE_LCN:
return "LCN";
case B43_PHYTYPE_LCNXN:
return "LCNXN";
case B43_PHYTYPE_LCN40:
return "LCN40";
case B43_PHYTYPE_AC:
return "AC";
}
return "UNKNOWN";
}
/* Get PHY and RADIO versioning numbers */
static int b43_phy_versioning(struct b43_wldev *dev)
{
struct b43_phy *phy = &dev->phy;
const u8 core_rev = dev->dev->core_rev;
u32 tmp;
u8 analog_type;
u8 phy_type;
u8 phy_rev;
u16 radio_manuf;
u16 radio_id;
u16 radio_rev;
u8 radio_ver;
int unsupported = 0;
/* Get PHY versioning */
tmp = b43_read16(dev, B43_MMIO_PHY_VER);
analog_type = (tmp & B43_PHYVER_ANALOG) >> B43_PHYVER_ANALOG_SHIFT;
phy_type = (tmp & B43_PHYVER_TYPE) >> B43_PHYVER_TYPE_SHIFT;
phy_rev = (tmp & B43_PHYVER_VERSION);
/* LCNXN is continuation of N which run out of revisions */
if (phy_type == B43_PHYTYPE_LCNXN) {
phy_type = B43_PHYTYPE_N;
phy_rev += 16;
}
switch (phy_type) {
#ifdef CONFIG_B43_PHY_G
case B43_PHYTYPE_G:
if (phy_rev > 9)
unsupported = 1;
break;
#endif
#ifdef CONFIG_B43_PHY_N
case B43_PHYTYPE_N:
if (phy_rev >= 19)
unsupported = 1;
break;
#endif
#ifdef CONFIG_B43_PHY_LP
case B43_PHYTYPE_LP:
if (phy_rev > 2)
unsupported = 1;
break;
#endif
#ifdef CONFIG_B43_PHY_HT
case B43_PHYTYPE_HT:
if (phy_rev > 1)
unsupported = 1;
break;
#endif
#ifdef CONFIG_B43_PHY_LCN
case B43_PHYTYPE_LCN:
if (phy_rev > 1)
unsupported = 1;
break;
#endif
default:
unsupported = 1;
}
if (unsupported) {
b43err(dev->wl, "FOUND UNSUPPORTED PHY (Analog %u, Type %d (%s), Revision %u)\n",
analog_type, phy_type, b43_phy_name(dev, phy_type),
phy_rev);
return -EOPNOTSUPP;
}
b43info(dev->wl, "Found PHY: Analog %u, Type %d (%s), Revision %u\n",
analog_type, phy_type, b43_phy_name(dev, phy_type), phy_rev);
/* Get RADIO versioning */
if (core_rev == 40 || core_rev == 42) {
radio_manuf = 0x17F;
b43_write16f(dev, B43_MMIO_RADIO24_CONTROL, 0);
radio_rev = b43_read16(dev, B43_MMIO_RADIO24_DATA);
b43_write16f(dev, B43_MMIO_RADIO24_CONTROL, 1);
radio_id = b43_read16(dev, B43_MMIO_RADIO24_DATA);
radio_ver = 0; /* Is there version somewhere? */
} else if (core_rev >= 24) {
u16 radio24[3];
for (tmp = 0; tmp < 3; tmp++) {
b43_write16f(dev, B43_MMIO_RADIO24_CONTROL, tmp);
radio24[tmp] = b43_read16(dev, B43_MMIO_RADIO24_DATA);
}
radio_manuf = 0x17F;
radio_id = (radio24[2] << 8) | radio24[1];
radio_rev = (radio24[0] & 0xF);
radio_ver = (radio24[0] & 0xF0) >> 4;
} else {
if (dev->dev->chip_id == 0x4317) {
if (dev->dev->chip_rev == 0)
tmp = 0x3205017F;
else if (dev->dev->chip_rev == 1)
tmp = 0x4205017F;
else
tmp = 0x5205017F;
} else {
b43_write16f(dev, B43_MMIO_RADIO_CONTROL,
B43_RADIOCTL_ID);
tmp = b43_read16(dev, B43_MMIO_RADIO_DATA_LOW);
b43_write16f(dev, B43_MMIO_RADIO_CONTROL,
B43_RADIOCTL_ID);
tmp |= b43_read16(dev, B43_MMIO_RADIO_DATA_HIGH) << 16;
}
radio_manuf = (tmp & 0x00000FFF);
radio_id = (tmp & 0x0FFFF000) >> 12;
radio_rev = (tmp & 0xF0000000) >> 28;
radio_ver = 0; /* Probably not available on old hw */
}
if (radio_manuf != 0x17F /* Broadcom */)
unsupported = 1;
switch (phy_type) {
case B43_PHYTYPE_A:
if (radio_id != 0x2060)
unsupported = 1;
if (radio_rev != 1)
unsupported = 1;
if (radio_manuf != 0x17F)
unsupported = 1;
break;
case B43_PHYTYPE_B:
if ((radio_id & 0xFFF0) != 0x2050)
unsupported = 1;
break;
case B43_PHYTYPE_G:
if (radio_id != 0x2050)
unsupported = 1;
break;
case B43_PHYTYPE_N:
if (radio_id != 0x2055 && radio_id != 0x2056 &&
radio_id != 0x2057)
unsupported = 1;
if (radio_id == 0x2057 &&
!(radio_rev == 9 || radio_rev == 14))
unsupported = 1;
break;
case B43_PHYTYPE_LP:
if (radio_id != 0x2062 && radio_id != 0x2063)
unsupported = 1;
break;
case B43_PHYTYPE_HT:
if (radio_id != 0x2059)
unsupported = 1;
break;
case B43_PHYTYPE_LCN:
if (radio_id != 0x2064)
unsupported = 1;
break;
default:
B43_WARN_ON(1);
}
if (unsupported) {
b43err(dev->wl,
"FOUND UNSUPPORTED RADIO (Manuf 0x%X, ID 0x%X, Revision %u, Version %u)\n",
radio_manuf, radio_id, radio_rev, radio_ver);
return -EOPNOTSUPP;
}
b43info(dev->wl,
"Found Radio: Manuf 0x%X, ID 0x%X, Revision %u, Version %u\n",
radio_manuf, radio_id, radio_rev, radio_ver);
/* FIXME: b43 treats "id" as "ver" and ignores the real "ver" */
phy->radio_manuf = radio_manuf;
phy->radio_ver = radio_id;
phy->radio_rev = radio_rev;
phy->analog = analog_type;
phy->type = phy_type;
phy->rev = phy_rev;
return 0;
}
static void setup_struct_phy_for_init(struct b43_wldev *dev,
struct b43_phy *phy)
{
phy->hardware_power_control = !!modparam_hwpctl;
phy->next_txpwr_check_time = jiffies;
/* PHY TX errors counter. */
atomic_set(&phy->txerr_cnt, B43_PHY_TX_BADNESS_LIMIT);
#if B43_DEBUG
phy->phy_locked = false;
phy->radio_locked = false;
#endif
}
static void setup_struct_wldev_for_init(struct b43_wldev *dev)
{
dev->dfq_valid = false;
/* Assume the radio is enabled. If it's not enabled, the state will
* immediately get fixed on the first periodic work run. */
dev->radio_hw_enable = true;
/* Stats */
memset(&dev->stats, 0, sizeof(dev->stats));
setup_struct_phy_for_init(dev, &dev->phy);
/* IRQ related flags */
dev->irq_reason = 0;
memset(dev->dma_reason, 0, sizeof(dev->dma_reason));
dev->irq_mask = B43_IRQ_MASKTEMPLATE;
if (b43_modparam_verbose < B43_VERBOSITY_DEBUG)
dev->irq_mask &= ~B43_IRQ_PHY_TXERR;
dev->mac_suspended = 1;
/* Noise calculation context */
memset(&dev->noisecalc, 0, sizeof(dev->noisecalc));
}
static void b43_bluetooth_coext_enable(struct b43_wldev *dev)
{
struct ssb_sprom *sprom = dev->dev->bus_sprom;
u64 hf;
if (!modparam_btcoex)
return;
if (!(sprom->boardflags_lo & B43_BFL_BTCOEXIST))
return;
if (dev->phy.type != B43_PHYTYPE_B && !dev->phy.gmode)
return;
hf = b43_hf_read(dev);
if (sprom->boardflags_lo & B43_BFL_BTCMOD)
hf |= B43_HF_BTCOEXALT;
else
hf |= B43_HF_BTCOEX;
b43_hf_write(dev, hf);
}
static void b43_bluetooth_coext_disable(struct b43_wldev *dev)
{
if (!modparam_btcoex)
return;
//TODO
}
static void b43_imcfglo_timeouts_workaround(struct b43_wldev *dev)
{
struct ssb_bus *bus;
u32 tmp;
#ifdef CONFIG_B43_SSB
if (dev->dev->bus_type != B43_BUS_SSB)
return;
#else
return;
#endif
bus = dev->dev->sdev->bus;
if ((bus->chip_id == 0x4311 && bus->chip_rev == 2) ||
(bus->chip_id == 0x4312)) {
tmp = ssb_read32(dev->dev->sdev, SSB_IMCFGLO);
tmp &= ~SSB_IMCFGLO_REQTO;
tmp &= ~SSB_IMCFGLO_SERTO;
tmp |= 0x3;
ssb_write32(dev->dev->sdev, SSB_IMCFGLO, tmp);
ssb_commit_settings(bus);
}
}
static void b43_set_synth_pu_delay(struct b43_wldev *dev, bool idle)
{
u16 pu_delay;
/* The time value is in microseconds. */
if (dev->phy.type == B43_PHYTYPE_A)
pu_delay = 3700;
else
pu_delay = 1050;
if (b43_is_mode(dev->wl, NL80211_IFTYPE_ADHOC) || idle)
pu_delay = 500;
if ((dev->phy.radio_ver == 0x2050) && (dev->phy.radio_rev == 8))
pu_delay = max(pu_delay, (u16)2400);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_SPUWKUP, pu_delay);
}
/* Set the TSF CFP pre-TargetBeaconTransmissionTime. */
static void b43_set_pretbtt(struct b43_wldev *dev)
{
u16 pretbtt;
/* The time value is in microseconds. */
if (b43_is_mode(dev->wl, NL80211_IFTYPE_ADHOC)) {
pretbtt = 2;
} else {
if (dev->phy.type == B43_PHYTYPE_A)
pretbtt = 120;
else
pretbtt = 250;
}
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_PRETBTT, pretbtt);
b43_write16(dev, B43_MMIO_TSF_CFP_PRETBTT, pretbtt);
}
/* Shutdown a wireless core */
/* Locking: wl->mutex */
static void b43_wireless_core_exit(struct b43_wldev *dev)
{
B43_WARN_ON(dev && b43_status(dev) > B43_STAT_INITIALIZED);
if (!dev || b43_status(dev) != B43_STAT_INITIALIZED)
return;
b43_set_status(dev, B43_STAT_UNINIT);
/* Stop the microcode PSM. */
b43_maskset32(dev, B43_MMIO_MACCTL, ~B43_MACCTL_PSM_RUN,
B43_MACCTL_PSM_JMP0);
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
bcma_core_pci_down(dev->dev->bdev->bus);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
/* TODO */
break;
#endif
}
b43_dma_free(dev);
b43_pio_free(dev);
b43_chip_exit(dev);
dev->phy.ops->switch_analog(dev, 0);
if (dev->wl->current_beacon) {
dev_kfree_skb_any(dev->wl->current_beacon);
dev->wl->current_beacon = NULL;
}
b43_device_disable(dev, 0);
b43_bus_may_powerdown(dev);
}
/* Initialize a wireless core */
static int b43_wireless_core_init(struct b43_wldev *dev)
{
struct ssb_sprom *sprom = dev->dev->bus_sprom;
struct b43_phy *phy = &dev->phy;
int err;
u64 hf;
B43_WARN_ON(b43_status(dev) != B43_STAT_UNINIT);
err = b43_bus_powerup(dev, 0);
if (err)
goto out;
if (!b43_device_is_enabled(dev))
b43_wireless_core_reset(dev, phy->gmode);
/* Reset all data structures. */
setup_struct_wldev_for_init(dev);
phy->ops->prepare_structs(dev);
/* Enable IRQ routing to this device. */
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
bcma_core_pci_irq_ctl(&dev->dev->bdev->bus->drv_pci[0],
dev->dev->bdev, true);
bcma_core_pci_up(dev->dev->bdev->bus);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
ssb_pcicore_dev_irqvecs_enable(&dev->dev->sdev->bus->pcicore,
dev->dev->sdev);
break;
#endif
}
b43_imcfglo_timeouts_workaround(dev);
b43_bluetooth_coext_disable(dev);
if (phy->ops->prepare_hardware) {
err = phy->ops->prepare_hardware(dev);
if (err)
goto err_busdown;
}
err = b43_chip_init(dev);
if (err)
goto err_busdown;
b43_shm_write16(dev, B43_SHM_SHARED,
B43_SHM_SH_WLCOREREV, dev->dev->core_rev);
hf = b43_hf_read(dev);
if (phy->type == B43_PHYTYPE_G) {
hf |= B43_HF_SYMW;
if (phy->rev == 1)
hf |= B43_HF_GDCW;
if (sprom->boardflags_lo & B43_BFL_PACTRL)
hf |= B43_HF_OFDMPABOOST;
}
if (phy->radio_ver == 0x2050) {
if (phy->radio_rev == 6)
hf |= B43_HF_4318TSSI;
if (phy->radio_rev < 6)
hf |= B43_HF_VCORECALC;
}
if (sprom->boardflags_lo & B43_BFL_XTAL_NOSLOW)
hf |= B43_HF_DSCRQ; /* Disable slowclock requests from ucode. */
#if defined(CONFIG_B43_SSB) && defined(CONFIG_SSB_DRIVER_PCICORE)
if (dev->dev->bus_type == B43_BUS_SSB &&
dev->dev->sdev->bus->bustype == SSB_BUSTYPE_PCI &&
dev->dev->sdev->bus->pcicore.dev->id.revision <= 10)
hf |= B43_HF_PCISCW; /* PCI slow clock workaround. */
#endif
hf &= ~B43_HF_SKCFPUP;
b43_hf_write(dev, hf);
/* tell the ucode MAC capabilities */
if (dev->dev->core_rev >= 13) {
u32 mac_hw_cap = b43_read32(dev, B43_MMIO_MAC_HW_CAP);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_MACHW_L,
mac_hw_cap & 0xffff);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_MACHW_H,
(mac_hw_cap >> 16) & 0xffff);
}
b43_set_retry_limits(dev, B43_DEFAULT_SHORT_RETRY_LIMIT,
B43_DEFAULT_LONG_RETRY_LIMIT);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_SFFBLIM, 3);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_LFFBLIM, 2);
/* Disable sending probe responses from firmware.
* Setting the MaxTime to one usec will always trigger
* a timeout, so we never send any probe resp.
* A timeout of zero is infinite. */
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_PRMAXTIME, 1);
b43_rate_memory_init(dev);
b43_set_phytxctl_defaults(dev);
/* Minimum Contention Window */
if (phy->type == B43_PHYTYPE_B)
b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_MINCONT, 0x1F);
else
b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_MINCONT, 0xF);
/* Maximum Contention Window */
b43_shm_write16(dev, B43_SHM_SCRATCH, B43_SHM_SC_MAXCONT, 0x3FF);
/* write phytype and phyvers */
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_PHYTYPE, phy->type);
b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_PHYVER, phy->rev);
if (b43_bus_host_is_pcmcia(dev->dev) ||
b43_bus_host_is_sdio(dev->dev)) {
dev->__using_pio_transfers = true;
err = b43_pio_init(dev);
} else if (dev->use_pio) {
b43warn(dev->wl, "Forced PIO by use_pio module parameter. "
"This should not be needed and will result in lower "
"performance.\n");
dev->__using_pio_transfers = true;
err = b43_pio_init(dev);
} else {
dev->__using_pio_transfers = false;
err = b43_dma_init(dev);
}
if (err)
goto err_chip_exit;
b43_qos_init(dev);
b43_set_synth_pu_delay(dev, 1);
b43_bluetooth_coext_enable(dev);
b43_bus_powerup(dev, !(sprom->boardflags_lo & B43_BFL_XTAL_NOSLOW));
b43_upload_card_macaddress(dev);
b43_security_init(dev);
ieee80211_wake_queues(dev->wl->hw);
b43_set_status(dev, B43_STAT_INITIALIZED);
out:
return err;
err_chip_exit:
b43_chip_exit(dev);
err_busdown:
b43_bus_may_powerdown(dev);
B43_WARN_ON(b43_status(dev) != B43_STAT_UNINIT);
return err;
}
static int b43_op_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
int err = -EOPNOTSUPP;
/* TODO: allow WDS/AP devices to coexist */
if (vif->type != NL80211_IFTYPE_AP &&
vif->type != NL80211_IFTYPE_MESH_POINT &&
vif->type != NL80211_IFTYPE_STATION &&
vif->type != NL80211_IFTYPE_WDS &&
vif->type != NL80211_IFTYPE_ADHOC)
return -EOPNOTSUPP;
mutex_lock(&wl->mutex);
if (wl->operating)
goto out_mutex_unlock;
b43dbg(wl, "Adding Interface type %d\n", vif->type);
dev = wl->current_dev;
wl->operating = true;
wl->vif = vif;
wl->if_type = vif->type;
memcpy(wl->mac_addr, vif->addr, ETH_ALEN);
b43_adjust_opmode(dev);
b43_set_pretbtt(dev);
b43_set_synth_pu_delay(dev, 0);
b43_upload_card_macaddress(dev);
err = 0;
out_mutex_unlock:
mutex_unlock(&wl->mutex);
if (err == 0)
b43_op_bss_info_changed(hw, vif, &vif->bss_conf, ~0);
return err;
}
static void b43_op_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev = wl->current_dev;
b43dbg(wl, "Removing Interface type %d\n", vif->type);
mutex_lock(&wl->mutex);
B43_WARN_ON(!wl->operating);
B43_WARN_ON(wl->vif != vif);
wl->vif = NULL;
wl->operating = false;
b43_adjust_opmode(dev);
memset(wl->mac_addr, 0, ETH_ALEN);
b43_upload_card_macaddress(dev);
mutex_unlock(&wl->mutex);
}
static int b43_op_start(struct ieee80211_hw *hw)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev = wl->current_dev;
int did_init = 0;
int err = 0;
/* Kill all old instance specific information to make sure
* the card won't use it in the short timeframe between start
* and mac80211 reconfiguring it. */
memset(wl->bssid, 0, ETH_ALEN);
memset(wl->mac_addr, 0, ETH_ALEN);
wl->filter_flags = 0;
wl->radiotap_enabled = false;
b43_qos_clear(wl);
wl->beacon0_uploaded = false;
wl->beacon1_uploaded = false;
wl->beacon_templates_virgin = true;
wl->radio_enabled = true;
mutex_lock(&wl->mutex);
if (b43_status(dev) < B43_STAT_INITIALIZED) {
err = b43_wireless_core_init(dev);
if (err)
goto out_mutex_unlock;
did_init = 1;
}
if (b43_status(dev) < B43_STAT_STARTED) {
err = b43_wireless_core_start(dev);
if (err) {
if (did_init)
b43_wireless_core_exit(dev);
goto out_mutex_unlock;
}
}
/* XXX: only do if device doesn't support rfkill irq */
wiphy_rfkill_start_polling(hw->wiphy);
out_mutex_unlock:
mutex_unlock(&wl->mutex);
/*
* Configuration may have been overwritten during initialization.
* Reload the configuration, but only if initialization was
* successful. Reloading the configuration after a failed init
* may hang the system.
*/
if (!err)
b43_op_config(hw, ~0);
return err;
}
static void b43_op_stop(struct ieee80211_hw *hw)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev = wl->current_dev;
cancel_work_sync(&(wl->beacon_update_trigger));
if (!dev)
goto out;
mutex_lock(&wl->mutex);
if (b43_status(dev) >= B43_STAT_STARTED) {
dev = b43_wireless_core_stop(dev);
if (!dev)
goto out_unlock;
}
b43_wireless_core_exit(dev);
wl->radio_enabled = false;
out_unlock:
mutex_unlock(&wl->mutex);
out:
cancel_work_sync(&(wl->txpower_adjust_work));
}
static int b43_op_beacon_set_tim(struct ieee80211_hw *hw,
struct ieee80211_sta *sta, bool set)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
/* FIXME: add locking */
b43_update_templates(wl);
return 0;
}
static void b43_op_sta_notify(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum sta_notify_cmd notify_cmd,
struct ieee80211_sta *sta)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
B43_WARN_ON(!vif || wl->vif != vif);
}
static void b43_op_sw_scan_start_notifier(struct ieee80211_hw *hw)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (dev && (b43_status(dev) >= B43_STAT_INITIALIZED)) {
/* Disable CFP update during scan on other channels. */
b43_hf_write(dev, b43_hf_read(dev) | B43_HF_SKCFPUP);
}
mutex_unlock(&wl->mutex);
}
static void b43_op_sw_scan_complete_notifier(struct ieee80211_hw *hw)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev;
mutex_lock(&wl->mutex);
dev = wl->current_dev;
if (dev && (b43_status(dev) >= B43_STAT_INITIALIZED)) {
/* Re-enable CFP update. */
b43_hf_write(dev, b43_hf_read(dev) & ~B43_HF_SKCFPUP);
}
mutex_unlock(&wl->mutex);
}
static int b43_op_get_survey(struct ieee80211_hw *hw, int idx,
struct survey_info *survey)
{
struct b43_wl *wl = hw_to_b43_wl(hw);
struct b43_wldev *dev = wl->current_dev;
struct ieee80211_conf *conf = &hw->conf;
if (idx != 0)
return -ENOENT;
survey->channel = conf->chandef.chan;
survey->filled = SURVEY_INFO_NOISE_DBM;
survey->noise = dev->stats.link_noise;
return 0;
}
static const struct ieee80211_ops b43_hw_ops = {
.tx = b43_op_tx,
.conf_tx = b43_op_conf_tx,
.add_interface = b43_op_add_interface,
.remove_interface = b43_op_remove_interface,
.config = b43_op_config,
.bss_info_changed = b43_op_bss_info_changed,
.configure_filter = b43_op_configure_filter,
.set_key = b43_op_set_key,
.update_tkip_key = b43_op_update_tkip_key,
.get_stats = b43_op_get_stats,
.get_tsf = b43_op_get_tsf,
.set_tsf = b43_op_set_tsf,
.start = b43_op_start,
.stop = b43_op_stop,
.set_tim = b43_op_beacon_set_tim,
.sta_notify = b43_op_sta_notify,
.sw_scan_start = b43_op_sw_scan_start_notifier,
.sw_scan_complete = b43_op_sw_scan_complete_notifier,
.get_survey = b43_op_get_survey,
.rfkill_poll = b43_rfkill_poll,
};
/* Hard-reset the chip. Do not call this directly.
* Use b43_controller_restart()
*/
static void b43_chip_reset(struct work_struct *work)
{
struct b43_wldev *dev =
container_of(work, struct b43_wldev, restart_work);
struct b43_wl *wl = dev->wl;
int err = 0;
int prev_status;
mutex_lock(&wl->mutex);
prev_status = b43_status(dev);
/* Bring the device down... */
if (prev_status >= B43_STAT_STARTED) {
dev = b43_wireless_core_stop(dev);
if (!dev) {
err = -ENODEV;
goto out;
}
}
if (prev_status >= B43_STAT_INITIALIZED)
b43_wireless_core_exit(dev);
/* ...and up again. */
if (prev_status >= B43_STAT_INITIALIZED) {
err = b43_wireless_core_init(dev);
if (err)
goto out;
}
if (prev_status >= B43_STAT_STARTED) {
err = b43_wireless_core_start(dev);
if (err) {
b43_wireless_core_exit(dev);
goto out;
}
}
out:
if (err)
wl->current_dev = NULL; /* Failed to init the dev. */
mutex_unlock(&wl->mutex);
if (err) {
b43err(wl, "Controller restart FAILED\n");
return;
}
/* reload configuration */
b43_op_config(wl->hw, ~0);
if (wl->vif)
b43_op_bss_info_changed(wl->hw, wl->vif, &wl->vif->bss_conf, ~0);
b43info(wl, "Controller restarted\n");
}
static int b43_setup_bands(struct b43_wldev *dev,
bool have_2ghz_phy, bool have_5ghz_phy)
{
struct ieee80211_hw *hw = dev->wl->hw;
struct b43_phy *phy = &dev->phy;
bool limited_2g;
bool limited_5g;
/* We don't support all 2 GHz channels on some devices */
limited_2g = phy->radio_ver == 0x2057 &&
(phy->radio_rev == 9 || phy->radio_rev == 14);
limited_5g = phy->radio_ver == 0x2057 &&
phy->radio_rev == 9;
if (have_2ghz_phy)
hw->wiphy->bands[IEEE80211_BAND_2GHZ] = limited_2g ?
&b43_band_2ghz_limited : &b43_band_2GHz;
if (dev->phy.type == B43_PHYTYPE_N) {
if (have_5ghz_phy)
hw->wiphy->bands[IEEE80211_BAND_5GHZ] = limited_5g ?
&b43_band_5GHz_nphy_limited :
&b43_band_5GHz_nphy;
} else {
if (have_5ghz_phy)
hw->wiphy->bands[IEEE80211_BAND_5GHZ] = &b43_band_5GHz_aphy;
}
dev->phy.supports_2ghz = have_2ghz_phy;
dev->phy.supports_5ghz = have_5ghz_phy;
return 0;
}
static void b43_wireless_core_detach(struct b43_wldev *dev)
{
/* We release firmware that late to not be required to re-request
* is all the time when we reinit the core. */
b43_release_firmware(dev);
b43_phy_free(dev);
}
static void b43_supported_bands(struct b43_wldev *dev, bool *have_2ghz_phy,
bool *have_5ghz_phy)
{
u16 dev_id = 0;
#ifdef CONFIG_B43_BCMA
if (dev->dev->bus_type == B43_BUS_BCMA &&
dev->dev->bdev->bus->hosttype == BCMA_HOSTTYPE_PCI)
dev_id = dev->dev->bdev->bus->host_pci->device;
#endif
#ifdef CONFIG_B43_SSB
if (dev->dev->bus_type == B43_BUS_SSB &&
dev->dev->sdev->bus->bustype == SSB_BUSTYPE_PCI)
dev_id = dev->dev->sdev->bus->host_pci->device;
#endif
/* Override with SPROM value if available */
if (dev->dev->bus_sprom->dev_id)
dev_id = dev->dev->bus_sprom->dev_id;
/* Note: below IDs can be "virtual" (not maching e.g. real PCI ID) */
switch (dev_id) {
case 0x4324: /* BCM4306 */
case 0x4312: /* BCM4311 */
case 0x4319: /* BCM4318 */
case 0x4328: /* BCM4321 */
case 0x432b: /* BCM4322 */
case 0x4350: /* BCM43222 */
case 0x4353: /* BCM43224 */
case 0x0576: /* BCM43224 */
case 0x435f: /* BCM6362 */
case 0x4331: /* BCM4331 */
case 0x4359: /* BCM43228 */
case 0x43a0: /* BCM4360 */
case 0x43b1: /* BCM4352 */
/* Dual band devices */
*have_2ghz_phy = true;
*have_5ghz_phy = true;
return;
case 0x4321: /* BCM4306 */
case 0x4313: /* BCM4311 */
case 0x431a: /* BCM4318 */
case 0x432a: /* BCM4321 */
case 0x432d: /* BCM4322 */
case 0x4352: /* BCM43222 */
case 0x4333: /* BCM4331 */
case 0x43a2: /* BCM4360 */
case 0x43b3: /* BCM4352 */
/* 5 GHz only devices */
*have_2ghz_phy = false;
*have_5ghz_phy = true;
return;
}
/* As a fallback, try to guess using PHY type */
switch (dev->phy.type) {
case B43_PHYTYPE_A:
*have_2ghz_phy = false;
*have_5ghz_phy = true;
return;
case B43_PHYTYPE_G:
case B43_PHYTYPE_N:
case B43_PHYTYPE_LP:
case B43_PHYTYPE_HT:
case B43_PHYTYPE_LCN:
*have_2ghz_phy = true;
*have_5ghz_phy = false;
return;
}
B43_WARN_ON(1);
}
static int b43_wireless_core_attach(struct b43_wldev *dev)
{
struct b43_wl *wl = dev->wl;
struct b43_phy *phy = &dev->phy;
int err;
u32 tmp;
bool have_2ghz_phy = false, have_5ghz_phy = false;
/* Do NOT do any device initialization here.
* Do it in wireless_core_init() instead.
* This function is for gathering basic information about the HW, only.
* Also some structs may be set up here. But most likely you want to have
* that in core_init(), too.
*/
err = b43_bus_powerup(dev, 0);
if (err) {
b43err(wl, "Bus powerup failed\n");
goto out;
}
phy->do_full_init = true;
/* Try to guess supported bands for the first init needs */
switch (dev->dev->bus_type) {
#ifdef CONFIG_B43_BCMA
case B43_BUS_BCMA:
tmp = bcma_aread32(dev->dev->bdev, BCMA_IOST);
have_2ghz_phy = !!(tmp & B43_BCMA_IOST_2G_PHY);
have_5ghz_phy = !!(tmp & B43_BCMA_IOST_5G_PHY);
break;
#endif
#ifdef CONFIG_B43_SSB
case B43_BUS_SSB:
if (dev->dev->core_rev >= 5) {
tmp = ssb_read32(dev->dev->sdev, SSB_TMSHIGH);
have_2ghz_phy = !!(tmp & B43_TMSHIGH_HAVE_2GHZ_PHY);
have_5ghz_phy = !!(tmp & B43_TMSHIGH_HAVE_5GHZ_PHY);
} else
B43_WARN_ON(1);
break;
#endif
}
dev->phy.gmode = have_2ghz_phy;
b43_wireless_core_reset(dev, dev->phy.gmode);
/* Get the PHY type. */
err = b43_phy_versioning(dev);
if (err)
goto err_powerdown;
/* Get real info about supported bands */
b43_supported_bands(dev, &have_2ghz_phy, &have_5ghz_phy);
/* We don't support 5 GHz on some PHYs yet */
if (have_5ghz_phy) {
switch (dev->phy.type) {
case B43_PHYTYPE_A:
case B43_PHYTYPE_G:
case B43_PHYTYPE_LP:
case B43_PHYTYPE_HT:
b43warn(wl, "5 GHz band is unsupported on this PHY\n");
have_5ghz_phy = false;
}
}
if (!have_2ghz_phy && !have_5ghz_phy) {
b43err(wl, "b43 can't support any band on this device\n");
err = -EOPNOTSUPP;
goto err_powerdown;
}
err = b43_phy_allocate(dev);
if (err)
goto err_powerdown;
dev->phy.gmode = have_2ghz_phy;
b43_wireless_core_reset(dev, dev->phy.gmode);
err = b43_validate_chipaccess(dev);
if (err)
goto err_phy_free;
err = b43_setup_bands(dev, have_2ghz_phy, have_5ghz_phy);
if (err)
goto err_phy_free;
/* Now set some default "current_dev" */
if (!wl->current_dev)
wl->current_dev = dev;
INIT_WORK(&dev->restart_work, b43_chip_reset);
dev->phy.ops->switch_analog(dev, 0);
b43_device_disable(dev, 0);
b43_bus_may_powerdown(dev);
out:
return err;
err_phy_free:
b43_phy_free(dev);
err_powerdown:
b43_bus_may_powerdown(dev);
return err;
}
static void b43_one_core_detach(struct b43_bus_dev *dev)
{
struct b43_wldev *wldev;
struct b43_wl *wl;
/* Do not cancel ieee80211-workqueue based work here.
* See comment in b43_remove(). */
wldev = b43_bus_get_wldev(dev);
wl = wldev->wl;
b43_debugfs_remove_device(wldev);
b43_wireless_core_detach(wldev);
list_del(&wldev->list);
b43_bus_set_wldev(dev, NULL);
kfree(wldev);
}
static int b43_one_core_attach(struct b43_bus_dev *dev, struct b43_wl *wl)
{
struct b43_wldev *wldev;
int err = -ENOMEM;
wldev = kzalloc(sizeof(*wldev), GFP_KERNEL);
if (!wldev)
goto out;
wldev->use_pio = b43_modparam_pio;
wldev->dev = dev;
wldev->wl = wl;
b43_set_status(wldev, B43_STAT_UNINIT);
wldev->bad_frames_preempt = modparam_bad_frames_preempt;
INIT_LIST_HEAD(&wldev->list);
err = b43_wireless_core_attach(wldev);
if (err)
goto err_kfree_wldev;
b43_bus_set_wldev(dev, wldev);
b43_debugfs_add_device(wldev);
out:
return err;
err_kfree_wldev:
kfree(wldev);
return err;
}
#define IS_PDEV(pdev, _vendor, _device, _subvendor, _subdevice) ( \
(pdev->vendor == PCI_VENDOR_ID_##_vendor) && \
(pdev->device == _device) && \
(pdev->subsystem_vendor == PCI_VENDOR_ID_##_subvendor) && \
(pdev->subsystem_device == _subdevice) )
#ifdef CONFIG_B43_SSB
static void b43_sprom_fixup(struct ssb_bus *bus)
{
struct pci_dev *pdev;
/* boardflags workarounds */
if (bus->boardinfo.vendor == SSB_BOARDVENDOR_DELL &&
bus->chip_id == 0x4301 && bus->sprom.board_rev == 0x74)
bus->sprom.boardflags_lo |= B43_BFL_BTCOEXIST;
if (bus->boardinfo.vendor == PCI_VENDOR_ID_APPLE &&
bus->boardinfo.type == 0x4E && bus->sprom.board_rev > 0x40)
bus->sprom.boardflags_lo |= B43_BFL_PACTRL;
if (bus->bustype == SSB_BUSTYPE_PCI) {
pdev = bus->host_pci;
if (IS_PDEV(pdev, BROADCOM, 0x4318, ASUSTEK, 0x100F) ||
IS_PDEV(pdev, BROADCOM, 0x4320, DELL, 0x0003) ||
IS_PDEV(pdev, BROADCOM, 0x4320, HP, 0x12f8) ||
IS_PDEV(pdev, BROADCOM, 0x4320, LINKSYS, 0x0015) ||
IS_PDEV(pdev, BROADCOM, 0x4320, LINKSYS, 0x0014) ||
IS_PDEV(pdev, BROADCOM, 0x4320, LINKSYS, 0x0013) ||
IS_PDEV(pdev, BROADCOM, 0x4320, MOTOROLA, 0x7010))
bus->sprom.boardflags_lo &= ~B43_BFL_BTCOEXIST;
}
}
static void b43_wireless_exit(struct b43_bus_dev *dev, struct b43_wl *wl)
{
struct ieee80211_hw *hw = wl->hw;
ssb_set_devtypedata(dev->sdev, NULL);
ieee80211_free_hw(hw);
}
#endif
static struct b43_wl *b43_wireless_init(struct b43_bus_dev *dev)
{
struct ssb_sprom *sprom = dev->bus_sprom;
struct ieee80211_hw *hw;
struct b43_wl *wl;
char chip_name[6];
int queue_num;
hw = ieee80211_alloc_hw(sizeof(*wl), &b43_hw_ops);
if (!hw) {
b43err(NULL, "Could not allocate ieee80211 device\n");
return ERR_PTR(-ENOMEM);
}
wl = hw_to_b43_wl(hw);
/* fill hw info */
hw->flags = IEEE80211_HW_RX_INCLUDES_FCS |
IEEE80211_HW_SIGNAL_DBM;
hw->wiphy->interface_modes =
BIT(NL80211_IFTYPE_AP) |
BIT(NL80211_IFTYPE_MESH_POINT) |
BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_WDS) |
BIT(NL80211_IFTYPE_ADHOC);
hw->wiphy->flags |= WIPHY_FLAG_IBSS_RSN;
wl->hw_registred = false;
hw->max_rates = 2;
SET_IEEE80211_DEV(hw, dev->dev);
if (is_valid_ether_addr(sprom->et1mac))
SET_IEEE80211_PERM_ADDR(hw, sprom->et1mac);
else
SET_IEEE80211_PERM_ADDR(hw, sprom->il0mac);
/* Initialize struct b43_wl */
wl->hw = hw;
mutex_init(&wl->mutex);
spin_lock_init(&wl->hardirq_lock);
INIT_WORK(&wl->beacon_update_trigger, b43_beacon_update_trigger_work);
INIT_WORK(&wl->txpower_adjust_work, b43_phy_txpower_adjust_work);
INIT_WORK(&wl->tx_work, b43_tx_work);
/* Initialize queues and flags. */
for (queue_num = 0; queue_num < B43_QOS_QUEUE_NUM; queue_num++) {
skb_queue_head_init(&wl->tx_queue[queue_num]);
wl->tx_queue_stopped[queue_num] = 0;
}
snprintf(chip_name, ARRAY_SIZE(chip_name),
(dev->chip_id > 0x9999) ? "%d" : "%04X", dev->chip_id);
b43info(wl, "Broadcom %s WLAN found (core revision %u)\n", chip_name,
dev->core_rev);
return wl;
}
#ifdef CONFIG_B43_BCMA
static int b43_bcma_probe(struct bcma_device *core)
{
struct b43_bus_dev *dev;
struct b43_wl *wl;
int err;
if (!modparam_allhwsupport &&
(core->id.rev == 0x17 || core->id.rev == 0x18)) {
pr_err("Support for cores revisions 0x17 and 0x18 disabled by module param allhwsupport=0. Try b43.allhwsupport=1\n");
return -ENOTSUPP;
}
dev = b43_bus_dev_bcma_init(core);
if (!dev)
return -ENODEV;
wl = b43_wireless_init(dev);
if (IS_ERR(wl)) {
err = PTR_ERR(wl);
goto bcma_out;
}
err = b43_one_core_attach(dev, wl);
if (err)
goto bcma_err_wireless_exit;
/* setup and start work to load firmware */
INIT_WORK(&wl->firmware_load, b43_request_firmware);
schedule_work(&wl->firmware_load);
bcma_out:
return err;
bcma_err_wireless_exit:
ieee80211_free_hw(wl->hw);
return err;
}
static void b43_bcma_remove(struct bcma_device *core)
{
struct b43_wldev *wldev = bcma_get_drvdata(core);
struct b43_wl *wl = wldev->wl;
/* We must cancel any work here before unregistering from ieee80211,
* as the ieee80211 unreg will destroy the workqueue. */
cancel_work_sync(&wldev->restart_work);
cancel_work_sync(&wl->firmware_load);
B43_WARN_ON(!wl);
if (!wldev->fw.ucode.data)
return; /* NULL if firmware never loaded */
if (wl->current_dev == wldev && wl->hw_registred) {
b43_leds_stop(wldev);
ieee80211_unregister_hw(wl->hw);
}
b43_one_core_detach(wldev->dev);
/* Unregister HW RNG driver */
b43_rng_exit(wl);
b43_leds_unregister(wl);
ieee80211_free_hw(wl->hw);
}
static struct bcma_driver b43_bcma_driver = {
.name = KBUILD_MODNAME,
.id_table = b43_bcma_tbl,
.probe = b43_bcma_probe,
.remove = b43_bcma_remove,
};
#endif
#ifdef CONFIG_B43_SSB
static
int b43_ssb_probe(struct ssb_device *sdev, const struct ssb_device_id *id)
{
struct b43_bus_dev *dev;
struct b43_wl *wl;
int err;
dev = b43_bus_dev_ssb_init(sdev);
if (!dev)
return -ENOMEM;
wl = ssb_get_devtypedata(sdev);
if (wl) {
b43err(NULL, "Dual-core devices are not supported\n");
err = -ENOTSUPP;
goto err_ssb_kfree_dev;
}
b43_sprom_fixup(sdev->bus);
wl = b43_wireless_init(dev);
if (IS_ERR(wl)) {
err = PTR_ERR(wl);
goto err_ssb_kfree_dev;
}
ssb_set_devtypedata(sdev, wl);
B43_WARN_ON(ssb_get_devtypedata(sdev) != wl);
err = b43_one_core_attach(dev, wl);
if (err)
goto err_ssb_wireless_exit;
/* setup and start work to load firmware */
INIT_WORK(&wl->firmware_load, b43_request_firmware);
schedule_work(&wl->firmware_load);
return err;
err_ssb_wireless_exit:
b43_wireless_exit(dev, wl);
err_ssb_kfree_dev:
kfree(dev);
return err;
}
static void b43_ssb_remove(struct ssb_device *sdev)
{
struct b43_wl *wl = ssb_get_devtypedata(sdev);
struct b43_wldev *wldev = ssb_get_drvdata(sdev);
struct b43_bus_dev *dev = wldev->dev;
/* We must cancel any work here before unregistering from ieee80211,
* as the ieee80211 unreg will destroy the workqueue. */
cancel_work_sync(&wldev->restart_work);
cancel_work_sync(&wl->firmware_load);
B43_WARN_ON(!wl);
if (!wldev->fw.ucode.data)
return; /* NULL if firmware never loaded */
if (wl->current_dev == wldev && wl->hw_registred) {
b43_leds_stop(wldev);
ieee80211_unregister_hw(wl->hw);
}
b43_one_core_detach(dev);
/* Unregister HW RNG driver */
b43_rng_exit(wl);
b43_leds_unregister(wl);
b43_wireless_exit(dev, wl);
}
static struct ssb_driver b43_ssb_driver = {
.name = KBUILD_MODNAME,
.id_table = b43_ssb_tbl,
.probe = b43_ssb_probe,
.remove = b43_ssb_remove,
};
#endif /* CONFIG_B43_SSB */
/* Perform a hardware reset. This can be called from any context. */
void b43_controller_restart(struct b43_wldev *dev, const char *reason)
{
/* Must avoid requeueing, if we are in shutdown. */
if (b43_status(dev) < B43_STAT_INITIALIZED)
return;
b43info(dev->wl, "Controller RESET (%s) ...\n", reason);
ieee80211_queue_work(dev->wl->hw, &dev->restart_work);
}
static void b43_print_driverinfo(void)
{
const char *feat_pci = "", *feat_pcmcia = "", *feat_nphy = "",
*feat_leds = "", *feat_sdio = "";
#ifdef CONFIG_B43_PCI_AUTOSELECT
feat_pci = "P";
#endif
#ifdef CONFIG_B43_PCMCIA
feat_pcmcia = "M";
#endif
#ifdef CONFIG_B43_PHY_N
feat_nphy = "N";
#endif
#ifdef CONFIG_B43_LEDS
feat_leds = "L";
#endif
#ifdef CONFIG_B43_SDIO
feat_sdio = "S";
#endif
printk(KERN_INFO "Broadcom 43xx driver loaded "
"[ Features: %s%s%s%s%s ]\n",
feat_pci, feat_pcmcia, feat_nphy,
feat_leds, feat_sdio);
}
static int __init b43_init(void)
{
int err;
b43_debugfs_init();
err = b43_pcmcia_init();
if (err)
goto err_dfs_exit;
err = b43_sdio_init();
if (err)
goto err_pcmcia_exit;
#ifdef CONFIG_B43_BCMA
err = bcma_driver_register(&b43_bcma_driver);
if (err)
goto err_sdio_exit;
#endif
#ifdef CONFIG_B43_SSB
err = ssb_driver_register(&b43_ssb_driver);
if (err)
goto err_bcma_driver_exit;
#endif
b43_print_driverinfo();
return err;
#ifdef CONFIG_B43_SSB
err_bcma_driver_exit:
#endif
#ifdef CONFIG_B43_BCMA
bcma_driver_unregister(&b43_bcma_driver);
err_sdio_exit:
#endif
b43_sdio_exit();
err_pcmcia_exit:
b43_pcmcia_exit();
err_dfs_exit:
b43_debugfs_exit();
return err;
}
static void __exit b43_exit(void)
{
#ifdef CONFIG_B43_SSB
ssb_driver_unregister(&b43_ssb_driver);
#endif
#ifdef CONFIG_B43_BCMA
bcma_driver_unregister(&b43_bcma_driver);
#endif
b43_sdio_exit();
b43_pcmcia_exit();
b43_debugfs_exit();
}
module_init(b43_init)
module_exit(b43_exit)
| gpl-2.0 |
embeddedarm/linux-vanilla-imx6 | drivers/cpufreq/freq_table.c | 154 | 7687 | /*
* linux/drivers/cpufreq/freq_table.c
*
* Copyright (C) 2002 - 2003 Dominik Brodowski
*
* 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.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/cpufreq.h>
#include <linux/module.h>
/*********************************************************************
* FREQUENCY TABLE HELPERS *
*********************************************************************/
int cpufreq_frequency_table_cpuinfo(struct cpufreq_policy *policy,
struct cpufreq_frequency_table *table)
{
struct cpufreq_frequency_table *pos;
unsigned int min_freq = ~0;
unsigned int max_freq = 0;
unsigned int freq;
cpufreq_for_each_valid_entry(pos, table) {
freq = pos->frequency;
if (!cpufreq_boost_enabled()
&& (pos->flags & CPUFREQ_BOOST_FREQ))
continue;
pr_debug("table entry %u: %u kHz\n", (int)(pos - table), freq);
if (freq < min_freq)
min_freq = freq;
if (freq > max_freq)
max_freq = freq;
}
policy->min = policy->cpuinfo.min_freq = min_freq;
policy->max = policy->cpuinfo.max_freq = max_freq;
if (policy->min == ~0)
return -EINVAL;
else
return 0;
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_table_cpuinfo);
int cpufreq_frequency_table_verify(struct cpufreq_policy *policy,
struct cpufreq_frequency_table *table)
{
struct cpufreq_frequency_table *pos;
unsigned int freq, next_larger = ~0;
bool found = false;
pr_debug("request for verification of policy (%u - %u kHz) for cpu %u\n",
policy->min, policy->max, policy->cpu);
cpufreq_verify_within_cpu_limits(policy);
cpufreq_for_each_valid_entry(pos, table) {
freq = pos->frequency;
if ((freq >= policy->min) && (freq <= policy->max)) {
found = true;
break;
}
if ((next_larger > freq) && (freq > policy->max))
next_larger = freq;
}
if (!found) {
policy->max = next_larger;
cpufreq_verify_within_cpu_limits(policy);
}
pr_debug("verification lead to (%u - %u kHz) for cpu %u\n",
policy->min, policy->max, policy->cpu);
return 0;
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_table_verify);
/*
* Generic routine to verify policy & frequency table, requires driver to set
* policy->freq_table prior to it.
*/
int cpufreq_generic_frequency_table_verify(struct cpufreq_policy *policy)
{
struct cpufreq_frequency_table *table =
cpufreq_frequency_get_table(policy->cpu);
if (!table)
return -ENODEV;
return cpufreq_frequency_table_verify(policy, table);
}
EXPORT_SYMBOL_GPL(cpufreq_generic_frequency_table_verify);
int cpufreq_frequency_table_target(struct cpufreq_policy *policy,
struct cpufreq_frequency_table *table,
unsigned int target_freq,
unsigned int relation,
unsigned int *index)
{
struct cpufreq_frequency_table optimal = {
.driver_data = ~0,
.frequency = 0,
};
struct cpufreq_frequency_table suboptimal = {
.driver_data = ~0,
.frequency = 0,
};
struct cpufreq_frequency_table *pos;
unsigned int freq, diff, i = 0;
pr_debug("request for target %u kHz (relation: %u) for cpu %u\n",
target_freq, relation, policy->cpu);
switch (relation) {
case CPUFREQ_RELATION_H:
suboptimal.frequency = ~0;
break;
case CPUFREQ_RELATION_L:
case CPUFREQ_RELATION_C:
optimal.frequency = ~0;
break;
}
cpufreq_for_each_valid_entry(pos, table) {
freq = pos->frequency;
i = pos - table;
if ((freq < policy->min) || (freq > policy->max))
continue;
if (freq == target_freq) {
optimal.driver_data = i;
break;
}
switch (relation) {
case CPUFREQ_RELATION_H:
if (freq < target_freq) {
if (freq >= optimal.frequency) {
optimal.frequency = freq;
optimal.driver_data = i;
}
} else {
if (freq <= suboptimal.frequency) {
suboptimal.frequency = freq;
suboptimal.driver_data = i;
}
}
break;
case CPUFREQ_RELATION_L:
if (freq > target_freq) {
if (freq <= optimal.frequency) {
optimal.frequency = freq;
optimal.driver_data = i;
}
} else {
if (freq >= suboptimal.frequency) {
suboptimal.frequency = freq;
suboptimal.driver_data = i;
}
}
break;
case CPUFREQ_RELATION_C:
diff = abs(freq - target_freq);
if (diff < optimal.frequency ||
(diff == optimal.frequency &&
freq > table[optimal.driver_data].frequency)) {
optimal.frequency = diff;
optimal.driver_data = i;
}
break;
}
}
if (optimal.driver_data > i) {
if (suboptimal.driver_data > i)
return -EINVAL;
*index = suboptimal.driver_data;
} else
*index = optimal.driver_data;
pr_debug("target index is %u, freq is:%u kHz\n", *index,
table[*index].frequency);
return 0;
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_table_target);
int cpufreq_frequency_table_get_index(struct cpufreq_policy *policy,
unsigned int freq)
{
struct cpufreq_frequency_table *pos, *table;
table = cpufreq_frequency_get_table(policy->cpu);
if (unlikely(!table)) {
pr_debug("%s: Unable to find frequency table\n", __func__);
return -ENOENT;
}
cpufreq_for_each_valid_entry(pos, table)
if (pos->frequency == freq)
return pos - table;
return -EINVAL;
}
EXPORT_SYMBOL_GPL(cpufreq_frequency_table_get_index);
/**
* show_available_freqs - show available frequencies for the specified CPU
*/
static ssize_t show_available_freqs(struct cpufreq_policy *policy, char *buf,
bool show_boost)
{
ssize_t count = 0;
struct cpufreq_frequency_table *pos, *table = policy->freq_table;
if (!table)
return -ENODEV;
cpufreq_for_each_valid_entry(pos, table) {
/*
* show_boost = true and driver_data = BOOST freq
* display BOOST freqs
*
* show_boost = false and driver_data = BOOST freq
* show_boost = true and driver_data != BOOST freq
* continue - do not display anything
*
* show_boost = false and driver_data != BOOST freq
* display NON BOOST freqs
*/
if (show_boost ^ (pos->flags & CPUFREQ_BOOST_FREQ))
continue;
count += sprintf(&buf[count], "%d ", pos->frequency);
}
count += sprintf(&buf[count], "\n");
return count;
}
#define cpufreq_attr_available_freq(_name) \
struct freq_attr cpufreq_freq_attr_##_name##_freqs = \
__ATTR_RO(_name##_frequencies)
/**
* show_scaling_available_frequencies - show available normal frequencies for
* the specified CPU
*/
static ssize_t scaling_available_frequencies_show(struct cpufreq_policy *policy,
char *buf)
{
return show_available_freqs(policy, buf, false);
}
cpufreq_attr_available_freq(scaling_available);
EXPORT_SYMBOL_GPL(cpufreq_freq_attr_scaling_available_freqs);
/**
* show_available_boost_freqs - show available boost frequencies for
* the specified CPU
*/
static ssize_t scaling_boost_frequencies_show(struct cpufreq_policy *policy,
char *buf)
{
return show_available_freqs(policy, buf, true);
}
cpufreq_attr_available_freq(scaling_boost);
EXPORT_SYMBOL_GPL(cpufreq_freq_attr_scaling_boost_freqs);
struct freq_attr *cpufreq_generic_attr[] = {
&cpufreq_freq_attr_scaling_available_freqs,
#ifdef CONFIG_CPU_FREQ_BOOST_SW
&cpufreq_freq_attr_scaling_boost_freqs,
#endif
NULL,
};
EXPORT_SYMBOL_GPL(cpufreq_generic_attr);
int cpufreq_table_validate_and_show(struct cpufreq_policy *policy,
struct cpufreq_frequency_table *table)
{
int ret = cpufreq_frequency_table_cpuinfo(policy, table);
if (!ret)
policy->freq_table = table;
return ret;
}
EXPORT_SYMBOL_GPL(cpufreq_table_validate_and_show);
MODULE_AUTHOR("Dominik Brodowski <linux@brodo.de>");
MODULE_DESCRIPTION("CPUfreq frequency table helpers");
MODULE_LICENSE("GPL");
| gpl-2.0 |
myjang0507/Polaris | drivers/net/wireless/bcmdhd4358a3/dhd_common.c | 154 | 74093 | /*
* Broadcom Dongle Host Driver (DHD), common DHD core.
*
* Copyright (C) 1999-2015, 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: dhd_common.c 531053 2015-02-02 07:23:56Z $
*/
#include <typedefs.h>
#include <osl.h>
#include <epivers.h>
#include <bcmutils.h>
#include <bcmendian.h>
#include <dngl_stats.h>
#include <wlioctl.h>
#include <dhd.h>
#include <dhd_ip.h>
#include <proto/bcmevent.h>
#ifdef SHOW_LOGTRACE
#include <event_log.h>
#endif /* SHOW_LOGTRACE */
#ifdef BCMPCIE
#include <dhd_flowring.h>
#endif
#include <dhd_bus.h>
#include <dhd_proto.h>
#include <dhd_dbg.h>
#include <msgtrace.h>
#ifdef WL_CFG80211
#include <wl_cfg80211.h>
#endif
#ifdef WLBTAMP
#include <proto/bt_amp_hci.h>
#include <dhd_bta.h>
#endif
#ifdef PNO_SUPPORT
#include <dhd_pno.h>
#endif
#ifdef RTT_SUPPORT
#include <dhd_rtt.h>
#endif
#define htod32(i) (i)
#define htod16(i) (i)
#define dtoh32(i) (i)
#define dtoh16(i) (i)
#define htodchanspec(i) (i)
#define dtohchanspec(i) (i)
#ifdef PROP_TXSTATUS
#include <wlfc_proto.h>
#include <dhd_wlfc.h>
#endif
int dhd_msg_level = DHD_ERROR_VAL;
#include <wl_iw.h>
#ifdef SOFTAP
char fw_path2[MOD_PARAM_PATHLEN];
extern bool softap_enabled;
#endif
/* Last connection success/failure status */
uint32 dhd_conn_event;
uint32 dhd_conn_status;
uint32 dhd_conn_reason;
#if defined(SHOW_EVENTS) && defined(SHOW_LOGTRACE)
static int check_event_log_sequence_number(uint32 seq_no);
#endif /* defined(SHOW_EVENTS) && defined(SHOW_LOGTRACE) */
extern int dhd_iscan_request(void * dhdp, uint16 action);
extern void dhd_ind_scan_confirm(void *h, bool status);
extern int dhd_iscan_in_progress(void *h);
void dhd_iscan_lock(void);
void dhd_iscan_unlock(void);
extern int dhd_change_mtu(dhd_pub_t *dhd, int new_mtu, int ifidx);
#if !defined(AP) && defined(WLP2P)
extern int dhd_get_concurrent_capabilites(dhd_pub_t *dhd);
#endif
bool ap_cfg_running = FALSE;
bool ap_fw_loaded = FALSE;
/* Version string to report */
#ifdef DHD_DEBUG
#ifndef SRCBASE
#define SRCBASE "drivers/net/wireless/bcmdhd"
#endif
#define DHD_COMPILED "\nCompiled in " SRCBASE
#endif /* DHD_DEBUG */
#if defined(DHD_DEBUG)
const char dhd_version[] = "Dongle Host Driver, version " EPI_VERSION_STR
DHD_COMPILED " on " __DATE__ " at " __TIME__;
#else
const char dhd_version[] = "\nDongle Host Driver, version " EPI_VERSION_STR "\nCompiled from ";
#endif
void dhd_set_timer(void *bus, uint wdtick);
/* IOVar table */
enum {
IOV_VERSION = 1,
IOV_MSGLEVEL,
IOV_BCMERRORSTR,
IOV_BCMERROR,
IOV_WDTICK,
IOV_DUMP,
IOV_CLEARCOUNTS,
IOV_LOGDUMP,
IOV_LOGCAL,
IOV_LOGSTAMP,
IOV_GPIOOB,
IOV_IOCTLTIMEOUT,
#ifdef WLBTAMP
IOV_HCI_CMD, /* HCI command */
IOV_HCI_ACL_DATA, /* HCI data packet */
#endif
#if defined(DHD_DEBUG)
IOV_CONS,
IOV_DCONSOLE_POLL,
#endif /* defined(DHD_DEBUG) */
#ifdef PROP_TXSTATUS
IOV_PROPTXSTATUS_ENABLE,
IOV_PROPTXSTATUS_MODE,
IOV_PROPTXSTATUS_OPT,
IOV_PROPTXSTATUS_MODULE_IGNORE,
IOV_PROPTXSTATUS_CREDIT_IGNORE,
IOV_PROPTXSTATUS_TXSTATUS_IGNORE,
IOV_PROPTXSTATUS_RXPKT_CHK,
#endif /* PROP_TXSTATUS */
IOV_BUS_TYPE,
IOV_CHANGEMTU,
IOV_HOSTREORDER_FLOWS,
#ifdef DHDTCPACK_SUPPRESS
IOV_TCPACK_SUPPRESS,
#endif /* DHDTCPACK_SUPPRESS */
IOV_AP_ISOLATE,
#ifdef DHD_UNICAST_DHCP
IOV_DHCP_UNICAST,
#endif /* DHD_UNICAST_DHCP */
#ifdef DHD_L2_FILTER
IOV_BLOCK_PING,
#endif
IOV_LAST
};
const bcm_iovar_t dhd_iovars[] = {
{"version", IOV_VERSION, 0, IOVT_BUFFER, sizeof(dhd_version) },
#ifdef DHD_DEBUG
{"msglevel", IOV_MSGLEVEL, 0, IOVT_UINT32, 0 },
#endif /* DHD_DEBUG */
{"bcmerrorstr", IOV_BCMERRORSTR, 0, IOVT_BUFFER, BCME_STRLEN },
{"bcmerror", IOV_BCMERROR, 0, IOVT_INT8, 0 },
{"wdtick", IOV_WDTICK, 0, IOVT_UINT32, 0 },
{"dump", IOV_DUMP, 0, IOVT_BUFFER, DHD_IOCTL_MAXLEN },
#ifdef DHD_DEBUG
{"cons", IOV_CONS, 0, IOVT_BUFFER, 0 },
{"dconpoll", IOV_DCONSOLE_POLL, 0, IOVT_UINT32, 0 },
#endif
{"clearcounts", IOV_CLEARCOUNTS, 0, IOVT_VOID, 0 },
{"gpioob", IOV_GPIOOB, 0, IOVT_UINT32, 0 },
{"ioctl_timeout", IOV_IOCTLTIMEOUT, 0, IOVT_UINT32, 0 },
#ifdef WLBTAMP
{"HCI_cmd", IOV_HCI_CMD, 0, IOVT_BUFFER, 0},
{"HCI_ACL_data", IOV_HCI_ACL_DATA, 0, IOVT_BUFFER, 0},
#endif
#ifdef PROP_TXSTATUS
{"proptx", IOV_PROPTXSTATUS_ENABLE, 0, IOVT_BOOL, 0 },
/*
set the proptxtstatus operation mode:
0 - Do not do any proptxtstatus flow control
1 - Use implied credit from a packet status
2 - Use explicit credit
*/
{"ptxmode", IOV_PROPTXSTATUS_MODE, 0, IOVT_UINT32, 0 },
{"proptx_opt", IOV_PROPTXSTATUS_OPT, 0, IOVT_UINT32, 0 },
{"pmodule_ignore", IOV_PROPTXSTATUS_MODULE_IGNORE, 0, IOVT_BOOL, 0 },
{"pcredit_ignore", IOV_PROPTXSTATUS_CREDIT_IGNORE, 0, IOVT_BOOL, 0 },
{"ptxstatus_ignore", IOV_PROPTXSTATUS_TXSTATUS_IGNORE, 0, IOVT_BOOL, 0 },
{"rxpkt_chk", IOV_PROPTXSTATUS_RXPKT_CHK, 0, IOVT_BOOL, 0 },
#endif /* PROP_TXSTATUS */
{"bustype", IOV_BUS_TYPE, 0, IOVT_UINT32, 0},
{"changemtu", IOV_CHANGEMTU, 0, IOVT_UINT32, 0 },
{"host_reorder_flows", IOV_HOSTREORDER_FLOWS, 0, IOVT_BUFFER,
(WLHOST_REORDERDATA_MAXFLOWS + 1) },
#ifdef DHDTCPACK_SUPPRESS
{"tcpack_suppress", IOV_TCPACK_SUPPRESS, 0, IOVT_UINT8, 0 },
#endif /* DHDTCPACK_SUPPRESS */
#ifdef DHD_UNICAST_DHCP
{"dhcp_unicast", IOV_DHCP_UNICAST, (0), IOVT_BOOL, 0 },
#endif /* DHD_UNICAST_DHCP */
{"ap_isolate", IOV_AP_ISOLATE, (0), IOVT_BOOL, 0},
#ifdef DHD_L2_FILTER
{"block_ping", IOV_BLOCK_PING, (0), IOVT_BOOL, 0},
#endif
{NULL, 0, 0, 0, 0 }
};
#define DHD_IOVAR_BUF_SIZE 128
void dhd_save_fwdump(dhd_pub_t *dhd_pub, void * buffer, uint32 length)
{
if (dhd_pub->soc_ram == NULL) {
#ifdef USE_STATIC_MEMDUMP
dhd_pub->soc_ram = (uint8*)DHD_OS_PREALLOC(dhd_pub,
DHD_PREALLOC_MEMDUMP_RAM, length);
#else
dhd_pub->soc_ram = (uint8*) MALLOC(dhd_pub->osh, length);
#endif /* USE_STATIC_MEMDUMP */
if (dhd_pub->soc_ram == NULL) {
DHD_ERROR(("%s: Failed to allocate memory for fw crash snap shot.\n",
__FUNCTION__));
return;
}
}
memset(dhd_pub->soc_ram, 0, length);
dhd_pub->soc_ram_length = length;
memcpy(dhd_pub->soc_ram, buffer, length);
}
/* to NDIS developer, the structure dhd_common is redundant,
* please do NOT merge it back from other branches !!!
*/
static int
dhd_dump(dhd_pub_t *dhdp, char *buf, int buflen)
{
char eabuf[ETHER_ADDR_STR_LEN];
struct bcmstrbuf b;
struct bcmstrbuf *strbuf = &b;
bcm_binit(strbuf, buf, buflen);
/* Base DHD info */
bcm_bprintf(strbuf, "%s\n", dhd_version);
bcm_bprintf(strbuf, "\n");
bcm_bprintf(strbuf, "pub.up %d pub.txoff %d pub.busstate %d\n",
dhdp->up, dhdp->txoff, dhdp->busstate);
bcm_bprintf(strbuf, "pub.hdrlen %u pub.maxctl %u pub.rxsz %u\n",
dhdp->hdrlen, dhdp->maxctl, dhdp->rxsz);
bcm_bprintf(strbuf, "pub.iswl %d pub.drv_version %ld pub.mac %s\n",
dhdp->iswl, dhdp->drv_version, bcm_ether_ntoa(&dhdp->mac, eabuf));
bcm_bprintf(strbuf, "pub.bcmerror %d tickcnt %u\n", dhdp->bcmerror, dhdp->tickcnt);
bcm_bprintf(strbuf, "dongle stats:\n");
bcm_bprintf(strbuf, "tx_packets %lu tx_bytes %lu tx_errors %lu tx_dropped %lu\n",
dhdp->dstats.tx_packets, dhdp->dstats.tx_bytes,
dhdp->dstats.tx_errors, dhdp->dstats.tx_dropped);
bcm_bprintf(strbuf, "rx_packets %lu rx_bytes %lu rx_errors %lu rx_dropped %lu\n",
dhdp->dstats.rx_packets, dhdp->dstats.rx_bytes,
dhdp->dstats.rx_errors, dhdp->dstats.rx_dropped);
bcm_bprintf(strbuf, "multicast %lu\n", dhdp->dstats.multicast);
bcm_bprintf(strbuf, "bus stats:\n");
bcm_bprintf(strbuf, "tx_packets %lu tx_dropped %lu tx_multicast %lu tx_errors %lu\n",
dhdp->tx_packets, dhdp->tx_dropped, dhdp->tx_multicast, dhdp->tx_errors);
bcm_bprintf(strbuf, "tx_ctlpkts %lu tx_ctlerrs %lu\n",
dhdp->tx_ctlpkts, dhdp->tx_ctlerrs);
bcm_bprintf(strbuf, "rx_packets %lu rx_multicast %lu rx_errors %lu \n",
dhdp->rx_packets, dhdp->rx_multicast, dhdp->rx_errors);
bcm_bprintf(strbuf, "rx_ctlpkts %lu rx_ctlerrs %lu rx_dropped %lu\n",
dhdp->rx_ctlpkts, dhdp->rx_ctlerrs, dhdp->rx_dropped);
bcm_bprintf(strbuf, "rx_readahead_cnt %lu tx_realloc %lu\n",
dhdp->rx_readahead_cnt, dhdp->tx_realloc);
bcm_bprintf(strbuf, "\n");
/* Add any prot info */
dhd_prot_dump(dhdp, strbuf);
bcm_bprintf(strbuf, "\n");
/* Add any bus info */
dhd_bus_dump(dhdp, strbuf);
return (!strbuf->size ? BCME_BUFTOOSHORT : 0);
}
void
dhd_dump_to_kernelog(dhd_pub_t *dhdp)
{
char buf[512];
bcm_bprintf_bypass = TRUE;
dhd_dump(dhdp, buf, sizeof(buf));
bcm_bprintf_bypass = FALSE;
}
int
dhd_wl_ioctl_cmd(dhd_pub_t *dhd_pub, int cmd, void *arg, int len, uint8 set, int ifidx)
{
wl_ioctl_t ioc;
ioc.cmd = cmd;
ioc.buf = arg;
ioc.len = len;
ioc.set = set;
return dhd_wl_ioctl(dhd_pub, ifidx, &ioc, arg, len);
}
int
dhd_wl_ioctl(dhd_pub_t *dhd_pub, int ifidx, wl_ioctl_t *ioc, void *buf, int len)
{
int ret = BCME_ERROR;
if (dhd_os_proto_block(dhd_pub))
{
ret = dhd_prot_ioctl(dhd_pub, ifidx, ioc, buf, len);
if (ret && dhd_pub->up) {
/* Send hang event only if dhd_open() was success */
dhd_os_check_hang(dhd_pub, ifidx, ret);
}
if (ret == -ETIMEDOUT && !dhd_pub->up) {
DHD_ERROR(("%s: 'resumed on timeout' error is "
"occurred before the interface does not"
" bring up\n", __FUNCTION__));
dhd_pub->busstate = DHD_BUS_DOWN;
}
dhd_os_proto_unblock(dhd_pub);
if (ret < 0) {
if (ioc->cmd == WLC_GET_VAR || ioc->cmd == WLC_SET_VAR) {
if (ret == BCME_UNSUPPORTED || ret == BCME_NOTASSOCIATED) {
DHD_ERROR(("%s: %s: %s, %s\n",
__FUNCTION__, ioc->cmd == WLC_GET_VAR ?
"WLC_GET_VAR" : "WLC_SET_VAR",
(char *)ioc->buf,
ret == BCME_UNSUPPORTED ? "UNSUPPORTED"
: "NOT ASSOCIATED"));
} else {
DHD_ERROR(("%s: %s: %s, ret = %d\n",
__FUNCTION__, ioc->cmd == WLC_GET_VAR ?
"WLC_GET_VAR" : "WLC_SET_VAR",
(char *)ioc->buf, ret));
}
} else {
if (ret == BCME_UNSUPPORTED || ret == BCME_NOTASSOCIATED) {
DHD_ERROR(("%s: WLC_IOCTL: cmd: %d, %s\n",
__FUNCTION__, ioc->cmd,
ret == BCME_UNSUPPORTED ? "UNSUPPORTED" :
"NOT ASSOCIATED"));
} else {
DHD_ERROR(("%s: WLC_IOCTL: cmd: %d, ret = %d\n",
__FUNCTION__, ioc->cmd, ret));
}
}
}
}
return ret;
}
uint wl_get_port_num(wl_io_pport_t *io_pport)
{
return 0;
}
/* Get bssidx from iovar params
* Input: dhd_pub - pointer to dhd_pub_t
* params - IOVAR params
* Output: idx - BSS index
* val - ponter to the IOVAR arguments
*/
static int
dhd_iovar_parse_bssidx(dhd_pub_t *dhd_pub, char *params, int *idx, char **val)
{
char *prefix = "bsscfg:";
uint32 bssidx;
if (!(strncmp(params, prefix, strlen(prefix)))) {
/* per bss setting should be prefixed with 'bsscfg:' */
char *p = (char *)params + strlen(prefix);
/* Skip Name */
while (*p != '\0')
p++;
/* consider null */
p = p + 1;
bcopy(p, &bssidx, sizeof(uint32));
/* Get corresponding dhd index */
bssidx = dhd_bssidx2idx(dhd_pub, bssidx);
if (bssidx >= DHD_MAX_IFS) {
DHD_ERROR(("%s Wrong bssidx provided\n", __FUNCTION__));
return BCME_ERROR;
}
/* skip bss idx */
p += sizeof(uint32);
*val = p;
*idx = bssidx;
} else {
DHD_ERROR(("%s: bad parameter for per bss iovar\n", __FUNCTION__));
return BCME_ERROR;
}
return BCME_OK;
}
static int
dhd_doiovar(dhd_pub_t *dhd_pub, const bcm_iovar_t *vi, uint32 actionid, const char *name,
void *params, int plen, void *arg, int len, int val_size)
{
int bcmerror = 0;
int32 int_val = 0;
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
DHD_TRACE(("%s: actionid = %d; name %s\n", __FUNCTION__, actionid, name));
if ((bcmerror = bcm_iovar_lencheck(vi, arg, len, IOV_ISSET(actionid))) != 0)
goto exit;
if (plen >= (int)sizeof(int_val))
bcopy(params, &int_val, sizeof(int_val));
switch (actionid) {
case IOV_GVAL(IOV_VERSION):
/* Need to have checked buffer length */
bcm_strncpy_s((char*)arg, len, dhd_version, len);
break;
case IOV_GVAL(IOV_MSGLEVEL):
int_val = (int32)dhd_msg_level;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_MSGLEVEL):
#ifdef WL_CFG80211
/* Enable DHD and WL logs in oneshot */
if (int_val & DHD_WL_VAL2)
wl_cfg80211_enable_trace(TRUE, int_val & (~DHD_WL_VAL2));
else if (int_val & DHD_WL_VAL)
wl_cfg80211_enable_trace(FALSE, WL_DBG_DBG);
if (!(int_val & DHD_WL_VAL2))
#endif /* WL_CFG80211 */
dhd_msg_level = int_val;
break;
case IOV_GVAL(IOV_BCMERRORSTR):
bcm_strncpy_s((char *)arg, len, bcmerrorstr(dhd_pub->bcmerror), BCME_STRLEN);
((char *)arg)[BCME_STRLEN - 1] = 0x00;
break;
case IOV_GVAL(IOV_BCMERROR):
int_val = (int32)dhd_pub->bcmerror;
bcopy(&int_val, arg, val_size);
break;
case IOV_GVAL(IOV_WDTICK):
int_val = (int32)dhd_watchdog_ms;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_WDTICK):
if (!dhd_pub->up) {
bcmerror = BCME_NOTUP;
break;
}
dhd_os_wd_timer(dhd_pub, (uint)int_val);
break;
case IOV_GVAL(IOV_DUMP):
bcmerror = dhd_dump(dhd_pub, arg, len);
break;
#ifdef DHD_DEBUG
case IOV_GVAL(IOV_DCONSOLE_POLL):
int_val = (int32)dhd_console_ms;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_DCONSOLE_POLL):
dhd_console_ms = (uint)int_val;
break;
case IOV_SVAL(IOV_CONS):
if (len > 0)
bcmerror = dhd_bus_console_in(dhd_pub, arg, len - 1);
break;
#endif /* DHD_DEBUG */
case IOV_SVAL(IOV_CLEARCOUNTS):
dhd_pub->tx_packets = dhd_pub->rx_packets = 0;
dhd_pub->tx_errors = dhd_pub->rx_errors = 0;
dhd_pub->tx_ctlpkts = dhd_pub->rx_ctlpkts = 0;
dhd_pub->tx_ctlerrs = dhd_pub->rx_ctlerrs = 0;
dhd_pub->tx_dropped = 0;
dhd_pub->rx_dropped = 0;
dhd_pub->rx_readahead_cnt = 0;
dhd_pub->tx_realloc = 0;
dhd_pub->wd_dpc_sched = 0;
memset(&dhd_pub->dstats, 0, sizeof(dhd_pub->dstats));
dhd_bus_clearcounts(dhd_pub);
#ifdef PROP_TXSTATUS
/* clear proptxstatus related counters */
dhd_wlfc_clear_counts(dhd_pub);
#endif /* PROP_TXSTATUS */
break;
case IOV_GVAL(IOV_IOCTLTIMEOUT): {
int_val = (int32)dhd_os_get_ioctl_resp_timeout();
bcopy(&int_val, arg, sizeof(int_val));
break;
}
case IOV_SVAL(IOV_IOCTLTIMEOUT): {
if (int_val <= 0)
bcmerror = BCME_BADARG;
else
dhd_os_set_ioctl_resp_timeout((unsigned int)int_val);
break;
}
#ifdef WLBTAMP
case IOV_SVAL(IOV_HCI_CMD): {
amp_hci_cmd_t *cmd = (amp_hci_cmd_t *)arg;
/* sanity check: command preamble present */
if (len < HCI_CMD_PREAMBLE_SIZE)
return BCME_BUFTOOSHORT;
/* sanity check: command parameters are present */
if (len < (int)(HCI_CMD_PREAMBLE_SIZE + cmd->plen))
return BCME_BUFTOOSHORT;
dhd_bta_docmd(dhd_pub, cmd, len);
break;
}
case IOV_SVAL(IOV_HCI_ACL_DATA): {
amp_hci_ACL_data_t *ACL_data = (amp_hci_ACL_data_t *)arg;
/* sanity check: HCI header present */
if (len < HCI_ACL_DATA_PREAMBLE_SIZE)
return BCME_BUFTOOSHORT;
/* sanity check: ACL data is present */
if (len < (int)(HCI_ACL_DATA_PREAMBLE_SIZE + ACL_data->dlen))
return BCME_BUFTOOSHORT;
dhd_bta_tx_hcidata(dhd_pub, ACL_data, len);
break;
}
#endif /* WLBTAMP */
#ifdef PROP_TXSTATUS
case IOV_GVAL(IOV_PROPTXSTATUS_ENABLE): {
bool wlfc_enab = FALSE;
bcmerror = dhd_wlfc_get_enable(dhd_pub, &wlfc_enab);
if (bcmerror != BCME_OK)
goto exit;
int_val = wlfc_enab ? 1 : 0;
bcopy(&int_val, arg, val_size);
break;
}
case IOV_SVAL(IOV_PROPTXSTATUS_ENABLE): {
bool wlfc_enab = FALSE;
bcmerror = dhd_wlfc_get_enable(dhd_pub, &wlfc_enab);
if (bcmerror != BCME_OK)
goto exit;
/* wlfc is already set as desired */
if (wlfc_enab == (int_val == 0 ? FALSE : TRUE))
goto exit;
if (int_val == TRUE)
bcmerror = dhd_wlfc_init(dhd_pub);
else
bcmerror = dhd_wlfc_deinit(dhd_pub);
break;
}
case IOV_GVAL(IOV_PROPTXSTATUS_MODE):
bcmerror = dhd_wlfc_get_mode(dhd_pub, &int_val);
if (bcmerror != BCME_OK)
goto exit;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_PROPTXSTATUS_MODE):
dhd_wlfc_set_mode(dhd_pub, int_val);
break;
case IOV_GVAL(IOV_PROPTXSTATUS_MODULE_IGNORE):
bcmerror = dhd_wlfc_get_module_ignore(dhd_pub, &int_val);
if (bcmerror != BCME_OK)
goto exit;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_PROPTXSTATUS_MODULE_IGNORE):
dhd_wlfc_set_module_ignore(dhd_pub, int_val);
break;
case IOV_GVAL(IOV_PROPTXSTATUS_CREDIT_IGNORE):
bcmerror = dhd_wlfc_get_credit_ignore(dhd_pub, &int_val);
if (bcmerror != BCME_OK)
goto exit;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_PROPTXSTATUS_CREDIT_IGNORE):
dhd_wlfc_set_credit_ignore(dhd_pub, int_val);
break;
case IOV_GVAL(IOV_PROPTXSTATUS_TXSTATUS_IGNORE):
bcmerror = dhd_wlfc_get_txstatus_ignore(dhd_pub, &int_val);
if (bcmerror != BCME_OK)
goto exit;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_PROPTXSTATUS_TXSTATUS_IGNORE):
dhd_wlfc_set_txstatus_ignore(dhd_pub, int_val);
break;
case IOV_GVAL(IOV_PROPTXSTATUS_RXPKT_CHK):
bcmerror = dhd_wlfc_get_rxpkt_chk(dhd_pub, &int_val);
if (bcmerror != BCME_OK)
goto exit;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_PROPTXSTATUS_RXPKT_CHK):
dhd_wlfc_set_rxpkt_chk(dhd_pub, int_val);
break;
#endif /* PROP_TXSTATUS */
case IOV_GVAL(IOV_BUS_TYPE):
/* The dhd application queries the driver to check if its usb or sdio. */
#ifdef BCMDHDUSB
int_val = BUS_TYPE_USB;
#endif
#ifdef BCMSDIO
int_val = BUS_TYPE_SDIO;
#endif
#ifdef PCIE_FULL_DONGLE
int_val = BUS_TYPE_PCIE;
#endif
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_CHANGEMTU):
int_val &= 0xffff;
bcmerror = dhd_change_mtu(dhd_pub, int_val, 0);
break;
case IOV_GVAL(IOV_HOSTREORDER_FLOWS):
{
uint i = 0;
uint8 *ptr = (uint8 *)arg;
uint8 count = 0;
ptr++;
for (i = 0; i < WLHOST_REORDERDATA_MAXFLOWS; i++) {
if (dhd_pub->reorder_bufs[i] != NULL) {
*ptr = dhd_pub->reorder_bufs[i]->flow_id;
ptr++;
count++;
}
}
ptr = (uint8 *)arg;
*ptr = count;
break;
}
#ifdef DHDTCPACK_SUPPRESS
case IOV_GVAL(IOV_TCPACK_SUPPRESS): {
int_val = (uint32)dhd_pub->tcpack_sup_mode;
bcopy(&int_val, arg, val_size);
break;
}
case IOV_SVAL(IOV_TCPACK_SUPPRESS): {
bcmerror = dhd_tcpack_suppress_set(dhd_pub, (uint8)int_val);
break;
}
#endif /* DHDTCPACK_SUPPRESS */
#ifdef DHD_UNICAST_DHCP
case IOV_GVAL(IOV_DHCP_UNICAST):
int_val = dhd_pub->dhcp_unicast;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_DHCP_UNICAST):
if (dhd_pub->dhcp_unicast == int_val)
break;
if (int_val >= OFF || int_val <= ON) {
dhd_pub->dhcp_unicast = int_val;
} else {
bcmerror = BCME_RANGE;
}
break;
#endif /* DHD_UNICAST_DHCP */
#ifdef DHD_L2_FILTER
case IOV_GVAL(IOV_BLOCK_PING):
int_val = dhd_pub->block_ping;
bcopy(&int_val, arg, val_size);
break;
case IOV_SVAL(IOV_BLOCK_PING):
if (dhd_pub->block_ping == int_val)
break;
if (int_val >= OFF || int_val <= ON) {
dhd_pub->block_ping = int_val;
} else {
bcmerror = BCME_RANGE;
}
break;
#endif
case IOV_GVAL(IOV_AP_ISOLATE): {
uint32 bssidx;
char *val;
if (dhd_iovar_parse_bssidx(dhd_pub, (char *)name, &bssidx, &val) != BCME_OK) {
DHD_ERROR(("%s: ap isoalate: bad parameter\n", __FUNCTION__));
bcmerror = BCME_BADARG;
break;
}
int_val = dhd_get_ap_isolate(dhd_pub, bssidx);
bcopy(&int_val, arg, val_size);
break;
}
case IOV_SVAL(IOV_AP_ISOLATE): {
uint32 bssidx;
char *val;
if (dhd_iovar_parse_bssidx(dhd_pub, (char *)name, &bssidx, &val) != BCME_OK) {
DHD_ERROR(("%s: ap isolate: bad parameter\n", __FUNCTION__));
bcmerror = BCME_BADARG;
break;
}
ASSERT(val);
bcopy(val, &int_val, sizeof(uint32));
dhd_set_ap_isolate(dhd_pub, bssidx, int_val);
break;
}
default:
bcmerror = BCME_UNSUPPORTED;
break;
}
exit:
DHD_TRACE(("%s: actionid %d, bcmerror %d\n", __FUNCTION__, actionid, bcmerror));
return bcmerror;
}
/* Store the status of a connection attempt for later retrieval by an iovar */
void
dhd_store_conn_status(uint32 event, uint32 status, uint32 reason)
{
/* Do not overwrite a WLC_E_PRUNE with a WLC_E_SET_SSID
* because an encryption/rsn mismatch results in both events, and
* the important information is in the WLC_E_PRUNE.
*/
if (!(event == WLC_E_SET_SSID && status == WLC_E_STATUS_FAIL &&
dhd_conn_event == WLC_E_PRUNE)) {
dhd_conn_event = event;
dhd_conn_status = status;
dhd_conn_reason = reason;
}
}
bool
dhd_prec_enq(dhd_pub_t *dhdp, struct pktq *q, void *pkt, int prec)
{
void *p;
int eprec = -1; /* precedence to evict from */
bool discard_oldest;
/* Fast case, precedence queue is not full and we are also not
* exceeding total queue length
*/
if (!pktq_pfull(q, prec) && !pktq_full(q)) {
pktq_penq(q, prec, pkt);
return TRUE;
}
/* Determine precedence from which to evict packet, if any */
if (pktq_pfull(q, prec))
eprec = prec;
else if (pktq_full(q)) {
p = pktq_peek_tail(q, &eprec);
ASSERT(p);
if (eprec > prec || eprec < 0)
return FALSE;
}
/* Evict if needed */
if (eprec >= 0) {
/* Detect queueing to unconfigured precedence */
ASSERT(!pktq_pempty(q, eprec));
discard_oldest = AC_BITMAP_TST(dhdp->wme_dp, eprec);
if (eprec == prec && !discard_oldest)
return FALSE; /* refuse newer (incoming) packet */
/* Evict packet according to discard policy */
p = discard_oldest ? pktq_pdeq(q, eprec) : pktq_pdeq_tail(q, eprec);
ASSERT(p);
#ifdef DHDTCPACK_SUPPRESS
if (dhd_tcpack_check_xmit(dhdp, p) == BCME_ERROR) {
DHD_ERROR(("%s %d: tcpack_suppress ERROR!!! Stop using it\n",
__FUNCTION__, __LINE__));
dhd_tcpack_suppress_set(dhdp, TCPACK_SUP_OFF);
}
#endif /* DHDTCPACK_SUPPRESS */
PKTFREE(dhdp->osh, p, TRUE);
}
/* Enqueue */
p = pktq_penq(q, prec, pkt);
ASSERT(p);
return TRUE;
}
/*
* Functions to drop proper pkts from queue:
* If one pkt in queue is non-fragmented, drop first non-fragmented pkt only
* If all pkts in queue are all fragmented, find and drop one whole set fragmented pkts
* If can't find pkts matching upper 2 cases, drop first pkt anyway
*/
bool
dhd_prec_drop_pkts(dhd_pub_t *dhdp, struct pktq *pq, int prec, f_droppkt_t fn)
{
struct pktq_prec *q = NULL;
void *p, *prev = NULL, *next = NULL, *first = NULL, *last = NULL, *prev_first = NULL;
pkt_frag_t frag_info;
ASSERT(dhdp && pq);
ASSERT(prec >= 0 && prec < pq->num_prec);
q = &pq->q[prec];
p = q->head;
if (p == NULL)
return FALSE;
while (p) {
frag_info = pkt_frag_info(dhdp->osh, p);
if (frag_info == DHD_PKT_FRAG_NONE) {
break;
} else if (frag_info == DHD_PKT_FRAG_FIRST) {
if (first) {
/* No last frag pkt, use prev as last */
last = prev;
break;
} else {
first = p;
prev_first = prev;
}
} else if (frag_info == DHD_PKT_FRAG_LAST) {
if (first) {
last = p;
break;
}
}
prev = p;
p = PKTLINK(p);
}
if ((p == NULL) || ((frag_info != DHD_PKT_FRAG_NONE) && !(first && last))) {
/* Not found matching pkts, use oldest */
prev = NULL;
p = q->head;
frag_info = 0;
}
if (frag_info == DHD_PKT_FRAG_NONE) {
first = last = p;
prev_first = prev;
}
p = first;
while (p) {
next = PKTLINK(p);
q->len--;
pq->len--;
PKTSETLINK(p, NULL);
if (fn)
fn(dhdp, prec, p, TRUE);
if (p == last)
break;
p = next;
}
if (prev_first == NULL) {
if ((q->head = next) == NULL)
q->tail = NULL;
} else {
PKTSETLINK(prev_first, next);
if (!next)
q->tail = prev_first;
}
return TRUE;
}
static int
dhd_iovar_op(dhd_pub_t *dhd_pub, const char *name,
void *params, int plen, void *arg, int len, bool set)
{
int bcmerror = 0;
int val_size;
const bcm_iovar_t *vi = NULL;
uint32 actionid;
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
ASSERT(name);
ASSERT(len >= 0);
/* Get MUST have return space */
ASSERT(set || (arg && len));
/* Set does NOT take qualifiers */
ASSERT(!set || (!params && !plen));
if ((vi = bcm_iovar_lookup(dhd_iovars, name)) == NULL) {
bcmerror = BCME_UNSUPPORTED;
goto exit;
}
DHD_CTL(("%s: %s %s, len %d plen %d\n", __FUNCTION__,
name, (set ? "set" : "get"), len, plen));
/* set up 'params' pointer in case this is a set command so that
* the convenience int and bool code can be common to set and get
*/
if (params == NULL) {
params = arg;
plen = len;
}
if (vi->type == IOVT_VOID)
val_size = 0;
else if (vi->type == IOVT_BUFFER)
val_size = len;
else
/* all other types are integer sized */
val_size = sizeof(int);
actionid = set ? IOV_SVAL(vi->varid) : IOV_GVAL(vi->varid);
bcmerror = dhd_doiovar(dhd_pub, vi, actionid, name, params, plen, arg, len, val_size);
exit:
return bcmerror;
}
int
dhd_ioctl(dhd_pub_t * dhd_pub, dhd_ioctl_t *ioc, void * buf, uint buflen)
{
int bcmerror = 0;
DHD_TRACE(("%s: Enter\n", __FUNCTION__));
if (!buf) {
return BCME_BADARG;
}
switch (ioc->cmd) {
case DHD_GET_MAGIC:
if (buflen < sizeof(int))
bcmerror = BCME_BUFTOOSHORT;
else
*(int*)buf = DHD_IOCTL_MAGIC;
break;
case DHD_GET_VERSION:
if (buflen < sizeof(int))
bcmerror = BCME_BUFTOOSHORT;
else
*(int*)buf = DHD_IOCTL_VERSION;
break;
case DHD_GET_VAR:
case DHD_SET_VAR: {
char *arg;
uint arglen;
/* scan past the name to any arguments */
for (arg = buf, arglen = buflen; *arg && arglen; arg++, arglen--)
;
if (*arg) {
bcmerror = BCME_BUFTOOSHORT;
break;
}
/* account for the NUL terminator */
arg++, arglen--;
/* call with the appropriate arguments */
if (ioc->cmd == DHD_GET_VAR)
bcmerror = dhd_iovar_op(dhd_pub, buf, arg, arglen,
buf, buflen, IOV_GET);
else
bcmerror = dhd_iovar_op(dhd_pub, buf, NULL, 0, arg, arglen, IOV_SET);
if (bcmerror != BCME_UNSUPPORTED)
break;
/* not in generic table, try protocol module */
if (ioc->cmd == DHD_GET_VAR)
bcmerror = dhd_prot_iovar_op(dhd_pub, buf, arg,
arglen, buf, buflen, IOV_GET);
else
bcmerror = dhd_prot_iovar_op(dhd_pub, buf,
NULL, 0, arg, arglen, IOV_SET);
if (bcmerror != BCME_UNSUPPORTED)
break;
/* if still not found, try bus module */
if (ioc->cmd == DHD_GET_VAR) {
bcmerror = dhd_bus_iovar_op(dhd_pub, buf,
arg, arglen, buf, buflen, IOV_GET);
} else {
bcmerror = dhd_bus_iovar_op(dhd_pub, buf,
NULL, 0, arg, arglen, IOV_SET);
}
break;
}
default:
bcmerror = BCME_UNSUPPORTED;
}
return bcmerror;
}
#ifdef SHOW_EVENTS
#ifdef SHOW_LOGTRACE
#define AVOID_BYTE 64
#define MAX_NO_OF_ARG 16
static int
check_event_log_sequence_number(uint32 seq_no)
{
int32 diff;
uint32 ret;
static uint32 logtrace_seqnum_prev = 0;
diff = ntoh32(seq_no)-logtrace_seqnum_prev;
switch (diff)
{
case 0:
ret = -1; /* duplicate packet . drop */
break;
case 1:
ret =0; /* in order */
break;
default:
if ((ntoh32(seq_no) == 0) &&
(logtrace_seqnum_prev == 0xFFFFFFFF) ) { /* in-order - Roll over */
ret = 0;
} else {
if (diff > 0) {
DHD_EVENT(("WLC_E_TRACE:"
"Event lost (log) seqnum %d nblost %d\n",
ntoh32(seq_no), (diff-1)));
} else {
DHD_EVENT(("WLC_E_TRACE:"
"Event Packets coming out of order!!\n"));
}
ret = 0;
}
}
logtrace_seqnum_prev = ntoh32(seq_no);
return ret;
}
#endif /* SHOW_LOGTRACE */
static void
wl_show_host_event(dhd_pub_t *dhd_pub, wl_event_msg_t *event, void *event_data,
void *raw_event_ptr, char *eventmask)
{
uint i, status, reason;
bool group = FALSE, flush_txq = FALSE, link = FALSE;
const char *auth_str;
const char *event_name;
uchar *buf;
char err_msg[256], eabuf[ETHER_ADDR_STR_LEN];
uint event_type, flags, auth_type, datalen;
event_type = ntoh32(event->event_type);
flags = ntoh16(event->flags);
status = ntoh32(event->status);
reason = ntoh32(event->reason);
BCM_REFERENCE(reason);
auth_type = ntoh32(event->auth_type);
datalen = ntoh32(event->datalen);
/* debug dump of event messages */
snprintf(eabuf, sizeof(eabuf), "%02x:%02x:%02x:%02x:%02x:%02x",
(uchar)event->addr.octet[0]&0xff,
(uchar)event->addr.octet[1]&0xff,
(uchar)event->addr.octet[2]&0xff,
(uchar)event->addr.octet[3]&0xff,
(uchar)event->addr.octet[4]&0xff,
(uchar)event->addr.octet[5]&0xff);
event_name = bcmevent_get_name(event_type);
BCM_REFERENCE(event_name);
if (flags & WLC_EVENT_MSG_LINK)
link = TRUE;
if (flags & WLC_EVENT_MSG_GROUP)
group = TRUE;
if (flags & WLC_EVENT_MSG_FLUSHTXQ)
flush_txq = TRUE;
switch (event_type) {
case WLC_E_START:
case WLC_E_DEAUTH:
case WLC_E_DISASSOC:
DHD_EVENT(("MACEVENT: %s, MAC %s\n", event_name, eabuf));
break;
case WLC_E_ASSOC_IND:
case WLC_E_REASSOC_IND:
DHD_EVENT(("MACEVENT: %s, MAC %s\n", event_name, eabuf));
break;
case WLC_E_ASSOC:
case WLC_E_REASSOC:
if (status == WLC_E_STATUS_SUCCESS) {
DHD_EVENT(("MACEVENT: %s, MAC %s, SUCCESS\n", event_name, eabuf));
} else if (status == WLC_E_STATUS_TIMEOUT) {
DHD_EVENT(("MACEVENT: %s, MAC %s, TIMEOUT\n", event_name, eabuf));
} else if (status == WLC_E_STATUS_FAIL) {
DHD_EVENT(("MACEVENT: %s, MAC %s, FAILURE, reason %d\n",
event_name, eabuf, (int)reason));
} else {
DHD_EVENT(("MACEVENT: %s, MAC %s, unexpected status %d\n",
event_name, eabuf, (int)status));
}
break;
case WLC_E_DEAUTH_IND:
case WLC_E_DISASSOC_IND:
DHD_EVENT(("MACEVENT: %s, MAC %s, reason %d\n", event_name, eabuf, (int)reason));
break;
case WLC_E_AUTH:
case WLC_E_AUTH_IND:
if (auth_type == DOT11_OPEN_SYSTEM)
auth_str = "Open System";
else if (auth_type == DOT11_SHARED_KEY)
auth_str = "Shared Key";
else {
snprintf(err_msg, sizeof(err_msg), "AUTH unknown: %d", (int)auth_type);
auth_str = err_msg;
}
if (event_type == WLC_E_AUTH_IND) {
DHD_EVENT(("MACEVENT: %s, MAC %s, %s\n", event_name, eabuf, auth_str));
} else if (status == WLC_E_STATUS_SUCCESS) {
DHD_EVENT(("MACEVENT: %s, MAC %s, %s, SUCCESS\n",
event_name, eabuf, auth_str));
} else if (status == WLC_E_STATUS_TIMEOUT) {
DHD_EVENT(("MACEVENT: %s, MAC %s, %s, TIMEOUT\n",
event_name, eabuf, auth_str));
} else if (status == WLC_E_STATUS_FAIL) {
DHD_EVENT(("MACEVENT: %s, MAC %s, %s, FAILURE, reason %d\n",
event_name, eabuf, auth_str, (int)reason));
}
BCM_REFERENCE(auth_str);
break;
case WLC_E_JOIN:
case WLC_E_ROAM:
case WLC_E_SET_SSID:
if (status == WLC_E_STATUS_SUCCESS) {
DHD_EVENT(("MACEVENT: %s, MAC %s\n", event_name, eabuf));
} else if (status == WLC_E_STATUS_FAIL) {
DHD_EVENT(("MACEVENT: %s, failed\n", event_name));
} else if (status == WLC_E_STATUS_NO_NETWORKS) {
DHD_EVENT(("MACEVENT: %s, no networks found\n", event_name));
} else {
DHD_EVENT(("MACEVENT: %s, unexpected status %d\n",
event_name, (int)status));
}
break;
case WLC_E_BEACON_RX:
if (status == WLC_E_STATUS_SUCCESS) {
DHD_EVENT(("MACEVENT: %s, SUCCESS\n", event_name));
} else if (status == WLC_E_STATUS_FAIL) {
DHD_EVENT(("MACEVENT: %s, FAIL\n", event_name));
} else {
DHD_EVENT(("MACEVENT: %s, status %d\n", event_name, status));
}
break;
case WLC_E_LINK:
DHD_EVENT(("MACEVENT: %s %s\n", event_name, link?"UP":"DOWN"));
BCM_REFERENCE(link);
break;
case WLC_E_MIC_ERROR:
DHD_EVENT(("MACEVENT: %s, MAC %s, Group %d, Flush %d\n",
event_name, eabuf, group, flush_txq));
BCM_REFERENCE(group);
BCM_REFERENCE(flush_txq);
break;
case WLC_E_ICV_ERROR:
case WLC_E_UNICAST_DECODE_ERROR:
case WLC_E_MULTICAST_DECODE_ERROR:
DHD_EVENT(("MACEVENT: %s, MAC %s\n",
event_name, eabuf));
break;
case WLC_E_TXFAIL:
DHD_EVENT(("MACEVENT: %s, RA %s\n", event_name, eabuf));
break;
case WLC_E_SCAN_COMPLETE:
case WLC_E_ASSOC_REQ_IE:
case WLC_E_ASSOC_RESP_IE:
case WLC_E_PMKID_CACHE:
DHD_EVENT(("MACEVENT: %s\n", event_name));
break;
case WLC_E_PFN_NET_FOUND:
case WLC_E_PFN_NET_LOST:
case WLC_E_PFN_SCAN_COMPLETE:
case WLC_E_PFN_SCAN_NONE:
case WLC_E_PFN_SCAN_ALLGONE:
case WLC_E_PFN_GSCAN_FULL_RESULT:
case WLC_E_PFN_SWC:
DHD_EVENT(("PNOEVENT: %s\n", event_name));
break;
case WLC_E_PSK_SUP:
case WLC_E_PRUNE:
DHD_EVENT(("MACEVENT: %s, status %d, reason %d\n",
event_name, (int)status, (int)reason));
break;
#ifdef WIFI_ACT_FRAME
case WLC_E_ACTION_FRAME:
DHD_TRACE(("MACEVENT: %s Bssid %s\n", event_name, eabuf));
break;
#endif /* WIFI_ACT_FRAME */
#ifdef SHOW_LOGTRACE
case WLC_E_TRACE:
{
msgtrace_hdr_t hdr;
uint32 nblost;
uint8 count;
char *s, *p;
static uint32 seqnum_prev = 0;
uint32 *record = NULL;
uint32 *log_ptr = NULL;
uint32 writeindex = 0;
event_log_hdr_t event_hdr;
int no_of_fmts = 0;
char *fmt = NULL;
dhd_event_log_t *raw_event = (dhd_event_log_t *) raw_event_ptr;
buf = (uchar *) event_data;
memcpy(&hdr, buf, MSGTRACE_HDRLEN);
if (hdr.version != MSGTRACE_VERSION) {
DHD_EVENT(("\nMACEVENT: %s [unsupported version --> "
"dhd version:%d dongle version:%d]\n",
event_name, MSGTRACE_VERSION, hdr.version));
/* Reset datalen to avoid display below */
datalen = 0;
break;
}
if (hdr.trace_type == MSGTRACE_HDR_TYPE_MSG) {
/* There are 2 bytes available at the end of data */
buf[MSGTRACE_HDRLEN + ntoh16(hdr.len)] = '\0';
if (ntoh32(hdr.discarded_bytes) || ntoh32(hdr.discarded_printf)) {
DHD_EVENT(("WLC_E_TRACE: [Discarded traces in dongle -->"
"discarded_bytes %d discarded_printf %d]\n",
ntoh32(hdr.discarded_bytes),
ntoh32(hdr.discarded_printf)));
}
nblost = ntoh32(hdr.seqnum) - seqnum_prev - 1;
if (nblost > 0) {
DHD_EVENT(("WLC_E_TRACE:"
"[Event lost (msg) --> seqnum %d nblost %d\n",
ntoh32(hdr.seqnum), nblost));
}
seqnum_prev = ntoh32(hdr.seqnum);
/* Display the trace buffer. Advance from
* \n to \n to avoid display big
* printf (issue with Linux printk )
*/
p = (char *)&buf[MSGTRACE_HDRLEN];
while (*p != '\0' && (s = strstr(p, "\n")) != NULL) {
*s = '\0';
DHD_EVENT(("%s\n", p));
p = s+1;
}
if (*p)
DHD_EVENT(("%s", p));
/* Reset datalen to avoid display below */
datalen = 0;
} else if (hdr.trace_type == MSGTRACE_HDR_TYPE_LOG) {
/* Let the standard event printing work for now */
uint32 timestamp, w, malloc_len;
if (check_event_log_sequence_number(hdr.seqnum)) {
DHD_EVENT(("%s: WLC_E_TRACE:"
"[Event duplicate (log) %d] dropping!!\n",
__FUNCTION__, hdr.seqnum));
return; /* drop duplicate events */
}
p = (char *)&buf[MSGTRACE_HDRLEN];
datalen -= MSGTRACE_HDRLEN;
w = ntoh32((uint32)*p);
p += 4;
datalen -= 4;
timestamp = ntoh32((uint32)*p);
BCM_REFERENCE(timestamp);
BCM_REFERENCE(w);
DHD_EVENT(("timestamp %x%x\n", timestamp, w));
if (raw_event->fmts) {
malloc_len = datalen+ AVOID_BYTE;
record = (uint32 *)MALLOC(dhd_pub->osh, malloc_len);
if (record == NULL) {
DHD_EVENT(("MSGTRACE_HDR_TYPE_LOG:"
"malloc failed\n"));
return;
}
log_ptr = (uint32 *) (p + datalen);
writeindex = datalen/4;
if (record) {
while (datalen > 4) {
log_ptr--;
datalen -= 4;
event_hdr.t = *log_ptr;
/*
* Check for partially overriten entries
*/
if (log_ptr - (uint32 *) p < event_hdr.count) {
break;
}
/*
* Check for end of the Frame.
*/
if (event_hdr.tag == EVENT_LOG_TAG_NULL) {
continue;
}
/*
* Check For Special Time Stamp Packet
*/
if (event_hdr.tag == EVENT_LOG_TAG_TS) {
datalen -= 12;
log_ptr = log_ptr - 3;
continue;
}
log_ptr[0] = event_hdr.t;
if (event_hdr.count > MAX_NO_OF_ARG) {
break;
}
/* Now place the header at the front
* and copy back.
*/
log_ptr -= event_hdr.count;
writeindex = writeindex - event_hdr.count;
record[writeindex++] = event_hdr.t;
for (count = 0; count < (event_hdr.count-1);
count++) {
record[writeindex++] = log_ptr[count];
}
writeindex = writeindex - event_hdr.count;
datalen = datalen - (event_hdr.count * 4);
no_of_fmts++;
}
}
while (no_of_fmts--)
{
event_log_hdr_t event_hdr;
event_hdr.t = record[writeindex];
if ((event_hdr.fmt_num>>2) < raw_event->num_fmts) {
fmt = raw_event->fmts[event_hdr.fmt_num>>2];
DHD_EVENT((fmt,
record[writeindex + 1],
record[writeindex + 2],
record[writeindex + 3],
record[writeindex + 4],
record[writeindex + 5],
record[writeindex + 6],
record[writeindex + 7],
record[writeindex + 8],
record[writeindex + 9],
record[writeindex + 10],
record[writeindex + 11],
record[writeindex + 12],
record[writeindex + 13],
record[writeindex + 14],
record[writeindex + 15],
record[writeindex + 16]));
if (fmt[strlen(fmt) - 1] != '\n') {
/* Add newline if missing */
DHD_EVENT(("\n"));
}
}
writeindex = writeindex + event_hdr.count;
}
if (record) {
MFREE(dhd_pub->osh, record, malloc_len);
record = NULL;
}
} else {
while (datalen > 4) {
p += 4;
datalen -= 4;
/* Print each word. DO NOT ntoh it. */
DHD_EVENT((" %8.8x", *((uint32 *) p)));
}
DHD_EVENT(("\n"));
}
datalen = 0;
}
break;
}
#endif /* SHOW_LOGTRACE */
case WLC_E_RSSI:
DHD_EVENT(("MACEVENT: %s %d\n", event_name, ntoh32(*((int *)event_data))));
break;
case WLC_E_SERVICE_FOUND:
case WLC_E_P2PO_ADD_DEVICE:
case WLC_E_P2PO_DEL_DEVICE:
DHD_EVENT(("MACEVENT: %s, MAC %s\n", event_name, eabuf));
break;
#ifdef BT_WIFI_HANDOBER
case WLC_E_BT_WIFI_HANDOVER_REQ:
DHD_EVENT(("MACEVENT: %s, MAC %s\n", event_name, eabuf));
break;
#endif
default:
DHD_EVENT(("MACEVENT: %s %d, MAC %s, status %d, reason %d, auth %d\n",
event_name, event_type, eabuf, (int)status, (int)reason,
(int)auth_type));
break;
}
/* show any appended data */
if (DHD_BYTES_ON() && DHD_EVENT_ON() && datalen) {
buf = (uchar *) event_data;
BCM_REFERENCE(buf);
DHD_EVENT((" data (%d) : ", datalen));
for (i = 0; i < datalen; i++)
DHD_EVENT((" 0x%02x ", *buf++));
DHD_EVENT(("\n"));
}
}
#endif /* SHOW_EVENTS */
int
wl_host_event(dhd_pub_t *dhd_pub, int *ifidx, void *pktdata,
wl_event_msg_t *event, void **data_ptr, void *raw_event)
{
/* check whether packet is a BRCM event pkt */
bcm_event_t *pvt_data = (bcm_event_t *)pktdata;
uint8 *event_data;
uint32 type, status, datalen;
uint16 flags;
int evlen;
int hostidx;
if (bcmp(BRCM_OUI, &pvt_data->bcm_hdr.oui[0], DOT11_OUI_LEN)) {
DHD_ERROR(("%s: mismatched OUI, bailing\n", __FUNCTION__));
return (BCME_ERROR);
}
/* BRCM event pkt may be unaligned - use xxx_ua to load user_subtype. */
if (ntoh16_ua((void *)&pvt_data->bcm_hdr.usr_subtype) != BCMILCP_BCM_SUBTYPE_EVENT) {
DHD_ERROR(("%s: mismatched subtype, bailing\n", __FUNCTION__));
return (BCME_ERROR);
}
*data_ptr = &pvt_data[1];
event_data = *data_ptr;
/* memcpy since BRCM event pkt may be unaligned. */
memcpy(event, &pvt_data->event, sizeof(wl_event_msg_t));
type = ntoh32_ua((void *)&event->event_type);
flags = ntoh16_ua((void *)&event->flags);
status = ntoh32_ua((void *)&event->status);
datalen = ntoh32_ua((void *)&event->datalen);
evlen = datalen + sizeof(bcm_event_t);
/* find equivalent host index for event ifidx */
hostidx = dhd_ifidx2hostidx(dhd_pub->info, event->ifidx);
switch (type) {
#ifdef PROP_TXSTATUS
case WLC_E_FIFO_CREDIT_MAP:
dhd_wlfc_enable(dhd_pub);
dhd_wlfc_FIFOcreditmap_event(dhd_pub, event_data);
WLFC_DBGMESG(("WLC_E_FIFO_CREDIT_MAP:(AC0,AC1,AC2,AC3),(BC_MC),(OTHER): "
"(%d,%d,%d,%d),(%d),(%d)\n", event_data[0], event_data[1],
event_data[2],
event_data[3], event_data[4], event_data[5]));
break;
case WLC_E_BCMC_CREDIT_SUPPORT:
dhd_wlfc_BCMCCredit_support_event(dhd_pub);
break;
#endif
case WLC_E_IF:
{
struct wl_event_data_if *ifevent = (struct wl_event_data_if *)event_data;
/* Ignore the event if NOIF is set */
if (ifevent->reserved & WLC_E_IF_FLAGS_BSSCFG_NOIF) {
DHD_ERROR(("WLC_E_IF: NO_IF set, event Ignored\r\n"));
return (BCME_UNSUPPORTED);
}
#ifdef PCIE_FULL_DONGLE
dhd_update_interface_flow_info(dhd_pub, ifevent->ifidx,
ifevent->opcode, ifevent->role);
#endif
#ifdef PROP_TXSTATUS
{
uint8* ea = pvt_data->eth.ether_dhost;
WLFC_DBGMESG(("WLC_E_IF: idx:%d, action:%s, iftype:%s, "
"[%02x:%02x:%02x:%02x:%02x:%02x]\n",
ifevent->ifidx,
((ifevent->opcode == WLC_E_IF_ADD) ? "ADD":"DEL"),
((ifevent->role == 0) ? "STA":"AP "),
ea[0], ea[1], ea[2], ea[3], ea[4], ea[5]));
(void)ea;
if (ifevent->opcode == WLC_E_IF_CHANGE)
dhd_wlfc_interface_event(dhd_pub,
eWLFC_MAC_ENTRY_ACTION_UPDATE,
ifevent->ifidx, ifevent->role, ea);
else
dhd_wlfc_interface_event(dhd_pub,
((ifevent->opcode == WLC_E_IF_ADD) ?
eWLFC_MAC_ENTRY_ACTION_ADD : eWLFC_MAC_ENTRY_ACTION_DEL),
ifevent->ifidx, ifevent->role, ea);
/* dhd already has created an interface by default, for 0 */
if (ifevent->ifidx == 0)
break;
}
#endif /* PROP_TXSTATUS */
if (ifevent->ifidx > 0 && ifevent->ifidx < DHD_MAX_IFS) {
if (ifevent->opcode == WLC_E_IF_ADD) {
if (dhd_event_ifadd(dhd_pub->info, ifevent, event->ifname,
event->addr.octet)) {
DHD_ERROR(("%s: dhd_event_ifadd failed ifidx: %d %s\n",
__FUNCTION__, ifevent->ifidx, event->ifname));
return (BCME_ERROR);
}
} else if (ifevent->opcode == WLC_E_IF_DEL) {
dhd_event_ifdel(dhd_pub->info, ifevent, event->ifname,
event->addr.octet);
} else if (ifevent->opcode == WLC_E_IF_CHANGE) {
#ifdef WL_CFG80211
wl_cfg80211_notify_ifchange(ifevent->ifidx,
event->ifname, event->addr.octet, ifevent->bssidx);
#endif /* WL_CFG80211 */
}
} else {
#if !defined(PROP_TXSTATUS) || !defined(PCIE_FULL_DONGLE)
DHD_ERROR(("%s: Invalid ifidx %d for %s\n",
__FUNCTION__, ifevent->ifidx, event->ifname));
#endif /* !PROP_TXSTATUS */
}
/* send up the if event: btamp user needs it */
*ifidx = hostidx;
/* push up to external supp/auth */
dhd_event(dhd_pub->info, (char *)pvt_data, evlen, *ifidx);
break;
}
case WLC_E_NDIS_LINK: {
uint32 temp = hton32(WLC_E_LINK);
memcpy((void *)(&pvt_data->event.event_type), &temp,
sizeof(pvt_data->event.event_type));
break;
}
case WLC_E_PFN_NET_FOUND:
case WLC_E_PFN_NET_LOST:
break;
#if defined(PNO_SUPPORT)
case WLC_E_PFN_BSSID_NET_FOUND:
case WLC_E_PFN_BSSID_NET_LOST:
case WLC_E_PFN_BEST_BATCHING:
dhd_pno_event_handler(dhd_pub, event, (void *)event_data);
break;
#endif
#if defined(RTT_SUPPORT)
case WLC_E_PROXD:
dhd_rtt_event_handler(dhd_pub, event, (void *)event_data);
break;
#endif /* RTT_SUPPORT */
/* These are what external supplicant/authenticator wants */
case WLC_E_ASSOC_IND:
case WLC_E_AUTH_IND:
case WLC_E_REASSOC_IND:
dhd_findadd_sta(dhd_pub, hostidx, &event->addr.octet);
break;
case WLC_E_LINK:
#ifdef PCIE_FULL_DONGLE
if (dhd_update_interface_link_status(dhd_pub, (uint8)hostidx,
(uint8)flags) != BCME_OK)
break;
if (!flags) {
dhd_flow_rings_delete(dhd_pub, hostidx);
}
/* fall through */
#endif
case WLC_E_DEAUTH:
case WLC_E_DEAUTH_IND:
case WLC_E_DISASSOC:
case WLC_E_DISASSOC_IND:
if (type != WLC_E_LINK) {
dhd_del_sta(dhd_pub, hostidx, &event->addr.octet);
}
DHD_EVENT(("%s: Link event %d, flags %x, status %x\n",
__FUNCTION__, type, flags, status));
#ifdef PCIE_FULL_DONGLE
if (type != WLC_E_LINK) {
uint8 ifindex = (uint8)hostidx;
uint8 role = dhd_flow_rings_ifindex2role(dhd_pub, ifindex);
if (DHD_IF_ROLE_STA(role)) {
dhd_flow_rings_delete(dhd_pub, ifindex);
} else {
dhd_flow_rings_delete_for_peer(dhd_pub, ifindex,
&event->addr.octet[0]);
}
}
#endif
/* fall through */
default:
*ifidx = hostidx;
/* push up to external supp/auth */
dhd_event(dhd_pub->info, (char *)pvt_data, evlen, *ifidx);
DHD_TRACE(("%s: MAC event %d, flags %x, status %x\n",
__FUNCTION__, type, flags, status));
BCM_REFERENCE(flags);
BCM_REFERENCE(status);
break;
}
#ifdef SHOW_EVENTS
wl_show_host_event(dhd_pub, event,
(void *)event_data, raw_event, dhd_pub->enable_log);
#endif /* SHOW_EVENTS */
return (BCME_OK);
}
void
wl_event_to_host_order(wl_event_msg_t * evt)
{
/* Event struct members passed from dongle to host are stored in network
* byte order. Convert all members to host-order.
*/
evt->event_type = ntoh32(evt->event_type);
evt->flags = ntoh16(evt->flags);
evt->status = ntoh32(evt->status);
evt->reason = ntoh32(evt->reason);
evt->auth_type = ntoh32(evt->auth_type);
evt->datalen = ntoh32(evt->datalen);
evt->version = ntoh16(evt->version);
}
void
dhd_print_buf(void *pbuf, int len, int bytes_per_line)
{
#ifdef DHD_DEBUG
int i, j = 0;
unsigned char *buf = pbuf;
if (bytes_per_line == 0) {
bytes_per_line = len;
}
for (i = 0; i < len; i++) {
printf("%2.2x", *buf++);
j++;
if (j == bytes_per_line) {
printf("\n");
j = 0;
} else {
printf(":");
}
}
printf("\n");
#endif /* DHD_DEBUG */
}
#ifndef strtoul
#define strtoul(nptr, endptr, base) bcm_strtoul((nptr), (endptr), (base))
#endif
#ifdef PKT_FILTER_SUPPORT
/* Convert user's input in hex pattern to byte-size mask */
static int
wl_pattern_atoh(char *src, char *dst)
{
int i;
if (strncmp(src, "0x", 2) != 0 &&
strncmp(src, "0X", 2) != 0) {
DHD_ERROR(("Mask invalid format. Needs to start with 0x\n"));
return -1;
}
src = src + 2; /* Skip past 0x */
if (strlen(src) % 2 != 0) {
DHD_ERROR(("Mask invalid format. Needs to be of even length\n"));
return -1;
}
for (i = 0; *src != '\0'; i++) {
char num[3];
bcm_strncpy_s(num, sizeof(num), src, 2);
num[2] = '\0';
dst[i] = (uint8)strtoul(num, NULL, 16);
src += 2;
}
return i;
}
void
dhd_pktfilter_offload_enable(dhd_pub_t * dhd, char *arg, int enable, int master_mode)
{
char *argv[8];
int i = 0;
const char *str;
int buf_len;
int str_len;
char *arg_save = 0, *arg_org = 0;
int rc;
char buf[32] = {0};
wl_pkt_filter_enable_t enable_parm;
wl_pkt_filter_enable_t * pkt_filterp;
if (!arg)
return;
if (!(arg_save = MALLOC(dhd->osh, strlen(arg) + 1))) {
DHD_ERROR(("%s: malloc failed\n", __FUNCTION__));
goto fail;
}
arg_org = arg_save;
memcpy(arg_save, arg, strlen(arg) + 1);
argv[i] = bcmstrtok(&arg_save, " ", 0);
i = 0;
if (argv[i] == NULL) {
DHD_ERROR(("No args provided\n"));
goto fail;
}
str = "pkt_filter_enable";
str_len = strlen(str);
bcm_strncpy_s(buf, sizeof(buf) - 1, str, sizeof(buf) - 1);
buf[ sizeof(buf) - 1 ] = '\0';
buf_len = str_len + 1;
pkt_filterp = (wl_pkt_filter_enable_t *)(buf + str_len + 1);
/* Parse packet filter id. */
enable_parm.id = htod32(strtoul(argv[i], NULL, 0));
/* Parse enable/disable value. */
enable_parm.enable = htod32(enable);
buf_len += sizeof(enable_parm);
memcpy((char *)pkt_filterp,
&enable_parm,
sizeof(enable_parm));
/* Enable/disable the specified filter. */
rc = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, buf, buf_len, TRUE, 0);
rc = rc >= 0 ? 0 : rc;
if (rc)
DHD_TRACE(("%s: failed to add pktfilter %s, retcode = %d\n",
__FUNCTION__, arg, rc));
else
DHD_TRACE(("%s: successfully added pktfilter %s\n",
__FUNCTION__, arg));
/* Contorl the master mode */
bcm_mkiovar("pkt_filter_mode", (char *)&master_mode, 4, buf, sizeof(buf));
rc = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, buf, sizeof(buf), TRUE, 0);
rc = rc >= 0 ? 0 : rc;
if (rc)
DHD_TRACE(("%s: failed to add pktfilter %s, retcode = %d\n",
__FUNCTION__, arg, rc));
fail:
if (arg_org)
MFREE(dhd->osh, arg_org, strlen(arg) + 1);
}
void
dhd_pktfilter_offload_set(dhd_pub_t * dhd, char *arg)
{
const char *str;
wl_pkt_filter_t pkt_filter;
wl_pkt_filter_t *pkt_filterp;
int buf_len;
int str_len;
int rc;
uint32 mask_size;
uint32 pattern_size;
char *argv[8], * buf = 0;
int i = 0;
char *arg_save = 0, *arg_org = 0;
#define BUF_SIZE 2048
if (!arg)
return;
if (!(arg_save = MALLOC(dhd->osh, strlen(arg) + 1))) {
DHD_ERROR(("%s: malloc failed\n", __FUNCTION__));
goto fail;
}
arg_org = arg_save;
if (!(buf = MALLOC(dhd->osh, BUF_SIZE))) {
DHD_ERROR(("%s: malloc failed\n", __FUNCTION__));
goto fail;
}
memcpy(arg_save, arg, strlen(arg) + 1);
if (strlen(arg) > BUF_SIZE) {
DHD_ERROR(("Not enough buffer %d < %d\n", (int)strlen(arg), (int)sizeof(buf)));
goto fail;
}
argv[i] = bcmstrtok(&arg_save, " ", 0);
while (argv[i++])
argv[i] = bcmstrtok(&arg_save, " ", 0);
i = 0;
if (argv[i] == NULL) {
DHD_ERROR(("No args provided\n"));
goto fail;
}
str = "pkt_filter_add";
str_len = strlen(str);
bcm_strncpy_s(buf, BUF_SIZE, str, str_len);
buf[ str_len ] = '\0';
buf_len = str_len + 1;
pkt_filterp = (wl_pkt_filter_t *) (buf + str_len + 1);
/* Parse packet filter id. */
pkt_filter.id = htod32(strtoul(argv[i], NULL, 0));
if (argv[++i] == NULL) {
DHD_ERROR(("Polarity not provided\n"));
goto fail;
}
/* Parse filter polarity. */
pkt_filter.negate_match = htod32(strtoul(argv[i], NULL, 0));
if (argv[++i] == NULL) {
DHD_ERROR(("Filter type not provided\n"));
goto fail;
}
/* Parse filter type. */
pkt_filter.type = htod32(strtoul(argv[i], NULL, 0));
if (argv[++i] == NULL) {
DHD_ERROR(("Offset not provided\n"));
goto fail;
}
/* Parse pattern filter offset. */
pkt_filter.u.pattern.offset = htod32(strtoul(argv[i], NULL, 0));
if (argv[++i] == NULL) {
DHD_ERROR(("Bitmask not provided\n"));
goto fail;
}
/* Parse pattern filter mask. */
mask_size =
htod32(wl_pattern_atoh(argv[i], (char *) pkt_filterp->u.pattern.mask_and_pattern));
if (argv[++i] == NULL) {
DHD_ERROR(("Pattern not provided\n"));
goto fail;
}
/* Parse pattern filter pattern. */
pattern_size =
htod32(wl_pattern_atoh(argv[i],
(char *) &pkt_filterp->u.pattern.mask_and_pattern[mask_size]));
if (mask_size != pattern_size) {
DHD_ERROR(("Mask and pattern not the same size\n"));
goto fail;
}
pkt_filter.u.pattern.size_bytes = mask_size;
buf_len += WL_PKT_FILTER_FIXED_LEN;
buf_len += (WL_PKT_FILTER_PATTERN_FIXED_LEN + 2 * mask_size);
/* Keep-alive attributes are set in local variable (keep_alive_pkt), and
** then memcpy'ed into buffer (keep_alive_pktp) since there is no
** guarantee that the buffer is properly aligned.
*/
memcpy((char *)pkt_filterp,
&pkt_filter,
WL_PKT_FILTER_FIXED_LEN + WL_PKT_FILTER_PATTERN_FIXED_LEN);
rc = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, buf, buf_len, TRUE, 0);
rc = rc >= 0 ? 0 : rc;
if (rc)
DHD_TRACE(("%s: failed to add pktfilter %s, retcode = %d\n",
__FUNCTION__, arg, rc));
else
DHD_TRACE(("%s: successfully added pktfilter %s\n",
__FUNCTION__, arg));
fail:
if (arg_org)
MFREE(dhd->osh, arg_org, strlen(arg) + 1);
if (buf)
MFREE(dhd->osh, buf, BUF_SIZE);
}
void dhd_pktfilter_offload_delete(dhd_pub_t *dhd, int id)
{
char iovbuf[32];
int ret;
bcm_mkiovar("pkt_filter_delete", (char *)&id, 4, iovbuf, sizeof(iovbuf));
ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, sizeof(iovbuf), TRUE, 0);
if (ret < 0) {
DHD_ERROR(("%s: Failed to delete filter ID:%d, ret=%d\n",
__FUNCTION__, id, ret));
}
}
#endif /* PKT_FILTER_SUPPORT */
/* ========================== */
/* ==== ARP OFFLOAD SUPPORT = */
/* ========================== */
#ifdef ARP_OFFLOAD_SUPPORT
void
dhd_arp_offload_set(dhd_pub_t * dhd, int arp_mode)
{
char iovbuf[DHD_IOVAR_BUF_SIZE];
int iovar_len;
int retcode;
iovar_len = bcm_mkiovar("arp_ol", (char *)&arp_mode, 4, iovbuf, sizeof(iovbuf));
if (!iovar_len) {
DHD_ERROR(("%s: Insufficient iovar buffer size %zu \n",
__FUNCTION__, sizeof(iovbuf)));
return;
}
retcode = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, iovar_len, TRUE, 0);
retcode = retcode >= 0 ? 0 : retcode;
if (retcode)
DHD_TRACE(("%s: failed to set ARP offload mode to 0x%x, retcode = %d\n",
__FUNCTION__, arp_mode, retcode));
else
DHD_TRACE(("%s: successfully set ARP offload mode to 0x%x\n",
__FUNCTION__, arp_mode));
}
void
dhd_arp_offload_enable(dhd_pub_t * dhd, int arp_enable)
{
char iovbuf[DHD_IOVAR_BUF_SIZE];
int iovar_len;
int retcode;
iovar_len = bcm_mkiovar("arpoe", (char *)&arp_enable, 4, iovbuf, sizeof(iovbuf));
if (!iovar_len) {
DHD_ERROR(("%s: Insufficient iovar buffer size %zu \n",
__FUNCTION__, sizeof(iovbuf)));
return;
}
retcode = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, iovar_len, TRUE, 0);
retcode = retcode >= 0 ? 0 : retcode;
if (retcode)
DHD_TRACE(("%s: failed to enabe ARP offload to %d, retcode = %d\n",
__FUNCTION__, arp_enable, retcode));
else
DHD_TRACE(("%s: successfully enabed ARP offload to %d\n",
__FUNCTION__, arp_enable));
if (arp_enable) {
uint32 version;
bcm_mkiovar("arp_version", 0, 0, iovbuf, sizeof(iovbuf));
retcode = dhd_wl_ioctl_cmd(dhd, WLC_GET_VAR, iovbuf, sizeof(iovbuf), FALSE, 0);
if (retcode) {
DHD_INFO(("%s: fail to get version (maybe version 1:retcode = %d\n",
__FUNCTION__, retcode));
dhd->arp_version = 1;
}
else {
memcpy(&version, iovbuf, sizeof(version));
DHD_INFO(("%s: ARP Version= %x\n", __FUNCTION__, version));
dhd->arp_version = version;
}
}
}
void
dhd_aoe_arp_clr(dhd_pub_t *dhd, int idx)
{
int ret = 0;
int iov_len = 0;
char iovbuf[DHD_IOVAR_BUF_SIZE];
if (dhd == NULL) return;
if (dhd->arp_version == 1)
idx = 0;
iov_len = bcm_mkiovar("arp_table_clear", 0, 0, iovbuf, sizeof(iovbuf));
if (!iov_len) {
DHD_ERROR(("%s: Insufficient iovar buffer size %zu \n",
__FUNCTION__, sizeof(iovbuf)));
return;
}
if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, iov_len, TRUE, idx)) < 0)
DHD_ERROR(("%s failed code %d\n", __FUNCTION__, ret));
}
void
dhd_aoe_hostip_clr(dhd_pub_t *dhd, int idx)
{
int ret = 0;
int iov_len = 0;
char iovbuf[DHD_IOVAR_BUF_SIZE];
if (dhd == NULL) return;
if (dhd->arp_version == 1)
idx = 0;
iov_len = bcm_mkiovar("arp_hostip_clear", 0, 0, iovbuf, sizeof(iovbuf));
if (!iov_len) {
DHD_ERROR(("%s: Insufficient iovar buffer size %zu \n",
__FUNCTION__, sizeof(iovbuf)));
return;
}
if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, iov_len, TRUE, idx)) < 0)
DHD_ERROR(("%s failed code %d\n", __FUNCTION__, ret));
}
void
dhd_arp_offload_add_ip(dhd_pub_t *dhd, uint32 ipaddr, int idx)
{
int iov_len = 0;
char iovbuf[DHD_IOVAR_BUF_SIZE];
int retcode;
if (dhd == NULL) return;
if (dhd->arp_version == 1)
idx = 0;
iov_len = bcm_mkiovar("arp_hostip", (char *)&ipaddr,
sizeof(ipaddr), iovbuf, sizeof(iovbuf));
if (!iov_len) {
DHD_ERROR(("%s: Insufficient iovar buffer size %zu \n",
__FUNCTION__, sizeof(iovbuf)));
return;
}
retcode = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, iov_len, TRUE, idx);
if (retcode)
DHD_TRACE(("%s: ARP ip addr add failed, retcode = %d\n",
__FUNCTION__, retcode));
else
DHD_TRACE(("%s: sARP H ipaddr entry added \n",
__FUNCTION__));
}
int
dhd_arp_get_arp_hostip_table(dhd_pub_t *dhd, void *buf, int buflen, int idx)
{
int retcode, i;
int iov_len;
uint32 *ptr32 = buf;
bool clr_bottom = FALSE;
if (!buf)
return -1;
if (dhd == NULL) return -1;
if (dhd->arp_version == 1)
idx = 0;
iov_len = bcm_mkiovar("arp_hostip", 0, 0, buf, buflen);
BCM_REFERENCE(iov_len);
retcode = dhd_wl_ioctl_cmd(dhd, WLC_GET_VAR, buf, buflen, FALSE, idx);
if (retcode) {
DHD_TRACE(("%s: ioctl WLC_GET_VAR error %d\n",
__FUNCTION__, retcode));
return -1;
}
/* clean up the buf, ascii reminder */
for (i = 0; i < MAX_IPV4_ENTRIES; i++) {
if (!clr_bottom) {
if (*ptr32 == 0)
clr_bottom = TRUE;
} else {
*ptr32 = 0;
}
ptr32++;
}
return 0;
}
#endif /* ARP_OFFLOAD_SUPPORT */
/*
* Neighbor Discovery Offload: enable NDO feature
* Called by ipv6 event handler when interface comes up/goes down
*/
int
dhd_ndo_enable(dhd_pub_t * dhd, int ndo_enable)
{
char iovbuf[DHD_IOVAR_BUF_SIZE];
int iov_len;
int retcode;
if (dhd == NULL)
return -1;
iov_len = bcm_mkiovar("ndoe", (char *)&ndo_enable, 4, iovbuf, sizeof(iovbuf));
if (!iov_len) {
DHD_ERROR(("%s: Insufficient iovar buffer size %zu \n",
__FUNCTION__, sizeof(iovbuf)));
return -1;
}
retcode = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, iov_len, TRUE, 0);
if (retcode)
DHD_ERROR(("%s: failed to enabe ndo to %d, retcode = %d\n",
__FUNCTION__, ndo_enable, retcode));
else
DHD_TRACE(("%s: successfully enabed ndo offload to %d\n",
__FUNCTION__, ndo_enable));
return retcode;
}
/*
* Neighbor Discover Offload: enable NDO feature
* Called by ipv6 event handler when interface comes up
*/
int
dhd_ndo_add_ip(dhd_pub_t *dhd, char* ipv6addr, int idx)
{
int iov_len = 0;
char iovbuf[DHD_IOVAR_BUF_SIZE];
int retcode;
if (dhd == NULL)
return -1;
iov_len = bcm_mkiovar("nd_hostip", (char *)ipv6addr,
IPV6_ADDR_LEN, iovbuf, sizeof(iovbuf));
if (!iov_len) {
DHD_ERROR(("%s: Insufficient iovar buffer size %zu \n",
__FUNCTION__, sizeof(iovbuf)));
return -1;
}
retcode = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, iov_len, TRUE, idx);
if (retcode)
DHD_ERROR(("%s: ndo ip addr add failed, retcode = %d\n",
__FUNCTION__, retcode));
else
DHD_TRACE(("%s: ndo ipaddr entry added \n",
__FUNCTION__));
return retcode;
}
/*
* Neighbor Discover Offload: enable NDO feature
* Called by ipv6 event handler when interface goes down
*/
int
dhd_ndo_remove_ip(dhd_pub_t *dhd, int idx)
{
int iov_len = 0;
char iovbuf[DHD_IOVAR_BUF_SIZE];
int retcode;
if (dhd == NULL)
return -1;
iov_len = bcm_mkiovar("nd_hostip_clear", NULL,
0, iovbuf, sizeof(iovbuf));
if (!iov_len) {
DHD_ERROR(("%s: Insufficient iovar buffer size %zu \n",
__FUNCTION__, sizeof(iovbuf)));
return -1;
}
retcode = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, iovbuf, iov_len, TRUE, idx);
if (retcode)
DHD_ERROR(("%s: ndo ip addr remove failed, retcode = %d\n",
__FUNCTION__, retcode));
else
DHD_TRACE(("%s: ndo ipaddr entry removed \n",
__FUNCTION__));
return retcode;
}
/* send up locally generated event */
void
dhd_sendup_event_common(dhd_pub_t *dhdp, wl_event_msg_t *event, void *data)
{
switch (ntoh32(event->event_type)) {
#ifdef WLBTAMP
case WLC_E_BTA_HCI_EVENT:
break;
#endif /* WLBTAMP */
default:
break;
}
/* Call per-port handler. */
dhd_sendup_event(dhdp, event, data);
}
#ifdef SIMPLE_ISCAN
uint iscan_thread_id = 0;
iscan_buf_t * iscan_chain = 0;
iscan_buf_t *
dhd_iscan_allocate_buf(dhd_pub_t *dhd, iscan_buf_t **iscanbuf)
{
iscan_buf_t *iscanbuf_alloc = 0;
iscan_buf_t *iscanbuf_head;
DHD_ISCAN(("%s: Entered\n", __FUNCTION__));
dhd_iscan_lock();
iscanbuf_alloc = (iscan_buf_t*)MALLOC(dhd->osh, sizeof(iscan_buf_t));
if (iscanbuf_alloc == NULL)
goto fail;
iscanbuf_alloc->next = NULL;
iscanbuf_head = *iscanbuf;
DHD_ISCAN(("%s: addr of allocated node = 0x%X"
"addr of iscanbuf_head = 0x%X dhd = 0x%X\n",
__FUNCTION__, iscanbuf_alloc, iscanbuf_head, dhd));
if (iscanbuf_head == NULL) {
*iscanbuf = iscanbuf_alloc;
DHD_ISCAN(("%s: Head is allocated\n", __FUNCTION__));
goto fail;
}
while (iscanbuf_head->next)
iscanbuf_head = iscanbuf_head->next;
iscanbuf_head->next = iscanbuf_alloc;
fail:
dhd_iscan_unlock();
return iscanbuf_alloc;
}
void
dhd_iscan_free_buf(void *dhdp, iscan_buf_t *iscan_delete)
{
iscan_buf_t *iscanbuf_free = 0;
iscan_buf_t *iscanbuf_prv = 0;
iscan_buf_t *iscanbuf_cur;
dhd_pub_t *dhd = dhd_bus_pub(dhdp);
DHD_ISCAN(("%s: Entered\n", __FUNCTION__));
dhd_iscan_lock();
iscanbuf_cur = iscan_chain;
/* If iscan_delete is null then delete the entire
* chain or else delete specific one provided
*/
if (!iscan_delete) {
while (iscanbuf_cur) {
iscanbuf_free = iscanbuf_cur;
iscanbuf_cur = iscanbuf_cur->next;
iscanbuf_free->next = 0;
MFREE(dhd->osh, iscanbuf_free, sizeof(iscan_buf_t));
}
iscan_chain = 0;
} else {
while (iscanbuf_cur) {
if (iscanbuf_cur == iscan_delete)
break;
iscanbuf_prv = iscanbuf_cur;
iscanbuf_cur = iscanbuf_cur->next;
}
if (iscanbuf_prv)
iscanbuf_prv->next = iscan_delete->next;
iscan_delete->next = 0;
MFREE(dhd->osh, iscan_delete, sizeof(iscan_buf_t));
if (!iscanbuf_prv)
iscan_chain = 0;
}
dhd_iscan_unlock();
}
iscan_buf_t *
dhd_iscan_result_buf(void)
{
return iscan_chain;
}
int
dhd_iscan_issue_request(void * dhdp, wl_iscan_params_t *pParams, uint32 size)
{
int rc = -1;
dhd_pub_t *dhd = dhd_bus_pub(dhdp);
char *buf;
char iovar[] = "iscan";
uint32 allocSize = 0;
wl_ioctl_t ioctl;
if (pParams) {
allocSize = (size + strlen(iovar) + 1);
if ((allocSize < size) || (allocSize < strlen(iovar)))
{
DHD_ERROR(("%s: overflow - allocation size too large %d < %d + %d!\n",
__FUNCTION__, allocSize, size, strlen(iovar)));
goto cleanUp;
}
buf = MALLOC(dhd->osh, allocSize);
if (buf == NULL)
{
DHD_ERROR(("%s: malloc of size %d failed!\n", __FUNCTION__, allocSize));
goto cleanUp;
}
ioctl.cmd = WLC_SET_VAR;
bcm_mkiovar(iovar, (char *)pParams, size, buf, allocSize);
rc = dhd_wl_ioctl(dhd, 0, &ioctl, buf, allocSize);
}
cleanUp:
if (buf) {
MFREE(dhd->osh, buf, allocSize);
}
return rc;
}
static int
dhd_iscan_get_partial_result(void *dhdp, uint *scan_count)
{
wl_iscan_results_t *list_buf;
wl_iscan_results_t list;
wl_scan_results_t *results;
iscan_buf_t *iscan_cur;
int status = -1;
dhd_pub_t *dhd = dhd_bus_pub(dhdp);
int rc;
wl_ioctl_t ioctl;
DHD_ISCAN(("%s: Enter\n", __FUNCTION__));
iscan_cur = dhd_iscan_allocate_buf(dhd, &iscan_chain);
if (!iscan_cur) {
DHD_ERROR(("%s: Failed to allocate node\n", __FUNCTION__));
dhd_iscan_free_buf(dhdp, 0);
dhd_iscan_request(dhdp, WL_SCAN_ACTION_ABORT);
dhd_ind_scan_confirm(dhdp, FALSE);
goto fail;
}
dhd_iscan_lock();
memset(iscan_cur->iscan_buf, 0, WLC_IW_ISCAN_MAXLEN);
list_buf = (wl_iscan_results_t*)iscan_cur->iscan_buf;
results = &list_buf->results;
results->buflen = WL_ISCAN_RESULTS_FIXED_SIZE;
results->version = 0;
results->count = 0;
memset(&list, 0, sizeof(list));
list.results.buflen = htod32(WLC_IW_ISCAN_MAXLEN);
bcm_mkiovar("iscanresults", (char *)&list, WL_ISCAN_RESULTS_FIXED_SIZE,
iscan_cur->iscan_buf, WLC_IW_ISCAN_MAXLEN);
ioctl.cmd = WLC_GET_VAR;
ioctl.set = FALSE;
rc = dhd_wl_ioctl(dhd, 0, &ioctl, iscan_cur->iscan_buf, WLC_IW_ISCAN_MAXLEN);
results->buflen = dtoh32(results->buflen);
results->version = dtoh32(results->version);
*scan_count = results->count = dtoh32(results->count);
status = dtoh32(list_buf->status);
DHD_ISCAN(("%s: Got %d resuls status = (%x)\n", __FUNCTION__, results->count, status));
dhd_iscan_unlock();
if (!(*scan_count)) {
/* TODO: race condition when FLUSH already called */
dhd_iscan_free_buf(dhdp, 0);
}
fail:
return status;
}
#endif /* SIMPLE_ISCAN */
/*
* returns = TRUE if associated, FALSE if not associated
*/
bool dhd_is_associated(dhd_pub_t *dhd, void *bss_buf, int *retval)
{
char bssid[6], zbuf[6];
int ret = -1;
bzero(bssid, 6);
bzero(zbuf, 6);
ret = dhd_wl_ioctl_cmd(dhd, WLC_GET_BSSID, (char *)&bssid, ETHER_ADDR_LEN, FALSE, 0);
DHD_TRACE((" %s WLC_GET_BSSID ioctl res = %d\n", __FUNCTION__, ret));
if (ret == BCME_NOTASSOCIATED) {
DHD_TRACE(("%s: not associated! res:%d\n", __FUNCTION__, ret));
}
if (retval)
*retval = ret;
if (ret < 0)
return FALSE;
if ((memcmp(bssid, zbuf, ETHER_ADDR_LEN) != 0)) {
/* STA is assocoated BSSID is non zero */
if (bss_buf) {
/* return bss if caller provided buf */
memcpy(bss_buf, bssid, ETHER_ADDR_LEN);
}
return TRUE;
} else {
DHD_TRACE(("%s: WLC_GET_BSSID ioctl returned zero bssid\n", __FUNCTION__));
return FALSE;
}
}
/* Function to estimate possible DTIM_SKIP value */
int
dhd_get_suspend_bcn_li_dtim(dhd_pub_t *dhd)
{
int bcn_li_dtim = 1; /* deafult no dtim skip setting */
int ret = -1;
int dtim_period = 0;
int ap_beacon = 0;
int allowed_skip_dtim_cnt = 0;
/* Check if associated */
if (dhd_is_associated(dhd, NULL, NULL) == FALSE) {
DHD_TRACE(("%s NOT assoc ret %d\n", __FUNCTION__, ret));
goto exit;
}
/* read associated AP beacon interval */
if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_GET_BCNPRD,
&ap_beacon, sizeof(ap_beacon), FALSE, 0)) < 0) {
DHD_ERROR(("%s get beacon failed code %d\n", __FUNCTION__, ret));
goto exit;
}
/* read associated ap's dtim setup */
if ((ret = dhd_wl_ioctl_cmd(dhd, WLC_GET_DTIMPRD,
&dtim_period, sizeof(dtim_period), FALSE, 0)) < 0) {
DHD_ERROR(("%s failed code %d\n", __FUNCTION__, ret));
goto exit;
}
/* if not assocated just eixt */
if (dtim_period == 0) {
goto exit;
}
/* attemp to use platform defined dtim skip interval */
bcn_li_dtim = dhd->suspend_bcn_li_dtim;
/* check if sta listen interval fits into AP dtim */
if (dtim_period > CUSTOM_LISTEN_INTERVAL) {
/* AP DTIM to big for our Listen Interval : no dtim skiping */
bcn_li_dtim = NO_DTIM_SKIP;
DHD_ERROR(("%s DTIM=%d > Listen=%d : too big ...\n",
__FUNCTION__, dtim_period, CUSTOM_LISTEN_INTERVAL));
goto exit;
}
if ((dtim_period * ap_beacon * bcn_li_dtim) > MAX_DTIM_ALLOWED_INTERVAL) {
allowed_skip_dtim_cnt = MAX_DTIM_ALLOWED_INTERVAL / (dtim_period * ap_beacon);
bcn_li_dtim = (allowed_skip_dtim_cnt != 0) ? allowed_skip_dtim_cnt : NO_DTIM_SKIP;
}
if ((bcn_li_dtim * dtim_period) > CUSTOM_LISTEN_INTERVAL) {
/* Round up dtim_skip to fit into STAs Listen Interval */
bcn_li_dtim = (int)(CUSTOM_LISTEN_INTERVAL / dtim_period);
DHD_TRACE(("%s agjust dtim_skip as %d\n", __FUNCTION__, bcn_li_dtim));
}
DHD_ERROR(("%s beacon=%d bcn_li_dtim=%d DTIM=%d Listen=%d\n",
__FUNCTION__, ap_beacon, bcn_li_dtim, dtim_period, CUSTOM_LISTEN_INTERVAL));
exit:
return bcn_li_dtim;
}
/* Check if the mode supports STA MODE */
bool dhd_support_sta_mode(dhd_pub_t *dhd)
{
#ifdef WL_CFG80211
if (!(dhd->op_mode & DHD_FLAG_STA_MODE))
return FALSE;
else
#endif /* WL_CFG80211 */
return TRUE;
}
#if defined(KEEP_ALIVE)
int dhd_keep_alive_onoff(dhd_pub_t *dhd)
{
char buf[32] = {0};
const char *str;
wl_mkeep_alive_pkt_t mkeep_alive_pkt = {0};
wl_mkeep_alive_pkt_t *mkeep_alive_pktp;
int buf_len;
int str_len;
int res = -1;
if (!dhd_support_sta_mode(dhd))
return res;
DHD_TRACE(("%s execution\n", __FUNCTION__));
str = "mkeep_alive";
str_len = strlen(str);
strncpy(buf, str, sizeof(buf) - 1);
buf[ sizeof(buf) - 1 ] = '\0';
mkeep_alive_pktp = (wl_mkeep_alive_pkt_t *) (buf + str_len + 1);
mkeep_alive_pkt.period_msec = CUSTOM_KEEP_ALIVE_SETTING;
buf_len = str_len + 1;
mkeep_alive_pkt.version = htod16(WL_MKEEP_ALIVE_VERSION);
mkeep_alive_pkt.length = htod16(WL_MKEEP_ALIVE_FIXED_LEN);
/* Setup keep alive zero for null packet generation */
mkeep_alive_pkt.keep_alive_id = 0;
mkeep_alive_pkt.len_bytes = 0;
buf_len += WL_MKEEP_ALIVE_FIXED_LEN;
bzero(mkeep_alive_pkt.data, sizeof(mkeep_alive_pkt.data));
/* Keep-alive attributes are set in local variable (mkeep_alive_pkt), and
* then memcpy'ed into buffer (mkeep_alive_pktp) since there is no
* guarantee that the buffer is properly aligned.
*/
memcpy((char *)mkeep_alive_pktp, &mkeep_alive_pkt, WL_MKEEP_ALIVE_FIXED_LEN);
res = dhd_wl_ioctl_cmd(dhd, WLC_SET_VAR, buf, buf_len, TRUE, 0);
return res;
}
#endif /* defined(KEEP_ALIVE) */
/* Android ComboSCAN support */
/*
* data parsing from ComboScan tlv list
*/
int
wl_iw_parse_data_tlv(char** list_str, void *dst, int dst_size, const char token,
int input_size, int *bytes_left)
{
char* str;
uint16 short_temp;
uint32 int_temp;
if ((list_str == NULL) || (*list_str == NULL) ||(bytes_left == NULL) || (*bytes_left < 0)) {
DHD_ERROR(("%s error paramters\n", __FUNCTION__));
return -1;
}
str = *list_str;
/* Clean all dest bytes */
memset(dst, 0, dst_size);
while (*bytes_left > 0) {
if (str[0] != token) {
DHD_TRACE(("%s NOT Type=%d get=%d left_parse=%d \n",
__FUNCTION__, token, str[0], *bytes_left));
return -1;
}
*bytes_left -= 1;
str += 1;
if (input_size == 1) {
memcpy(dst, str, input_size);
}
else if (input_size == 2) {
memcpy(dst, (char *)htod16(memcpy(&short_temp, str, input_size)),
input_size);
}
else if (input_size == 4) {
memcpy(dst, (char *)htod32(memcpy(&int_temp, str, input_size)),
input_size);
}
*bytes_left -= input_size;
str += input_size;
*list_str = str;
return 1;
}
return 1;
}
/*
* channel list parsing from cscan tlv list
*/
int
wl_iw_parse_channel_list_tlv(char** list_str, uint16* channel_list,
int channel_num, int *bytes_left)
{
char* str;
int idx = 0;
if ((list_str == NULL) || (*list_str == NULL) ||(bytes_left == NULL) || (*bytes_left < 0)) {
DHD_ERROR(("%s error paramters\n", __FUNCTION__));
return -1;
}
str = *list_str;
while (*bytes_left > 0) {
if (str[0] != CSCAN_TLV_TYPE_CHANNEL_IE) {
*list_str = str;
DHD_TRACE(("End channel=%d left_parse=%d %d\n", idx, *bytes_left, str[0]));
return idx;
}
/* Get proper CSCAN_TLV_TYPE_CHANNEL_IE */
*bytes_left -= 1;
str += 1;
if (str[0] == 0) {
/* All channels */
channel_list[idx] = 0x0;
}
else {
channel_list[idx] = (uint16)str[0];
DHD_TRACE(("%s channel=%d \n", __FUNCTION__, channel_list[idx]));
}
*bytes_left -= 1;
str += 1;
if (idx++ > 255) {
DHD_ERROR(("%s Too many channels \n", __FUNCTION__));
return -1;
}
}
*list_str = str;
return idx;
}
/*
* SSIDs list parsing from cscan tlv list
*/
int
wl_iw_parse_ssid_list_tlv(char** list_str, wlc_ssid_ext_t* ssid, int max, int *bytes_left)
{
char* str;
int idx = 0;
if ((list_str == NULL) || (*list_str == NULL) || (*bytes_left < 0)) {
DHD_ERROR(("%s error paramters\n", __FUNCTION__));
return -1;
}
str = *list_str;
while (*bytes_left > 0) {
if (str[0] != CSCAN_TLV_TYPE_SSID_IE) {
*list_str = str;
DHD_TRACE(("nssid=%d left_parse=%d %d\n", idx, *bytes_left, str[0]));
return idx;
}
/* Get proper CSCAN_TLV_TYPE_SSID_IE */
*bytes_left -= 1;
str += 1;
if (str[0] == 0) {
/* Broadcast SSID */
ssid[idx].SSID_len = 0;
memset((char*)ssid[idx].SSID, 0x0, DOT11_MAX_SSID_LEN);
*bytes_left -= 1;
str += 1;
DHD_TRACE(("BROADCAST SCAN left=%d\n", *bytes_left));
}
else if (str[0] <= DOT11_MAX_SSID_LEN) {
/* Get proper SSID size */
ssid[idx].SSID_len = str[0];
*bytes_left -= 1;
str += 1;
/* Get SSID */
if (ssid[idx].SSID_len > *bytes_left) {
DHD_ERROR(("%s out of memory range len=%d but left=%d\n",
__FUNCTION__, ssid[idx].SSID_len, *bytes_left));
return -1;
}
memcpy((char*)ssid[idx].SSID, str, ssid[idx].SSID_len);
*bytes_left -= ssid[idx].SSID_len;
str += ssid[idx].SSID_len;
ssid[idx].hidden = TRUE;
DHD_TRACE(("%s :size=%d left=%d\n",
(char*)ssid[idx].SSID, ssid[idx].SSID_len, *bytes_left));
}
else {
DHD_ERROR(("### SSID size more that %d\n", str[0]));
return -1;
}
if (idx++ > max) {
DHD_ERROR(("%s number of SSIDs more that %d\n", __FUNCTION__, idx));
return -1;
}
}
*list_str = str;
return idx;
}
/* Parse a comma-separated list from list_str into ssid array, starting
* at index idx. Max specifies size of the ssid array. Parses ssids
* and returns updated idx; if idx >= max not all fit, the excess have
* not been copied. Returns -1 on empty string, or on ssid too long.
*/
int
wl_iw_parse_ssid_list(char** list_str, wlc_ssid_t* ssid, int idx, int max)
{
char* str, *ptr;
if ((list_str == NULL) || (*list_str == NULL))
return -1;
for (str = *list_str; str != NULL; str = ptr) {
/* check for next TAG */
if (!strncmp(str, GET_CHANNEL, strlen(GET_CHANNEL))) {
*list_str = str + strlen(GET_CHANNEL);
return idx;
}
if ((ptr = strchr(str, ',')) != NULL) {
*ptr++ = '\0';
}
if (strlen(str) > DOT11_MAX_SSID_LEN) {
DHD_ERROR(("ssid <%s> exceeds %d\n", str, DOT11_MAX_SSID_LEN));
return -1;
}
if (strlen(str) == 0)
ssid[idx].SSID_len = 0;
if (idx < max) {
bzero(ssid[idx].SSID, sizeof(ssid[idx].SSID));
strncpy((char*)ssid[idx].SSID, str, sizeof(ssid[idx].SSID) - 1);
ssid[idx].SSID_len = strlen(str);
}
idx++;
}
return idx;
}
/*
* Parse channel list from iwpriv CSCAN
*/
int
wl_iw_parse_channel_list(char** list_str, uint16* channel_list, int channel_num)
{
int num;
int val;
char* str;
char* endptr = NULL;
if ((list_str == NULL)||(*list_str == NULL))
return -1;
str = *list_str;
num = 0;
while (strncmp(str, GET_NPROBE, strlen(GET_NPROBE))) {
val = (int)strtoul(str, &endptr, 0);
if (endptr == str) {
printf("could not parse channel number starting at"
" substring \"%s\" in list:\n%s\n",
str, *list_str);
return -1;
}
str = endptr + strspn(endptr, " ,");
if (num == channel_num) {
DHD_ERROR(("too many channels (more than %d) in channel list:\n%s\n",
channel_num, *list_str));
return -1;
}
channel_list[num++] = (uint16)val;
}
*list_str = str;
return num;
}
| gpl-2.0 |
darth-llamah/a510_almoststock | drivers/gpio/gpio-mcp23s08.c | 410 | 16005 | /*
* MCP23S08 SPI/GPIO gpio expander driver
*/
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/mutex.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/spi/spi.h>
#include <linux/spi/mcp23s08.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
/**
* MCP types supported by driver
*/
#define MCP_TYPE_S08 0
#define MCP_TYPE_S17 1
#define MCP_TYPE_008 2
#define MCP_TYPE_017 3
/* Registers are all 8 bits wide.
*
* The mcp23s17 has twice as many bits, and can be configured to work
* with either 16 bit registers or with two adjacent 8 bit banks.
*/
#define MCP_IODIR 0x00 /* init/reset: all ones */
#define MCP_IPOL 0x01
#define MCP_GPINTEN 0x02
#define MCP_DEFVAL 0x03
#define MCP_INTCON 0x04
#define MCP_IOCON 0x05
# define IOCON_SEQOP (1 << 5)
# define IOCON_HAEN (1 << 3)
# define IOCON_ODR (1 << 2)
# define IOCON_INTPOL (1 << 1)
#define MCP_GPPU 0x06
#define MCP_INTF 0x07
#define MCP_INTCAP 0x08
#define MCP_GPIO 0x09
#define MCP_OLAT 0x0a
struct mcp23s08;
struct mcp23s08_ops {
int (*read)(struct mcp23s08 *mcp, unsigned reg);
int (*write)(struct mcp23s08 *mcp, unsigned reg, unsigned val);
int (*read_regs)(struct mcp23s08 *mcp, unsigned reg,
u16 *vals, unsigned n);
};
struct mcp23s08 {
u8 addr;
u16 cache[11];
/* lock protects the cached values */
struct mutex lock;
struct gpio_chip chip;
const struct mcp23s08_ops *ops;
void *data; /* ops specific data */
};
/* A given spi_device can represent up to eight mcp23sxx chips
* sharing the same chipselect but using different addresses
* (e.g. chips #0 and #3 might be populated, but not #1 or $2).
* Driver data holds all the per-chip data.
*/
struct mcp23s08_driver_data {
unsigned ngpio;
struct mcp23s08 *mcp[8];
struct mcp23s08 chip[];
};
/*----------------------------------------------------------------------*/
#ifdef CONFIG_I2C
static int mcp23008_read(struct mcp23s08 *mcp, unsigned reg)
{
return i2c_smbus_read_byte_data(mcp->data, reg);
}
static int mcp23008_write(struct mcp23s08 *mcp, unsigned reg, unsigned val)
{
return i2c_smbus_write_byte_data(mcp->data, reg, val);
}
static int
mcp23008_read_regs(struct mcp23s08 *mcp, unsigned reg, u16 *vals, unsigned n)
{
while (n--) {
int ret = mcp23008_read(mcp, reg++);
if (ret < 0)
return ret;
*vals++ = ret;
}
return 0;
}
static int mcp23017_read(struct mcp23s08 *mcp, unsigned reg)
{
return i2c_smbus_read_word_data(mcp->data, reg << 1);
}
static int mcp23017_write(struct mcp23s08 *mcp, unsigned reg, unsigned val)
{
return i2c_smbus_write_word_data(mcp->data, reg << 1, val);
}
static int
mcp23017_read_regs(struct mcp23s08 *mcp, unsigned reg, u16 *vals, unsigned n)
{
while (n--) {
int ret = mcp23017_read(mcp, reg++);
if (ret < 0)
return ret;
*vals++ = ret;
}
return 0;
}
static const struct mcp23s08_ops mcp23008_ops = {
.read = mcp23008_read,
.write = mcp23008_write,
.read_regs = mcp23008_read_regs,
};
static const struct mcp23s08_ops mcp23017_ops = {
.read = mcp23017_read,
.write = mcp23017_write,
.read_regs = mcp23017_read_regs,
};
#endif /* CONFIG_I2C */
/*----------------------------------------------------------------------*/
#ifdef CONFIG_SPI_MASTER
static int mcp23s08_read(struct mcp23s08 *mcp, unsigned reg)
{
u8 tx[2], rx[1];
int status;
tx[0] = mcp->addr | 0x01;
tx[1] = reg;
status = spi_write_then_read(mcp->data, tx, sizeof tx, rx, sizeof rx);
return (status < 0) ? status : rx[0];
}
static int mcp23s08_write(struct mcp23s08 *mcp, unsigned reg, unsigned val)
{
u8 tx[3];
tx[0] = mcp->addr;
tx[1] = reg;
tx[2] = val;
return spi_write_then_read(mcp->data, tx, sizeof tx, NULL, 0);
}
static int
mcp23s08_read_regs(struct mcp23s08 *mcp, unsigned reg, u16 *vals, unsigned n)
{
u8 tx[2], *tmp;
int status;
if ((n + reg) > sizeof mcp->cache)
return -EINVAL;
tx[0] = mcp->addr | 0x01;
tx[1] = reg;
tmp = (u8 *)vals;
status = spi_write_then_read(mcp->data, tx, sizeof tx, tmp, n);
if (status >= 0) {
while (n--)
vals[n] = tmp[n]; /* expand to 16bit */
}
return status;
}
static int mcp23s17_read(struct mcp23s08 *mcp, unsigned reg)
{
u8 tx[2], rx[2];
int status;
tx[0] = mcp->addr | 0x01;
tx[1] = reg << 1;
status = spi_write_then_read(mcp->data, tx, sizeof tx, rx, sizeof rx);
return (status < 0) ? status : (rx[0] | (rx[1] << 8));
}
static int mcp23s17_write(struct mcp23s08 *mcp, unsigned reg, unsigned val)
{
u8 tx[4];
tx[0] = mcp->addr;
tx[1] = reg << 1;
tx[2] = val;
tx[3] = val >> 8;
return spi_write_then_read(mcp->data, tx, sizeof tx, NULL, 0);
}
static int
mcp23s17_read_regs(struct mcp23s08 *mcp, unsigned reg, u16 *vals, unsigned n)
{
u8 tx[2];
int status;
if ((n + reg) > sizeof mcp->cache)
return -EINVAL;
tx[0] = mcp->addr | 0x01;
tx[1] = reg << 1;
status = spi_write_then_read(mcp->data, tx, sizeof tx,
(u8 *)vals, n * 2);
if (status >= 0) {
while (n--)
vals[n] = __le16_to_cpu((__le16)vals[n]);
}
return status;
}
static const struct mcp23s08_ops mcp23s08_ops = {
.read = mcp23s08_read,
.write = mcp23s08_write,
.read_regs = mcp23s08_read_regs,
};
static const struct mcp23s08_ops mcp23s17_ops = {
.read = mcp23s17_read,
.write = mcp23s17_write,
.read_regs = mcp23s17_read_regs,
};
#endif /* CONFIG_SPI_MASTER */
/*----------------------------------------------------------------------*/
static int mcp23s08_direction_input(struct gpio_chip *chip, unsigned offset)
{
struct mcp23s08 *mcp = container_of(chip, struct mcp23s08, chip);
int status;
mutex_lock(&mcp->lock);
mcp->cache[MCP_IODIR] |= (1 << offset);
status = mcp->ops->write(mcp, MCP_IODIR, mcp->cache[MCP_IODIR]);
mutex_unlock(&mcp->lock);
return status;
}
static int mcp23s08_get(struct gpio_chip *chip, unsigned offset)
{
struct mcp23s08 *mcp = container_of(chip, struct mcp23s08, chip);
int status;
mutex_lock(&mcp->lock);
/* REVISIT reading this clears any IRQ ... */
status = mcp->ops->read(mcp, MCP_GPIO);
if (status < 0)
status = 0;
else {
mcp->cache[MCP_GPIO] = status;
status = !!(status & (1 << offset));
}
mutex_unlock(&mcp->lock);
return status;
}
static int __mcp23s08_set(struct mcp23s08 *mcp, unsigned mask, int value)
{
unsigned olat = mcp->cache[MCP_OLAT];
if (value)
olat |= mask;
else
olat &= ~mask;
mcp->cache[MCP_OLAT] = olat;
return mcp->ops->write(mcp, MCP_OLAT, olat);
}
static void mcp23s08_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct mcp23s08 *mcp = container_of(chip, struct mcp23s08, chip);
unsigned mask = 1 << offset;
mutex_lock(&mcp->lock);
__mcp23s08_set(mcp, mask, value);
mutex_unlock(&mcp->lock);
}
static int
mcp23s08_direction_output(struct gpio_chip *chip, unsigned offset, int value)
{
struct mcp23s08 *mcp = container_of(chip, struct mcp23s08, chip);
unsigned mask = 1 << offset;
int status;
mutex_lock(&mcp->lock);
status = __mcp23s08_set(mcp, mask, value);
if (status == 0) {
mcp->cache[MCP_IODIR] &= ~mask;
status = mcp->ops->write(mcp, MCP_IODIR, mcp->cache[MCP_IODIR]);
}
mutex_unlock(&mcp->lock);
return status;
}
/*----------------------------------------------------------------------*/
#ifdef CONFIG_DEBUG_FS
#include <linux/seq_file.h>
/*
* This shows more info than the generic gpio dump code:
* pullups, deglitching, open drain drive.
*/
static void mcp23s08_dbg_show(struct seq_file *s, struct gpio_chip *chip)
{
struct mcp23s08 *mcp;
char bank;
int t;
unsigned mask;
mcp = container_of(chip, struct mcp23s08, chip);
/* NOTE: we only handle one bank for now ... */
bank = '0' + ((mcp->addr >> 1) & 0x7);
mutex_lock(&mcp->lock);
t = mcp->ops->read_regs(mcp, 0, mcp->cache, ARRAY_SIZE(mcp->cache));
if (t < 0) {
seq_printf(s, " I/O ERROR %d\n", t);
goto done;
}
for (t = 0, mask = 1; t < chip->ngpio; t++, mask <<= 1) {
const char *label;
label = gpiochip_is_requested(chip, t);
if (!label)
continue;
seq_printf(s, " gpio-%-3d P%c.%d (%-12s) %s %s %s",
chip->base + t, bank, t, label,
(mcp->cache[MCP_IODIR] & mask) ? "in " : "out",
(mcp->cache[MCP_GPIO] & mask) ? "hi" : "lo",
(mcp->cache[MCP_GPPU] & mask) ? " " : "up");
/* NOTE: ignoring the irq-related registers */
seq_printf(s, "\n");
}
done:
mutex_unlock(&mcp->lock);
}
#else
#define mcp23s08_dbg_show NULL
#endif
/*----------------------------------------------------------------------*/
static int mcp23s08_probe_one(struct mcp23s08 *mcp, struct device *dev,
void *data, unsigned addr,
unsigned type, unsigned base, unsigned pullups)
{
int status;
mutex_init(&mcp->lock);
mcp->data = data;
mcp->addr = addr;
mcp->chip.direction_input = mcp23s08_direction_input;
mcp->chip.get = mcp23s08_get;
mcp->chip.direction_output = mcp23s08_direction_output;
mcp->chip.set = mcp23s08_set;
mcp->chip.dbg_show = mcp23s08_dbg_show;
switch (type) {
#ifdef CONFIG_SPI_MASTER
case MCP_TYPE_S08:
mcp->ops = &mcp23s08_ops;
mcp->chip.ngpio = 8;
mcp->chip.label = "mcp23s08";
break;
case MCP_TYPE_S17:
mcp->ops = &mcp23s17_ops;
mcp->chip.ngpio = 16;
mcp->chip.label = "mcp23s17";
break;
#endif /* CONFIG_SPI_MASTER */
#ifdef CONFIG_I2C
case MCP_TYPE_008:
mcp->ops = &mcp23008_ops;
mcp->chip.ngpio = 8;
mcp->chip.label = "mcp23008";
break;
case MCP_TYPE_017:
mcp->ops = &mcp23017_ops;
mcp->chip.ngpio = 16;
mcp->chip.label = "mcp23017";
break;
#endif /* CONFIG_I2C */
default:
dev_err(dev, "invalid device type (%d)\n", type);
return -EINVAL;
}
mcp->chip.base = base;
mcp->chip.can_sleep = 1;
mcp->chip.dev = dev;
mcp->chip.owner = THIS_MODULE;
/* verify MCP_IOCON.SEQOP = 0, so sequential reads work,
* and MCP_IOCON.HAEN = 1, so we work with all chips.
*/
status = mcp->ops->read(mcp, MCP_IOCON);
if (status < 0)
goto fail;
if ((status & IOCON_SEQOP) || !(status & IOCON_HAEN)) {
/* mcp23s17 has IOCON twice, make sure they are in sync */
status &= ~(IOCON_SEQOP | (IOCON_SEQOP << 8));
status |= IOCON_HAEN | (IOCON_HAEN << 8);
status = mcp->ops->write(mcp, MCP_IOCON, status);
if (status < 0)
goto fail;
}
/* configure ~100K pullups */
status = mcp->ops->write(mcp, MCP_GPPU, pullups);
if (status < 0)
goto fail;
status = mcp->ops->read_regs(mcp, 0, mcp->cache, ARRAY_SIZE(mcp->cache));
if (status < 0)
goto fail;
/* disable inverter on input */
if (mcp->cache[MCP_IPOL] != 0) {
mcp->cache[MCP_IPOL] = 0;
status = mcp->ops->write(mcp, MCP_IPOL, 0);
if (status < 0)
goto fail;
}
/* disable irqs */
if (mcp->cache[MCP_GPINTEN] != 0) {
mcp->cache[MCP_GPINTEN] = 0;
status = mcp->ops->write(mcp, MCP_GPINTEN, 0);
if (status < 0)
goto fail;
}
status = gpiochip_add(&mcp->chip);
fail:
if (status < 0)
dev_dbg(dev, "can't setup chip %d, --> %d\n",
addr, status);
return status;
}
/*----------------------------------------------------------------------*/
#ifdef CONFIG_I2C
static int __devinit mcp230xx_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct mcp23s08_platform_data *pdata;
struct mcp23s08 *mcp;
int status;
pdata = client->dev.platform_data;
if (!pdata || !gpio_is_valid(pdata->base)) {
dev_dbg(&client->dev, "invalid or missing platform data\n");
return -EINVAL;
}
mcp = kzalloc(sizeof *mcp, GFP_KERNEL);
if (!mcp)
return -ENOMEM;
status = mcp23s08_probe_one(mcp, &client->dev, client, client->addr,
id->driver_data, pdata->base,
pdata->chip[0].pullups);
if (status)
goto fail;
i2c_set_clientdata(client, mcp);
return 0;
fail:
kfree(mcp);
return status;
}
static int __devexit mcp230xx_remove(struct i2c_client *client)
{
struct mcp23s08 *mcp = i2c_get_clientdata(client);
int status;
status = gpiochip_remove(&mcp->chip);
if (status == 0)
kfree(mcp);
return status;
}
static const struct i2c_device_id mcp230xx_id[] = {
{ "mcp23008", MCP_TYPE_008 },
{ "mcp23017", MCP_TYPE_017 },
{ },
};
MODULE_DEVICE_TABLE(i2c, mcp230xx_id);
static struct i2c_driver mcp230xx_driver = {
.driver = {
.name = "mcp230xx",
.owner = THIS_MODULE,
},
.probe = mcp230xx_probe,
.remove = __devexit_p(mcp230xx_remove),
.id_table = mcp230xx_id,
};
static int __init mcp23s08_i2c_init(void)
{
return i2c_add_driver(&mcp230xx_driver);
}
static void mcp23s08_i2c_exit(void)
{
i2c_del_driver(&mcp230xx_driver);
}
#else
static int __init mcp23s08_i2c_init(void) { return 0; }
static void mcp23s08_i2c_exit(void) { }
#endif /* CONFIG_I2C */
/*----------------------------------------------------------------------*/
#ifdef CONFIG_SPI_MASTER
static int mcp23s08_probe(struct spi_device *spi)
{
struct mcp23s08_platform_data *pdata;
unsigned addr;
unsigned chips = 0;
struct mcp23s08_driver_data *data;
int status, type;
unsigned base;
type = spi_get_device_id(spi)->driver_data;
pdata = spi->dev.platform_data;
if (!pdata || !gpio_is_valid(pdata->base)) {
dev_dbg(&spi->dev, "invalid or missing platform data\n");
return -EINVAL;
}
for (addr = 0; addr < ARRAY_SIZE(pdata->chip); addr++) {
if (!pdata->chip[addr].is_present)
continue;
chips++;
if ((type == MCP_TYPE_S08) && (addr > 3)) {
dev_err(&spi->dev,
"mcp23s08 only supports address 0..3\n");
return -EINVAL;
}
}
if (!chips)
return -ENODEV;
data = kzalloc(sizeof *data + chips * sizeof(struct mcp23s08),
GFP_KERNEL);
if (!data)
return -ENOMEM;
spi_set_drvdata(spi, data);
base = pdata->base;
for (addr = 0; addr < ARRAY_SIZE(pdata->chip); addr++) {
if (!pdata->chip[addr].is_present)
continue;
chips--;
data->mcp[addr] = &data->chip[chips];
status = mcp23s08_probe_one(data->mcp[addr], &spi->dev, spi,
0x40 | (addr << 1), type, base,
pdata->chip[addr].pullups);
if (status < 0)
goto fail;
base += (type == MCP_TYPE_S17) ? 16 : 8;
}
data->ngpio = base - pdata->base;
/* NOTE: these chips have a relatively sane IRQ framework, with
* per-signal masking and level/edge triggering. It's not yet
* handled here...
*/
return 0;
fail:
for (addr = 0; addr < ARRAY_SIZE(data->mcp); addr++) {
int tmp;
if (!data->mcp[addr])
continue;
tmp = gpiochip_remove(&data->mcp[addr]->chip);
if (tmp < 0)
dev_err(&spi->dev, "%s --> %d\n", "remove", tmp);
}
kfree(data);
return status;
}
static int mcp23s08_remove(struct spi_device *spi)
{
struct mcp23s08_driver_data *data = spi_get_drvdata(spi);
unsigned addr;
int status = 0;
for (addr = 0; addr < ARRAY_SIZE(data->mcp); addr++) {
int tmp;
if (!data->mcp[addr])
continue;
tmp = gpiochip_remove(&data->mcp[addr]->chip);
if (tmp < 0) {
dev_err(&spi->dev, "%s --> %d\n", "remove", tmp);
status = tmp;
}
}
if (status == 0)
kfree(data);
return status;
}
static const struct spi_device_id mcp23s08_ids[] = {
{ "mcp23s08", MCP_TYPE_S08 },
{ "mcp23s17", MCP_TYPE_S17 },
{ },
};
MODULE_DEVICE_TABLE(spi, mcp23s08_ids);
static struct spi_driver mcp23s08_driver = {
.probe = mcp23s08_probe,
.remove = mcp23s08_remove,
.id_table = mcp23s08_ids,
.driver = {
.name = "mcp23s08",
.owner = THIS_MODULE,
},
};
static int __init mcp23s08_spi_init(void)
{
return spi_register_driver(&mcp23s08_driver);
}
static void mcp23s08_spi_exit(void)
{
spi_unregister_driver(&mcp23s08_driver);
}
#else
static int __init mcp23s08_spi_init(void) { return 0; }
static void mcp23s08_spi_exit(void) { }
#endif /* CONFIG_SPI_MASTER */
/*----------------------------------------------------------------------*/
static int __init mcp23s08_init(void)
{
int ret;
ret = mcp23s08_spi_init();
if (ret)
goto spi_fail;
ret = mcp23s08_i2c_init();
if (ret)
goto i2c_fail;
return 0;
i2c_fail:
mcp23s08_spi_exit();
spi_fail:
return ret;
}
/* register after spi/i2c postcore initcall and before
* subsys initcalls that may rely on these GPIOs
*/
subsys_initcall(mcp23s08_init);
static void __exit mcp23s08_exit(void)
{
mcp23s08_spi_exit();
mcp23s08_i2c_exit();
}
module_exit(mcp23s08_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Mathijsz/razdroid-kernel | arch/mips/kernel/smp-mt.c | 666 | 7322 | /*
* 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.
*
* Copyright (C) 2004, 05, 06 MIPS Technologies, Inc.
* Elizabeth Clarke (beth@mips.com)
* Ralf Baechle (ralf@linux-mips.org)
* Copyright (C) 2006 Ralf Baechle (ralf@linux-mips.org)
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/cpumask.h>
#include <linux/interrupt.h>
#include <linux/compiler.h>
#include <linux/smp.h>
#include <linux/atomic.h>
#include <asm/cacheflush.h>
#include <asm/cpu.h>
#include <asm/processor.h>
#include <asm/system.h>
#include <asm/hardirq.h>
#include <asm/mmu_context.h>
#include <asm/time.h>
#include <asm/mipsregs.h>
#include <asm/mipsmtregs.h>
#include <asm/mips_mt.h>
static void __init smvp_copy_vpe_config(void)
{
write_vpe_c0_status(
(read_c0_status() & ~(ST0_IM | ST0_IE | ST0_KSU)) | ST0_CU0);
/* set config to be the same as vpe0, particularly kseg0 coherency alg */
write_vpe_c0_config( read_c0_config());
/* make sure there are no software interrupts pending */
write_vpe_c0_cause(0);
/* Propagate Config7 */
write_vpe_c0_config7(read_c0_config7());
write_vpe_c0_count(read_c0_count());
}
static unsigned int __init smvp_vpe_init(unsigned int tc, unsigned int mvpconf0,
unsigned int ncpu)
{
if (tc > ((mvpconf0 & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT))
return ncpu;
/* Deactivate all but VPE 0 */
if (tc != 0) {
unsigned long tmp = read_vpe_c0_vpeconf0();
tmp &= ~VPECONF0_VPA;
/* master VPE */
tmp |= VPECONF0_MVP;
write_vpe_c0_vpeconf0(tmp);
/* Record this as available CPU */
set_cpu_possible(tc, true);
__cpu_number_map[tc] = ++ncpu;
__cpu_logical_map[ncpu] = tc;
}
/* Disable multi-threading with TC's */
write_vpe_c0_vpecontrol(read_vpe_c0_vpecontrol() & ~VPECONTROL_TE);
if (tc != 0)
smvp_copy_vpe_config();
return ncpu;
}
static void __init smvp_tc_init(unsigned int tc, unsigned int mvpconf0)
{
unsigned long tmp;
if (!tc)
return;
/* bind a TC to each VPE, May as well put all excess TC's
on the last VPE */
if (tc >= (((mvpconf0 & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT)+1))
write_tc_c0_tcbind(read_tc_c0_tcbind() | ((mvpconf0 & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT));
else {
write_tc_c0_tcbind(read_tc_c0_tcbind() | tc);
/* and set XTC */
write_vpe_c0_vpeconf0(read_vpe_c0_vpeconf0() | (tc << VPECONF0_XTC_SHIFT));
}
tmp = read_tc_c0_tcstatus();
/* mark not allocated and not dynamically allocatable */
tmp &= ~(TCSTATUS_A | TCSTATUS_DA);
tmp |= TCSTATUS_IXMT; /* interrupt exempt */
write_tc_c0_tcstatus(tmp);
write_tc_c0_tchalt(TCHALT_H);
}
static void vsmp_send_ipi_single(int cpu, unsigned int action)
{
int i;
unsigned long flags;
int vpflags;
local_irq_save(flags);
vpflags = dvpe(); /* can't access the other CPU's registers whilst MVPE enabled */
switch (action) {
case SMP_CALL_FUNCTION:
i = C_SW1;
break;
case SMP_RESCHEDULE_YOURSELF:
default:
i = C_SW0;
break;
}
/* 1:1 mapping of vpe and tc... */
settc(cpu);
write_vpe_c0_cause(read_vpe_c0_cause() | i);
evpe(vpflags);
local_irq_restore(flags);
}
static void vsmp_send_ipi_mask(const struct cpumask *mask, unsigned int action)
{
unsigned int i;
for_each_cpu(i, mask)
vsmp_send_ipi_single(i, action);
}
static void __cpuinit vsmp_init_secondary(void)
{
extern int gic_present;
/* This is Malta specific: IPI,performance and timer interrupts */
if (gic_present)
change_c0_status(ST0_IM, STATUSF_IP3 | STATUSF_IP4 |
STATUSF_IP6 | STATUSF_IP7);
else
change_c0_status(ST0_IM, STATUSF_IP0 | STATUSF_IP1 |
STATUSF_IP6 | STATUSF_IP7);
}
static void __cpuinit vsmp_smp_finish(void)
{
/* CDFIXME: remove this? */
write_c0_compare(read_c0_count() + (8* mips_hpt_frequency/HZ));
#ifdef CONFIG_MIPS_MT_FPAFF
/* If we have an FPU, enroll ourselves in the FPU-full mask */
if (cpu_has_fpu)
cpu_set(smp_processor_id(), mt_fpu_cpumask);
#endif /* CONFIG_MIPS_MT_FPAFF */
local_irq_enable();
}
static void vsmp_cpus_done(void)
{
}
/*
* Setup the PC, SP, and GP of a secondary processor and start it
* running!
* smp_bootstrap is the place to resume from
* __KSTK_TOS(idle) is apparently the stack pointer
* (unsigned long)idle->thread_info the gp
* assumes a 1:1 mapping of TC => VPE
*/
static void __cpuinit vsmp_boot_secondary(int cpu, struct task_struct *idle)
{
struct thread_info *gp = task_thread_info(idle);
dvpe();
set_c0_mvpcontrol(MVPCONTROL_VPC);
settc(cpu);
/* restart */
write_tc_c0_tcrestart((unsigned long)&smp_bootstrap);
/* enable the tc this vpe/cpu will be running */
write_tc_c0_tcstatus((read_tc_c0_tcstatus() & ~TCSTATUS_IXMT) | TCSTATUS_A);
write_tc_c0_tchalt(0);
/* enable the VPE */
write_vpe_c0_vpeconf0(read_vpe_c0_vpeconf0() | VPECONF0_VPA);
/* stack pointer */
write_tc_gpr_sp( __KSTK_TOS(idle));
/* global pointer */
write_tc_gpr_gp((unsigned long)gp);
flush_icache_range((unsigned long)gp,
(unsigned long)(gp + sizeof(struct thread_info)));
/* finally out of configuration and into chaos */
clear_c0_mvpcontrol(MVPCONTROL_VPC);
evpe(EVPE_ENABLE);
}
/*
* Common setup before any secondaries are started
* Make sure all CPU's are in a sensible state before we boot any of the
* secondaries
*/
static void __init vsmp_smp_setup(void)
{
unsigned int mvpconf0, ntc, tc, ncpu = 0;
unsigned int nvpe;
#ifdef CONFIG_MIPS_MT_FPAFF
/* If we have an FPU, enroll ourselves in the FPU-full mask */
if (cpu_has_fpu)
cpu_set(0, mt_fpu_cpumask);
#endif /* CONFIG_MIPS_MT_FPAFF */
if (!cpu_has_mipsmt)
return;
/* disable MT so we can configure */
dvpe();
dmt();
/* Put MVPE's into 'configuration state' */
set_c0_mvpcontrol(MVPCONTROL_VPC);
mvpconf0 = read_c0_mvpconf0();
ntc = (mvpconf0 & MVPCONF0_PTC) >> MVPCONF0_PTC_SHIFT;
nvpe = ((mvpconf0 & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT) + 1;
smp_num_siblings = nvpe;
/* we'll always have more TC's than VPE's, so loop setting everything
to a sensible state */
for (tc = 0; tc <= ntc; tc++) {
settc(tc);
smvp_tc_init(tc, mvpconf0);
ncpu = smvp_vpe_init(tc, mvpconf0, ncpu);
}
/* Release config state */
clear_c0_mvpcontrol(MVPCONTROL_VPC);
/* We'll wait until starting the secondaries before starting MVPE */
printk(KERN_INFO "Detected %i available secondary CPU(s)\n", ncpu);
}
static void __init vsmp_prepare_cpus(unsigned int max_cpus)
{
mips_mt_set_cpuoptions();
}
struct plat_smp_ops vsmp_smp_ops = {
.send_ipi_single = vsmp_send_ipi_single,
.send_ipi_mask = vsmp_send_ipi_mask,
.init_secondary = vsmp_init_secondary,
.smp_finish = vsmp_smp_finish,
.cpus_done = vsmp_cpus_done,
.boot_secondary = vsmp_boot_secondary,
.smp_setup = vsmp_smp_setup,
.prepare_cpus = vsmp_prepare_cpus,
};
| gpl-2.0 |
infectedmushi/kernel-sony-copyleft | arch/mips/pmcs-msp71xx/msp_irq_cic.c | 922 | 5018 | /*
* Copyright 2010 PMC-Sierra, Inc, derived from irq_cpu.c
*
* This file define the irq handler for MSP CIC 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/bitops.h>
#include <linux/irq.h>
#include <asm/mipsregs.h>
#include <msp_cic_int.h>
#include <msp_regs.h>
/*
* External API
*/
extern void msp_per_irq_init(void);
extern void msp_per_irq_dispatch(void);
/*
* Convenience Macro. Should be somewhere generic.
*/
#define get_current_vpe() \
((read_c0_tcbind() >> TCBIND_CURVPE_SHIFT) & TCBIND_CURVPE)
#ifdef CONFIG_SMP
#define LOCK_VPE(flags, mtflags) \
do { \
local_irq_save(flags); \
mtflags = dmt(); \
} while (0)
#define UNLOCK_VPE(flags, mtflags) \
do { \
emt(mtflags); \
local_irq_restore(flags);\
} while (0)
#define LOCK_CORE(flags, mtflags) \
do { \
local_irq_save(flags); \
mtflags = dvpe(); \
} while (0)
#define UNLOCK_CORE(flags, mtflags) \
do { \
evpe(mtflags); \
local_irq_restore(flags);\
} while (0)
#else
#define LOCK_VPE(flags, mtflags)
#define UNLOCK_VPE(flags, mtflags)
#endif
/* ensure writes to cic are completed */
static inline void cic_wmb(void)
{
const volatile void __iomem *cic_mem = CIC_VPE0_MSK_REG;
volatile u32 dummy_read;
wmb();
dummy_read = __raw_readl(cic_mem);
dummy_read++;
}
static void unmask_cic_irq(struct irq_data *d)
{
volatile u32 *cic_msk_reg = CIC_VPE0_MSK_REG;
int vpe;
#ifdef CONFIG_SMP
unsigned int mtflags;
unsigned long flags;
/*
* Make sure we have IRQ affinity. It may have changed while
* we were processing the IRQ.
*/
if (!cpumask_test_cpu(smp_processor_id(), d->affinity))
return;
#endif
vpe = get_current_vpe();
LOCK_VPE(flags, mtflags);
cic_msk_reg[vpe] |= (1 << (d->irq - MSP_CIC_INTBASE));
UNLOCK_VPE(flags, mtflags);
cic_wmb();
}
static void mask_cic_irq(struct irq_data *d)
{
volatile u32 *cic_msk_reg = CIC_VPE0_MSK_REG;
int vpe = get_current_vpe();
#ifdef CONFIG_SMP
unsigned long flags, mtflags;
#endif
LOCK_VPE(flags, mtflags);
cic_msk_reg[vpe] &= ~(1 << (d->irq - MSP_CIC_INTBASE));
UNLOCK_VPE(flags, mtflags);
cic_wmb();
}
static void msp_cic_irq_ack(struct irq_data *d)
{
mask_cic_irq(d);
/*
* Only really necessary for 18, 16-14 and sometimes 3:0
* (since these can be edge sensitive) but it doesn't
* hurt for the others
*/
*CIC_STS_REG = (1 << (d->irq - MSP_CIC_INTBASE));
}
/* Note: Limiting to VSMP. */
#ifdef CONFIG_MIPS_MT_SMP
static int msp_cic_irq_set_affinity(struct irq_data *d,
const struct cpumask *cpumask, bool force)
{
int cpu;
unsigned long flags;
unsigned int mtflags;
unsigned long imask = (1 << (d->irq - MSP_CIC_INTBASE));
volatile u32 *cic_mask = (volatile u32 *)CIC_VPE0_MSK_REG;
/* timer balancing should be disabled in kernel code */
BUG_ON(d->irq == MSP_INT_VPE0_TIMER || d->irq == MSP_INT_VPE1_TIMER);
LOCK_CORE(flags, mtflags);
/* enable if any of each VPE's TCs require this IRQ */
for_each_online_cpu(cpu) {
if (cpumask_test_cpu(cpu, cpumask))
cic_mask[cpu] |= imask;
else
cic_mask[cpu] &= ~imask;
}
UNLOCK_CORE(flags, mtflags);
return 0;
}
#endif
static struct irq_chip msp_cic_irq_controller = {
.name = "MSP_CIC",
.irq_mask = mask_cic_irq,
.irq_mask_ack = msp_cic_irq_ack,
.irq_unmask = unmask_cic_irq,
.irq_ack = msp_cic_irq_ack,
#ifdef CONFIG_MIPS_MT_SMP
.irq_set_affinity = msp_cic_irq_set_affinity,
#endif
};
void __init msp_cic_irq_init(void)
{
int i;
/* Mask/clear interrupts. */
*CIC_VPE0_MSK_REG = 0x00000000;
*CIC_VPE1_MSK_REG = 0x00000000;
*CIC_STS_REG = 0xFFFFFFFF;
/*
* The MSP7120 RG and EVBD boards use IRQ[6:4] for PCI.
* These inputs map to EXT_INT_POL[6:4] inside the CIC.
* They are to be active low, level sensitive.
*/
*CIC_EXT_CFG_REG &= 0xFFFF8F8F;
/* initialize all the IRQ descriptors */
for (i = MSP_CIC_INTBASE ; i < MSP_CIC_INTBASE + 32 ; i++) {
irq_set_chip_and_handler(i, &msp_cic_irq_controller,
handle_level_irq);
}
/* Initialize the PER interrupt sub-system */
msp_per_irq_init();
}
/* CIC masked by CIC vector processing before dispatch called */
void msp_cic_irq_dispatch(void)
{
volatile u32 *cic_msk_reg = (volatile u32 *)CIC_VPE0_MSK_REG;
u32 cic_mask;
u32 pending;
int cic_status = *CIC_STS_REG;
cic_mask = cic_msk_reg[get_current_vpe()];
pending = cic_status & cic_mask;
if (pending & (1 << (MSP_INT_VPE0_TIMER - MSP_CIC_INTBASE))) {
do_IRQ(MSP_INT_VPE0_TIMER);
} else if (pending & (1 << (MSP_INT_VPE1_TIMER - MSP_CIC_INTBASE))) {
do_IRQ(MSP_INT_VPE1_TIMER);
} else if (pending & (1 << (MSP_INT_PER - MSP_CIC_INTBASE))) {
msp_per_irq_dispatch();
} else if (pending) {
do_IRQ(ffs(pending) + MSP_CIC_INTBASE - 1);
} else{
spurious_interrupt();
}
}
| gpl-2.0 |
oguz298/FTL-Kernel | arch/arm/mach-s3c24xx/s3c2416.c | 1178 | 4129 | /* linux/arch/arm/mach-s3c2416/s3c2416.c
*
* Copyright (c) 2009 Yauhen Kharuzhy <jekhor@gmail.com>,
* as part of OpenInkpot project
* Copyright (c) 2009 Promwad Innovation Company
* Yauhen Kharuzhy <yauhen.kharuzhy@promwad.com>
*
* Samsung S3C2416 Mobile CPU 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; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/serial_core.h>
#include <linux/device.h>
#include <linux/syscore_ops.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <asm/proc-fns.h>
#include <asm/irq.h>
#include <asm/system_misc.h>
#include <mach/regs-s3c2443-clock.h>
#include <plat/gpio-core.h>
#include <plat/gpio-cfg.h>
#include <plat/gpio-cfg-helpers.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/sdhci.h>
#include <plat/pm.h>
#include <plat/iic-core.h>
#include <plat/fb-core.h>
#include <plat/nand-core.h>
#include <plat/adc-core.h>
#include <plat/rtc-core.h>
#include <plat/spi-core.h>
#include "common.h"
static struct map_desc s3c2416_iodesc[] __initdata = {
IODESC_ENT(WATCHDOG),
IODESC_ENT(CLKPWR),
IODESC_ENT(TIMER),
};
struct bus_type s3c2416_subsys = {
.name = "s3c2416-core",
.dev_name = "s3c2416-core",
};
static struct device s3c2416_dev = {
.bus = &s3c2416_subsys,
};
void s3c2416_restart(char mode, const char *cmd)
{
if (mode == 's')
soft_restart(0);
__raw_writel(S3C2443_SWRST_RESET, S3C2443_SWRST);
}
int __init s3c2416_init(void)
{
printk(KERN_INFO "S3C2416: Initializing architecture\n");
/* change WDT IRQ number */
s3c_device_wdt.resource[1].start = IRQ_S3C2443_WDT;
s3c_device_wdt.resource[1].end = IRQ_S3C2443_WDT;
/* the i2c devices are directly compatible with s3c2440 */
s3c_i2c0_setname("s3c2440-i2c");
s3c_i2c1_setname("s3c2440-i2c");
s3c_fb_setname("s3c2443-fb");
s3c_adc_setname("s3c2416-adc");
s3c_rtc_setname("s3c2416-rtc");
#ifdef CONFIG_PM
register_syscore_ops(&s3c2416_pm_syscore_ops);
register_syscore_ops(&s3c24xx_irq_syscore_ops);
register_syscore_ops(&s3c2416_irq_syscore_ops);
#endif
return device_register(&s3c2416_dev);
}
void __init s3c2416_init_uarts(struct s3c2410_uartcfg *cfg, int no)
{
s3c24xx_init_uartdevs("s3c2440-uart", s3c2410_uart_resources, cfg, no);
s3c_nand_setname("s3c2412-nand");
}
/* s3c2416_map_io
*
* register the standard cpu IO areas, and any passed in from the
* machine specific initialisation.
*/
void __init s3c2416_map_io(void)
{
s3c24xx_gpiocfg_default.set_pull = samsung_gpio_setpull_updown;
s3c24xx_gpiocfg_default.get_pull = samsung_gpio_getpull_updown;
/* initialize device information early */
s3c2416_default_sdhci0();
s3c2416_default_sdhci1();
s3c64xx_spi_setname("s3c2443-spi");
iotable_init(s3c2416_iodesc, ARRAY_SIZE(s3c2416_iodesc));
}
/* need to register the subsystem before we actually register the device, and
* we also need to ensure that it has been initialised before any of the
* drivers even try to use it (even if not on an s3c2416 based system)
* as a driver which may support both 2443 and 2440 may try and use it.
*/
static int __init s3c2416_core_init(void)
{
return subsys_system_register(&s3c2416_subsys, NULL);
}
core_initcall(s3c2416_core_init);
| gpl-2.0 |
CyanogenMod/android_kernel_motorola_msm8916 | fs/ocfs2/dlmfs/dlmfs.c | 2202 | 17204 | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* dlmfs.c
*
* Code which implements the kernel side of a minimal userspace
* interface to our DLM. This file handles the virtual file system
* used for communication with userspace. Credit should go to ramfs,
* which was a template for the fs side of this module.
*
* Copyright (C) 2003, 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.
*/
/* Simple VFS hooks based on: */
/*
* Resizable simple ram filesystem for Linux.
*
* Copyright (C) 2000 Linus Torvalds.
* 2000 Transmeta Corp.
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/pagemap.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/highmem.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/backing-dev.h>
#include <linux/poll.h>
#include <asm/uaccess.h>
#include "stackglue.h"
#include "userdlm.h"
#include "dlmfsver.h"
#define MLOG_MASK_PREFIX ML_DLMFS
#include "cluster/masklog.h"
static const struct super_operations dlmfs_ops;
static const struct file_operations dlmfs_file_operations;
static const struct inode_operations dlmfs_dir_inode_operations;
static const struct inode_operations dlmfs_root_inode_operations;
static const struct inode_operations dlmfs_file_inode_operations;
static struct kmem_cache *dlmfs_inode_cache;
struct workqueue_struct *user_dlm_worker;
/*
* These are the ABI capabilities of dlmfs.
*
* Over time, dlmfs has added some features that were not part of the
* initial ABI. Unfortunately, some of these features are not detectable
* via standard usage. For example, Linux's default poll always returns
* POLLIN, so there is no way for a caller of poll(2) to know when dlmfs
* added poll support. Instead, we provide this list of new capabilities.
*
* Capabilities is a read-only attribute. We do it as a module parameter
* so we can discover it whether dlmfs is built in, loaded, or even not
* loaded.
*
* The ABI features are local to this machine's dlmfs mount. This is
* distinct from the locking protocol, which is concerned with inter-node
* interaction.
*
* Capabilities:
* - bast : POLLIN against the file descriptor of a held lock
* signifies a bast fired on the lock.
*/
#define DLMFS_CAPABILITIES "bast stackglue"
static int param_set_dlmfs_capabilities(const char *val,
struct kernel_param *kp)
{
printk(KERN_ERR "%s: readonly parameter\n", kp->name);
return -EINVAL;
}
static int param_get_dlmfs_capabilities(char *buffer,
struct kernel_param *kp)
{
return strlcpy(buffer, DLMFS_CAPABILITIES,
strlen(DLMFS_CAPABILITIES) + 1);
}
module_param_call(capabilities, param_set_dlmfs_capabilities,
param_get_dlmfs_capabilities, NULL, 0444);
MODULE_PARM_DESC(capabilities, DLMFS_CAPABILITIES);
/*
* decodes a set of open flags into a valid lock level and a set of flags.
* returns < 0 if we have invalid flags
* flags which mean something to us:
* O_RDONLY -> PRMODE level
* O_WRONLY -> EXMODE level
*
* O_NONBLOCK -> NOQUEUE
*/
static int dlmfs_decode_open_flags(int open_flags,
int *level,
int *flags)
{
if (open_flags & (O_WRONLY|O_RDWR))
*level = DLM_LOCK_EX;
else
*level = DLM_LOCK_PR;
*flags = 0;
if (open_flags & O_NONBLOCK)
*flags |= DLM_LKF_NOQUEUE;
return 0;
}
static int dlmfs_file_open(struct inode *inode,
struct file *file)
{
int status, level, flags;
struct dlmfs_filp_private *fp = NULL;
struct dlmfs_inode_private *ip;
if (S_ISDIR(inode->i_mode))
BUG();
mlog(0, "open called on inode %lu, flags 0x%x\n", inode->i_ino,
file->f_flags);
status = dlmfs_decode_open_flags(file->f_flags, &level, &flags);
if (status < 0)
goto bail;
/* We don't want to honor O_APPEND at read/write time as it
* doesn't make sense for LVB writes. */
file->f_flags &= ~O_APPEND;
fp = kmalloc(sizeof(*fp), GFP_NOFS);
if (!fp) {
status = -ENOMEM;
goto bail;
}
fp->fp_lock_level = level;
ip = DLMFS_I(inode);
status = user_dlm_cluster_lock(&ip->ip_lockres, level, flags);
if (status < 0) {
/* this is a strange error to return here but I want
* to be able userspace to be able to distinguish a
* valid lock request from one that simply couldn't be
* granted. */
if (flags & DLM_LKF_NOQUEUE && status == -EAGAIN)
status = -ETXTBSY;
kfree(fp);
goto bail;
}
file->private_data = fp;
bail:
return status;
}
static int dlmfs_file_release(struct inode *inode,
struct file *file)
{
int level, status;
struct dlmfs_inode_private *ip = DLMFS_I(inode);
struct dlmfs_filp_private *fp = file->private_data;
if (S_ISDIR(inode->i_mode))
BUG();
mlog(0, "close called on inode %lu\n", inode->i_ino);
status = 0;
if (fp) {
level = fp->fp_lock_level;
if (level != DLM_LOCK_IV)
user_dlm_cluster_unlock(&ip->ip_lockres, level);
kfree(fp);
file->private_data = NULL;
}
return 0;
}
/*
* We do ->setattr() just to override size changes. Our size is the size
* of the LVB and nothing else.
*/
static int dlmfs_file_setattr(struct dentry *dentry, struct iattr *attr)
{
int error;
struct inode *inode = dentry->d_inode;
attr->ia_valid &= ~ATTR_SIZE;
error = inode_change_ok(inode, attr);
if (error)
return error;
setattr_copy(inode, attr);
mark_inode_dirty(inode);
return 0;
}
static unsigned int dlmfs_file_poll(struct file *file, poll_table *wait)
{
int event = 0;
struct inode *inode = file_inode(file);
struct dlmfs_inode_private *ip = DLMFS_I(inode);
poll_wait(file, &ip->ip_lockres.l_event, wait);
spin_lock(&ip->ip_lockres.l_lock);
if (ip->ip_lockres.l_flags & USER_LOCK_BLOCKED)
event = POLLIN | POLLRDNORM;
spin_unlock(&ip->ip_lockres.l_lock);
return event;
}
static ssize_t dlmfs_file_read(struct file *filp,
char __user *buf,
size_t count,
loff_t *ppos)
{
int bytes_left;
ssize_t readlen, got;
char *lvb_buf;
struct inode *inode = file_inode(filp);
mlog(0, "inode %lu, count = %zu, *ppos = %llu\n",
inode->i_ino, count, *ppos);
if (*ppos >= i_size_read(inode))
return 0;
if (!count)
return 0;
if (!access_ok(VERIFY_WRITE, buf, count))
return -EFAULT;
/* don't read past the lvb */
if ((count + *ppos) > i_size_read(inode))
readlen = i_size_read(inode) - *ppos;
else
readlen = count;
lvb_buf = kmalloc(readlen, GFP_NOFS);
if (!lvb_buf)
return -ENOMEM;
got = user_dlm_read_lvb(inode, lvb_buf, readlen);
if (got) {
BUG_ON(got != readlen);
bytes_left = __copy_to_user(buf, lvb_buf, readlen);
readlen -= bytes_left;
} else
readlen = 0;
kfree(lvb_buf);
*ppos = *ppos + readlen;
mlog(0, "read %zd bytes\n", readlen);
return readlen;
}
static ssize_t dlmfs_file_write(struct file *filp,
const char __user *buf,
size_t count,
loff_t *ppos)
{
int bytes_left;
ssize_t writelen;
char *lvb_buf;
struct inode *inode = file_inode(filp);
mlog(0, "inode %lu, count = %zu, *ppos = %llu\n",
inode->i_ino, count, *ppos);
if (*ppos >= i_size_read(inode))
return -ENOSPC;
if (!count)
return 0;
if (!access_ok(VERIFY_READ, buf, count))
return -EFAULT;
/* don't write past the lvb */
if ((count + *ppos) > i_size_read(inode))
writelen = i_size_read(inode) - *ppos;
else
writelen = count - *ppos;
lvb_buf = kmalloc(writelen, GFP_NOFS);
if (!lvb_buf)
return -ENOMEM;
bytes_left = copy_from_user(lvb_buf, buf, writelen);
writelen -= bytes_left;
if (writelen)
user_dlm_write_lvb(inode, lvb_buf, writelen);
kfree(lvb_buf);
*ppos = *ppos + writelen;
mlog(0, "wrote %zd bytes\n", writelen);
return writelen;
}
static void dlmfs_init_once(void *foo)
{
struct dlmfs_inode_private *ip =
(struct dlmfs_inode_private *) foo;
ip->ip_conn = NULL;
ip->ip_parent = NULL;
inode_init_once(&ip->ip_vfs_inode);
}
static struct inode *dlmfs_alloc_inode(struct super_block *sb)
{
struct dlmfs_inode_private *ip;
ip = kmem_cache_alloc(dlmfs_inode_cache, GFP_NOFS);
if (!ip)
return NULL;
return &ip->ip_vfs_inode;
}
static void dlmfs_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(dlmfs_inode_cache, DLMFS_I(inode));
}
static void dlmfs_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, dlmfs_i_callback);
}
static void dlmfs_evict_inode(struct inode *inode)
{
int status;
struct dlmfs_inode_private *ip;
clear_inode(inode);
mlog(0, "inode %lu\n", inode->i_ino);
ip = DLMFS_I(inode);
if (S_ISREG(inode->i_mode)) {
status = user_dlm_destroy_lock(&ip->ip_lockres);
if (status < 0)
mlog_errno(status);
iput(ip->ip_parent);
goto clear_fields;
}
mlog(0, "we're a directory, ip->ip_conn = 0x%p\n", ip->ip_conn);
/* we must be a directory. If required, lets unregister the
* dlm context now. */
if (ip->ip_conn)
user_dlm_unregister(ip->ip_conn);
clear_fields:
ip->ip_parent = NULL;
ip->ip_conn = NULL;
}
static struct backing_dev_info dlmfs_backing_dev_info = {
.name = "ocfs2-dlmfs",
.ra_pages = 0, /* No readahead */
.capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
};
static struct inode *dlmfs_get_root_inode(struct super_block *sb)
{
struct inode *inode = new_inode(sb);
umode_t mode = S_IFDIR | 0755;
struct dlmfs_inode_private *ip;
if (inode) {
ip = DLMFS_I(inode);
inode->i_ino = get_next_ino();
inode_init_owner(inode, NULL, mode);
inode->i_mapping->backing_dev_info = &dlmfs_backing_dev_info;
inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
inc_nlink(inode);
inode->i_fop = &simple_dir_operations;
inode->i_op = &dlmfs_root_inode_operations;
}
return inode;
}
static struct inode *dlmfs_get_inode(struct inode *parent,
struct dentry *dentry,
umode_t mode)
{
struct super_block *sb = parent->i_sb;
struct inode * inode = new_inode(sb);
struct dlmfs_inode_private *ip;
if (!inode)
return NULL;
inode->i_ino = get_next_ino();
inode_init_owner(inode, parent, mode);
inode->i_mapping->backing_dev_info = &dlmfs_backing_dev_info;
inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
ip = DLMFS_I(inode);
ip->ip_conn = DLMFS_I(parent)->ip_conn;
switch (mode & S_IFMT) {
default:
/* for now we don't support anything other than
* directories and regular files. */
BUG();
break;
case S_IFREG:
inode->i_op = &dlmfs_file_inode_operations;
inode->i_fop = &dlmfs_file_operations;
i_size_write(inode, DLM_LVB_LEN);
user_dlm_lock_res_init(&ip->ip_lockres, dentry);
/* released at clear_inode time, this insures that we
* get to drop the dlm reference on each lock *before*
* we call the unregister code for releasing parent
* directories. */
ip->ip_parent = igrab(parent);
BUG_ON(!ip->ip_parent);
break;
case S_IFDIR:
inode->i_op = &dlmfs_dir_inode_operations;
inode->i_fop = &simple_dir_operations;
/* directory inodes start off with i_nlink ==
* 2 (for "." entry) */
inc_nlink(inode);
break;
}
return inode;
}
/*
* File creation. Allocate an inode, and we're done..
*/
/* SMP-safe */
static int dlmfs_mkdir(struct inode * dir,
struct dentry * dentry,
umode_t mode)
{
int status;
struct inode *inode = NULL;
struct qstr *domain = &dentry->d_name;
struct dlmfs_inode_private *ip;
struct ocfs2_cluster_connection *conn;
mlog(0, "mkdir %.*s\n", domain->len, domain->name);
/* verify that we have a proper domain */
if (domain->len >= GROUP_NAME_MAX) {
status = -EINVAL;
mlog(ML_ERROR, "invalid domain name for directory.\n");
goto bail;
}
inode = dlmfs_get_inode(dir, dentry, mode | S_IFDIR);
if (!inode) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
ip = DLMFS_I(inode);
conn = user_dlm_register(domain);
if (IS_ERR(conn)) {
status = PTR_ERR(conn);
mlog(ML_ERROR, "Error %d could not register domain \"%.*s\"\n",
status, domain->len, domain->name);
goto bail;
}
ip->ip_conn = conn;
inc_nlink(dir);
d_instantiate(dentry, inode);
dget(dentry); /* Extra count - pin the dentry in core */
status = 0;
bail:
if (status < 0)
iput(inode);
return status;
}
static int dlmfs_create(struct inode *dir,
struct dentry *dentry,
umode_t mode,
bool excl)
{
int status = 0;
struct inode *inode;
struct qstr *name = &dentry->d_name;
mlog(0, "create %.*s\n", name->len, name->name);
/* verify name is valid and doesn't contain any dlm reserved
* characters */
if (name->len >= USER_DLM_LOCK_ID_MAX_LEN ||
name->name[0] == '$') {
status = -EINVAL;
mlog(ML_ERROR, "invalid lock name, %.*s\n", name->len,
name->name);
goto bail;
}
inode = dlmfs_get_inode(dir, dentry, mode | S_IFREG);
if (!inode) {
status = -ENOMEM;
mlog_errno(status);
goto bail;
}
d_instantiate(dentry, inode);
dget(dentry); /* Extra count - pin the dentry in core */
bail:
return status;
}
static int dlmfs_unlink(struct inode *dir,
struct dentry *dentry)
{
int status;
struct inode *inode = dentry->d_inode;
mlog(0, "unlink inode %lu\n", inode->i_ino);
/* if there are no current holders, or none that are waiting
* to acquire a lock, this basically destroys our lockres. */
status = user_dlm_destroy_lock(&DLMFS_I(inode)->ip_lockres);
if (status < 0) {
mlog(ML_ERROR, "unlink %.*s, error %d from destroy\n",
dentry->d_name.len, dentry->d_name.name, status);
goto bail;
}
status = simple_unlink(dir, dentry);
bail:
return status;
}
static int dlmfs_fill_super(struct super_block * sb,
void * data,
int silent)
{
sb->s_maxbytes = MAX_LFS_FILESIZE;
sb->s_blocksize = PAGE_CACHE_SIZE;
sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
sb->s_magic = DLMFS_MAGIC;
sb->s_op = &dlmfs_ops;
sb->s_root = d_make_root(dlmfs_get_root_inode(sb));
if (!sb->s_root)
return -ENOMEM;
return 0;
}
static const struct file_operations dlmfs_file_operations = {
.open = dlmfs_file_open,
.release = dlmfs_file_release,
.poll = dlmfs_file_poll,
.read = dlmfs_file_read,
.write = dlmfs_file_write,
.llseek = default_llseek,
};
static const struct inode_operations dlmfs_dir_inode_operations = {
.create = dlmfs_create,
.lookup = simple_lookup,
.unlink = dlmfs_unlink,
};
/* this way we can restrict mkdir to only the toplevel of the fs. */
static const struct inode_operations dlmfs_root_inode_operations = {
.lookup = simple_lookup,
.mkdir = dlmfs_mkdir,
.rmdir = simple_rmdir,
};
static const struct super_operations dlmfs_ops = {
.statfs = simple_statfs,
.alloc_inode = dlmfs_alloc_inode,
.destroy_inode = dlmfs_destroy_inode,
.evict_inode = dlmfs_evict_inode,
.drop_inode = generic_delete_inode,
};
static const struct inode_operations dlmfs_file_inode_operations = {
.getattr = simple_getattr,
.setattr = dlmfs_file_setattr,
};
static struct dentry *dlmfs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_nodev(fs_type, flags, data, dlmfs_fill_super);
}
static struct file_system_type dlmfs_fs_type = {
.owner = THIS_MODULE,
.name = "ocfs2_dlmfs",
.mount = dlmfs_mount,
.kill_sb = kill_litter_super,
};
MODULE_ALIAS_FS("ocfs2_dlmfs");
static int __init init_dlmfs_fs(void)
{
int status;
int cleanup_inode = 0, cleanup_worker = 0;
dlmfs_print_version();
status = bdi_init(&dlmfs_backing_dev_info);
if (status)
return status;
dlmfs_inode_cache = kmem_cache_create("dlmfs_inode_cache",
sizeof(struct dlmfs_inode_private),
0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
dlmfs_init_once);
if (!dlmfs_inode_cache) {
status = -ENOMEM;
goto bail;
}
cleanup_inode = 1;
user_dlm_worker = create_singlethread_workqueue("user_dlm");
if (!user_dlm_worker) {
status = -ENOMEM;
goto bail;
}
cleanup_worker = 1;
user_dlm_set_locking_protocol();
status = register_filesystem(&dlmfs_fs_type);
bail:
if (status) {
if (cleanup_inode)
kmem_cache_destroy(dlmfs_inode_cache);
if (cleanup_worker)
destroy_workqueue(user_dlm_worker);
bdi_destroy(&dlmfs_backing_dev_info);
} else
printk("OCFS2 User DLM kernel interface loaded\n");
return status;
}
static void __exit exit_dlmfs_fs(void)
{
unregister_filesystem(&dlmfs_fs_type);
flush_workqueue(user_dlm_worker);
destroy_workqueue(user_dlm_worker);
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(dlmfs_inode_cache);
bdi_destroy(&dlmfs_backing_dev_info);
}
MODULE_AUTHOR("Oracle");
MODULE_LICENSE("GPL");
module_init(init_dlmfs_fs)
module_exit(exit_dlmfs_fs)
| gpl-2.0 |
garyd9/linux_kernel_GT-P6210 | net/netfilter/nfnetlink.c | 3482 | 5667 | /* Netfilter messages via netlink socket. Allows for user space
* protocol helpers and general trouble making from userspace.
*
* (C) 2001 by Jay Schulist <jschlst@samba.org>,
* (C) 2002-2005 by Harald Welte <laforge@gnumonks.org>
* (C) 2005,2007 by Pablo Neira Ayuso <pablo@netfilter.org>
*
* Initial netfilter messages via netlink development funded and
* generally made possible by Network Robots, Inc. (www.networkrobots.com)
*
* Further development of this code funded by Astaro AG (http://www.astaro.com)
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/skbuff.h>
#include <asm/uaccess.h>
#include <asm/system.h>
#include <net/sock.h>
#include <net/netlink.h>
#include <linux/init.h>
#include <linux/netlink.h>
#include <linux/netfilter/nfnetlink.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_NETFILTER);
static char __initdata nfversion[] = "0.30";
static const struct nfnetlink_subsystem *subsys_table[NFNL_SUBSYS_COUNT];
static DEFINE_MUTEX(nfnl_mutex);
void nfnl_lock(void)
{
mutex_lock(&nfnl_mutex);
}
EXPORT_SYMBOL_GPL(nfnl_lock);
void nfnl_unlock(void)
{
mutex_unlock(&nfnl_mutex);
}
EXPORT_SYMBOL_GPL(nfnl_unlock);
int nfnetlink_subsys_register(const struct nfnetlink_subsystem *n)
{
nfnl_lock();
if (subsys_table[n->subsys_id]) {
nfnl_unlock();
return -EBUSY;
}
subsys_table[n->subsys_id] = n;
nfnl_unlock();
return 0;
}
EXPORT_SYMBOL_GPL(nfnetlink_subsys_register);
int nfnetlink_subsys_unregister(const struct nfnetlink_subsystem *n)
{
nfnl_lock();
subsys_table[n->subsys_id] = NULL;
nfnl_unlock();
return 0;
}
EXPORT_SYMBOL_GPL(nfnetlink_subsys_unregister);
static inline const struct nfnetlink_subsystem *nfnetlink_get_subsys(u_int16_t type)
{
u_int8_t subsys_id = NFNL_SUBSYS_ID(type);
if (subsys_id >= NFNL_SUBSYS_COUNT)
return NULL;
return subsys_table[subsys_id];
}
static inline const struct nfnl_callback *
nfnetlink_find_client(u_int16_t type, const struct nfnetlink_subsystem *ss)
{
u_int8_t cb_id = NFNL_MSG_TYPE(type);
if (cb_id >= ss->cb_count)
return NULL;
return &ss->cb[cb_id];
}
int nfnetlink_has_listeners(struct net *net, unsigned int group)
{
return netlink_has_listeners(net->nfnl, group);
}
EXPORT_SYMBOL_GPL(nfnetlink_has_listeners);
int nfnetlink_send(struct sk_buff *skb, struct net *net, u32 pid,
unsigned group, int echo, gfp_t flags)
{
return nlmsg_notify(net->nfnl, skb, pid, group, echo, flags);
}
EXPORT_SYMBOL_GPL(nfnetlink_send);
int nfnetlink_set_err(struct net *net, u32 pid, u32 group, int error)
{
return netlink_set_err(net->nfnl, pid, group, error);
}
EXPORT_SYMBOL_GPL(nfnetlink_set_err);
int nfnetlink_unicast(struct sk_buff *skb, struct net *net, u_int32_t pid, int flags)
{
return netlink_unicast(net->nfnl, skb, pid, flags);
}
EXPORT_SYMBOL_GPL(nfnetlink_unicast);
/* Process one complete nfnetlink message. */
static int nfnetlink_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
const struct nfnl_callback *nc;
const struct nfnetlink_subsystem *ss;
int type, err;
if (security_netlink_recv(skb, CAP_NET_ADMIN))
return -EPERM;
/* All the messages must at least contain nfgenmsg */
if (nlh->nlmsg_len < NLMSG_LENGTH(sizeof(struct nfgenmsg)))
return 0;
type = nlh->nlmsg_type;
replay:
ss = nfnetlink_get_subsys(type);
if (!ss) {
#ifdef CONFIG_MODULES
nfnl_unlock();
request_module("nfnetlink-subsys-%d", NFNL_SUBSYS_ID(type));
nfnl_lock();
ss = nfnetlink_get_subsys(type);
if (!ss)
#endif
return -EINVAL;
}
nc = nfnetlink_find_client(type, ss);
if (!nc)
return -EINVAL;
{
int min_len = NLMSG_SPACE(sizeof(struct nfgenmsg));
u_int8_t cb_id = NFNL_MSG_TYPE(nlh->nlmsg_type);
struct nlattr *cda[ss->cb[cb_id].attr_count + 1];
struct nlattr *attr = (void *)nlh + min_len;
int attrlen = nlh->nlmsg_len - min_len;
err = nla_parse(cda, ss->cb[cb_id].attr_count,
attr, attrlen, ss->cb[cb_id].policy);
if (err < 0)
return err;
err = nc->call(net->nfnl, skb, nlh, (const struct nlattr **)cda);
if (err == -EAGAIN)
goto replay;
return err;
}
}
static void nfnetlink_rcv(struct sk_buff *skb)
{
nfnl_lock();
netlink_rcv_skb(skb, &nfnetlink_rcv_msg);
nfnl_unlock();
}
static int __net_init nfnetlink_net_init(struct net *net)
{
struct sock *nfnl;
nfnl = netlink_kernel_create(net, NETLINK_NETFILTER, NFNLGRP_MAX,
nfnetlink_rcv, NULL, THIS_MODULE);
if (!nfnl)
return -ENOMEM;
net->nfnl_stash = nfnl;
rcu_assign_pointer(net->nfnl, nfnl);
return 0;
}
static void __net_exit nfnetlink_net_exit_batch(struct list_head *net_exit_list)
{
struct net *net;
list_for_each_entry(net, net_exit_list, exit_list)
rcu_assign_pointer(net->nfnl, NULL);
synchronize_net();
list_for_each_entry(net, net_exit_list, exit_list)
netlink_kernel_release(net->nfnl_stash);
}
static struct pernet_operations nfnetlink_net_ops = {
.init = nfnetlink_net_init,
.exit_batch = nfnetlink_net_exit_batch,
};
static int __init nfnetlink_init(void)
{
pr_info("Netfilter messages via NETLINK v%s.\n", nfversion);
return register_pernet_subsys(&nfnetlink_net_ops);
}
static void __exit nfnetlink_exit(void)
{
pr_info("Removing netfilter NETLINK layer.\n");
unregister_pernet_subsys(&nfnetlink_net_ops);
}
module_init(nfnetlink_init);
module_exit(nfnetlink_exit);
| gpl-2.0 |
PaulMilbank/g300_kernel | drivers/input/misc/ati_remote.c | 3994 | 28140 | /*
* USB ATI Remote support
*
* Version 2.2.0 Copyright (c) 2004 Torrey Hoffman <thoffman@arnor.net>
* Version 2.1.1 Copyright (c) 2002 Vladimir Dergachev
*
* This 2.2.0 version is a rewrite / cleanup of the 2.1.1 driver, including
* porting to the 2.6 kernel interfaces, along with other modification
* to better match the style of the existing usb/input drivers. However, the
* protocol and hardware handling is essentially unchanged from 2.1.1.
*
* The 2.1.1 driver was derived from the usbati_remote and usbkbd drivers by
* Vojtech Pavlik.
*
* Changes:
*
* Feb 2004: Torrey Hoffman <thoffman@arnor.net>
* Version 2.2.0
* Jun 2004: Torrey Hoffman <thoffman@arnor.net>
* Version 2.2.1
* Added key repeat support contributed by:
* Vincent Vanackere <vanackere@lif.univ-mrs.fr>
* Added support for the "Lola" remote contributed by:
* Seth Cohn <sethcohn@yahoo.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
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Hardware & software notes
*
* These remote controls are distributed by ATI as part of their
* "All-In-Wonder" video card packages. The receiver self-identifies as a
* "USB Receiver" with manufacturer "X10 Wireless Technology Inc".
*
* The "Lola" remote is available from X10. See:
* http://www.x10.com/products/lola_sg1.htm
* The Lola is similar to the ATI remote but has no mouse support, and slightly
* different keys.
*
* It is possible to use multiple receivers and remotes on multiple computers
* simultaneously by configuring them to use specific channels.
*
* The RF protocol used by the remote supports 16 distinct channels, 1 to 16.
* Actually, it may even support more, at least in some revisions of the
* hardware.
*
* Each remote can be configured to transmit on one channel as follows:
* - Press and hold the "hand icon" button.
* - When the red LED starts to blink, let go of the "hand icon" button.
* - When it stops blinking, input the channel code as two digits, from 01
* to 16, and press the hand icon again.
*
* The timing can be a little tricky. Try loading the module with debug=1
* to have the kernel print out messages about the remote control number
* and mask. Note: debugging prints remote numbers as zero-based hexadecimal.
*
* The driver has a "channel_mask" parameter. This bitmask specifies which
* channels will be ignored by the module. To mask out channels, just add
* all the 2^channel_number values together.
*
* For instance, set channel_mask = 2^4 = 16 (binary 10000) to make ati_remote
* ignore signals coming from remote controls transmitting on channel 4, but
* accept all other channels.
*
* Or, set channel_mask = 65533, (0xFFFD), and all channels except 1 will be
* ignored.
*
* The default is 0 (respond to all channels). Bit 0 and bits 17-32 of this
* parameter are unused.
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/usb/input.h>
#include <linux/wait.h>
#include <linux/jiffies.h>
/*
* Module and Version Information, Module Parameters
*/
#define ATI_REMOTE_VENDOR_ID 0x0bc7
#define LOLA_REMOTE_PRODUCT_ID 0x0002
#define LOLA2_REMOTE_PRODUCT_ID 0x0003
#define ATI_REMOTE_PRODUCT_ID 0x0004
#define NVIDIA_REMOTE_PRODUCT_ID 0x0005
#define MEDION_REMOTE_PRODUCT_ID 0x0006
#define DRIVER_VERSION "2.2.1"
#define DRIVER_AUTHOR "Torrey Hoffman <thoffman@arnor.net>"
#define DRIVER_DESC "ATI/X10 RF USB Remote Control"
#define NAME_BUFSIZE 80 /* size of product name, path buffers */
#define DATA_BUFSIZE 63 /* size of URB data buffers */
/*
* Duplicate event filtering time.
* Sequential, identical KIND_FILTERED inputs with less than
* FILTER_TIME milliseconds between them are considered as repeat
* events. The hardware generates 5 events for the first keypress
* and we have to take this into account for an accurate repeat
* behaviour.
*/
#define FILTER_TIME 60 /* msec */
#define REPEAT_DELAY 500 /* msec */
static unsigned long channel_mask;
module_param(channel_mask, ulong, 0644);
MODULE_PARM_DESC(channel_mask, "Bitmask of remote control channels to ignore");
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Enable extra debug messages and information");
static int repeat_filter = FILTER_TIME;
module_param(repeat_filter, int, 0644);
MODULE_PARM_DESC(repeat_filter, "Repeat filter time, default = 60 msec");
static int repeat_delay = REPEAT_DELAY;
module_param(repeat_delay, int, 0644);
MODULE_PARM_DESC(repeat_delay, "Delay before sending repeats, default = 500 msec");
#define dbginfo(dev, format, arg...) do { if (debug) dev_info(dev , format , ## arg); } while (0)
#undef err
#define err(format, arg...) printk(KERN_ERR format , ## arg)
static struct usb_device_id ati_remote_table[] = {
{ USB_DEVICE(ATI_REMOTE_VENDOR_ID, LOLA_REMOTE_PRODUCT_ID) },
{ USB_DEVICE(ATI_REMOTE_VENDOR_ID, LOLA2_REMOTE_PRODUCT_ID) },
{ USB_DEVICE(ATI_REMOTE_VENDOR_ID, ATI_REMOTE_PRODUCT_ID) },
{ USB_DEVICE(ATI_REMOTE_VENDOR_ID, NVIDIA_REMOTE_PRODUCT_ID) },
{ USB_DEVICE(ATI_REMOTE_VENDOR_ID, MEDION_REMOTE_PRODUCT_ID) },
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, ati_remote_table);
/* Get hi and low bytes of a 16-bits int */
#define HI(a) ((unsigned char)((a) >> 8))
#define LO(a) ((unsigned char)((a) & 0xff))
#define SEND_FLAG_IN_PROGRESS 1
#define SEND_FLAG_COMPLETE 2
/* Device initialization strings */
static char init1[] = { 0x01, 0x00, 0x20, 0x14 };
static char init2[] = { 0x01, 0x00, 0x20, 0x14, 0x20, 0x20, 0x20 };
struct ati_remote {
struct input_dev *idev;
struct usb_device *udev;
struct usb_interface *interface;
struct urb *irq_urb;
struct urb *out_urb;
struct usb_endpoint_descriptor *endpoint_in;
struct usb_endpoint_descriptor *endpoint_out;
unsigned char *inbuf;
unsigned char *outbuf;
dma_addr_t inbuf_dma;
dma_addr_t outbuf_dma;
unsigned char old_data[2]; /* Detect duplicate events */
unsigned long old_jiffies;
unsigned long acc_jiffies; /* handle acceleration */
unsigned long first_jiffies;
unsigned int repeat_count;
char name[NAME_BUFSIZE];
char phys[NAME_BUFSIZE];
wait_queue_head_t wait;
int send_flags;
};
/* "Kinds" of messages sent from the hardware to the driver. */
#define KIND_END 0
#define KIND_LITERAL 1 /* Simply pass to input system */
#define KIND_FILTERED 2 /* Add artificial key-up events, drop keyrepeats */
#define KIND_LU 3 /* Directional keypad diagonals - left up, */
#define KIND_RU 4 /* right up, */
#define KIND_LD 5 /* left down, */
#define KIND_RD 6 /* right down */
#define KIND_ACCEL 7 /* Directional keypad - left, right, up, down.*/
/* Translation table from hardware messages to input events. */
static const struct {
short kind;
unsigned char data1, data2;
int type;
unsigned int code;
int value;
} ati_remote_tbl[] = {
/* Directional control pad axes */
{KIND_ACCEL, 0x35, 0x70, EV_REL, REL_X, -1}, /* left */
{KIND_ACCEL, 0x36, 0x71, EV_REL, REL_X, 1}, /* right */
{KIND_ACCEL, 0x37, 0x72, EV_REL, REL_Y, -1}, /* up */
{KIND_ACCEL, 0x38, 0x73, EV_REL, REL_Y, 1}, /* down */
/* Directional control pad diagonals */
{KIND_LU, 0x39, 0x74, EV_REL, 0, 0}, /* left up */
{KIND_RU, 0x3a, 0x75, EV_REL, 0, 0}, /* right up */
{KIND_LD, 0x3c, 0x77, EV_REL, 0, 0}, /* left down */
{KIND_RD, 0x3b, 0x76, EV_REL, 0, 0}, /* right down */
/* "Mouse button" buttons */
{KIND_LITERAL, 0x3d, 0x78, EV_KEY, BTN_LEFT, 1}, /* left btn down */
{KIND_LITERAL, 0x3e, 0x79, EV_KEY, BTN_LEFT, 0}, /* left btn up */
{KIND_LITERAL, 0x41, 0x7c, EV_KEY, BTN_RIGHT, 1},/* right btn down */
{KIND_LITERAL, 0x42, 0x7d, EV_KEY, BTN_RIGHT, 0},/* right btn up */
/* Artificial "doubleclick" events are generated by the hardware.
* They are mapped to the "side" and "extra" mouse buttons here. */
{KIND_FILTERED, 0x3f, 0x7a, EV_KEY, BTN_SIDE, 1}, /* left dblclick */
{KIND_FILTERED, 0x43, 0x7e, EV_KEY, BTN_EXTRA, 1},/* right dblclick */
/* keyboard. */
{KIND_FILTERED, 0xd2, 0x0d, EV_KEY, KEY_1, 1},
{KIND_FILTERED, 0xd3, 0x0e, EV_KEY, KEY_2, 1},
{KIND_FILTERED, 0xd4, 0x0f, EV_KEY, KEY_3, 1},
{KIND_FILTERED, 0xd5, 0x10, EV_KEY, KEY_4, 1},
{KIND_FILTERED, 0xd6, 0x11, EV_KEY, KEY_5, 1},
{KIND_FILTERED, 0xd7, 0x12, EV_KEY, KEY_6, 1},
{KIND_FILTERED, 0xd8, 0x13, EV_KEY, KEY_7, 1},
{KIND_FILTERED, 0xd9, 0x14, EV_KEY, KEY_8, 1},
{KIND_FILTERED, 0xda, 0x15, EV_KEY, KEY_9, 1},
{KIND_FILTERED, 0xdc, 0x17, EV_KEY, KEY_0, 1},
{KIND_FILTERED, 0xc5, 0x00, EV_KEY, KEY_A, 1},
{KIND_FILTERED, 0xc6, 0x01, EV_KEY, KEY_B, 1},
{KIND_FILTERED, 0xde, 0x19, EV_KEY, KEY_C, 1},
{KIND_FILTERED, 0xe0, 0x1b, EV_KEY, KEY_D, 1},
{KIND_FILTERED, 0xe6, 0x21, EV_KEY, KEY_E, 1},
{KIND_FILTERED, 0xe8, 0x23, EV_KEY, KEY_F, 1},
/* "special" keys */
{KIND_FILTERED, 0xdd, 0x18, EV_KEY, KEY_KPENTER, 1}, /* "check" */
{KIND_FILTERED, 0xdb, 0x16, EV_KEY, KEY_MENU, 1}, /* "menu" */
{KIND_FILTERED, 0xc7, 0x02, EV_KEY, KEY_POWER, 1}, /* Power */
{KIND_FILTERED, 0xc8, 0x03, EV_KEY, KEY_TV, 1}, /* TV */
{KIND_FILTERED, 0xc9, 0x04, EV_KEY, KEY_DVD, 1}, /* DVD */
{KIND_FILTERED, 0xca, 0x05, EV_KEY, KEY_WWW, 1}, /* WEB */
{KIND_FILTERED, 0xcb, 0x06, EV_KEY, KEY_BOOKMARKS, 1}, /* "book" */
{KIND_FILTERED, 0xcc, 0x07, EV_KEY, KEY_EDIT, 1}, /* "hand" */
{KIND_FILTERED, 0xe1, 0x1c, EV_KEY, KEY_COFFEE, 1}, /* "timer" */
{KIND_FILTERED, 0xe5, 0x20, EV_KEY, KEY_FRONT, 1}, /* "max" */
{KIND_FILTERED, 0xe2, 0x1d, EV_KEY, KEY_LEFT, 1}, /* left */
{KIND_FILTERED, 0xe4, 0x1f, EV_KEY, KEY_RIGHT, 1}, /* right */
{KIND_FILTERED, 0xe7, 0x22, EV_KEY, KEY_DOWN, 1}, /* down */
{KIND_FILTERED, 0xdf, 0x1a, EV_KEY, KEY_UP, 1}, /* up */
{KIND_FILTERED, 0xe3, 0x1e, EV_KEY, KEY_OK, 1}, /* "OK" */
{KIND_FILTERED, 0xce, 0x09, EV_KEY, KEY_VOLUMEDOWN, 1}, /* VOL + */
{KIND_FILTERED, 0xcd, 0x08, EV_KEY, KEY_VOLUMEUP, 1}, /* VOL - */
{KIND_FILTERED, 0xcf, 0x0a, EV_KEY, KEY_MUTE, 1}, /* MUTE */
{KIND_FILTERED, 0xd0, 0x0b, EV_KEY, KEY_CHANNELUP, 1}, /* CH + */
{KIND_FILTERED, 0xd1, 0x0c, EV_KEY, KEY_CHANNELDOWN, 1},/* CH - */
{KIND_FILTERED, 0xec, 0x27, EV_KEY, KEY_RECORD, 1}, /* ( o) red */
{KIND_FILTERED, 0xea, 0x25, EV_KEY, KEY_PLAY, 1}, /* ( >) */
{KIND_FILTERED, 0xe9, 0x24, EV_KEY, KEY_REWIND, 1}, /* (<<) */
{KIND_FILTERED, 0xeb, 0x26, EV_KEY, KEY_FORWARD, 1}, /* (>>) */
{KIND_FILTERED, 0xed, 0x28, EV_KEY, KEY_STOP, 1}, /* ([]) */
{KIND_FILTERED, 0xee, 0x29, EV_KEY, KEY_PAUSE, 1}, /* ('') */
{KIND_FILTERED, 0xf0, 0x2b, EV_KEY, KEY_PREVIOUS, 1}, /* (<-) */
{KIND_FILTERED, 0xef, 0x2a, EV_KEY, KEY_NEXT, 1}, /* (>+) */
{KIND_FILTERED, 0xf2, 0x2D, EV_KEY, KEY_INFO, 1}, /* PLAYING */
{KIND_FILTERED, 0xf3, 0x2E, EV_KEY, KEY_HOME, 1}, /* TOP */
{KIND_FILTERED, 0xf4, 0x2F, EV_KEY, KEY_END, 1}, /* END */
{KIND_FILTERED, 0xf5, 0x30, EV_KEY, KEY_SELECT, 1}, /* SELECT */
{KIND_END, 0x00, 0x00, EV_MAX + 1, 0, 0}
};
/* Local function prototypes */
static int ati_remote_open (struct input_dev *inputdev);
static void ati_remote_close (struct input_dev *inputdev);
static int ati_remote_sendpacket (struct ati_remote *ati_remote, u16 cmd, unsigned char *data);
static void ati_remote_irq_out (struct urb *urb);
static void ati_remote_irq_in (struct urb *urb);
static void ati_remote_input_report (struct urb *urb);
static int ati_remote_initialize (struct ati_remote *ati_remote);
static int ati_remote_probe (struct usb_interface *interface, const struct usb_device_id *id);
static void ati_remote_disconnect (struct usb_interface *interface);
/* usb specific object to register with the usb subsystem */
static struct usb_driver ati_remote_driver = {
.name = "ati_remote",
.probe = ati_remote_probe,
.disconnect = ati_remote_disconnect,
.id_table = ati_remote_table,
};
/*
* ati_remote_dump_input
*/
static void ati_remote_dump(struct device *dev, unsigned char *data,
unsigned int len)
{
if ((len == 1) && (data[0] != (unsigned char)0xff) && (data[0] != 0x00))
dev_warn(dev, "Weird byte 0x%02x\n", data[0]);
else if (len == 4)
dev_warn(dev, "Weird key %02x %02x %02x %02x\n",
data[0], data[1], data[2], data[3]);
else
dev_warn(dev, "Weird data, len=%d %02x %02x %02x %02x %02x %02x ...\n",
len, data[0], data[1], data[2], data[3], data[4], data[5]);
}
/*
* ati_remote_open
*/
static int ati_remote_open(struct input_dev *inputdev)
{
struct ati_remote *ati_remote = input_get_drvdata(inputdev);
/* On first open, submit the read urb which was set up previously. */
ati_remote->irq_urb->dev = ati_remote->udev;
if (usb_submit_urb(ati_remote->irq_urb, GFP_KERNEL)) {
dev_err(&ati_remote->interface->dev,
"%s: usb_submit_urb failed!\n", __func__);
return -EIO;
}
return 0;
}
/*
* ati_remote_close
*/
static void ati_remote_close(struct input_dev *inputdev)
{
struct ati_remote *ati_remote = input_get_drvdata(inputdev);
usb_kill_urb(ati_remote->irq_urb);
}
/*
* ati_remote_irq_out
*/
static void ati_remote_irq_out(struct urb *urb)
{
struct ati_remote *ati_remote = urb->context;
if (urb->status) {
dev_dbg(&ati_remote->interface->dev, "%s: status %d\n",
__func__, urb->status);
return;
}
ati_remote->send_flags |= SEND_FLAG_COMPLETE;
wmb();
wake_up(&ati_remote->wait);
}
/*
* ati_remote_sendpacket
*
* Used to send device initialization strings
*/
static int ati_remote_sendpacket(struct ati_remote *ati_remote, u16 cmd, unsigned char *data)
{
int retval = 0;
/* Set up out_urb */
memcpy(ati_remote->out_urb->transfer_buffer + 1, data, LO(cmd));
((char *) ati_remote->out_urb->transfer_buffer)[0] = HI(cmd);
ati_remote->out_urb->transfer_buffer_length = LO(cmd) + 1;
ati_remote->out_urb->dev = ati_remote->udev;
ati_remote->send_flags = SEND_FLAG_IN_PROGRESS;
retval = usb_submit_urb(ati_remote->out_urb, GFP_ATOMIC);
if (retval) {
dev_dbg(&ati_remote->interface->dev,
"sendpacket: usb_submit_urb failed: %d\n", retval);
return retval;
}
wait_event_timeout(ati_remote->wait,
((ati_remote->out_urb->status != -EINPROGRESS) ||
(ati_remote->send_flags & SEND_FLAG_COMPLETE)),
HZ);
usb_kill_urb(ati_remote->out_urb);
return retval;
}
/*
* ati_remote_event_lookup
*/
static int ati_remote_event_lookup(int rem, unsigned char d1, unsigned char d2)
{
int i;
for (i = 0; ati_remote_tbl[i].kind != KIND_END; i++) {
/*
* Decide if the table entry matches the remote input.
*/
if ((((ati_remote_tbl[i].data1 & 0x0f) == (d1 & 0x0f))) &&
((((ati_remote_tbl[i].data1 >> 4) -
(d1 >> 4) + rem) & 0x0f) == 0x0f) &&
(ati_remote_tbl[i].data2 == d2))
return i;
}
return -1;
}
/*
* ati_remote_compute_accel
*
* Implements acceleration curve for directional control pad
* If elapsed time since last event is > 1/4 second, user "stopped",
* so reset acceleration. Otherwise, user is probably holding the control
* pad down, so we increase acceleration, ramping up over two seconds to
* a maximum speed.
*/
static int ati_remote_compute_accel(struct ati_remote *ati_remote)
{
static const char accel[] = { 1, 2, 4, 6, 9, 13, 20 };
unsigned long now = jiffies;
int acc;
if (time_after(now, ati_remote->old_jiffies + msecs_to_jiffies(250))) {
acc = 1;
ati_remote->acc_jiffies = now;
}
else if (time_before(now, ati_remote->acc_jiffies + msecs_to_jiffies(125)))
acc = accel[0];
else if (time_before(now, ati_remote->acc_jiffies + msecs_to_jiffies(250)))
acc = accel[1];
else if (time_before(now, ati_remote->acc_jiffies + msecs_to_jiffies(500)))
acc = accel[2];
else if (time_before(now, ati_remote->acc_jiffies + msecs_to_jiffies(1000)))
acc = accel[3];
else if (time_before(now, ati_remote->acc_jiffies + msecs_to_jiffies(1500)))
acc = accel[4];
else if (time_before(now, ati_remote->acc_jiffies + msecs_to_jiffies(2000)))
acc = accel[5];
else
acc = accel[6];
return acc;
}
/*
* ati_remote_report_input
*/
static void ati_remote_input_report(struct urb *urb)
{
struct ati_remote *ati_remote = urb->context;
unsigned char *data= ati_remote->inbuf;
struct input_dev *dev = ati_remote->idev;
int index, acc;
int remote_num;
/* Deal with strange looking inputs */
if ( (urb->actual_length != 4) || (data[0] != 0x14) ||
((data[3] & 0x0f) != 0x00) ) {
ati_remote_dump(&urb->dev->dev, data, urb->actual_length);
return;
}
/* Mask unwanted remote channels. */
/* note: remote_num is 0-based, channel 1 on remote == 0 here */
remote_num = (data[3] >> 4) & 0x0f;
if (channel_mask & (1 << (remote_num + 1))) {
dbginfo(&ati_remote->interface->dev,
"Masked input from channel 0x%02x: data %02x,%02x, mask= 0x%02lx\n",
remote_num, data[1], data[2], channel_mask);
return;
}
/* Look up event code index in translation table */
index = ati_remote_event_lookup(remote_num, data[1], data[2]);
if (index < 0) {
dev_warn(&ati_remote->interface->dev,
"Unknown input from channel 0x%02x: data %02x,%02x\n",
remote_num, data[1], data[2]);
return;
}
dbginfo(&ati_remote->interface->dev,
"channel 0x%02x; data %02x,%02x; index %d; keycode %d\n",
remote_num, data[1], data[2], index, ati_remote_tbl[index].code);
if (ati_remote_tbl[index].kind == KIND_LITERAL) {
input_event(dev, ati_remote_tbl[index].type,
ati_remote_tbl[index].code,
ati_remote_tbl[index].value);
input_sync(dev);
ati_remote->old_jiffies = jiffies;
return;
}
if (ati_remote_tbl[index].kind == KIND_FILTERED) {
unsigned long now = jiffies;
/* Filter duplicate events which happen "too close" together. */
if (ati_remote->old_data[0] == data[1] &&
ati_remote->old_data[1] == data[2] &&
time_before(now, ati_remote->old_jiffies +
msecs_to_jiffies(repeat_filter))) {
ati_remote->repeat_count++;
} else {
ati_remote->repeat_count = 0;
ati_remote->first_jiffies = now;
}
ati_remote->old_data[0] = data[1];
ati_remote->old_data[1] = data[2];
ati_remote->old_jiffies = now;
/* Ensure we skip at least the 4 first duplicate events (generated
* by a single keypress), and continue skipping until repeat_delay
* msecs have passed
*/
if (ati_remote->repeat_count > 0 &&
(ati_remote->repeat_count < 5 ||
time_before(now, ati_remote->first_jiffies +
msecs_to_jiffies(repeat_delay))))
return;
input_event(dev, ati_remote_tbl[index].type,
ati_remote_tbl[index].code, 1);
input_sync(dev);
input_event(dev, ati_remote_tbl[index].type,
ati_remote_tbl[index].code, 0);
input_sync(dev);
} else {
/*
* Other event kinds are from the directional control pad, and have an
* acceleration factor applied to them. Without this acceleration, the
* control pad is mostly unusable.
*/
acc = ati_remote_compute_accel(ati_remote);
switch (ati_remote_tbl[index].kind) {
case KIND_ACCEL:
input_event(dev, ati_remote_tbl[index].type,
ati_remote_tbl[index].code,
ati_remote_tbl[index].value * acc);
break;
case KIND_LU:
input_report_rel(dev, REL_X, -acc);
input_report_rel(dev, REL_Y, -acc);
break;
case KIND_RU:
input_report_rel(dev, REL_X, acc);
input_report_rel(dev, REL_Y, -acc);
break;
case KIND_LD:
input_report_rel(dev, REL_X, -acc);
input_report_rel(dev, REL_Y, acc);
break;
case KIND_RD:
input_report_rel(dev, REL_X, acc);
input_report_rel(dev, REL_Y, acc);
break;
default:
dev_dbg(&ati_remote->interface->dev, "ati_remote kind=%d\n",
ati_remote_tbl[index].kind);
}
input_sync(dev);
ati_remote->old_jiffies = jiffies;
ati_remote->old_data[0] = data[1];
ati_remote->old_data[1] = data[2];
}
}
/*
* ati_remote_irq_in
*/
static void ati_remote_irq_in(struct urb *urb)
{
struct ati_remote *ati_remote = urb->context;
int retval;
switch (urb->status) {
case 0: /* success */
ati_remote_input_report(urb);
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
dev_dbg(&ati_remote->interface->dev, "%s: urb error status, unlink? \n",
__func__);
return;
default: /* error */
dev_dbg(&ati_remote->interface->dev, "%s: Nonzero urb status %d\n",
__func__, urb->status);
}
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
dev_err(&ati_remote->interface->dev, "%s: usb_submit_urb()=%d\n",
__func__, retval);
}
/*
* ati_remote_alloc_buffers
*/
static int ati_remote_alloc_buffers(struct usb_device *udev,
struct ati_remote *ati_remote)
{
ati_remote->inbuf = usb_alloc_coherent(udev, DATA_BUFSIZE, GFP_ATOMIC,
&ati_remote->inbuf_dma);
if (!ati_remote->inbuf)
return -1;
ati_remote->outbuf = usb_alloc_coherent(udev, DATA_BUFSIZE, GFP_ATOMIC,
&ati_remote->outbuf_dma);
if (!ati_remote->outbuf)
return -1;
ati_remote->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!ati_remote->irq_urb)
return -1;
ati_remote->out_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!ati_remote->out_urb)
return -1;
return 0;
}
/*
* ati_remote_free_buffers
*/
static void ati_remote_free_buffers(struct ati_remote *ati_remote)
{
usb_free_urb(ati_remote->irq_urb);
usb_free_urb(ati_remote->out_urb);
usb_free_coherent(ati_remote->udev, DATA_BUFSIZE,
ati_remote->inbuf, ati_remote->inbuf_dma);
usb_free_coherent(ati_remote->udev, DATA_BUFSIZE,
ati_remote->outbuf, ati_remote->outbuf_dma);
}
static void ati_remote_input_init(struct ati_remote *ati_remote)
{
struct input_dev *idev = ati_remote->idev;
int i;
idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
idev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_SIDE) | BIT_MASK(BTN_EXTRA);
idev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y);
for (i = 0; ati_remote_tbl[i].kind != KIND_END; i++)
if (ati_remote_tbl[i].type == EV_KEY)
set_bit(ati_remote_tbl[i].code, idev->keybit);
input_set_drvdata(idev, ati_remote);
idev->open = ati_remote_open;
idev->close = ati_remote_close;
idev->name = ati_remote->name;
idev->phys = ati_remote->phys;
usb_to_input_id(ati_remote->udev, &idev->id);
idev->dev.parent = &ati_remote->udev->dev;
}
static int ati_remote_initialize(struct ati_remote *ati_remote)
{
struct usb_device *udev = ati_remote->udev;
int pipe, maxp;
init_waitqueue_head(&ati_remote->wait);
/* Set up irq_urb */
pipe = usb_rcvintpipe(udev, ati_remote->endpoint_in->bEndpointAddress);
maxp = usb_maxpacket(udev, pipe, usb_pipeout(pipe));
maxp = (maxp > DATA_BUFSIZE) ? DATA_BUFSIZE : maxp;
usb_fill_int_urb(ati_remote->irq_urb, udev, pipe, ati_remote->inbuf,
maxp, ati_remote_irq_in, ati_remote,
ati_remote->endpoint_in->bInterval);
ati_remote->irq_urb->transfer_dma = ati_remote->inbuf_dma;
ati_remote->irq_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* Set up out_urb */
pipe = usb_sndintpipe(udev, ati_remote->endpoint_out->bEndpointAddress);
maxp = usb_maxpacket(udev, pipe, usb_pipeout(pipe));
maxp = (maxp > DATA_BUFSIZE) ? DATA_BUFSIZE : maxp;
usb_fill_int_urb(ati_remote->out_urb, udev, pipe, ati_remote->outbuf,
maxp, ati_remote_irq_out, ati_remote,
ati_remote->endpoint_out->bInterval);
ati_remote->out_urb->transfer_dma = ati_remote->outbuf_dma;
ati_remote->out_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
/* send initialization strings */
if ((ati_remote_sendpacket(ati_remote, 0x8004, init1)) ||
(ati_remote_sendpacket(ati_remote, 0x8007, init2))) {
dev_err(&ati_remote->interface->dev,
"Initializing ati_remote hardware failed.\n");
return -EIO;
}
return 0;
}
/*
* ati_remote_probe
*/
static int ati_remote_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(interface);
struct usb_host_interface *iface_host = interface->cur_altsetting;
struct usb_endpoint_descriptor *endpoint_in, *endpoint_out;
struct ati_remote *ati_remote;
struct input_dev *input_dev;
int err = -ENOMEM;
if (iface_host->desc.bNumEndpoints != 2) {
err("%s: Unexpected desc.bNumEndpoints\n", __func__);
return -ENODEV;
}
endpoint_in = &iface_host->endpoint[0].desc;
endpoint_out = &iface_host->endpoint[1].desc;
if (!usb_endpoint_is_int_in(endpoint_in)) {
err("%s: Unexpected endpoint_in\n", __func__);
return -ENODEV;
}
if (le16_to_cpu(endpoint_in->wMaxPacketSize) == 0) {
err("%s: endpoint_in message size==0? \n", __func__);
return -ENODEV;
}
ati_remote = kzalloc(sizeof (struct ati_remote), GFP_KERNEL);
input_dev = input_allocate_device();
if (!ati_remote || !input_dev)
goto fail1;
/* Allocate URB buffers, URBs */
if (ati_remote_alloc_buffers(udev, ati_remote))
goto fail2;
ati_remote->endpoint_in = endpoint_in;
ati_remote->endpoint_out = endpoint_out;
ati_remote->udev = udev;
ati_remote->idev = input_dev;
ati_remote->interface = interface;
usb_make_path(udev, ati_remote->phys, sizeof(ati_remote->phys));
strlcat(ati_remote->phys, "/input0", sizeof(ati_remote->phys));
if (udev->manufacturer)
strlcpy(ati_remote->name, udev->manufacturer, sizeof(ati_remote->name));
if (udev->product)
snprintf(ati_remote->name, sizeof(ati_remote->name),
"%s %s", ati_remote->name, udev->product);
if (!strlen(ati_remote->name))
snprintf(ati_remote->name, sizeof(ati_remote->name),
DRIVER_DESC "(%04x,%04x)",
le16_to_cpu(ati_remote->udev->descriptor.idVendor),
le16_to_cpu(ati_remote->udev->descriptor.idProduct));
ati_remote_input_init(ati_remote);
/* Device Hardware Initialization - fills in ati_remote->idev from udev. */
err = ati_remote_initialize(ati_remote);
if (err)
goto fail3;
/* Set up and register input device */
err = input_register_device(ati_remote->idev);
if (err)
goto fail3;
usb_set_intfdata(interface, ati_remote);
return 0;
fail3: usb_kill_urb(ati_remote->irq_urb);
usb_kill_urb(ati_remote->out_urb);
fail2: ati_remote_free_buffers(ati_remote);
fail1: input_free_device(input_dev);
kfree(ati_remote);
return err;
}
/*
* ati_remote_disconnect
*/
static void ati_remote_disconnect(struct usb_interface *interface)
{
struct ati_remote *ati_remote;
ati_remote = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
if (!ati_remote) {
dev_warn(&interface->dev, "%s - null device?\n", __func__);
return;
}
usb_kill_urb(ati_remote->irq_urb);
usb_kill_urb(ati_remote->out_urb);
input_unregister_device(ati_remote->idev);
ati_remote_free_buffers(ati_remote);
kfree(ati_remote);
}
/*
* ati_remote_init
*/
static int __init ati_remote_init(void)
{
int result;
result = usb_register(&ati_remote_driver);
if (result)
printk(KERN_ERR KBUILD_MODNAME
": usb_register error #%d\n", result);
else
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
return result;
}
/*
* ati_remote_exit
*/
static void __exit ati_remote_exit(void)
{
usb_deregister(&ati_remote_driver);
}
/*
* module specification
*/
module_init(ati_remote_init);
module_exit(ati_remote_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
jmztaylor/android_kernel_pantech_pororo | arch/arm/kernel/xscale-cp0.c | 4250 | 4029 | /*
* linux/arch/arm/kernel/xscale-cp0.c
*
* XScale DSP and iWMMXt coprocessor context switching and handling
*
* 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/types.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/io.h>
#include <asm/thread_notify.h>
static inline void dsp_save_state(u32 *state)
{
__asm__ __volatile__ (
"mrrc p0, 0, %0, %1, c0\n"
: "=r" (state[0]), "=r" (state[1]));
}
static inline void dsp_load_state(u32 *state)
{
__asm__ __volatile__ (
"mcrr p0, 0, %0, %1, c0\n"
: : "r" (state[0]), "r" (state[1]));
}
static int dsp_do(struct notifier_block *self, unsigned long cmd, void *t)
{
struct thread_info *thread = t;
switch (cmd) {
case THREAD_NOTIFY_FLUSH:
thread->cpu_context.extra[0] = 0;
thread->cpu_context.extra[1] = 0;
break;
case THREAD_NOTIFY_SWITCH:
dsp_save_state(current_thread_info()->cpu_context.extra);
dsp_load_state(thread->cpu_context.extra);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block dsp_notifier_block = {
.notifier_call = dsp_do,
};
#ifdef CONFIG_IWMMXT
static int iwmmxt_do(struct notifier_block *self, unsigned long cmd, void *t)
{
struct thread_info *thread = t;
switch (cmd) {
case THREAD_NOTIFY_FLUSH:
/*
* flush_thread() zeroes thread->fpstate, so no need
* to do anything here.
*
* FALLTHROUGH: Ensure we don't try to overwrite our newly
* initialised state information on the first fault.
*/
case THREAD_NOTIFY_EXIT:
iwmmxt_task_release(thread);
break;
case THREAD_NOTIFY_SWITCH:
iwmmxt_task_switch(thread);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block iwmmxt_notifier_block = {
.notifier_call = iwmmxt_do,
};
#endif
static u32 __init xscale_cp_access_read(void)
{
u32 value;
__asm__ __volatile__ (
"mrc p15, 0, %0, c15, c1, 0\n\t"
: "=r" (value));
return value;
}
static void __init xscale_cp_access_write(u32 value)
{
u32 temp;
__asm__ __volatile__ (
"mcr p15, 0, %1, c15, c1, 0\n\t"
"mrc p15, 0, %0, c15, c1, 0\n\t"
"mov %0, %0\n\t"
"sub pc, pc, #4\n\t"
: "=r" (temp) : "r" (value));
}
/*
* Detect whether we have a MAC coprocessor (40 bit register) or an
* iWMMXt coprocessor (64 bit registers) by loading 00000100:00000000
* into a coprocessor register and reading it back, and checking
* whether the upper word survived intact.
*/
static int __init cpu_has_iwmmxt(void)
{
u32 lo;
u32 hi;
/*
* This sequence is interpreted by the DSP coprocessor as:
* mar acc0, %2, %3
* mra %0, %1, acc0
*
* And by the iWMMXt coprocessor as:
* tmcrr wR0, %2, %3
* tmrrc %0, %1, wR0
*/
__asm__ __volatile__ (
"mcrr p0, 0, %2, %3, c0\n"
"mrrc p0, 0, %0, %1, c0\n"
: "=r" (lo), "=r" (hi)
: "r" (0), "r" (0x100));
return !!hi;
}
/*
* If we detect that the CPU has iWMMXt (and CONFIG_IWMMXT=y), we
* disable CP0/CP1 on boot, and let call_fpe() and the iWMMXt lazy
* switch code handle iWMMXt context switching. If on the other
* hand the CPU has a DSP coprocessor, we keep access to CP0 enabled
* all the time, and save/restore acc0 on context switch in non-lazy
* fashion.
*/
static int __init xscale_cp0_init(void)
{
u32 cp_access;
cp_access = xscale_cp_access_read() & ~3;
xscale_cp_access_write(cp_access | 1);
if (cpu_has_iwmmxt()) {
#ifndef CONFIG_IWMMXT
printk(KERN_WARNING "CAUTION: XScale iWMMXt coprocessor "
"detected, but kernel support is missing.\n");
#else
printk(KERN_INFO "XScale iWMMXt coprocessor detected.\n");
elf_hwcap |= HWCAP_IWMMXT;
thread_register_notifier(&iwmmxt_notifier_block);
#endif
} else {
printk(KERN_INFO "XScale DSP coprocessor detected.\n");
thread_register_notifier(&dsp_notifier_block);
cp_access |= 1;
}
xscale_cp_access_write(cp_access);
return 0;
}
late_initcall(xscale_cp0_init);
| gpl-2.0 |
mkasick/android_kernel_samsung_jfltespr | drivers/usb/musb/musb_host.c | 4762 | 65619 | /*
* MUSB OTG driver host support
*
* Copyright 2005 Mentor Graphics Corporation
* Copyright (C) 2005-2006 by Texas Instruments
* Copyright (C) 2006-2007 Nokia Corporation
* Copyright (C) 2008-2009 MontaVista Software, Inc. <source@mvista.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
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHORS 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/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/dma-mapping.h>
#include "musb_core.h"
#include "musb_host.h"
/* MUSB HOST status 22-mar-2006
*
* - There's still lots of partial code duplication for fault paths, so
* they aren't handled as consistently as they need to be.
*
* - PIO mostly behaved when last tested.
* + including ep0, with all usbtest cases 9, 10
* + usbtest 14 (ep0out) doesn't seem to run at all
* + double buffered OUT/TX endpoints saw stalls(!) with certain usbtest
* configurations, but otherwise double buffering passes basic tests.
* + for 2.6.N, for N > ~10, needs API changes for hcd framework.
*
* - DMA (CPPI) ... partially behaves, not currently recommended
* + about 1/15 the speed of typical EHCI implementations (PCI)
* + RX, all too often reqpkt seems to misbehave after tx
* + TX, no known issues (other than evident silicon issue)
*
* - DMA (Mentor/OMAP) ...has at least toggle update problems
*
* - [23-feb-2009] minimal traffic scheduling to avoid bulk RX packet
* starvation ... nothing yet for TX, interrupt, or bulk.
*
* - Not tested with HNP, but some SRP paths seem to behave.
*
* NOTE 24-August-2006:
*
* - Bulk traffic finally uses both sides of hardware ep1, freeing up an
* extra endpoint for periodic use enabling hub + keybd + mouse. That
* mostly works, except that with "usbnet" it's easy to trigger cases
* with "ping" where RX loses. (a) ping to davinci, even "ping -f",
* fine; but (b) ping _from_ davinci, even "ping -c 1", ICMP RX loses
* although ARP RX wins. (That test was done with a full speed link.)
*/
/*
* NOTE on endpoint usage:
*
* CONTROL transfers all go through ep0. BULK ones go through dedicated IN
* and OUT endpoints ... hardware is dedicated for those "async" queue(s).
* (Yes, bulk _could_ use more of the endpoints than that, and would even
* benefit from it.)
*
* INTERUPPT and ISOCHRONOUS transfers are scheduled to the other endpoints.
* So far that scheduling is both dumb and optimistic: the endpoint will be
* "claimed" until its software queue is no longer refilled. No multiplexing
* of transfers between endpoints, or anything clever.
*/
static void musb_ep_program(struct musb *musb, u8 epnum,
struct urb *urb, int is_out,
u8 *buf, u32 offset, u32 len);
/*
* Clear TX fifo. Needed to avoid BABBLE errors.
*/
static void musb_h_tx_flush_fifo(struct musb_hw_ep *ep)
{
struct musb *musb = ep->musb;
void __iomem *epio = ep->regs;
u16 csr;
u16 lastcsr = 0;
int retries = 1000;
csr = musb_readw(epio, MUSB_TXCSR);
while (csr & MUSB_TXCSR_FIFONOTEMPTY) {
if (csr != lastcsr)
dev_dbg(musb->controller, "Host TX FIFONOTEMPTY csr: %02x\n", csr);
lastcsr = csr;
csr |= MUSB_TXCSR_FLUSHFIFO;
musb_writew(epio, MUSB_TXCSR, csr);
csr = musb_readw(epio, MUSB_TXCSR);
if (WARN(retries-- < 1,
"Could not flush host TX%d fifo: csr: %04x\n",
ep->epnum, csr))
return;
mdelay(1);
}
}
static void musb_h_ep0_flush_fifo(struct musb_hw_ep *ep)
{
void __iomem *epio = ep->regs;
u16 csr;
int retries = 5;
/* scrub any data left in the fifo */
do {
csr = musb_readw(epio, MUSB_TXCSR);
if (!(csr & (MUSB_CSR0_TXPKTRDY | MUSB_CSR0_RXPKTRDY)))
break;
musb_writew(epio, MUSB_TXCSR, MUSB_CSR0_FLUSHFIFO);
csr = musb_readw(epio, MUSB_TXCSR);
udelay(10);
} while (--retries);
WARN(!retries, "Could not flush host TX%d fifo: csr: %04x\n",
ep->epnum, csr);
/* and reset for the next transfer */
musb_writew(epio, MUSB_TXCSR, 0);
}
/*
* Start transmit. Caller is responsible for locking shared resources.
* musb must be locked.
*/
static inline void musb_h_tx_start(struct musb_hw_ep *ep)
{
u16 txcsr;
/* NOTE: no locks here; caller should lock and select EP */
if (ep->epnum) {
txcsr = musb_readw(ep->regs, MUSB_TXCSR);
txcsr |= MUSB_TXCSR_TXPKTRDY | MUSB_TXCSR_H_WZC_BITS;
musb_writew(ep->regs, MUSB_TXCSR, txcsr);
} else {
txcsr = MUSB_CSR0_H_SETUPPKT | MUSB_CSR0_TXPKTRDY;
musb_writew(ep->regs, MUSB_CSR0, txcsr);
}
}
static inline void musb_h_tx_dma_start(struct musb_hw_ep *ep)
{
u16 txcsr;
/* NOTE: no locks here; caller should lock and select EP */
txcsr = musb_readw(ep->regs, MUSB_TXCSR);
txcsr |= MUSB_TXCSR_DMAENAB | MUSB_TXCSR_H_WZC_BITS;
if (is_cppi_enabled())
txcsr |= MUSB_TXCSR_DMAMODE;
musb_writew(ep->regs, MUSB_TXCSR, txcsr);
}
static void musb_ep_set_qh(struct musb_hw_ep *ep, int is_in, struct musb_qh *qh)
{
if (is_in != 0 || ep->is_shared_fifo)
ep->in_qh = qh;
if (is_in == 0 || ep->is_shared_fifo)
ep->out_qh = qh;
}
static struct musb_qh *musb_ep_get_qh(struct musb_hw_ep *ep, int is_in)
{
return is_in ? ep->in_qh : ep->out_qh;
}
/*
* Start the URB at the front of an endpoint's queue
* end must be claimed from the caller.
*
* Context: controller locked, irqs blocked
*/
static void
musb_start_urb(struct musb *musb, int is_in, struct musb_qh *qh)
{
u16 frame;
u32 len;
void __iomem *mbase = musb->mregs;
struct urb *urb = next_urb(qh);
void *buf = urb->transfer_buffer;
u32 offset = 0;
struct musb_hw_ep *hw_ep = qh->hw_ep;
unsigned pipe = urb->pipe;
u8 address = usb_pipedevice(pipe);
int epnum = hw_ep->epnum;
/* initialize software qh state */
qh->offset = 0;
qh->segsize = 0;
/* gather right source of data */
switch (qh->type) {
case USB_ENDPOINT_XFER_CONTROL:
/* control transfers always start with SETUP */
is_in = 0;
musb->ep0_stage = MUSB_EP0_START;
buf = urb->setup_packet;
len = 8;
break;
case USB_ENDPOINT_XFER_ISOC:
qh->iso_idx = 0;
qh->frame = 0;
offset = urb->iso_frame_desc[0].offset;
len = urb->iso_frame_desc[0].length;
break;
default: /* bulk, interrupt */
/* actual_length may be nonzero on retry paths */
buf = urb->transfer_buffer + urb->actual_length;
len = urb->transfer_buffer_length - urb->actual_length;
}
dev_dbg(musb->controller, "qh %p urb %p dev%d ep%d%s%s, hw_ep %d, %p/%d\n",
qh, urb, address, qh->epnum,
is_in ? "in" : "out",
({char *s; switch (qh->type) {
case USB_ENDPOINT_XFER_CONTROL: s = ""; break;
case USB_ENDPOINT_XFER_BULK: s = "-bulk"; break;
case USB_ENDPOINT_XFER_ISOC: s = "-iso"; break;
default: s = "-intr"; break;
}; s; }),
epnum, buf + offset, len);
/* Configure endpoint */
musb_ep_set_qh(hw_ep, is_in, qh);
musb_ep_program(musb, epnum, urb, !is_in, buf, offset, len);
/* transmit may have more work: start it when it is time */
if (is_in)
return;
/* determine if the time is right for a periodic transfer */
switch (qh->type) {
case USB_ENDPOINT_XFER_ISOC:
case USB_ENDPOINT_XFER_INT:
dev_dbg(musb->controller, "check whether there's still time for periodic Tx\n");
frame = musb_readw(mbase, MUSB_FRAME);
/* FIXME this doesn't implement that scheduling policy ...
* or handle framecounter wrapping
*/
if ((urb->transfer_flags & URB_ISO_ASAP)
|| (frame >= urb->start_frame)) {
/* REVISIT the SOF irq handler shouldn't duplicate
* this code; and we don't init urb->start_frame...
*/
qh->frame = 0;
goto start;
} else {
qh->frame = urb->start_frame;
/* enable SOF interrupt so we can count down */
dev_dbg(musb->controller, "SOF for %d\n", epnum);
#if 1 /* ifndef CONFIG_ARCH_DAVINCI */
musb_writeb(mbase, MUSB_INTRUSBE, 0xff);
#endif
}
break;
default:
start:
dev_dbg(musb->controller, "Start TX%d %s\n", epnum,
hw_ep->tx_channel ? "dma" : "pio");
if (!hw_ep->tx_channel)
musb_h_tx_start(hw_ep);
else if (is_cppi_enabled() || tusb_dma_omap())
musb_h_tx_dma_start(hw_ep);
}
}
/* Context: caller owns controller lock, IRQs are blocked */
static void musb_giveback(struct musb *musb, struct urb *urb, int status)
__releases(musb->lock)
__acquires(musb->lock)
{
dev_dbg(musb->controller,
"complete %p %pF (%d), dev%d ep%d%s, %d/%d\n",
urb, urb->complete, status,
usb_pipedevice(urb->pipe),
usb_pipeendpoint(urb->pipe),
usb_pipein(urb->pipe) ? "in" : "out",
urb->actual_length, urb->transfer_buffer_length
);
usb_hcd_unlink_urb_from_ep(musb_to_hcd(musb), urb);
spin_unlock(&musb->lock);
usb_hcd_giveback_urb(musb_to_hcd(musb), urb, status);
spin_lock(&musb->lock);
}
/* For bulk/interrupt endpoints only */
static inline void musb_save_toggle(struct musb_qh *qh, int is_in,
struct urb *urb)
{
void __iomem *epio = qh->hw_ep->regs;
u16 csr;
/*
* FIXME: the current Mentor DMA code seems to have
* problems getting toggle correct.
*/
if (is_in)
csr = musb_readw(epio, MUSB_RXCSR) & MUSB_RXCSR_H_DATATOGGLE;
else
csr = musb_readw(epio, MUSB_TXCSR) & MUSB_TXCSR_H_DATATOGGLE;
usb_settoggle(urb->dev, qh->epnum, !is_in, csr ? 1 : 0);
}
/*
* Advance this hardware endpoint's queue, completing the specified URB and
* advancing to either the next URB queued to that qh, or else invalidating
* that qh and advancing to the next qh scheduled after the current one.
*
* Context: caller owns controller lock, IRQs are blocked
*/
static void musb_advance_schedule(struct musb *musb, struct urb *urb,
struct musb_hw_ep *hw_ep, int is_in)
{
struct musb_qh *qh = musb_ep_get_qh(hw_ep, is_in);
struct musb_hw_ep *ep = qh->hw_ep;
int ready = qh->is_ready;
int status;
status = (urb->status == -EINPROGRESS) ? 0 : urb->status;
/* save toggle eagerly, for paranoia */
switch (qh->type) {
case USB_ENDPOINT_XFER_BULK:
case USB_ENDPOINT_XFER_INT:
musb_save_toggle(qh, is_in, urb);
break;
case USB_ENDPOINT_XFER_ISOC:
if (status == 0 && urb->error_count)
status = -EXDEV;
break;
}
qh->is_ready = 0;
musb_giveback(musb, urb, status);
qh->is_ready = ready;
/* reclaim resources (and bandwidth) ASAP; deschedule it, and
* invalidate qh as soon as list_empty(&hep->urb_list)
*/
if (list_empty(&qh->hep->urb_list)) {
struct list_head *head;
if (is_in)
ep->rx_reinit = 1;
else
ep->tx_reinit = 1;
/* Clobber old pointers to this qh */
musb_ep_set_qh(ep, is_in, NULL);
qh->hep->hcpriv = NULL;
switch (qh->type) {
case USB_ENDPOINT_XFER_CONTROL:
case USB_ENDPOINT_XFER_BULK:
/* fifo policy for these lists, except that NAKing
* should rotate a qh to the end (for fairness).
*/
if (qh->mux == 1) {
head = qh->ring.prev;
list_del(&qh->ring);
kfree(qh);
qh = first_qh(head);
break;
}
case USB_ENDPOINT_XFER_ISOC:
case USB_ENDPOINT_XFER_INT:
/* this is where periodic bandwidth should be
* de-allocated if it's tracked and allocated;
* and where we'd update the schedule tree...
*/
kfree(qh);
qh = NULL;
break;
}
}
if (qh != NULL && qh->is_ready) {
dev_dbg(musb->controller, "... next ep%d %cX urb %p\n",
hw_ep->epnum, is_in ? 'R' : 'T', next_urb(qh));
musb_start_urb(musb, is_in, qh);
}
}
static u16 musb_h_flush_rxfifo(struct musb_hw_ep *hw_ep, u16 csr)
{
/* we don't want fifo to fill itself again;
* ignore dma (various models),
* leave toggle alone (may not have been saved yet)
*/
csr |= MUSB_RXCSR_FLUSHFIFO | MUSB_RXCSR_RXPKTRDY;
csr &= ~(MUSB_RXCSR_H_REQPKT
| MUSB_RXCSR_H_AUTOREQ
| MUSB_RXCSR_AUTOCLEAR);
/* write 2x to allow double buffering */
musb_writew(hw_ep->regs, MUSB_RXCSR, csr);
musb_writew(hw_ep->regs, MUSB_RXCSR, csr);
/* flush writebuffer */
return musb_readw(hw_ep->regs, MUSB_RXCSR);
}
/*
* PIO RX for a packet (or part of it).
*/
static bool
musb_host_packet_rx(struct musb *musb, struct urb *urb, u8 epnum, u8 iso_err)
{
u16 rx_count;
u8 *buf;
u16 csr;
bool done = false;
u32 length;
int do_flush = 0;
struct musb_hw_ep *hw_ep = musb->endpoints + epnum;
void __iomem *epio = hw_ep->regs;
struct musb_qh *qh = hw_ep->in_qh;
int pipe = urb->pipe;
void *buffer = urb->transfer_buffer;
/* musb_ep_select(mbase, epnum); */
rx_count = musb_readw(epio, MUSB_RXCOUNT);
dev_dbg(musb->controller, "RX%d count %d, buffer %p len %d/%d\n", epnum, rx_count,
urb->transfer_buffer, qh->offset,
urb->transfer_buffer_length);
/* unload FIFO */
if (usb_pipeisoc(pipe)) {
int status = 0;
struct usb_iso_packet_descriptor *d;
if (iso_err) {
status = -EILSEQ;
urb->error_count++;
}
d = urb->iso_frame_desc + qh->iso_idx;
buf = buffer + d->offset;
length = d->length;
if (rx_count > length) {
if (status == 0) {
status = -EOVERFLOW;
urb->error_count++;
}
dev_dbg(musb->controller, "** OVERFLOW %d into %d\n", rx_count, length);
do_flush = 1;
} else
length = rx_count;
urb->actual_length += length;
d->actual_length = length;
d->status = status;
/* see if we are done */
done = (++qh->iso_idx >= urb->number_of_packets);
} else {
/* non-isoch */
buf = buffer + qh->offset;
length = urb->transfer_buffer_length - qh->offset;
if (rx_count > length) {
if (urb->status == -EINPROGRESS)
urb->status = -EOVERFLOW;
dev_dbg(musb->controller, "** OVERFLOW %d into %d\n", rx_count, length);
do_flush = 1;
} else
length = rx_count;
urb->actual_length += length;
qh->offset += length;
/* see if we are done */
done = (urb->actual_length == urb->transfer_buffer_length)
|| (rx_count < qh->maxpacket)
|| (urb->status != -EINPROGRESS);
if (done
&& (urb->status == -EINPROGRESS)
&& (urb->transfer_flags & URB_SHORT_NOT_OK)
&& (urb->actual_length
< urb->transfer_buffer_length))
urb->status = -EREMOTEIO;
}
musb_read_fifo(hw_ep, length, buf);
csr = musb_readw(epio, MUSB_RXCSR);
csr |= MUSB_RXCSR_H_WZC_BITS;
if (unlikely(do_flush))
musb_h_flush_rxfifo(hw_ep, csr);
else {
/* REVISIT this assumes AUTOCLEAR is never set */
csr &= ~(MUSB_RXCSR_RXPKTRDY | MUSB_RXCSR_H_REQPKT);
if (!done)
csr |= MUSB_RXCSR_H_REQPKT;
musb_writew(epio, MUSB_RXCSR, csr);
}
return done;
}
/* we don't always need to reinit a given side of an endpoint...
* when we do, use tx/rx reinit routine and then construct a new CSR
* to address data toggle, NYET, and DMA or PIO.
*
* it's possible that driver bugs (especially for DMA) or aborting a
* transfer might have left the endpoint busier than it should be.
* the busy/not-empty tests are basically paranoia.
*/
static void
musb_rx_reinit(struct musb *musb, struct musb_qh *qh, struct musb_hw_ep *ep)
{
u16 csr;
/* NOTE: we know the "rx" fifo reinit never triggers for ep0.
* That always uses tx_reinit since ep0 repurposes TX register
* offsets; the initial SETUP packet is also a kind of OUT.
*/
/* if programmed for Tx, put it in RX mode */
if (ep->is_shared_fifo) {
csr = musb_readw(ep->regs, MUSB_TXCSR);
if (csr & MUSB_TXCSR_MODE) {
musb_h_tx_flush_fifo(ep);
csr = musb_readw(ep->regs, MUSB_TXCSR);
musb_writew(ep->regs, MUSB_TXCSR,
csr | MUSB_TXCSR_FRCDATATOG);
}
/*
* Clear the MODE bit (and everything else) to enable Rx.
* NOTE: we mustn't clear the DMAMODE bit before DMAENAB.
*/
if (csr & MUSB_TXCSR_DMAMODE)
musb_writew(ep->regs, MUSB_TXCSR, MUSB_TXCSR_DMAMODE);
musb_writew(ep->regs, MUSB_TXCSR, 0);
/* scrub all previous state, clearing toggle */
} else {
csr = musb_readw(ep->regs, MUSB_RXCSR);
if (csr & MUSB_RXCSR_RXPKTRDY)
WARNING("rx%d, packet/%d ready?\n", ep->epnum,
musb_readw(ep->regs, MUSB_RXCOUNT));
musb_h_flush_rxfifo(ep, MUSB_RXCSR_CLRDATATOG);
}
/* target addr and (for multipoint) hub addr/port */
if (musb->is_multipoint) {
musb_write_rxfunaddr(ep->target_regs, qh->addr_reg);
musb_write_rxhubaddr(ep->target_regs, qh->h_addr_reg);
musb_write_rxhubport(ep->target_regs, qh->h_port_reg);
} else
musb_writeb(musb->mregs, MUSB_FADDR, qh->addr_reg);
/* protocol/endpoint, interval/NAKlimit, i/o size */
musb_writeb(ep->regs, MUSB_RXTYPE, qh->type_reg);
musb_writeb(ep->regs, MUSB_RXINTERVAL, qh->intv_reg);
/* NOTE: bulk combining rewrites high bits of maxpacket */
/* Set RXMAXP with the FIFO size of the endpoint
* to disable double buffer mode.
*/
if (musb->double_buffer_not_ok)
musb_writew(ep->regs, MUSB_RXMAXP, ep->max_packet_sz_rx);
else
musb_writew(ep->regs, MUSB_RXMAXP,
qh->maxpacket | ((qh->hb_mult - 1) << 11));
ep->rx_reinit = 0;
}
static bool musb_tx_dma_program(struct dma_controller *dma,
struct musb_hw_ep *hw_ep, struct musb_qh *qh,
struct urb *urb, u32 offset, u32 length)
{
struct dma_channel *channel = hw_ep->tx_channel;
void __iomem *epio = hw_ep->regs;
u16 pkt_size = qh->maxpacket;
u16 csr;
u8 mode;
#ifdef CONFIG_USB_INVENTRA_DMA
if (length > channel->max_len)
length = channel->max_len;
csr = musb_readw(epio, MUSB_TXCSR);
if (length > pkt_size) {
mode = 1;
csr |= MUSB_TXCSR_DMAMODE | MUSB_TXCSR_DMAENAB;
/* autoset shouldn't be set in high bandwidth */
if (qh->hb_mult == 1)
csr |= MUSB_TXCSR_AUTOSET;
} else {
mode = 0;
csr &= ~(MUSB_TXCSR_AUTOSET | MUSB_TXCSR_DMAMODE);
csr |= MUSB_TXCSR_DMAENAB; /* against programmer's guide */
}
channel->desired_mode = mode;
musb_writew(epio, MUSB_TXCSR, csr);
#else
if (!is_cppi_enabled() && !tusb_dma_omap())
return false;
channel->actual_len = 0;
/*
* TX uses "RNDIS" mode automatically but needs help
* to identify the zero-length-final-packet case.
*/
mode = (urb->transfer_flags & URB_ZERO_PACKET) ? 1 : 0;
#endif
qh->segsize = length;
/*
* Ensure the data reaches to main memory before starting
* DMA transfer
*/
wmb();
if (!dma->channel_program(channel, pkt_size, mode,
urb->transfer_dma + offset, length)) {
dma->channel_release(channel);
hw_ep->tx_channel = NULL;
csr = musb_readw(epio, MUSB_TXCSR);
csr &= ~(MUSB_TXCSR_AUTOSET | MUSB_TXCSR_DMAENAB);
musb_writew(epio, MUSB_TXCSR, csr | MUSB_TXCSR_H_WZC_BITS);
return false;
}
return true;
}
/*
* Program an HDRC endpoint as per the given URB
* Context: irqs blocked, controller lock held
*/
static void musb_ep_program(struct musb *musb, u8 epnum,
struct urb *urb, int is_out,
u8 *buf, u32 offset, u32 len)
{
struct dma_controller *dma_controller;
struct dma_channel *dma_channel;
u8 dma_ok;
void __iomem *mbase = musb->mregs;
struct musb_hw_ep *hw_ep = musb->endpoints + epnum;
void __iomem *epio = hw_ep->regs;
struct musb_qh *qh = musb_ep_get_qh(hw_ep, !is_out);
u16 packet_sz = qh->maxpacket;
dev_dbg(musb->controller, "%s hw%d urb %p spd%d dev%d ep%d%s "
"h_addr%02x h_port%02x bytes %d\n",
is_out ? "-->" : "<--",
epnum, urb, urb->dev->speed,
qh->addr_reg, qh->epnum, is_out ? "out" : "in",
qh->h_addr_reg, qh->h_port_reg,
len);
musb_ep_select(mbase, epnum);
/* candidate for DMA? */
dma_controller = musb->dma_controller;
if (is_dma_capable() && epnum && dma_controller) {
dma_channel = is_out ? hw_ep->tx_channel : hw_ep->rx_channel;
if (!dma_channel) {
dma_channel = dma_controller->channel_alloc(
dma_controller, hw_ep, is_out);
if (is_out)
hw_ep->tx_channel = dma_channel;
else
hw_ep->rx_channel = dma_channel;
}
} else
dma_channel = NULL;
/* make sure we clear DMAEnab, autoSet bits from previous run */
/* OUT/transmit/EP0 or IN/receive? */
if (is_out) {
u16 csr;
u16 int_txe;
u16 load_count;
csr = musb_readw(epio, MUSB_TXCSR);
/* disable interrupt in case we flush */
int_txe = musb_readw(mbase, MUSB_INTRTXE);
musb_writew(mbase, MUSB_INTRTXE, int_txe & ~(1 << epnum));
/* general endpoint setup */
if (epnum) {
/* flush all old state, set default */
musb_h_tx_flush_fifo(hw_ep);
/*
* We must not clear the DMAMODE bit before or in
* the same cycle with the DMAENAB bit, so we clear
* the latter first...
*/
csr &= ~(MUSB_TXCSR_H_NAKTIMEOUT
| MUSB_TXCSR_AUTOSET
| MUSB_TXCSR_DMAENAB
| MUSB_TXCSR_FRCDATATOG
| MUSB_TXCSR_H_RXSTALL
| MUSB_TXCSR_H_ERROR
| MUSB_TXCSR_TXPKTRDY
);
csr |= MUSB_TXCSR_MODE;
if (usb_gettoggle(urb->dev, qh->epnum, 1))
csr |= MUSB_TXCSR_H_WR_DATATOGGLE
| MUSB_TXCSR_H_DATATOGGLE;
else
csr |= MUSB_TXCSR_CLRDATATOG;
musb_writew(epio, MUSB_TXCSR, csr);
/* REVISIT may need to clear FLUSHFIFO ... */
csr &= ~MUSB_TXCSR_DMAMODE;
musb_writew(epio, MUSB_TXCSR, csr);
csr = musb_readw(epio, MUSB_TXCSR);
} else {
/* endpoint 0: just flush */
musb_h_ep0_flush_fifo(hw_ep);
}
/* target addr and (for multipoint) hub addr/port */
if (musb->is_multipoint) {
musb_write_txfunaddr(mbase, epnum, qh->addr_reg);
musb_write_txhubaddr(mbase, epnum, qh->h_addr_reg);
musb_write_txhubport(mbase, epnum, qh->h_port_reg);
/* FIXME if !epnum, do the same for RX ... */
} else
musb_writeb(mbase, MUSB_FADDR, qh->addr_reg);
/* protocol/endpoint/interval/NAKlimit */
if (epnum) {
musb_writeb(epio, MUSB_TXTYPE, qh->type_reg);
if (musb->double_buffer_not_ok)
musb_writew(epio, MUSB_TXMAXP,
hw_ep->max_packet_sz_tx);
else if (can_bulk_split(musb, qh->type))
musb_writew(epio, MUSB_TXMAXP, packet_sz
| ((hw_ep->max_packet_sz_tx /
packet_sz) - 1) << 11);
else
musb_writew(epio, MUSB_TXMAXP,
qh->maxpacket |
((qh->hb_mult - 1) << 11));
musb_writeb(epio, MUSB_TXINTERVAL, qh->intv_reg);
} else {
musb_writeb(epio, MUSB_NAKLIMIT0, qh->intv_reg);
if (musb->is_multipoint)
musb_writeb(epio, MUSB_TYPE0,
qh->type_reg);
}
if (can_bulk_split(musb, qh->type))
load_count = min((u32) hw_ep->max_packet_sz_tx,
len);
else
load_count = min((u32) packet_sz, len);
if (dma_channel && musb_tx_dma_program(dma_controller,
hw_ep, qh, urb, offset, len))
load_count = 0;
if (load_count) {
/* PIO to load FIFO */
qh->segsize = load_count;
musb_write_fifo(hw_ep, load_count, buf);
}
/* re-enable interrupt */
musb_writew(mbase, MUSB_INTRTXE, int_txe);
/* IN/receive */
} else {
u16 csr;
if (hw_ep->rx_reinit) {
musb_rx_reinit(musb, qh, hw_ep);
/* init new state: toggle and NYET, maybe DMA later */
if (usb_gettoggle(urb->dev, qh->epnum, 0))
csr = MUSB_RXCSR_H_WR_DATATOGGLE
| MUSB_RXCSR_H_DATATOGGLE;
else
csr = 0;
if (qh->type == USB_ENDPOINT_XFER_INT)
csr |= MUSB_RXCSR_DISNYET;
} else {
csr = musb_readw(hw_ep->regs, MUSB_RXCSR);
if (csr & (MUSB_RXCSR_RXPKTRDY
| MUSB_RXCSR_DMAENAB
| MUSB_RXCSR_H_REQPKT))
ERR("broken !rx_reinit, ep%d csr %04x\n",
hw_ep->epnum, csr);
/* scrub any stale state, leaving toggle alone */
csr &= MUSB_RXCSR_DISNYET;
}
/* kick things off */
if ((is_cppi_enabled() || tusb_dma_omap()) && dma_channel) {
/* Candidate for DMA */
dma_channel->actual_len = 0L;
qh->segsize = len;
/* AUTOREQ is in a DMA register */
musb_writew(hw_ep->regs, MUSB_RXCSR, csr);
csr = musb_readw(hw_ep->regs, MUSB_RXCSR);
/*
* Unless caller treats short RX transfers as
* errors, we dare not queue multiple transfers.
*/
dma_ok = dma_controller->channel_program(dma_channel,
packet_sz, !(urb->transfer_flags &
URB_SHORT_NOT_OK),
urb->transfer_dma + offset,
qh->segsize);
if (!dma_ok) {
dma_controller->channel_release(dma_channel);
hw_ep->rx_channel = dma_channel = NULL;
} else
csr |= MUSB_RXCSR_DMAENAB;
}
csr |= MUSB_RXCSR_H_REQPKT;
dev_dbg(musb->controller, "RXCSR%d := %04x\n", epnum, csr);
musb_writew(hw_ep->regs, MUSB_RXCSR, csr);
csr = musb_readw(hw_ep->regs, MUSB_RXCSR);
}
}
/*
* Service the default endpoint (ep0) as host.
* Return true until it's time to start the status stage.
*/
static bool musb_h_ep0_continue(struct musb *musb, u16 len, struct urb *urb)
{
bool more = false;
u8 *fifo_dest = NULL;
u16 fifo_count = 0;
struct musb_hw_ep *hw_ep = musb->control_ep;
struct musb_qh *qh = hw_ep->in_qh;
struct usb_ctrlrequest *request;
switch (musb->ep0_stage) {
case MUSB_EP0_IN:
fifo_dest = urb->transfer_buffer + urb->actual_length;
fifo_count = min_t(size_t, len, urb->transfer_buffer_length -
urb->actual_length);
if (fifo_count < len)
urb->status = -EOVERFLOW;
musb_read_fifo(hw_ep, fifo_count, fifo_dest);
urb->actual_length += fifo_count;
if (len < qh->maxpacket) {
/* always terminate on short read; it's
* rarely reported as an error.
*/
} else if (urb->actual_length <
urb->transfer_buffer_length)
more = true;
break;
case MUSB_EP0_START:
request = (struct usb_ctrlrequest *) urb->setup_packet;
if (!request->wLength) {
dev_dbg(musb->controller, "start no-DATA\n");
break;
} else if (request->bRequestType & USB_DIR_IN) {
dev_dbg(musb->controller, "start IN-DATA\n");
musb->ep0_stage = MUSB_EP0_IN;
more = true;
break;
} else {
dev_dbg(musb->controller, "start OUT-DATA\n");
musb->ep0_stage = MUSB_EP0_OUT;
more = true;
}
/* FALLTHROUGH */
case MUSB_EP0_OUT:
fifo_count = min_t(size_t, qh->maxpacket,
urb->transfer_buffer_length -
urb->actual_length);
if (fifo_count) {
fifo_dest = (u8 *) (urb->transfer_buffer
+ urb->actual_length);
dev_dbg(musb->controller, "Sending %d byte%s to ep0 fifo %p\n",
fifo_count,
(fifo_count == 1) ? "" : "s",
fifo_dest);
musb_write_fifo(hw_ep, fifo_count, fifo_dest);
urb->actual_length += fifo_count;
more = true;
}
break;
default:
ERR("bogus ep0 stage %d\n", musb->ep0_stage);
break;
}
return more;
}
/*
* Handle default endpoint interrupt as host. Only called in IRQ time
* from musb_interrupt().
*
* called with controller irqlocked
*/
irqreturn_t musb_h_ep0_irq(struct musb *musb)
{
struct urb *urb;
u16 csr, len;
int status = 0;
void __iomem *mbase = musb->mregs;
struct musb_hw_ep *hw_ep = musb->control_ep;
void __iomem *epio = hw_ep->regs;
struct musb_qh *qh = hw_ep->in_qh;
bool complete = false;
irqreturn_t retval = IRQ_NONE;
/* ep0 only has one queue, "in" */
urb = next_urb(qh);
musb_ep_select(mbase, 0);
csr = musb_readw(epio, MUSB_CSR0);
len = (csr & MUSB_CSR0_RXPKTRDY)
? musb_readb(epio, MUSB_COUNT0)
: 0;
dev_dbg(musb->controller, "<== csr0 %04x, qh %p, count %d, urb %p, stage %d\n",
csr, qh, len, urb, musb->ep0_stage);
/* if we just did status stage, we are done */
if (MUSB_EP0_STATUS == musb->ep0_stage) {
retval = IRQ_HANDLED;
complete = true;
}
/* prepare status */
if (csr & MUSB_CSR0_H_RXSTALL) {
dev_dbg(musb->controller, "STALLING ENDPOINT\n");
status = -EPIPE;
} else if (csr & MUSB_CSR0_H_ERROR) {
dev_dbg(musb->controller, "no response, csr0 %04x\n", csr);
status = -EPROTO;
} else if (csr & MUSB_CSR0_H_NAKTIMEOUT) {
dev_dbg(musb->controller, "control NAK timeout\n");
/* NOTE: this code path would be a good place to PAUSE a
* control transfer, if another one is queued, so that
* ep0 is more likely to stay busy. That's already done
* for bulk RX transfers.
*
* if (qh->ring.next != &musb->control), then
* we have a candidate... NAKing is *NOT* an error
*/
musb_writew(epio, MUSB_CSR0, 0);
retval = IRQ_HANDLED;
}
if (status) {
dev_dbg(musb->controller, "aborting\n");
retval = IRQ_HANDLED;
if (urb)
urb->status = status;
complete = true;
/* use the proper sequence to abort the transfer */
if (csr & MUSB_CSR0_H_REQPKT) {
csr &= ~MUSB_CSR0_H_REQPKT;
musb_writew(epio, MUSB_CSR0, csr);
csr &= ~MUSB_CSR0_H_NAKTIMEOUT;
musb_writew(epio, MUSB_CSR0, csr);
} else {
musb_h_ep0_flush_fifo(hw_ep);
}
musb_writeb(epio, MUSB_NAKLIMIT0, 0);
/* clear it */
musb_writew(epio, MUSB_CSR0, 0);
}
if (unlikely(!urb)) {
/* stop endpoint since we have no place for its data, this
* SHOULD NEVER HAPPEN! */
ERR("no URB for end 0\n");
musb_h_ep0_flush_fifo(hw_ep);
goto done;
}
if (!complete) {
/* call common logic and prepare response */
if (musb_h_ep0_continue(musb, len, urb)) {
/* more packets required */
csr = (MUSB_EP0_IN == musb->ep0_stage)
? MUSB_CSR0_H_REQPKT : MUSB_CSR0_TXPKTRDY;
} else {
/* data transfer complete; perform status phase */
if (usb_pipeout(urb->pipe)
|| !urb->transfer_buffer_length)
csr = MUSB_CSR0_H_STATUSPKT
| MUSB_CSR0_H_REQPKT;
else
csr = MUSB_CSR0_H_STATUSPKT
| MUSB_CSR0_TXPKTRDY;
/* flag status stage */
musb->ep0_stage = MUSB_EP0_STATUS;
dev_dbg(musb->controller, "ep0 STATUS, csr %04x\n", csr);
}
musb_writew(epio, MUSB_CSR0, csr);
retval = IRQ_HANDLED;
} else
musb->ep0_stage = MUSB_EP0_IDLE;
/* call completion handler if done */
if (complete)
musb_advance_schedule(musb, urb, hw_ep, 1);
done:
return retval;
}
#ifdef CONFIG_USB_INVENTRA_DMA
/* Host side TX (OUT) using Mentor DMA works as follows:
submit_urb ->
- if queue was empty, Program Endpoint
- ... which starts DMA to fifo in mode 1 or 0
DMA Isr (transfer complete) -> TxAvail()
- Stop DMA (~DmaEnab) (<--- Alert ... currently happens
only in musb_cleanup_urb)
- TxPktRdy has to be set in mode 0 or for
short packets in mode 1.
*/
#endif
/* Service a Tx-Available or dma completion irq for the endpoint */
void musb_host_tx(struct musb *musb, u8 epnum)
{
int pipe;
bool done = false;
u16 tx_csr;
size_t length = 0;
size_t offset = 0;
struct musb_hw_ep *hw_ep = musb->endpoints + epnum;
void __iomem *epio = hw_ep->regs;
struct musb_qh *qh = hw_ep->out_qh;
struct urb *urb = next_urb(qh);
u32 status = 0;
void __iomem *mbase = musb->mregs;
struct dma_channel *dma;
bool transfer_pending = false;
musb_ep_select(mbase, epnum);
tx_csr = musb_readw(epio, MUSB_TXCSR);
/* with CPPI, DMA sometimes triggers "extra" irqs */
if (!urb) {
dev_dbg(musb->controller, "extra TX%d ready, csr %04x\n", epnum, tx_csr);
return;
}
pipe = urb->pipe;
dma = is_dma_capable() ? hw_ep->tx_channel : NULL;
dev_dbg(musb->controller, "OUT/TX%d end, csr %04x%s\n", epnum, tx_csr,
dma ? ", dma" : "");
/* check for errors */
if (tx_csr & MUSB_TXCSR_H_RXSTALL) {
/* dma was disabled, fifo flushed */
dev_dbg(musb->controller, "TX end %d stall\n", epnum);
/* stall; record URB status */
status = -EPIPE;
} else if (tx_csr & MUSB_TXCSR_H_ERROR) {
/* (NON-ISO) dma was disabled, fifo flushed */
dev_dbg(musb->controller, "TX 3strikes on ep=%d\n", epnum);
status = -ETIMEDOUT;
} else if (tx_csr & MUSB_TXCSR_H_NAKTIMEOUT) {
dev_dbg(musb->controller, "TX end=%d device not responding\n", epnum);
/* NOTE: this code path would be a good place to PAUSE a
* transfer, if there's some other (nonperiodic) tx urb
* that could use this fifo. (dma complicates it...)
* That's already done for bulk RX transfers.
*
* if (bulk && qh->ring.next != &musb->out_bulk), then
* we have a candidate... NAKing is *NOT* an error
*/
musb_ep_select(mbase, epnum);
musb_writew(epio, MUSB_TXCSR,
MUSB_TXCSR_H_WZC_BITS
| MUSB_TXCSR_TXPKTRDY);
return;
}
if (status) {
if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
dma->status = MUSB_DMA_STATUS_CORE_ABORT;
(void) musb->dma_controller->channel_abort(dma);
}
/* do the proper sequence to abort the transfer in the
* usb core; the dma engine should already be stopped.
*/
musb_h_tx_flush_fifo(hw_ep);
tx_csr &= ~(MUSB_TXCSR_AUTOSET
| MUSB_TXCSR_DMAENAB
| MUSB_TXCSR_H_ERROR
| MUSB_TXCSR_H_RXSTALL
| MUSB_TXCSR_H_NAKTIMEOUT
);
musb_ep_select(mbase, epnum);
musb_writew(epio, MUSB_TXCSR, tx_csr);
/* REVISIT may need to clear FLUSHFIFO ... */
musb_writew(epio, MUSB_TXCSR, tx_csr);
musb_writeb(epio, MUSB_TXINTERVAL, 0);
done = true;
}
/* second cppi case */
if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
dev_dbg(musb->controller, "extra TX%d ready, csr %04x\n", epnum, tx_csr);
return;
}
if (is_dma_capable() && dma && !status) {
/*
* DMA has completed. But if we're using DMA mode 1 (multi
* packet DMA), we need a terminal TXPKTRDY interrupt before
* we can consider this transfer completed, lest we trash
* its last packet when writing the next URB's data. So we
* switch back to mode 0 to get that interrupt; we'll come
* back here once it happens.
*/
if (tx_csr & MUSB_TXCSR_DMAMODE) {
/*
* We shouldn't clear DMAMODE with DMAENAB set; so
* clear them in a safe order. That should be OK
* once TXPKTRDY has been set (and I've never seen
* it being 0 at this moment -- DMA interrupt latency
* is significant) but if it hasn't been then we have
* no choice but to stop being polite and ignore the
* programmer's guide... :-)
*
* Note that we must write TXCSR with TXPKTRDY cleared
* in order not to re-trigger the packet send (this bit
* can't be cleared by CPU), and there's another caveat:
* TXPKTRDY may be set shortly and then cleared in the
* double-buffered FIFO mode, so we do an extra TXCSR
* read for debouncing...
*/
tx_csr &= musb_readw(epio, MUSB_TXCSR);
if (tx_csr & MUSB_TXCSR_TXPKTRDY) {
tx_csr &= ~(MUSB_TXCSR_DMAENAB |
MUSB_TXCSR_TXPKTRDY);
musb_writew(epio, MUSB_TXCSR,
tx_csr | MUSB_TXCSR_H_WZC_BITS);
}
tx_csr &= ~(MUSB_TXCSR_DMAMODE |
MUSB_TXCSR_TXPKTRDY);
musb_writew(epio, MUSB_TXCSR,
tx_csr | MUSB_TXCSR_H_WZC_BITS);
/*
* There is no guarantee that we'll get an interrupt
* after clearing DMAMODE as we might have done this
* too late (after TXPKTRDY was cleared by controller).
* Re-read TXCSR as we have spoiled its previous value.
*/
tx_csr = musb_readw(epio, MUSB_TXCSR);
}
/*
* We may get here from a DMA completion or TXPKTRDY interrupt.
* In any case, we must check the FIFO status here and bail out
* only if the FIFO still has data -- that should prevent the
* "missed" TXPKTRDY interrupts and deal with double-buffered
* FIFO mode too...
*/
if (tx_csr & (MUSB_TXCSR_FIFONOTEMPTY | MUSB_TXCSR_TXPKTRDY)) {
dev_dbg(musb->controller, "DMA complete but packet still in FIFO, "
"CSR %04x\n", tx_csr);
return;
}
}
if (!status || dma || usb_pipeisoc(pipe)) {
if (dma)
length = dma->actual_len;
else
length = qh->segsize;
qh->offset += length;
if (usb_pipeisoc(pipe)) {
struct usb_iso_packet_descriptor *d;
d = urb->iso_frame_desc + qh->iso_idx;
d->actual_length = length;
d->status = status;
if (++qh->iso_idx >= urb->number_of_packets) {
done = true;
} else {
d++;
offset = d->offset;
length = d->length;
}
} else if (dma && urb->transfer_buffer_length == qh->offset) {
done = true;
} else {
/* see if we need to send more data, or ZLP */
if (qh->segsize < qh->maxpacket)
done = true;
else if (qh->offset == urb->transfer_buffer_length
&& !(urb->transfer_flags
& URB_ZERO_PACKET))
done = true;
if (!done) {
offset = qh->offset;
length = urb->transfer_buffer_length - offset;
transfer_pending = true;
}
}
}
/* urb->status != -EINPROGRESS means request has been faulted,
* so we must abort this transfer after cleanup
*/
if (urb->status != -EINPROGRESS) {
done = true;
if (status == 0)
status = urb->status;
}
if (done) {
/* set status */
urb->status = status;
urb->actual_length = qh->offset;
musb_advance_schedule(musb, urb, hw_ep, USB_DIR_OUT);
return;
} else if ((usb_pipeisoc(pipe) || transfer_pending) && dma) {
if (musb_tx_dma_program(musb->dma_controller, hw_ep, qh, urb,
offset, length)) {
if (is_cppi_enabled() || tusb_dma_omap())
musb_h_tx_dma_start(hw_ep);
return;
}
} else if (tx_csr & MUSB_TXCSR_DMAENAB) {
dev_dbg(musb->controller, "not complete, but DMA enabled?\n");
return;
}
/*
* PIO: start next packet in this URB.
*
* REVISIT: some docs say that when hw_ep->tx_double_buffered,
* (and presumably, FIFO is not half-full) we should write *two*
* packets before updating TXCSR; other docs disagree...
*/
if (length > qh->maxpacket)
length = qh->maxpacket;
/* Unmap the buffer so that CPU can use it */
usb_hcd_unmap_urb_for_dma(musb_to_hcd(musb), urb);
musb_write_fifo(hw_ep, length, urb->transfer_buffer + offset);
qh->segsize = length;
musb_ep_select(mbase, epnum);
musb_writew(epio, MUSB_TXCSR,
MUSB_TXCSR_H_WZC_BITS | MUSB_TXCSR_TXPKTRDY);
}
#ifdef CONFIG_USB_INVENTRA_DMA
/* Host side RX (IN) using Mentor DMA works as follows:
submit_urb ->
- if queue was empty, ProgramEndpoint
- first IN token is sent out (by setting ReqPkt)
LinuxIsr -> RxReady()
/\ => first packet is received
| - Set in mode 0 (DmaEnab, ~ReqPkt)
| -> DMA Isr (transfer complete) -> RxReady()
| - Ack receive (~RxPktRdy), turn off DMA (~DmaEnab)
| - if urb not complete, send next IN token (ReqPkt)
| | else complete urb.
| |
---------------------------
*
* Nuances of mode 1:
* For short packets, no ack (+RxPktRdy) is sent automatically
* (even if AutoClear is ON)
* For full packets, ack (~RxPktRdy) and next IN token (+ReqPkt) is sent
* automatically => major problem, as collecting the next packet becomes
* difficult. Hence mode 1 is not used.
*
* REVISIT
* All we care about at this driver level is that
* (a) all URBs terminate with REQPKT cleared and fifo(s) empty;
* (b) termination conditions are: short RX, or buffer full;
* (c) fault modes include
* - iff URB_SHORT_NOT_OK, short RX status is -EREMOTEIO.
* (and that endpoint's dma queue stops immediately)
* - overflow (full, PLUS more bytes in the terminal packet)
*
* So for example, usb-storage sets URB_SHORT_NOT_OK, and would
* thus be a great candidate for using mode 1 ... for all but the
* last packet of one URB's transfer.
*/
#endif
/* Schedule next QH from musb->in_bulk and move the current qh to
* the end; avoids starvation for other endpoints.
*/
static void musb_bulk_rx_nak_timeout(struct musb *musb, struct musb_hw_ep *ep)
{
struct dma_channel *dma;
struct urb *urb;
void __iomem *mbase = musb->mregs;
void __iomem *epio = ep->regs;
struct musb_qh *cur_qh, *next_qh;
u16 rx_csr;
musb_ep_select(mbase, ep->epnum);
dma = is_dma_capable() ? ep->rx_channel : NULL;
/* clear nak timeout bit */
rx_csr = musb_readw(epio, MUSB_RXCSR);
rx_csr |= MUSB_RXCSR_H_WZC_BITS;
rx_csr &= ~MUSB_RXCSR_DATAERROR;
musb_writew(epio, MUSB_RXCSR, rx_csr);
cur_qh = first_qh(&musb->in_bulk);
if (cur_qh) {
urb = next_urb(cur_qh);
if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
dma->status = MUSB_DMA_STATUS_CORE_ABORT;
musb->dma_controller->channel_abort(dma);
urb->actual_length += dma->actual_len;
dma->actual_len = 0L;
}
musb_save_toggle(cur_qh, 1, urb);
/* move cur_qh to end of queue */
list_move_tail(&cur_qh->ring, &musb->in_bulk);
/* get the next qh from musb->in_bulk */
next_qh = first_qh(&musb->in_bulk);
/* set rx_reinit and schedule the next qh */
ep->rx_reinit = 1;
musb_start_urb(musb, 1, next_qh);
}
}
/*
* Service an RX interrupt for the given IN endpoint; docs cover bulk, iso,
* and high-bandwidth IN transfer cases.
*/
void musb_host_rx(struct musb *musb, u8 epnum)
{
struct urb *urb;
struct musb_hw_ep *hw_ep = musb->endpoints + epnum;
void __iomem *epio = hw_ep->regs;
struct musb_qh *qh = hw_ep->in_qh;
size_t xfer_len;
void __iomem *mbase = musb->mregs;
int pipe;
u16 rx_csr, val;
bool iso_err = false;
bool done = false;
u32 status;
struct dma_channel *dma;
musb_ep_select(mbase, epnum);
urb = next_urb(qh);
dma = is_dma_capable() ? hw_ep->rx_channel : NULL;
status = 0;
xfer_len = 0;
rx_csr = musb_readw(epio, MUSB_RXCSR);
val = rx_csr;
if (unlikely(!urb)) {
/* REVISIT -- THIS SHOULD NEVER HAPPEN ... but, at least
* usbtest #11 (unlinks) triggers it regularly, sometimes
* with fifo full. (Only with DMA??)
*/
dev_dbg(musb->controller, "BOGUS RX%d ready, csr %04x, count %d\n", epnum, val,
musb_readw(epio, MUSB_RXCOUNT));
musb_h_flush_rxfifo(hw_ep, MUSB_RXCSR_CLRDATATOG);
return;
}
pipe = urb->pipe;
dev_dbg(musb->controller, "<== hw %d rxcsr %04x, urb actual %d (+dma %zu)\n",
epnum, rx_csr, urb->actual_length,
dma ? dma->actual_len : 0);
/* check for errors, concurrent stall & unlink is not really
* handled yet! */
if (rx_csr & MUSB_RXCSR_H_RXSTALL) {
dev_dbg(musb->controller, "RX end %d STALL\n", epnum);
/* stall; record URB status */
status = -EPIPE;
} else if (rx_csr & MUSB_RXCSR_H_ERROR) {
dev_dbg(musb->controller, "end %d RX proto error\n", epnum);
status = -EPROTO;
musb_writeb(epio, MUSB_RXINTERVAL, 0);
} else if (rx_csr & MUSB_RXCSR_DATAERROR) {
if (USB_ENDPOINT_XFER_ISOC != qh->type) {
dev_dbg(musb->controller, "RX end %d NAK timeout\n", epnum);
/* NOTE: NAKing is *NOT* an error, so we want to
* continue. Except ... if there's a request for
* another QH, use that instead of starving it.
*
* Devices like Ethernet and serial adapters keep
* reads posted at all times, which will starve
* other devices without this logic.
*/
if (usb_pipebulk(urb->pipe)
&& qh->mux == 1
&& !list_is_singular(&musb->in_bulk)) {
musb_bulk_rx_nak_timeout(musb, hw_ep);
return;
}
musb_ep_select(mbase, epnum);
rx_csr |= MUSB_RXCSR_H_WZC_BITS;
rx_csr &= ~MUSB_RXCSR_DATAERROR;
musb_writew(epio, MUSB_RXCSR, rx_csr);
goto finish;
} else {
dev_dbg(musb->controller, "RX end %d ISO data error\n", epnum);
/* packet error reported later */
iso_err = true;
}
} else if (rx_csr & MUSB_RXCSR_INCOMPRX) {
dev_dbg(musb->controller, "end %d high bandwidth incomplete ISO packet RX\n",
epnum);
status = -EPROTO;
}
/* faults abort the transfer */
if (status) {
/* clean up dma and collect transfer count */
if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
dma->status = MUSB_DMA_STATUS_CORE_ABORT;
(void) musb->dma_controller->channel_abort(dma);
xfer_len = dma->actual_len;
}
musb_h_flush_rxfifo(hw_ep, MUSB_RXCSR_CLRDATATOG);
musb_writeb(epio, MUSB_RXINTERVAL, 0);
done = true;
goto finish;
}
if (unlikely(dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY)) {
/* SHOULD NEVER HAPPEN ... but at least DaVinci has done it */
ERR("RX%d dma busy, csr %04x\n", epnum, rx_csr);
goto finish;
}
/* thorough shutdown for now ... given more precise fault handling
* and better queueing support, we might keep a DMA pipeline going
* while processing this irq for earlier completions.
*/
/* FIXME this is _way_ too much in-line logic for Mentor DMA */
#ifndef CONFIG_USB_INVENTRA_DMA
if (rx_csr & MUSB_RXCSR_H_REQPKT) {
/* REVISIT this happened for a while on some short reads...
* the cleanup still needs investigation... looks bad...
* and also duplicates dma cleanup code above ... plus,
* shouldn't this be the "half full" double buffer case?
*/
if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) {
dma->status = MUSB_DMA_STATUS_CORE_ABORT;
(void) musb->dma_controller->channel_abort(dma);
xfer_len = dma->actual_len;
done = true;
}
dev_dbg(musb->controller, "RXCSR%d %04x, reqpkt, len %zu%s\n", epnum, rx_csr,
xfer_len, dma ? ", dma" : "");
rx_csr &= ~MUSB_RXCSR_H_REQPKT;
musb_ep_select(mbase, epnum);
musb_writew(epio, MUSB_RXCSR,
MUSB_RXCSR_H_WZC_BITS | rx_csr);
}
#endif
if (dma && (rx_csr & MUSB_RXCSR_DMAENAB)) {
xfer_len = dma->actual_len;
val &= ~(MUSB_RXCSR_DMAENAB
| MUSB_RXCSR_H_AUTOREQ
| MUSB_RXCSR_AUTOCLEAR
| MUSB_RXCSR_RXPKTRDY);
musb_writew(hw_ep->regs, MUSB_RXCSR, val);
#ifdef CONFIG_USB_INVENTRA_DMA
if (usb_pipeisoc(pipe)) {
struct usb_iso_packet_descriptor *d;
d = urb->iso_frame_desc + qh->iso_idx;
d->actual_length = xfer_len;
/* even if there was an error, we did the dma
* for iso_frame_desc->length
*/
if (d->status != -EILSEQ && d->status != -EOVERFLOW)
d->status = 0;
if (++qh->iso_idx >= urb->number_of_packets)
done = true;
else
done = false;
} else {
/* done if urb buffer is full or short packet is recd */
done = (urb->actual_length + xfer_len >=
urb->transfer_buffer_length
|| dma->actual_len < qh->maxpacket);
}
/* send IN token for next packet, without AUTOREQ */
if (!done) {
val |= MUSB_RXCSR_H_REQPKT;
musb_writew(epio, MUSB_RXCSR,
MUSB_RXCSR_H_WZC_BITS | val);
}
dev_dbg(musb->controller, "ep %d dma %s, rxcsr %04x, rxcount %d\n", epnum,
done ? "off" : "reset",
musb_readw(epio, MUSB_RXCSR),
musb_readw(epio, MUSB_RXCOUNT));
#else
done = true;
#endif
} else if (urb->status == -EINPROGRESS) {
/* if no errors, be sure a packet is ready for unloading */
if (unlikely(!(rx_csr & MUSB_RXCSR_RXPKTRDY))) {
status = -EPROTO;
ERR("Rx interrupt with no errors or packet!\n");
/* FIXME this is another "SHOULD NEVER HAPPEN" */
/* SCRUB (RX) */
/* do the proper sequence to abort the transfer */
musb_ep_select(mbase, epnum);
val &= ~MUSB_RXCSR_H_REQPKT;
musb_writew(epio, MUSB_RXCSR, val);
goto finish;
}
/* we are expecting IN packets */
#ifdef CONFIG_USB_INVENTRA_DMA
if (dma) {
struct dma_controller *c;
u16 rx_count;
int ret, length;
dma_addr_t buf;
rx_count = musb_readw(epio, MUSB_RXCOUNT);
dev_dbg(musb->controller, "RX%d count %d, buffer 0x%x len %d/%d\n",
epnum, rx_count,
urb->transfer_dma
+ urb->actual_length,
qh->offset,
urb->transfer_buffer_length);
c = musb->dma_controller;
if (usb_pipeisoc(pipe)) {
int d_status = 0;
struct usb_iso_packet_descriptor *d;
d = urb->iso_frame_desc + qh->iso_idx;
if (iso_err) {
d_status = -EILSEQ;
urb->error_count++;
}
if (rx_count > d->length) {
if (d_status == 0) {
d_status = -EOVERFLOW;
urb->error_count++;
}
dev_dbg(musb->controller, "** OVERFLOW %d into %d\n",\
rx_count, d->length);
length = d->length;
} else
length = rx_count;
d->status = d_status;
buf = urb->transfer_dma + d->offset;
} else {
length = rx_count;
buf = urb->transfer_dma +
urb->actual_length;
}
dma->desired_mode = 0;
#ifdef USE_MODE1
/* because of the issue below, mode 1 will
* only rarely behave with correct semantics.
*/
if ((urb->transfer_flags &
URB_SHORT_NOT_OK)
&& (urb->transfer_buffer_length -
urb->actual_length)
> qh->maxpacket)
dma->desired_mode = 1;
if (rx_count < hw_ep->max_packet_sz_rx) {
length = rx_count;
dma->desired_mode = 0;
} else {
length = urb->transfer_buffer_length;
}
#endif
/* Disadvantage of using mode 1:
* It's basically usable only for mass storage class; essentially all
* other protocols also terminate transfers on short packets.
*
* Details:
* An extra IN token is sent at the end of the transfer (due to AUTOREQ)
* If you try to use mode 1 for (transfer_buffer_length - 512), and try
* to use the extra IN token to grab the last packet using mode 0, then
* the problem is that you cannot be sure when the device will send the
* last packet and RxPktRdy set. Sometimes the packet is recd too soon
* such that it gets lost when RxCSR is re-set at the end of the mode 1
* transfer, while sometimes it is recd just a little late so that if you
* try to configure for mode 0 soon after the mode 1 transfer is
* completed, you will find rxcount 0. Okay, so you might think why not
* wait for an interrupt when the pkt is recd. Well, you won't get any!
*/
val = musb_readw(epio, MUSB_RXCSR);
val &= ~MUSB_RXCSR_H_REQPKT;
if (dma->desired_mode == 0)
val &= ~MUSB_RXCSR_H_AUTOREQ;
else
val |= MUSB_RXCSR_H_AUTOREQ;
val |= MUSB_RXCSR_DMAENAB;
/* autoclear shouldn't be set in high bandwidth */
if (qh->hb_mult == 1)
val |= MUSB_RXCSR_AUTOCLEAR;
musb_writew(epio, MUSB_RXCSR,
MUSB_RXCSR_H_WZC_BITS | val);
/* REVISIT if when actual_length != 0,
* transfer_buffer_length needs to be
* adjusted first...
*/
ret = c->channel_program(
dma, qh->maxpacket,
dma->desired_mode, buf, length);
if (!ret) {
c->channel_release(dma);
hw_ep->rx_channel = NULL;
dma = NULL;
/* REVISIT reset CSR */
}
}
#endif /* Mentor DMA */
if (!dma) {
/* Unmap the buffer so that CPU can use it */
usb_hcd_unmap_urb_for_dma(musb_to_hcd(musb), urb);
done = musb_host_packet_rx(musb, urb,
epnum, iso_err);
dev_dbg(musb->controller, "read %spacket\n", done ? "last " : "");
}
}
finish:
urb->actual_length += xfer_len;
qh->offset += xfer_len;
if (done) {
if (urb->status == -EINPROGRESS)
urb->status = status;
musb_advance_schedule(musb, urb, hw_ep, USB_DIR_IN);
}
}
/* schedule nodes correspond to peripheral endpoints, like an OHCI QH.
* the software schedule associates multiple such nodes with a given
* host side hardware endpoint + direction; scheduling may activate
* that hardware endpoint.
*/
static int musb_schedule(
struct musb *musb,
struct musb_qh *qh,
int is_in)
{
int idle;
int best_diff;
int best_end, epnum;
struct musb_hw_ep *hw_ep = NULL;
struct list_head *head = NULL;
u8 toggle;
u8 txtype;
struct urb *urb = next_urb(qh);
/* use fixed hardware for control and bulk */
if (qh->type == USB_ENDPOINT_XFER_CONTROL) {
head = &musb->control;
hw_ep = musb->control_ep;
goto success;
}
/* else, periodic transfers get muxed to other endpoints */
/*
* We know this qh hasn't been scheduled, so all we need to do
* is choose which hardware endpoint to put it on ...
*
* REVISIT what we really want here is a regular schedule tree
* like e.g. OHCI uses.
*/
best_diff = 4096;
best_end = -1;
for (epnum = 1, hw_ep = musb->endpoints + 1;
epnum < musb->nr_endpoints;
epnum++, hw_ep++) {
int diff;
if (musb_ep_get_qh(hw_ep, is_in) != NULL)
continue;
if (hw_ep == musb->bulk_ep)
continue;
if (is_in)
diff = hw_ep->max_packet_sz_rx;
else
diff = hw_ep->max_packet_sz_tx;
diff -= (qh->maxpacket * qh->hb_mult);
if (diff >= 0 && best_diff > diff) {
/*
* Mentor controller has a bug in that if we schedule
* a BULK Tx transfer on an endpoint that had earlier
* handled ISOC then the BULK transfer has to start on
* a zero toggle. If the BULK transfer starts on a 1
* toggle then this transfer will fail as the mentor
* controller starts the Bulk transfer on a 0 toggle
* irrespective of the programming of the toggle bits
* in the TXCSR register. Check for this condition
* while allocating the EP for a Tx Bulk transfer. If
* so skip this EP.
*/
hw_ep = musb->endpoints + epnum;
toggle = usb_gettoggle(urb->dev, qh->epnum, !is_in);
txtype = (musb_readb(hw_ep->regs, MUSB_TXTYPE)
>> 4) & 0x3;
if (!is_in && (qh->type == USB_ENDPOINT_XFER_BULK) &&
toggle && (txtype == USB_ENDPOINT_XFER_ISOC))
continue;
best_diff = diff;
best_end = epnum;
}
}
/* use bulk reserved ep1 if no other ep is free */
if (best_end < 0 && qh->type == USB_ENDPOINT_XFER_BULK) {
hw_ep = musb->bulk_ep;
if (is_in)
head = &musb->in_bulk;
else
head = &musb->out_bulk;
/* Enable bulk RX NAK timeout scheme when bulk requests are
* multiplexed. This scheme doen't work in high speed to full
* speed scenario as NAK interrupts are not coming from a
* full speed device connected to a high speed device.
* NAK timeout interval is 8 (128 uframe or 16ms) for HS and
* 4 (8 frame or 8ms) for FS device.
*/
if (is_in && qh->dev)
qh->intv_reg =
(USB_SPEED_HIGH == qh->dev->speed) ? 8 : 4;
goto success;
} else if (best_end < 0) {
return -ENOSPC;
}
idle = 1;
qh->mux = 0;
hw_ep = musb->endpoints + best_end;
dev_dbg(musb->controller, "qh %p periodic slot %d\n", qh, best_end);
success:
if (head) {
idle = list_empty(head);
list_add_tail(&qh->ring, head);
qh->mux = 1;
}
qh->hw_ep = hw_ep;
qh->hep->hcpriv = qh;
if (idle)
musb_start_urb(musb, is_in, qh);
return 0;
}
static int musb_urb_enqueue(
struct usb_hcd *hcd,
struct urb *urb,
gfp_t mem_flags)
{
unsigned long flags;
struct musb *musb = hcd_to_musb(hcd);
struct usb_host_endpoint *hep = urb->ep;
struct musb_qh *qh;
struct usb_endpoint_descriptor *epd = &hep->desc;
int ret;
unsigned type_reg;
unsigned interval;
/* host role must be active */
if (!is_host_active(musb) || !musb->is_active)
return -ENODEV;
spin_lock_irqsave(&musb->lock, flags);
ret = usb_hcd_link_urb_to_ep(hcd, urb);
qh = ret ? NULL : hep->hcpriv;
if (qh)
urb->hcpriv = qh;
spin_unlock_irqrestore(&musb->lock, flags);
/* DMA mapping was already done, if needed, and this urb is on
* hep->urb_list now ... so we're done, unless hep wasn't yet
* scheduled onto a live qh.
*
* REVISIT best to keep hep->hcpriv valid until the endpoint gets
* disabled, testing for empty qh->ring and avoiding qh setup costs
* except for the first urb queued after a config change.
*/
if (qh || ret)
return ret;
/* Allocate and initialize qh, minimizing the work done each time
* hw_ep gets reprogrammed, or with irqs blocked. Then schedule it.
*
* REVISIT consider a dedicated qh kmem_cache, so it's harder
* for bugs in other kernel code to break this driver...
*/
qh = kzalloc(sizeof *qh, mem_flags);
if (!qh) {
spin_lock_irqsave(&musb->lock, flags);
usb_hcd_unlink_urb_from_ep(hcd, urb);
spin_unlock_irqrestore(&musb->lock, flags);
return -ENOMEM;
}
qh->hep = hep;
qh->dev = urb->dev;
INIT_LIST_HEAD(&qh->ring);
qh->is_ready = 1;
qh->maxpacket = usb_endpoint_maxp(epd);
qh->type = usb_endpoint_type(epd);
/* Bits 11 & 12 of wMaxPacketSize encode high bandwidth multiplier.
* Some musb cores don't support high bandwidth ISO transfers; and
* we don't (yet!) support high bandwidth interrupt transfers.
*/
qh->hb_mult = 1 + ((qh->maxpacket >> 11) & 0x03);
if (qh->hb_mult > 1) {
int ok = (qh->type == USB_ENDPOINT_XFER_ISOC);
if (ok)
ok = (usb_pipein(urb->pipe) && musb->hb_iso_rx)
|| (usb_pipeout(urb->pipe) && musb->hb_iso_tx);
if (!ok) {
ret = -EMSGSIZE;
goto done;
}
qh->maxpacket &= 0x7ff;
}
qh->epnum = usb_endpoint_num(epd);
/* NOTE: urb->dev->devnum is wrong during SET_ADDRESS */
qh->addr_reg = (u8) usb_pipedevice(urb->pipe);
/* precompute rxtype/txtype/type0 register */
type_reg = (qh->type << 4) | qh->epnum;
switch (urb->dev->speed) {
case USB_SPEED_LOW:
type_reg |= 0xc0;
break;
case USB_SPEED_FULL:
type_reg |= 0x80;
break;
default:
type_reg |= 0x40;
}
qh->type_reg = type_reg;
/* Precompute RXINTERVAL/TXINTERVAL register */
switch (qh->type) {
case USB_ENDPOINT_XFER_INT:
/*
* Full/low speeds use the linear encoding,
* high speed uses the logarithmic encoding.
*/
if (urb->dev->speed <= USB_SPEED_FULL) {
interval = max_t(u8, epd->bInterval, 1);
break;
}
/* FALLTHROUGH */
case USB_ENDPOINT_XFER_ISOC:
/* ISO always uses logarithmic encoding */
interval = min_t(u8, epd->bInterval, 16);
break;
default:
/* REVISIT we actually want to use NAK limits, hinting to the
* transfer scheduling logic to try some other qh, e.g. try
* for 2 msec first:
*
* interval = (USB_SPEED_HIGH == urb->dev->speed) ? 16 : 2;
*
* The downside of disabling this is that transfer scheduling
* gets VERY unfair for nonperiodic transfers; a misbehaving
* peripheral could make that hurt. That's perfectly normal
* for reads from network or serial adapters ... so we have
* partial NAKlimit support for bulk RX.
*
* The upside of disabling it is simpler transfer scheduling.
*/
interval = 0;
}
qh->intv_reg = interval;
/* precompute addressing for external hub/tt ports */
if (musb->is_multipoint) {
struct usb_device *parent = urb->dev->parent;
if (parent != hcd->self.root_hub) {
qh->h_addr_reg = (u8) parent->devnum;
/* set up tt info if needed */
if (urb->dev->tt) {
qh->h_port_reg = (u8) urb->dev->ttport;
if (urb->dev->tt->hub)
qh->h_addr_reg =
(u8) urb->dev->tt->hub->devnum;
if (urb->dev->tt->multi)
qh->h_addr_reg |= 0x80;
}
}
}
/* invariant: hep->hcpriv is null OR the qh that's already scheduled.
* until we get real dma queues (with an entry for each urb/buffer),
* we only have work to do in the former case.
*/
spin_lock_irqsave(&musb->lock, flags);
if (hep->hcpriv) {
/* some concurrent activity submitted another urb to hep...
* odd, rare, error prone, but legal.
*/
kfree(qh);
qh = NULL;
ret = 0;
} else
ret = musb_schedule(musb, qh,
epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK);
if (ret == 0) {
urb->hcpriv = qh;
/* FIXME set urb->start_frame for iso/intr, it's tested in
* musb_start_urb(), but otherwise only konicawc cares ...
*/
}
spin_unlock_irqrestore(&musb->lock, flags);
done:
if (ret != 0) {
spin_lock_irqsave(&musb->lock, flags);
usb_hcd_unlink_urb_from_ep(hcd, urb);
spin_unlock_irqrestore(&musb->lock, flags);
kfree(qh);
}
return ret;
}
/*
* abort a transfer that's at the head of a hardware queue.
* called with controller locked, irqs blocked
* that hardware queue advances to the next transfer, unless prevented
*/
static int musb_cleanup_urb(struct urb *urb, struct musb_qh *qh)
{
struct musb_hw_ep *ep = qh->hw_ep;
struct musb *musb = ep->musb;
void __iomem *epio = ep->regs;
unsigned hw_end = ep->epnum;
void __iomem *regs = ep->musb->mregs;
int is_in = usb_pipein(urb->pipe);
int status = 0;
u16 csr;
musb_ep_select(regs, hw_end);
if (is_dma_capable()) {
struct dma_channel *dma;
dma = is_in ? ep->rx_channel : ep->tx_channel;
if (dma) {
status = ep->musb->dma_controller->channel_abort(dma);
dev_dbg(musb->controller,
"abort %cX%d DMA for urb %p --> %d\n",
is_in ? 'R' : 'T', ep->epnum,
urb, status);
urb->actual_length += dma->actual_len;
}
}
/* turn off DMA requests, discard state, stop polling ... */
if (ep->epnum && is_in) {
/* giveback saves bulk toggle */
csr = musb_h_flush_rxfifo(ep, 0);
/* REVISIT we still get an irq; should likely clear the
* endpoint's irq status here to avoid bogus irqs.
* clearing that status is platform-specific...
*/
} else if (ep->epnum) {
musb_h_tx_flush_fifo(ep);
csr = musb_readw(epio, MUSB_TXCSR);
csr &= ~(MUSB_TXCSR_AUTOSET
| MUSB_TXCSR_DMAENAB
| MUSB_TXCSR_H_RXSTALL
| MUSB_TXCSR_H_NAKTIMEOUT
| MUSB_TXCSR_H_ERROR
| MUSB_TXCSR_TXPKTRDY);
musb_writew(epio, MUSB_TXCSR, csr);
/* REVISIT may need to clear FLUSHFIFO ... */
musb_writew(epio, MUSB_TXCSR, csr);
/* flush cpu writebuffer */
csr = musb_readw(epio, MUSB_TXCSR);
} else {
musb_h_ep0_flush_fifo(ep);
}
if (status == 0)
musb_advance_schedule(ep->musb, urb, ep, is_in);
return status;
}
static int musb_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
{
struct musb *musb = hcd_to_musb(hcd);
struct musb_qh *qh;
unsigned long flags;
int is_in = usb_pipein(urb->pipe);
int ret;
dev_dbg(musb->controller, "urb=%p, dev%d ep%d%s\n", urb,
usb_pipedevice(urb->pipe),
usb_pipeendpoint(urb->pipe),
is_in ? "in" : "out");
spin_lock_irqsave(&musb->lock, flags);
ret = usb_hcd_check_unlink_urb(hcd, urb, status);
if (ret)
goto done;
qh = urb->hcpriv;
if (!qh)
goto done;
/*
* Any URB not actively programmed into endpoint hardware can be
* immediately given back; that's any URB not at the head of an
* endpoint queue, unless someday we get real DMA queues. And even
* if it's at the head, it might not be known to the hardware...
*
* Otherwise abort current transfer, pending DMA, etc.; urb->status
* has already been updated. This is a synchronous abort; it'd be
* OK to hold off until after some IRQ, though.
*
* NOTE: qh is invalid unless !list_empty(&hep->urb_list)
*/
if (!qh->is_ready
|| urb->urb_list.prev != &qh->hep->urb_list
|| musb_ep_get_qh(qh->hw_ep, is_in) != qh) {
int ready = qh->is_ready;
qh->is_ready = 0;
musb_giveback(musb, urb, 0);
qh->is_ready = ready;
/* If nothing else (usually musb_giveback) is using it
* and its URB list has emptied, recycle this qh.
*/
if (ready && list_empty(&qh->hep->urb_list)) {
qh->hep->hcpriv = NULL;
list_del(&qh->ring);
kfree(qh);
}
} else
ret = musb_cleanup_urb(urb, qh);
done:
spin_unlock_irqrestore(&musb->lock, flags);
return ret;
}
/* disable an endpoint */
static void
musb_h_disable(struct usb_hcd *hcd, struct usb_host_endpoint *hep)
{
u8 is_in = hep->desc.bEndpointAddress & USB_DIR_IN;
unsigned long flags;
struct musb *musb = hcd_to_musb(hcd);
struct musb_qh *qh;
struct urb *urb;
spin_lock_irqsave(&musb->lock, flags);
qh = hep->hcpriv;
if (qh == NULL)
goto exit;
/* NOTE: qh is invalid unless !list_empty(&hep->urb_list) */
/* Kick the first URB off the hardware, if needed */
qh->is_ready = 0;
if (musb_ep_get_qh(qh->hw_ep, is_in) == qh) {
urb = next_urb(qh);
/* make software (then hardware) stop ASAP */
if (!urb->unlinked)
urb->status = -ESHUTDOWN;
/* cleanup */
musb_cleanup_urb(urb, qh);
/* Then nuke all the others ... and advance the
* queue on hw_ep (e.g. bulk ring) when we're done.
*/
while (!list_empty(&hep->urb_list)) {
urb = next_urb(qh);
urb->status = -ESHUTDOWN;
musb_advance_schedule(musb, urb, qh->hw_ep, is_in);
}
} else {
/* Just empty the queue; the hardware is busy with
* other transfers, and since !qh->is_ready nothing
* will activate any of these as it advances.
*/
while (!list_empty(&hep->urb_list))
musb_giveback(musb, next_urb(qh), -ESHUTDOWN);
hep->hcpriv = NULL;
list_del(&qh->ring);
kfree(qh);
}
exit:
spin_unlock_irqrestore(&musb->lock, flags);
}
static int musb_h_get_frame_number(struct usb_hcd *hcd)
{
struct musb *musb = hcd_to_musb(hcd);
return musb_readw(musb->mregs, MUSB_FRAME);
}
static int musb_h_start(struct usb_hcd *hcd)
{
struct musb *musb = hcd_to_musb(hcd);
/* NOTE: musb_start() is called when the hub driver turns
* on port power, or when (OTG) peripheral starts.
*/
hcd->state = HC_STATE_RUNNING;
musb->port1_status = 0;
return 0;
}
static void musb_h_stop(struct usb_hcd *hcd)
{
musb_stop(hcd_to_musb(hcd));
hcd->state = HC_STATE_HALT;
}
static int musb_bus_suspend(struct usb_hcd *hcd)
{
struct musb *musb = hcd_to_musb(hcd);
u8 devctl;
if (!is_host_active(musb))
return 0;
switch (musb->xceiv->state) {
case OTG_STATE_A_SUSPEND:
return 0;
case OTG_STATE_A_WAIT_VRISE:
/* ID could be grounded even if there's no device
* on the other end of the cable. NOTE that the
* A_WAIT_VRISE timers are messy with MUSB...
*/
devctl = musb_readb(musb->mregs, MUSB_DEVCTL);
if ((devctl & MUSB_DEVCTL_VBUS) == MUSB_DEVCTL_VBUS)
musb->xceiv->state = OTG_STATE_A_WAIT_BCON;
break;
default:
break;
}
if (musb->is_active) {
WARNING("trying to suspend as %s while active\n",
otg_state_string(musb->xceiv->state));
return -EBUSY;
} else
return 0;
}
static int musb_bus_resume(struct usb_hcd *hcd)
{
/* resuming child port does the work */
return 0;
}
const struct hc_driver musb_hc_driver = {
.description = "musb-hcd",
.product_desc = "MUSB HDRC host driver",
.hcd_priv_size = sizeof(struct musb),
.flags = HCD_USB2 | HCD_MEMORY,
/* not using irq handler or reset hooks from usbcore, since
* those must be shared with peripheral code for OTG configs
*/
.start = musb_h_start,
.stop = musb_h_stop,
.get_frame_number = musb_h_get_frame_number,
.urb_enqueue = musb_urb_enqueue,
.urb_dequeue = musb_urb_dequeue,
.endpoint_disable = musb_h_disable,
.hub_status_data = musb_hub_status_data,
.hub_control = musb_hub_control,
.bus_suspend = musb_bus_suspend,
.bus_resume = musb_bus_resume,
/* .start_port_reset = NULL, */
/* .hub_irq_enable = NULL, */
};
| gpl-2.0 |
AndropaX/Resurrected-Kernel | drivers/isdn/mISDN/layer1.c | 4762 | 9951 | /*
*
* Author Karsten Keil <kkeil@novell.com>
*
* Copyright 2008 by Karsten Keil <kkeil@novell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/mISDNhw.h>
#include "core.h"
#include "layer1.h"
#include "fsm.h"
static u_int *debug;
struct layer1 {
u_long Flags;
struct FsmInst l1m;
struct FsmTimer timer3;
struct FsmTimer timerX;
int delay;
int t3_value;
struct dchannel *dch;
dchannel_l1callback *dcb;
};
#define TIMER3_DEFAULT_VALUE 7000
static
struct Fsm l1fsm_s = {NULL, 0, 0, NULL, NULL};
enum {
ST_L1_F2,
ST_L1_F3,
ST_L1_F4,
ST_L1_F5,
ST_L1_F6,
ST_L1_F7,
ST_L1_F8,
};
#define L1S_STATE_COUNT (ST_L1_F8 + 1)
static char *strL1SState[] =
{
"ST_L1_F2",
"ST_L1_F3",
"ST_L1_F4",
"ST_L1_F5",
"ST_L1_F6",
"ST_L1_F7",
"ST_L1_F8",
};
enum {
EV_PH_ACTIVATE,
EV_PH_DEACTIVATE,
EV_RESET_IND,
EV_DEACT_CNF,
EV_DEACT_IND,
EV_POWER_UP,
EV_ANYSIG_IND,
EV_INFO2_IND,
EV_INFO4_IND,
EV_TIMER_DEACT,
EV_TIMER_ACT,
EV_TIMER3,
};
#define L1_EVENT_COUNT (EV_TIMER3 + 1)
static char *strL1Event[] =
{
"EV_PH_ACTIVATE",
"EV_PH_DEACTIVATE",
"EV_RESET_IND",
"EV_DEACT_CNF",
"EV_DEACT_IND",
"EV_POWER_UP",
"EV_ANYSIG_IND",
"EV_INFO2_IND",
"EV_INFO4_IND",
"EV_TIMER_DEACT",
"EV_TIMER_ACT",
"EV_TIMER3",
};
static void
l1m_debug(struct FsmInst *fi, char *fmt, ...)
{
struct layer1 *l1 = fi->userdata;
struct va_format vaf;
va_list va;
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
printk(KERN_DEBUG "%s: %pV\n", dev_name(&l1->dch->dev.dev), &vaf);
va_end(va);
}
static void
l1_reset(struct FsmInst *fi, int event, void *arg)
{
mISDN_FsmChangeState(fi, ST_L1_F3);
}
static void
l1_deact_cnf(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
mISDN_FsmChangeState(fi, ST_L1_F3);
if (test_bit(FLG_L1_ACTIVATING, &l1->Flags))
l1->dcb(l1->dch, HW_POWERUP_REQ);
}
static void
l1_deact_req_s(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
mISDN_FsmChangeState(fi, ST_L1_F3);
mISDN_FsmRestartTimer(&l1->timerX, 550, EV_TIMER_DEACT, NULL, 2);
test_and_set_bit(FLG_L1_DEACTTIMER, &l1->Flags);
}
static void
l1_power_up_s(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
if (test_bit(FLG_L1_ACTIVATING, &l1->Flags)) {
mISDN_FsmChangeState(fi, ST_L1_F4);
l1->dcb(l1->dch, INFO3_P8);
} else
mISDN_FsmChangeState(fi, ST_L1_F3);
}
static void
l1_go_F5(struct FsmInst *fi, int event, void *arg)
{
mISDN_FsmChangeState(fi, ST_L1_F5);
}
static void
l1_go_F8(struct FsmInst *fi, int event, void *arg)
{
mISDN_FsmChangeState(fi, ST_L1_F8);
}
static void
l1_info2_ind(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
mISDN_FsmChangeState(fi, ST_L1_F6);
l1->dcb(l1->dch, INFO3_P8);
}
static void
l1_info4_ind(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
mISDN_FsmChangeState(fi, ST_L1_F7);
l1->dcb(l1->dch, INFO3_P8);
if (test_and_clear_bit(FLG_L1_DEACTTIMER, &l1->Flags))
mISDN_FsmDelTimer(&l1->timerX, 4);
if (!test_bit(FLG_L1_ACTIVATED, &l1->Flags)) {
if (test_and_clear_bit(FLG_L1_T3RUN, &l1->Flags))
mISDN_FsmDelTimer(&l1->timer3, 3);
mISDN_FsmRestartTimer(&l1->timerX, 110, EV_TIMER_ACT, NULL, 2);
test_and_set_bit(FLG_L1_ACTTIMER, &l1->Flags);
}
}
static void
l1_timer3(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
test_and_clear_bit(FLG_L1_T3RUN, &l1->Flags);
if (test_and_clear_bit(FLG_L1_ACTIVATING, &l1->Flags)) {
if (test_and_clear_bit(FLG_L1_DBLOCKED, &l1->Flags))
l1->dcb(l1->dch, HW_D_NOBLOCKED);
l1->dcb(l1->dch, PH_DEACTIVATE_IND);
}
if (l1->l1m.state != ST_L1_F6) {
mISDN_FsmChangeState(fi, ST_L1_F3);
/* do not force anything here, we need send INFO 0 */
}
}
static void
l1_timer_act(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
test_and_clear_bit(FLG_L1_ACTTIMER, &l1->Flags);
test_and_set_bit(FLG_L1_ACTIVATED, &l1->Flags);
l1->dcb(l1->dch, PH_ACTIVATE_IND);
}
static void
l1_timer_deact(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
test_and_clear_bit(FLG_L1_DEACTTIMER, &l1->Flags);
test_and_clear_bit(FLG_L1_ACTIVATED, &l1->Flags);
if (test_and_clear_bit(FLG_L1_DBLOCKED, &l1->Flags))
l1->dcb(l1->dch, HW_D_NOBLOCKED);
l1->dcb(l1->dch, PH_DEACTIVATE_IND);
l1->dcb(l1->dch, HW_DEACT_REQ);
}
static void
l1_activate_s(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
mISDN_FsmRestartTimer(&l1->timer3, l1->t3_value, EV_TIMER3, NULL, 2);
test_and_set_bit(FLG_L1_T3RUN, &l1->Flags);
/* Tell HW to send INFO 1 */
l1->dcb(l1->dch, HW_RESET_REQ);
}
static void
l1_activate_no(struct FsmInst *fi, int event, void *arg)
{
struct layer1 *l1 = fi->userdata;
if ((!test_bit(FLG_L1_DEACTTIMER, &l1->Flags)) &&
(!test_bit(FLG_L1_T3RUN, &l1->Flags))) {
test_and_clear_bit(FLG_L1_ACTIVATING, &l1->Flags);
if (test_and_clear_bit(FLG_L1_DBLOCKED, &l1->Flags))
l1->dcb(l1->dch, HW_D_NOBLOCKED);
l1->dcb(l1->dch, PH_DEACTIVATE_IND);
}
}
static struct FsmNode L1SFnList[] =
{
{ST_L1_F3, EV_PH_ACTIVATE, l1_activate_s},
{ST_L1_F6, EV_PH_ACTIVATE, l1_activate_no},
{ST_L1_F8, EV_PH_ACTIVATE, l1_activate_no},
{ST_L1_F3, EV_RESET_IND, l1_reset},
{ST_L1_F4, EV_RESET_IND, l1_reset},
{ST_L1_F5, EV_RESET_IND, l1_reset},
{ST_L1_F6, EV_RESET_IND, l1_reset},
{ST_L1_F7, EV_RESET_IND, l1_reset},
{ST_L1_F8, EV_RESET_IND, l1_reset},
{ST_L1_F3, EV_DEACT_CNF, l1_deact_cnf},
{ST_L1_F4, EV_DEACT_CNF, l1_deact_cnf},
{ST_L1_F5, EV_DEACT_CNF, l1_deact_cnf},
{ST_L1_F6, EV_DEACT_CNF, l1_deact_cnf},
{ST_L1_F7, EV_DEACT_CNF, l1_deact_cnf},
{ST_L1_F8, EV_DEACT_CNF, l1_deact_cnf},
{ST_L1_F6, EV_DEACT_IND, l1_deact_req_s},
{ST_L1_F7, EV_DEACT_IND, l1_deact_req_s},
{ST_L1_F8, EV_DEACT_IND, l1_deact_req_s},
{ST_L1_F3, EV_POWER_UP, l1_power_up_s},
{ST_L1_F4, EV_ANYSIG_IND, l1_go_F5},
{ST_L1_F6, EV_ANYSIG_IND, l1_go_F8},
{ST_L1_F7, EV_ANYSIG_IND, l1_go_F8},
{ST_L1_F3, EV_INFO2_IND, l1_info2_ind},
{ST_L1_F4, EV_INFO2_IND, l1_info2_ind},
{ST_L1_F5, EV_INFO2_IND, l1_info2_ind},
{ST_L1_F7, EV_INFO2_IND, l1_info2_ind},
{ST_L1_F8, EV_INFO2_IND, l1_info2_ind},
{ST_L1_F3, EV_INFO4_IND, l1_info4_ind},
{ST_L1_F4, EV_INFO4_IND, l1_info4_ind},
{ST_L1_F5, EV_INFO4_IND, l1_info4_ind},
{ST_L1_F6, EV_INFO4_IND, l1_info4_ind},
{ST_L1_F8, EV_INFO4_IND, l1_info4_ind},
{ST_L1_F3, EV_TIMER3, l1_timer3},
{ST_L1_F4, EV_TIMER3, l1_timer3},
{ST_L1_F5, EV_TIMER3, l1_timer3},
{ST_L1_F6, EV_TIMER3, l1_timer3},
{ST_L1_F8, EV_TIMER3, l1_timer3},
{ST_L1_F7, EV_TIMER_ACT, l1_timer_act},
{ST_L1_F3, EV_TIMER_DEACT, l1_timer_deact},
{ST_L1_F4, EV_TIMER_DEACT, l1_timer_deact},
{ST_L1_F5, EV_TIMER_DEACT, l1_timer_deact},
{ST_L1_F6, EV_TIMER_DEACT, l1_timer_deact},
{ST_L1_F7, EV_TIMER_DEACT, l1_timer_deact},
{ST_L1_F8, EV_TIMER_DEACT, l1_timer_deact},
};
static void
release_l1(struct layer1 *l1) {
mISDN_FsmDelTimer(&l1->timerX, 0);
mISDN_FsmDelTimer(&l1->timer3, 0);
if (l1->dch)
l1->dch->l1 = NULL;
module_put(THIS_MODULE);
kfree(l1);
}
int
l1_event(struct layer1 *l1, u_int event)
{
int err = 0;
if (!l1)
return -EINVAL;
switch (event) {
case HW_RESET_IND:
mISDN_FsmEvent(&l1->l1m, EV_RESET_IND, NULL);
break;
case HW_DEACT_IND:
mISDN_FsmEvent(&l1->l1m, EV_DEACT_IND, NULL);
break;
case HW_POWERUP_IND:
mISDN_FsmEvent(&l1->l1m, EV_POWER_UP, NULL);
break;
case HW_DEACT_CNF:
mISDN_FsmEvent(&l1->l1m, EV_DEACT_CNF, NULL);
break;
case ANYSIGNAL:
mISDN_FsmEvent(&l1->l1m, EV_ANYSIG_IND, NULL);
break;
case LOSTFRAMING:
mISDN_FsmEvent(&l1->l1m, EV_ANYSIG_IND, NULL);
break;
case INFO2:
mISDN_FsmEvent(&l1->l1m, EV_INFO2_IND, NULL);
break;
case INFO4_P8:
mISDN_FsmEvent(&l1->l1m, EV_INFO4_IND, NULL);
break;
case INFO4_P10:
mISDN_FsmEvent(&l1->l1m, EV_INFO4_IND, NULL);
break;
case PH_ACTIVATE_REQ:
if (test_bit(FLG_L1_ACTIVATED, &l1->Flags))
l1->dcb(l1->dch, PH_ACTIVATE_IND);
else {
test_and_set_bit(FLG_L1_ACTIVATING, &l1->Flags);
mISDN_FsmEvent(&l1->l1m, EV_PH_ACTIVATE, NULL);
}
break;
case CLOSE_CHANNEL:
release_l1(l1);
break;
default:
if ((event & ~HW_TIMER3_VMASK) == HW_TIMER3_VALUE) {
int val = event & HW_TIMER3_VMASK;
if (val < 5)
val = 5;
if (val > 30)
val = 30;
l1->t3_value = val;
break;
}
if (*debug & DEBUG_L1)
printk(KERN_DEBUG "%s %x unhandled\n",
__func__, event);
err = -EINVAL;
}
return err;
}
EXPORT_SYMBOL(l1_event);
int
create_l1(struct dchannel *dch, dchannel_l1callback *dcb) {
struct layer1 *nl1;
nl1 = kzalloc(sizeof(struct layer1), GFP_ATOMIC);
if (!nl1) {
printk(KERN_ERR "kmalloc struct layer1 failed\n");
return -ENOMEM;
}
nl1->l1m.fsm = &l1fsm_s;
nl1->l1m.state = ST_L1_F3;
nl1->Flags = 0;
nl1->t3_value = TIMER3_DEFAULT_VALUE;
nl1->l1m.debug = *debug & DEBUG_L1_FSM;
nl1->l1m.userdata = nl1;
nl1->l1m.userint = 0;
nl1->l1m.printdebug = l1m_debug;
nl1->dch = dch;
nl1->dcb = dcb;
mISDN_FsmInitTimer(&nl1->l1m, &nl1->timer3);
mISDN_FsmInitTimer(&nl1->l1m, &nl1->timerX);
__module_get(THIS_MODULE);
dch->l1 = nl1;
return 0;
}
EXPORT_SYMBOL(create_l1);
int
l1_init(u_int *deb)
{
debug = deb;
l1fsm_s.state_count = L1S_STATE_COUNT;
l1fsm_s.event_count = L1_EVENT_COUNT;
l1fsm_s.strEvent = strL1Event;
l1fsm_s.strState = strL1SState;
mISDN_FsmNew(&l1fsm_s, L1SFnList, ARRAY_SIZE(L1SFnList));
return 0;
}
void
l1_cleanup(void)
{
mISDN_FsmFree(&l1fsm_s);
}
| gpl-2.0 |
boa19861105/BOA | fs/sysv/ialloc.c | 5018 | 5819 | /*
* linux/fs/sysv/ialloc.c
*
* minix/bitmap.c
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext/freelists.c
* Copyright (C) 1992 Remy Card (card@masi.ibp.fr)
*
* xenix/alloc.c
* Copyright (C) 1992 Doug Evans
*
* coh/alloc.c
* Copyright (C) 1993 Pascal Haible, Bruno Haible
*
* sysv/ialloc.c
* Copyright (C) 1993 Bruno Haible
*
* This file contains code for allocating/freeing inodes.
*/
#include <linux/kernel.h>
#include <linux/stddef.h>
#include <linux/sched.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/buffer_head.h>
#include <linux/writeback.h>
#include "sysv.h"
/* We don't trust the value of
sb->sv_sbd2->s_tinode = *sb->sv_sb_total_free_inodes
but we nevertheless keep it up to date. */
/* An inode on disk is considered free if both i_mode == 0 and i_nlink == 0. */
/* return &sb->sv_sb_fic_inodes[i] = &sbd->s_inode[i]; */
static inline sysv_ino_t *
sv_sb_fic_inode(struct super_block * sb, unsigned int i)
{
struct sysv_sb_info *sbi = SYSV_SB(sb);
if (sbi->s_bh1 == sbi->s_bh2)
return &sbi->s_sb_fic_inodes[i];
else {
/* 512 byte Xenix FS */
unsigned int offset = offsetof(struct xenix_super_block, s_inode[i]);
if (offset < 512)
return (sysv_ino_t*)(sbi->s_sbd1 + offset);
else
return (sysv_ino_t*)(sbi->s_sbd2 + offset);
}
}
struct sysv_inode *
sysv_raw_inode(struct super_block *sb, unsigned ino, struct buffer_head **bh)
{
struct sysv_sb_info *sbi = SYSV_SB(sb);
struct sysv_inode *res;
int block = sbi->s_firstinodezone + sbi->s_block_base;
block += (ino-1) >> sbi->s_inodes_per_block_bits;
*bh = sb_bread(sb, block);
if (!*bh)
return NULL;
res = (struct sysv_inode *)(*bh)->b_data;
return res + ((ino-1) & sbi->s_inodes_per_block_1);
}
static int refill_free_cache(struct super_block *sb)
{
struct sysv_sb_info *sbi = SYSV_SB(sb);
struct buffer_head * bh;
struct sysv_inode * raw_inode;
int i = 0, ino;
ino = SYSV_ROOT_INO+1;
raw_inode = sysv_raw_inode(sb, ino, &bh);
if (!raw_inode)
goto out;
while (ino <= sbi->s_ninodes) {
if (raw_inode->i_mode == 0 && raw_inode->i_nlink == 0) {
*sv_sb_fic_inode(sb,i++) = cpu_to_fs16(SYSV_SB(sb), ino);
if (i == sbi->s_fic_size)
break;
}
if ((ino++ & sbi->s_inodes_per_block_1) == 0) {
brelse(bh);
raw_inode = sysv_raw_inode(sb, ino, &bh);
if (!raw_inode)
goto out;
} else
raw_inode++;
}
brelse(bh);
out:
return i;
}
void sysv_free_inode(struct inode * inode)
{
struct super_block *sb = inode->i_sb;
struct sysv_sb_info *sbi = SYSV_SB(sb);
unsigned int ino;
struct buffer_head * bh;
struct sysv_inode * raw_inode;
unsigned count;
sb = inode->i_sb;
ino = inode->i_ino;
if (ino <= SYSV_ROOT_INO || ino > sbi->s_ninodes) {
printk("sysv_free_inode: inode 0,1,2 or nonexistent inode\n");
return;
}
raw_inode = sysv_raw_inode(sb, ino, &bh);
if (!raw_inode) {
printk("sysv_free_inode: unable to read inode block on device "
"%s\n", inode->i_sb->s_id);
return;
}
lock_super(sb);
count = fs16_to_cpu(sbi, *sbi->s_sb_fic_count);
if (count < sbi->s_fic_size) {
*sv_sb_fic_inode(sb,count++) = cpu_to_fs16(sbi, ino);
*sbi->s_sb_fic_count = cpu_to_fs16(sbi, count);
}
fs16_add(sbi, sbi->s_sb_total_free_inodes, 1);
dirty_sb(sb);
memset(raw_inode, 0, sizeof(struct sysv_inode));
mark_buffer_dirty(bh);
unlock_super(sb);
brelse(bh);
}
struct inode * sysv_new_inode(const struct inode * dir, umode_t mode)
{
struct super_block *sb = dir->i_sb;
struct sysv_sb_info *sbi = SYSV_SB(sb);
struct inode *inode;
sysv_ino_t ino;
unsigned count;
struct writeback_control wbc = {
.sync_mode = WB_SYNC_NONE
};
inode = new_inode(sb);
if (!inode)
return ERR_PTR(-ENOMEM);
lock_super(sb);
count = fs16_to_cpu(sbi, *sbi->s_sb_fic_count);
if (count == 0 || (*sv_sb_fic_inode(sb,count-1) == 0)) {
count = refill_free_cache(sb);
if (count == 0) {
iput(inode);
unlock_super(sb);
return ERR_PTR(-ENOSPC);
}
}
/* Now count > 0. */
ino = *sv_sb_fic_inode(sb,--count);
*sbi->s_sb_fic_count = cpu_to_fs16(sbi, count);
fs16_add(sbi, sbi->s_sb_total_free_inodes, -1);
dirty_sb(sb);
inode_init_owner(inode, dir, mode);
inode->i_ino = fs16_to_cpu(sbi, ino);
inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME_SEC;
inode->i_blocks = 0;
memset(SYSV_I(inode)->i_data, 0, sizeof(SYSV_I(inode)->i_data));
SYSV_I(inode)->i_dir_start_lookup = 0;
insert_inode_hash(inode);
mark_inode_dirty(inode);
sysv_write_inode(inode, &wbc); /* ensure inode not allocated again */
mark_inode_dirty(inode); /* cleared by sysv_write_inode() */
/* That's it. */
unlock_super(sb);
return inode;
}
unsigned long sysv_count_free_inodes(struct super_block * sb)
{
struct sysv_sb_info *sbi = SYSV_SB(sb);
struct buffer_head * bh;
struct sysv_inode * raw_inode;
int ino, count, sb_count;
lock_super(sb);
sb_count = fs16_to_cpu(sbi, *sbi->s_sb_total_free_inodes);
if (0)
goto trust_sb;
/* this causes a lot of disk traffic ... */
count = 0;
ino = SYSV_ROOT_INO+1;
raw_inode = sysv_raw_inode(sb, ino, &bh);
if (!raw_inode)
goto Eio;
while (ino <= sbi->s_ninodes) {
if (raw_inode->i_mode == 0 && raw_inode->i_nlink == 0)
count++;
if ((ino++ & sbi->s_inodes_per_block_1) == 0) {
brelse(bh);
raw_inode = sysv_raw_inode(sb, ino, &bh);
if (!raw_inode)
goto Eio;
} else
raw_inode++;
}
brelse(bh);
if (count != sb_count)
goto Einval;
out:
unlock_super(sb);
return count;
Einval:
printk("sysv_count_free_inodes: "
"free inode count was %d, correcting to %d\n",
sb_count, count);
if (!(sb->s_flags & MS_RDONLY)) {
*sbi->s_sb_total_free_inodes = cpu_to_fs16(SYSV_SB(sb), count);
dirty_sb(sb);
}
goto out;
Eio:
printk("sysv_count_free_inodes: unable to read inode table\n");
trust_sb:
count = sb_count;
goto out;
}
| gpl-2.0 |
StelixROM/android_kernel_google_msm | drivers/i2c/busses/i2c-iop3xx.c | 5018 | 12879 | /* ------------------------------------------------------------------------- */
/* i2c-iop3xx.c i2c driver algorithms for Intel XScale IOP3xx & IXP46x */
/* ------------------------------------------------------------------------- */
/* Copyright (C) 2003 Peter Milne, D-TACQ Solutions Ltd
* <Peter dot Milne at D hyphen TACQ dot com>
*
* With acknowledgements to i2c-algo-ibm_ocp.c by
* Ian DaSilva, MontaVista Software, Inc. idasilva@mvista.com
*
* And i2c-algo-pcf.c, which was created by Simon G. Vogl and Hans Berglund:
*
* Copyright (C) 1995-1997 Simon G. Vogl, 1998-2000 Hans Berglund
*
* And which acknowledged Kyösti Mälkki <kmalkki@cc.hut.fi>,
* Frodo Looijaard <frodol@dds.nl>, Martin Bailey<mbailey@littlefeet-inc.com>
*
* Major cleanup by Deepak Saxena <dsaxena@plexity.net>, 01/2005:
*
* - Use driver model to pass per-chip info instead of hardcoding and #ifdefs
* - Use ioremap/__raw_readl/__raw_writel instead of direct dereference
* - Make it work with IXP46x chips
* - Cleanup function names, coding style, etc
*
* - writing to slave address causes latchup on iop331.
* fix: driver refuses to address self.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2.
*/
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/io.h>
#include "i2c-iop3xx.h"
/* global unit counter */
static int i2c_id;
static inline unsigned char
iic_cook_addr(struct i2c_msg *msg)
{
unsigned char addr;
addr = (msg->addr << 1);
if (msg->flags & I2C_M_RD)
addr |= 1;
return addr;
}
static void
iop3xx_i2c_reset(struct i2c_algo_iop3xx_data *iop3xx_adap)
{
/* Follows devman 9.3 */
__raw_writel(IOP3XX_ICR_UNIT_RESET, iop3xx_adap->ioaddr + CR_OFFSET);
__raw_writel(IOP3XX_ISR_CLEARBITS, iop3xx_adap->ioaddr + SR_OFFSET);
__raw_writel(0, iop3xx_adap->ioaddr + CR_OFFSET);
}
static void
iop3xx_i2c_enable(struct i2c_algo_iop3xx_data *iop3xx_adap)
{
u32 cr = IOP3XX_ICR_GCD | IOP3XX_ICR_SCLEN | IOP3XX_ICR_UE;
/*
* Every time unit enable is asserted, GPOD needs to be cleared
* on IOP3XX to avoid data corruption on the bus.
*/
#if defined(CONFIG_ARCH_IOP32X) || defined(CONFIG_ARCH_IOP33X)
if (iop3xx_adap->id == 0) {
gpio_line_set(IOP3XX_GPIO_LINE(7), GPIO_LOW);
gpio_line_set(IOP3XX_GPIO_LINE(6), GPIO_LOW);
} else {
gpio_line_set(IOP3XX_GPIO_LINE(5), GPIO_LOW);
gpio_line_set(IOP3XX_GPIO_LINE(4), GPIO_LOW);
}
#endif
/* NB SR bits not same position as CR IE bits :-( */
iop3xx_adap->SR_enabled =
IOP3XX_ISR_ALD | IOP3XX_ISR_BERRD |
IOP3XX_ISR_RXFULL | IOP3XX_ISR_TXEMPTY;
cr |= IOP3XX_ICR_ALD_IE | IOP3XX_ICR_BERR_IE |
IOP3XX_ICR_RXFULL_IE | IOP3XX_ICR_TXEMPTY_IE;
__raw_writel(cr, iop3xx_adap->ioaddr + CR_OFFSET);
}
static void
iop3xx_i2c_transaction_cleanup(struct i2c_algo_iop3xx_data *iop3xx_adap)
{
unsigned long cr = __raw_readl(iop3xx_adap->ioaddr + CR_OFFSET);
cr &= ~(IOP3XX_ICR_MSTART | IOP3XX_ICR_TBYTE |
IOP3XX_ICR_MSTOP | IOP3XX_ICR_SCLEN);
__raw_writel(cr, iop3xx_adap->ioaddr + CR_OFFSET);
}
/*
* NB: the handler has to clear the source of the interrupt!
* Then it passes the SR flags of interest to BH via adap data
*/
static irqreturn_t
iop3xx_i2c_irq_handler(int this_irq, void *dev_id)
{
struct i2c_algo_iop3xx_data *iop3xx_adap = dev_id;
u32 sr = __raw_readl(iop3xx_adap->ioaddr + SR_OFFSET);
if ((sr &= iop3xx_adap->SR_enabled)) {
__raw_writel(sr, iop3xx_adap->ioaddr + SR_OFFSET);
iop3xx_adap->SR_received |= sr;
wake_up_interruptible(&iop3xx_adap->waitq);
}
return IRQ_HANDLED;
}
/* check all error conditions, clear them , report most important */
static int
iop3xx_i2c_error(u32 sr)
{
int rc = 0;
if ((sr & IOP3XX_ISR_BERRD)) {
if ( !rc ) rc = -I2C_ERR_BERR;
}
if ((sr & IOP3XX_ISR_ALD)) {
if ( !rc ) rc = -I2C_ERR_ALD;
}
return rc;
}
static inline u32
iop3xx_i2c_get_srstat(struct i2c_algo_iop3xx_data *iop3xx_adap)
{
unsigned long flags;
u32 sr;
spin_lock_irqsave(&iop3xx_adap->lock, flags);
sr = iop3xx_adap->SR_received;
iop3xx_adap->SR_received = 0;
spin_unlock_irqrestore(&iop3xx_adap->lock, flags);
return sr;
}
/*
* sleep until interrupted, then recover and analyse the SR
* saved by handler
*/
typedef int (* compare_func)(unsigned test, unsigned mask);
/* returns 1 on correct comparison */
static int
iop3xx_i2c_wait_event(struct i2c_algo_iop3xx_data *iop3xx_adap,
unsigned flags, unsigned* status,
compare_func compare)
{
unsigned sr = 0;
int interrupted;
int done;
int rc = 0;
do {
interrupted = wait_event_interruptible_timeout (
iop3xx_adap->waitq,
(done = compare( sr = iop3xx_i2c_get_srstat(iop3xx_adap) ,flags )),
1 * HZ;
);
if ((rc = iop3xx_i2c_error(sr)) < 0) {
*status = sr;
return rc;
} else if (!interrupted) {
*status = sr;
return -ETIMEDOUT;
}
} while(!done);
*status = sr;
return 0;
}
/*
* Concrete compare_funcs
*/
static int
all_bits_clear(unsigned test, unsigned mask)
{
return (test & mask) == 0;
}
static int
any_bits_set(unsigned test, unsigned mask)
{
return (test & mask) != 0;
}
static int
iop3xx_i2c_wait_tx_done(struct i2c_algo_iop3xx_data *iop3xx_adap, int *status)
{
return iop3xx_i2c_wait_event(
iop3xx_adap,
IOP3XX_ISR_TXEMPTY | IOP3XX_ISR_ALD | IOP3XX_ISR_BERRD,
status, any_bits_set);
}
static int
iop3xx_i2c_wait_rx_done(struct i2c_algo_iop3xx_data *iop3xx_adap, int *status)
{
return iop3xx_i2c_wait_event(
iop3xx_adap,
IOP3XX_ISR_RXFULL | IOP3XX_ISR_ALD | IOP3XX_ISR_BERRD,
status, any_bits_set);
}
static int
iop3xx_i2c_wait_idle(struct i2c_algo_iop3xx_data *iop3xx_adap, int *status)
{
return iop3xx_i2c_wait_event(
iop3xx_adap, IOP3XX_ISR_UNITBUSY, status, all_bits_clear);
}
static int
iop3xx_i2c_send_target_addr(struct i2c_algo_iop3xx_data *iop3xx_adap,
struct i2c_msg* msg)
{
unsigned long cr = __raw_readl(iop3xx_adap->ioaddr + CR_OFFSET);
int status;
int rc;
/* avoid writing to my slave address (hangs on 80331),
* forbidden in Intel developer manual
*/
if (msg->addr == MYSAR) {
return -EBUSY;
}
__raw_writel(iic_cook_addr(msg), iop3xx_adap->ioaddr + DBR_OFFSET);
cr &= ~(IOP3XX_ICR_MSTOP | IOP3XX_ICR_NACK);
cr |= IOP3XX_ICR_MSTART | IOP3XX_ICR_TBYTE;
__raw_writel(cr, iop3xx_adap->ioaddr + CR_OFFSET);
rc = iop3xx_i2c_wait_tx_done(iop3xx_adap, &status);
return rc;
}
static int
iop3xx_i2c_write_byte(struct i2c_algo_iop3xx_data *iop3xx_adap, char byte,
int stop)
{
unsigned long cr = __raw_readl(iop3xx_adap->ioaddr + CR_OFFSET);
int status;
int rc = 0;
__raw_writel(byte, iop3xx_adap->ioaddr + DBR_OFFSET);
cr &= ~IOP3XX_ICR_MSTART;
if (stop) {
cr |= IOP3XX_ICR_MSTOP;
} else {
cr &= ~IOP3XX_ICR_MSTOP;
}
cr |= IOP3XX_ICR_TBYTE;
__raw_writel(cr, iop3xx_adap->ioaddr + CR_OFFSET);
rc = iop3xx_i2c_wait_tx_done(iop3xx_adap, &status);
return rc;
}
static int
iop3xx_i2c_read_byte(struct i2c_algo_iop3xx_data *iop3xx_adap, char* byte,
int stop)
{
unsigned long cr = __raw_readl(iop3xx_adap->ioaddr + CR_OFFSET);
int status;
int rc = 0;
cr &= ~IOP3XX_ICR_MSTART;
if (stop) {
cr |= IOP3XX_ICR_MSTOP | IOP3XX_ICR_NACK;
} else {
cr &= ~(IOP3XX_ICR_MSTOP | IOP3XX_ICR_NACK);
}
cr |= IOP3XX_ICR_TBYTE;
__raw_writel(cr, iop3xx_adap->ioaddr + CR_OFFSET);
rc = iop3xx_i2c_wait_rx_done(iop3xx_adap, &status);
*byte = __raw_readl(iop3xx_adap->ioaddr + DBR_OFFSET);
return rc;
}
static int
iop3xx_i2c_writebytes(struct i2c_adapter *i2c_adap, const char *buf, int count)
{
struct i2c_algo_iop3xx_data *iop3xx_adap = i2c_adap->algo_data;
int ii;
int rc = 0;
for (ii = 0; rc == 0 && ii != count; ++ii)
rc = iop3xx_i2c_write_byte(iop3xx_adap, buf[ii], ii==count-1);
return rc;
}
static int
iop3xx_i2c_readbytes(struct i2c_adapter *i2c_adap, char *buf, int count)
{
struct i2c_algo_iop3xx_data *iop3xx_adap = i2c_adap->algo_data;
int ii;
int rc = 0;
for (ii = 0; rc == 0 && ii != count; ++ii)
rc = iop3xx_i2c_read_byte(iop3xx_adap, &buf[ii], ii==count-1);
return rc;
}
/*
* Description: This function implements combined transactions. Combined
* transactions consist of combinations of reading and writing blocks of data.
* FROM THE SAME ADDRESS
* Each transfer (i.e. a read or a write) is separated by a repeated start
* condition.
*/
static int
iop3xx_i2c_handle_msg(struct i2c_adapter *i2c_adap, struct i2c_msg* pmsg)
{
struct i2c_algo_iop3xx_data *iop3xx_adap = i2c_adap->algo_data;
int rc;
rc = iop3xx_i2c_send_target_addr(iop3xx_adap, pmsg);
if (rc < 0) {
return rc;
}
if ((pmsg->flags&I2C_M_RD)) {
return iop3xx_i2c_readbytes(i2c_adap, pmsg->buf, pmsg->len);
} else {
return iop3xx_i2c_writebytes(i2c_adap, pmsg->buf, pmsg->len);
}
}
/*
* master_xfer() - main read/write entry
*/
static int
iop3xx_i2c_master_xfer(struct i2c_adapter *i2c_adap, struct i2c_msg *msgs,
int num)
{
struct i2c_algo_iop3xx_data *iop3xx_adap = i2c_adap->algo_data;
int im = 0;
int ret = 0;
int status;
iop3xx_i2c_wait_idle(iop3xx_adap, &status);
iop3xx_i2c_reset(iop3xx_adap);
iop3xx_i2c_enable(iop3xx_adap);
for (im = 0; ret == 0 && im != num; im++) {
ret = iop3xx_i2c_handle_msg(i2c_adap, &msgs[im]);
}
iop3xx_i2c_transaction_cleanup(iop3xx_adap);
if(ret)
return ret;
return im;
}
static u32
iop3xx_i2c_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static const struct i2c_algorithm iop3xx_i2c_algo = {
.master_xfer = iop3xx_i2c_master_xfer,
.functionality = iop3xx_i2c_func,
};
static int
iop3xx_i2c_remove(struct platform_device *pdev)
{
struct i2c_adapter *padapter = platform_get_drvdata(pdev);
struct i2c_algo_iop3xx_data *adapter_data =
(struct i2c_algo_iop3xx_data *)padapter->algo_data;
struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
unsigned long cr = __raw_readl(adapter_data->ioaddr + CR_OFFSET);
/*
* Disable the actual HW unit
*/
cr &= ~(IOP3XX_ICR_ALD_IE | IOP3XX_ICR_BERR_IE |
IOP3XX_ICR_RXFULL_IE | IOP3XX_ICR_TXEMPTY_IE);
__raw_writel(cr, adapter_data->ioaddr + CR_OFFSET);
iounmap(adapter_data->ioaddr);
release_mem_region(res->start, IOP3XX_I2C_IO_SIZE);
kfree(adapter_data);
kfree(padapter);
platform_set_drvdata(pdev, NULL);
return 0;
}
static int
iop3xx_i2c_probe(struct platform_device *pdev)
{
struct resource *res;
int ret, irq;
struct i2c_adapter *new_adapter;
struct i2c_algo_iop3xx_data *adapter_data;
new_adapter = kzalloc(sizeof(struct i2c_adapter), GFP_KERNEL);
if (!new_adapter) {
ret = -ENOMEM;
goto out;
}
adapter_data = kzalloc(sizeof(struct i2c_algo_iop3xx_data), GFP_KERNEL);
if (!adapter_data) {
ret = -ENOMEM;
goto free_adapter;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
goto free_both;
}
if (!request_mem_region(res->start, IOP3XX_I2C_IO_SIZE, pdev->name)) {
ret = -EBUSY;
goto free_both;
}
/* set the adapter enumeration # */
adapter_data->id = i2c_id++;
adapter_data->ioaddr = ioremap(res->start, IOP3XX_I2C_IO_SIZE);
if (!adapter_data->ioaddr) {
ret = -ENOMEM;
goto release_region;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
ret = -ENXIO;
goto unmap;
}
ret = request_irq(irq, iop3xx_i2c_irq_handler, 0,
pdev->name, adapter_data);
if (ret) {
ret = -EIO;
goto unmap;
}
memcpy(new_adapter->name, pdev->name, strlen(pdev->name));
new_adapter->owner = THIS_MODULE;
new_adapter->class = I2C_CLASS_HWMON | I2C_CLASS_SPD;
new_adapter->dev.parent = &pdev->dev;
new_adapter->nr = pdev->id;
/*
* Default values...should these come in from board code?
*/
new_adapter->timeout = HZ;
new_adapter->algo = &iop3xx_i2c_algo;
init_waitqueue_head(&adapter_data->waitq);
spin_lock_init(&adapter_data->lock);
iop3xx_i2c_reset(adapter_data);
iop3xx_i2c_enable(adapter_data);
platform_set_drvdata(pdev, new_adapter);
new_adapter->algo_data = adapter_data;
i2c_add_numbered_adapter(new_adapter);
return 0;
unmap:
iounmap(adapter_data->ioaddr);
release_region:
release_mem_region(res->start, IOP3XX_I2C_IO_SIZE);
free_both:
kfree(adapter_data);
free_adapter:
kfree(new_adapter);
out:
return ret;
}
static struct platform_driver iop3xx_i2c_driver = {
.probe = iop3xx_i2c_probe,
.remove = iop3xx_i2c_remove,
.driver = {
.owner = THIS_MODULE,
.name = "IOP3xx-I2C",
},
};
module_platform_driver(iop3xx_i2c_driver);
MODULE_AUTHOR("D-TACQ Solutions Ltd <www.d-tacq.com>");
MODULE_DESCRIPTION("IOP3xx iic algorithm and driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:IOP3xx-I2C");
| gpl-2.0 |
faux123/mako | tools/perf/arch/powerpc/util/dwarf-regs.c | 5274 | 2413 | /*
* Mapping of DWARF debug register numbers into register names.
*
* Copyright (C) 2010 Ian Munsie, IBM Corporation.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <stdlib.h>
#ifndef __UCLIBC__
#include <libio.h>
#endif
#include <dwarf-regs.h>
struct pt_regs_dwarfnum {
const char *name;
unsigned int dwarfnum;
};
#define STR(s) #s
#define REG_DWARFNUM_NAME(r, num) {.name = r, .dwarfnum = num}
#define GPR_DWARFNUM_NAME(num) \
{.name = STR(%gpr##num), .dwarfnum = num}
#define REG_DWARFNUM_END {.name = NULL, .dwarfnum = 0}
/*
* Reference:
* http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi-1.9.html
*/
static const struct pt_regs_dwarfnum regdwarfnum_table[] = {
GPR_DWARFNUM_NAME(0),
GPR_DWARFNUM_NAME(1),
GPR_DWARFNUM_NAME(2),
GPR_DWARFNUM_NAME(3),
GPR_DWARFNUM_NAME(4),
GPR_DWARFNUM_NAME(5),
GPR_DWARFNUM_NAME(6),
GPR_DWARFNUM_NAME(7),
GPR_DWARFNUM_NAME(8),
GPR_DWARFNUM_NAME(9),
GPR_DWARFNUM_NAME(10),
GPR_DWARFNUM_NAME(11),
GPR_DWARFNUM_NAME(12),
GPR_DWARFNUM_NAME(13),
GPR_DWARFNUM_NAME(14),
GPR_DWARFNUM_NAME(15),
GPR_DWARFNUM_NAME(16),
GPR_DWARFNUM_NAME(17),
GPR_DWARFNUM_NAME(18),
GPR_DWARFNUM_NAME(19),
GPR_DWARFNUM_NAME(20),
GPR_DWARFNUM_NAME(21),
GPR_DWARFNUM_NAME(22),
GPR_DWARFNUM_NAME(23),
GPR_DWARFNUM_NAME(24),
GPR_DWARFNUM_NAME(25),
GPR_DWARFNUM_NAME(26),
GPR_DWARFNUM_NAME(27),
GPR_DWARFNUM_NAME(28),
GPR_DWARFNUM_NAME(29),
GPR_DWARFNUM_NAME(30),
GPR_DWARFNUM_NAME(31),
REG_DWARFNUM_NAME("%msr", 66),
REG_DWARFNUM_NAME("%ctr", 109),
REG_DWARFNUM_NAME("%link", 108),
REG_DWARFNUM_NAME("%xer", 101),
REG_DWARFNUM_NAME("%dar", 119),
REG_DWARFNUM_NAME("%dsisr", 118),
REG_DWARFNUM_END,
};
/**
* get_arch_regstr() - lookup register name from it's DWARF register number
* @n: the DWARF register number
*
* get_arch_regstr() returns the name of the register in struct
* regdwarfnum_table from it's DWARF register number. If the register is not
* found in the table, this returns NULL;
*/
const char *get_arch_regstr(unsigned int n)
{
const struct pt_regs_dwarfnum *roff;
for (roff = regdwarfnum_table; roff->name != NULL; roff++)
if (roff->dwarfnum == n)
return roff->name;
return NULL;
}
| gpl-2.0 |
percy-g2/android_kernel_motorola_msm8610 | drivers/leds/leds-cobalt-raq.c | 5274 | 3334 | /*
* LEDs driver for the Cobalt Raq series.
*
* Copyright (C) 2007 Yoichi Yuasa <yuasa@linux-mips.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/init.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/leds.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <linux/export.h>
#define LED_WEB 0x04
#define LED_POWER_OFF 0x08
static void __iomem *led_port;
static u8 led_value;
static DEFINE_SPINLOCK(led_value_lock);
static void raq_web_led_set(struct led_classdev *led_cdev,
enum led_brightness brightness)
{
unsigned long flags;
spin_lock_irqsave(&led_value_lock, flags);
if (brightness)
led_value |= LED_WEB;
else
led_value &= ~LED_WEB;
writeb(led_value, led_port);
spin_unlock_irqrestore(&led_value_lock, flags);
}
static struct led_classdev raq_web_led = {
.name = "raq::web",
.brightness_set = raq_web_led_set,
};
static void raq_power_off_led_set(struct led_classdev *led_cdev,
enum led_brightness brightness)
{
unsigned long flags;
spin_lock_irqsave(&led_value_lock, flags);
if (brightness)
led_value |= LED_POWER_OFF;
else
led_value &= ~LED_POWER_OFF;
writeb(led_value, led_port);
spin_unlock_irqrestore(&led_value_lock, flags);
}
static struct led_classdev raq_power_off_led = {
.name = "raq::power-off",
.brightness_set = raq_power_off_led_set,
.default_trigger = "power-off",
};
static int __devinit cobalt_raq_led_probe(struct platform_device *pdev)
{
struct resource *res;
int retval;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -EBUSY;
led_port = ioremap(res->start, resource_size(res));
if (!led_port)
return -ENOMEM;
retval = led_classdev_register(&pdev->dev, &raq_power_off_led);
if (retval)
goto err_iounmap;
retval = led_classdev_register(&pdev->dev, &raq_web_led);
if (retval)
goto err_unregister;
return 0;
err_unregister:
led_classdev_unregister(&raq_power_off_led);
err_iounmap:
iounmap(led_port);
led_port = NULL;
return retval;
}
static int __devexit cobalt_raq_led_remove(struct platform_device *pdev)
{
led_classdev_unregister(&raq_power_off_led);
led_classdev_unregister(&raq_web_led);
if (led_port) {
iounmap(led_port);
led_port = NULL;
}
return 0;
}
static struct platform_driver cobalt_raq_led_driver = {
.probe = cobalt_raq_led_probe,
.remove = __devexit_p(cobalt_raq_led_remove),
.driver = {
.name = "cobalt-raq-leds",
.owner = THIS_MODULE,
},
};
static int __init cobalt_raq_led_init(void)
{
return platform_driver_register(&cobalt_raq_led_driver);
}
module_init(cobalt_raq_led_init);
| gpl-2.0 |
EPDCenter/android_kernel_bq_qc | drivers/mtd/maps/pci.c | 7834 | 8823 | /*
* linux/drivers/mtd/maps/pci.c
*
* Copyright (C) 2001 Russell King, All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Generic PCI memory map driver. We support the following boards:
* - Intel IQ80310 ATU.
* - Intel EBSA285 (blank rom programming mode). Tested working 27/09/2001
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>
struct map_pci_info;
struct mtd_pci_info {
int (*init)(struct pci_dev *dev, struct map_pci_info *map);
void (*exit)(struct pci_dev *dev, struct map_pci_info *map);
unsigned long (*translate)(struct map_pci_info *map, unsigned long ofs);
const char *map_name;
};
struct map_pci_info {
struct map_info map;
void __iomem *base;
void (*exit)(struct pci_dev *dev, struct map_pci_info *map);
unsigned long (*translate)(struct map_pci_info *map, unsigned long ofs);
struct pci_dev *dev;
};
static map_word mtd_pci_read8(struct map_info *_map, unsigned long ofs)
{
struct map_pci_info *map = (struct map_pci_info *)_map;
map_word val;
val.x[0]= readb(map->base + map->translate(map, ofs));
// printk("read8 : %08lx => %02x\n", ofs, val.x[0]);
return val;
}
#if 0
static map_word mtd_pci_read16(struct map_info *_map, unsigned long ofs)
{
struct map_pci_info *map = (struct map_pci_info *)_map;
map_word val;
val.x[0] = readw(map->base + map->translate(map, ofs));
// printk("read16: %08lx => %04x\n", ofs, val.x[0]);
return val;
}
#endif
static map_word mtd_pci_read32(struct map_info *_map, unsigned long ofs)
{
struct map_pci_info *map = (struct map_pci_info *)_map;
map_word val;
val.x[0] = readl(map->base + map->translate(map, ofs));
// printk("read32: %08lx => %08x\n", ofs, val.x[0]);
return val;
}
static void mtd_pci_copyfrom(struct map_info *_map, void *to, unsigned long from, ssize_t len)
{
struct map_pci_info *map = (struct map_pci_info *)_map;
memcpy_fromio(to, map->base + map->translate(map, from), len);
}
static void mtd_pci_write8(struct map_info *_map, map_word val, unsigned long ofs)
{
struct map_pci_info *map = (struct map_pci_info *)_map;
// printk("write8 : %08lx <= %02x\n", ofs, val.x[0]);
writeb(val.x[0], map->base + map->translate(map, ofs));
}
#if 0
static void mtd_pci_write16(struct map_info *_map, map_word val, unsigned long ofs)
{
struct map_pci_info *map = (struct map_pci_info *)_map;
// printk("write16: %08lx <= %04x\n", ofs, val.x[0]);
writew(val.x[0], map->base + map->translate(map, ofs));
}
#endif
static void mtd_pci_write32(struct map_info *_map, map_word val, unsigned long ofs)
{
struct map_pci_info *map = (struct map_pci_info *)_map;
// printk("write32: %08lx <= %08x\n", ofs, val.x[0]);
writel(val.x[0], map->base + map->translate(map, ofs));
}
static void mtd_pci_copyto(struct map_info *_map, unsigned long to, const void *from, ssize_t len)
{
struct map_pci_info *map = (struct map_pci_info *)_map;
memcpy_toio(map->base + map->translate(map, to), from, len);
}
static const struct map_info mtd_pci_map = {
.phys = NO_XIP,
.copy_from = mtd_pci_copyfrom,
.copy_to = mtd_pci_copyto,
};
/*
* Intel IOP80310 Flash driver
*/
static int
intel_iq80310_init(struct pci_dev *dev, struct map_pci_info *map)
{
u32 win_base;
map->map.bankwidth = 1;
map->map.read = mtd_pci_read8,
map->map.write = mtd_pci_write8,
map->map.size = 0x00800000;
map->base = ioremap_nocache(pci_resource_start(dev, 0),
pci_resource_len(dev, 0));
if (!map->base)
return -ENOMEM;
/*
* We want to base the memory window at Xscale
* bus address 0, not 0x1000.
*/
pci_read_config_dword(dev, 0x44, &win_base);
pci_write_config_dword(dev, 0x44, 0);
map->map.map_priv_2 = win_base;
return 0;
}
static void
intel_iq80310_exit(struct pci_dev *dev, struct map_pci_info *map)
{
if (map->base)
iounmap(map->base);
pci_write_config_dword(dev, 0x44, map->map.map_priv_2);
}
static unsigned long
intel_iq80310_translate(struct map_pci_info *map, unsigned long ofs)
{
unsigned long page_addr = ofs & 0x00400000;
/*
* This mundges the flash location so we avoid
* the first 80 bytes (they appear to read nonsense).
*/
if (page_addr) {
writel(0x00000008, map->base + 0x1558);
writel(0x00000000, map->base + 0x1550);
} else {
writel(0x00000007, map->base + 0x1558);
writel(0x00800000, map->base + 0x1550);
ofs += 0x00800000;
}
return ofs;
}
static struct mtd_pci_info intel_iq80310_info = {
.init = intel_iq80310_init,
.exit = intel_iq80310_exit,
.translate = intel_iq80310_translate,
.map_name = "cfi_probe",
};
/*
* Intel DC21285 driver
*/
static int
intel_dc21285_init(struct pci_dev *dev, struct map_pci_info *map)
{
unsigned long base, len;
base = pci_resource_start(dev, PCI_ROM_RESOURCE);
len = pci_resource_len(dev, PCI_ROM_RESOURCE);
if (!len || !base) {
/*
* No ROM resource
*/
base = pci_resource_start(dev, 2);
len = pci_resource_len(dev, 2);
/*
* We need to re-allocate PCI BAR2 address range to the
* PCI ROM BAR, and disable PCI BAR2.
*/
} else {
/*
* Hmm, if an address was allocated to the ROM resource, but
* not enabled, should we be allocating a new resource for it
* or simply enabling it?
*/
pci_enable_rom(dev);
printk("%s: enabling expansion ROM\n", pci_name(dev));
}
if (!len || !base)
return -ENXIO;
map->map.bankwidth = 4;
map->map.read = mtd_pci_read32,
map->map.write = mtd_pci_write32,
map->map.size = len;
map->base = ioremap_nocache(base, len);
if (!map->base)
return -ENOMEM;
return 0;
}
static void
intel_dc21285_exit(struct pci_dev *dev, struct map_pci_info *map)
{
if (map->base)
iounmap(map->base);
/*
* We need to undo the PCI BAR2/PCI ROM BAR address alteration.
*/
pci_disable_rom(dev);
}
static unsigned long
intel_dc21285_translate(struct map_pci_info *map, unsigned long ofs)
{
return ofs & 0x00ffffc0 ? ofs : (ofs ^ (1 << 5));
}
static struct mtd_pci_info intel_dc21285_info = {
.init = intel_dc21285_init,
.exit = intel_dc21285_exit,
.translate = intel_dc21285_translate,
.map_name = "jedec_probe",
};
/*
* PCI device ID table
*/
static struct pci_device_id mtd_pci_ids[] = {
{
.vendor = PCI_VENDOR_ID_INTEL,
.device = 0x530d,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
.class = PCI_CLASS_MEMORY_OTHER << 8,
.class_mask = 0xffff00,
.driver_data = (unsigned long)&intel_iq80310_info,
},
{
.vendor = PCI_VENDOR_ID_DEC,
.device = PCI_DEVICE_ID_DEC_21285,
.subvendor = 0, /* DC21285 defaults to 0 on reset */
.subdevice = 0, /* DC21285 defaults to 0 on reset */
.driver_data = (unsigned long)&intel_dc21285_info,
},
{ 0, }
};
/*
* Generic code follows.
*/
static int __devinit
mtd_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
struct mtd_pci_info *info = (struct mtd_pci_info *)id->driver_data;
struct map_pci_info *map = NULL;
struct mtd_info *mtd = NULL;
int err;
err = pci_enable_device(dev);
if (err)
goto out;
err = pci_request_regions(dev, "pci mtd");
if (err)
goto out;
map = kmalloc(sizeof(*map), GFP_KERNEL);
err = -ENOMEM;
if (!map)
goto release;
map->map = mtd_pci_map;
map->map.name = pci_name(dev);
map->dev = dev;
map->exit = info->exit;
map->translate = info->translate;
err = info->init(dev, map);
if (err)
goto release;
/* tsk - do_map_probe should take const char * */
mtd = do_map_probe((char *)info->map_name, &map->map);
err = -ENODEV;
if (!mtd)
goto release;
mtd->owner = THIS_MODULE;
mtd_device_register(mtd, NULL, 0);
pci_set_drvdata(dev, mtd);
return 0;
release:
if (map) {
map->exit(dev, map);
kfree(map);
}
pci_release_regions(dev);
out:
return err;
}
static void __devexit
mtd_pci_remove(struct pci_dev *dev)
{
struct mtd_info *mtd = pci_get_drvdata(dev);
struct map_pci_info *map = mtd->priv;
mtd_device_unregister(mtd);
map_destroy(mtd);
map->exit(dev, map);
kfree(map);
pci_set_drvdata(dev, NULL);
pci_release_regions(dev);
}
static struct pci_driver mtd_pci_driver = {
.name = "MTD PCI",
.probe = mtd_pci_probe,
.remove = __devexit_p(mtd_pci_remove),
.id_table = mtd_pci_ids,
};
static int __init mtd_pci_maps_init(void)
{
return pci_register_driver(&mtd_pci_driver);
}
static void __exit mtd_pci_maps_exit(void)
{
pci_unregister_driver(&mtd_pci_driver);
}
module_init(mtd_pci_maps_init);
module_exit(mtd_pci_maps_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Russell King <rmk@arm.linux.org.uk>");
MODULE_DESCRIPTION("Generic PCI map driver");
MODULE_DEVICE_TABLE(pci, mtd_pci_ids);
| gpl-2.0 |
cm-a7lte/device_samsung_a7lte | drivers/memstick/host/tifm_ms.c | 9626 | 17033 | /*
* TI FlashMedia driver
*
* Copyright (C) 2007 Alex Dubov <oakad@yahoo.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.
*
* Special thanks to Carlos Corbacho for providing various MemoryStick cards
* that made this driver possible.
*
*/
#include <linux/tifm.h>
#include <linux/memstick.h>
#include <linux/highmem.h>
#include <linux/scatterlist.h>
#include <linux/log2.h>
#include <linux/module.h>
#include <asm/io.h>
#define DRIVER_NAME "tifm_ms"
static bool no_dma;
module_param(no_dma, bool, 0644);
/*
* Some control bits of TIFM appear to conform to Sony's reference design,
* so I'm just assuming they all are.
*/
#define TIFM_MS_STAT_DRQ 0x04000
#define TIFM_MS_STAT_MSINT 0x02000
#define TIFM_MS_STAT_RDY 0x01000
#define TIFM_MS_STAT_CRC 0x00200
#define TIFM_MS_STAT_TOE 0x00100
#define TIFM_MS_STAT_EMP 0x00020
#define TIFM_MS_STAT_FUL 0x00010
#define TIFM_MS_STAT_CED 0x00008
#define TIFM_MS_STAT_ERR 0x00004
#define TIFM_MS_STAT_BRQ 0x00002
#define TIFM_MS_STAT_CNK 0x00001
#define TIFM_MS_SYS_DMA 0x10000
#define TIFM_MS_SYS_RESET 0x08000
#define TIFM_MS_SYS_SRAC 0x04000
#define TIFM_MS_SYS_INTEN 0x02000
#define TIFM_MS_SYS_NOCRC 0x01000
#define TIFM_MS_SYS_INTCLR 0x00800
#define TIFM_MS_SYS_MSIEN 0x00400
#define TIFM_MS_SYS_FCLR 0x00200
#define TIFM_MS_SYS_FDIR 0x00100
#define TIFM_MS_SYS_DAM 0x00080
#define TIFM_MS_SYS_DRM 0x00040
#define TIFM_MS_SYS_DRQSL 0x00020
#define TIFM_MS_SYS_REI 0x00010
#define TIFM_MS_SYS_REO 0x00008
#define TIFM_MS_SYS_BSY_MASK 0x00007
#define TIFM_MS_SYS_FIFO (TIFM_MS_SYS_INTEN | TIFM_MS_SYS_MSIEN \
| TIFM_MS_SYS_FCLR | TIFM_MS_SYS_BSY_MASK)
/* Hardware flags */
enum {
CMD_READY = 0x01,
FIFO_READY = 0x02,
CARD_INT = 0x04
};
struct tifm_ms {
struct tifm_dev *dev;
struct timer_list timer;
struct memstick_request *req;
struct tasklet_struct notify;
unsigned int mode_mask;
unsigned int block_pos;
unsigned long timeout_jiffies;
unsigned char eject:1,
use_dma:1;
unsigned char cmd_flags;
unsigned char io_pos;
unsigned int io_word;
};
static unsigned int tifm_ms_read_data(struct tifm_ms *host,
unsigned char *buf, unsigned int length)
{
struct tifm_dev *sock = host->dev;
unsigned int off = 0;
while (host->io_pos && length) {
buf[off++] = host->io_word & 0xff;
host->io_word >>= 8;
length--;
host->io_pos--;
}
if (!length)
return off;
while (!(TIFM_MS_STAT_EMP & readl(sock->addr + SOCK_MS_STATUS))) {
if (length < 4)
break;
*(unsigned int *)(buf + off) = __raw_readl(sock->addr
+ SOCK_MS_DATA);
length -= 4;
off += 4;
}
if (length
&& !(TIFM_MS_STAT_EMP & readl(sock->addr + SOCK_MS_STATUS))) {
host->io_word = readl(sock->addr + SOCK_MS_DATA);
for (host->io_pos = 4; host->io_pos; --host->io_pos) {
buf[off++] = host->io_word & 0xff;
host->io_word >>= 8;
length--;
if (!length)
break;
}
}
return off;
}
static unsigned int tifm_ms_write_data(struct tifm_ms *host,
unsigned char *buf, unsigned int length)
{
struct tifm_dev *sock = host->dev;
unsigned int off = 0;
if (host->io_pos) {
while (host->io_pos < 4 && length) {
host->io_word |= buf[off++] << (host->io_pos * 8);
host->io_pos++;
length--;
}
}
if (host->io_pos == 4
&& !(TIFM_MS_STAT_FUL & readl(sock->addr + SOCK_MS_STATUS))) {
writel(TIFM_MS_SYS_FDIR | readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
writel(host->io_word, sock->addr + SOCK_MS_DATA);
host->io_pos = 0;
host->io_word = 0;
} else if (host->io_pos) {
return off;
}
if (!length)
return off;
while (!(TIFM_MS_STAT_FUL & readl(sock->addr + SOCK_MS_STATUS))) {
if (length < 4)
break;
writel(TIFM_MS_SYS_FDIR | readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
__raw_writel(*(unsigned int *)(buf + off),
sock->addr + SOCK_MS_DATA);
length -= 4;
off += 4;
}
switch (length) {
case 3:
host->io_word |= buf[off + 2] << 16;
host->io_pos++;
case 2:
host->io_word |= buf[off + 1] << 8;
host->io_pos++;
case 1:
host->io_word |= buf[off];
host->io_pos++;
}
off += host->io_pos;
return off;
}
static unsigned int tifm_ms_transfer_data(struct tifm_ms *host)
{
struct tifm_dev *sock = host->dev;
unsigned int length;
unsigned int off;
unsigned int t_size, p_cnt;
unsigned char *buf;
struct page *pg;
unsigned long flags = 0;
if (host->req->long_data) {
length = host->req->sg.length - host->block_pos;
off = host->req->sg.offset + host->block_pos;
} else {
length = host->req->data_len - host->block_pos;
off = 0;
}
dev_dbg(&sock->dev, "fifo data transfer, %d, %d\n", length,
host->block_pos);
while (length) {
unsigned int uninitialized_var(p_off);
if (host->req->long_data) {
pg = nth_page(sg_page(&host->req->sg),
off >> PAGE_SHIFT);
p_off = offset_in_page(off);
p_cnt = PAGE_SIZE - p_off;
p_cnt = min(p_cnt, length);
local_irq_save(flags);
buf = kmap_atomic(pg) + p_off;
} else {
buf = host->req->data + host->block_pos;
p_cnt = host->req->data_len - host->block_pos;
}
t_size = host->req->data_dir == WRITE
? tifm_ms_write_data(host, buf, p_cnt)
: tifm_ms_read_data(host, buf, p_cnt);
if (host->req->long_data) {
kunmap_atomic(buf - p_off);
local_irq_restore(flags);
}
if (!t_size)
break;
host->block_pos += t_size;
length -= t_size;
off += t_size;
}
dev_dbg(&sock->dev, "fifo data transfer, %d remaining\n", length);
if (!length && (host->req->data_dir == WRITE)) {
if (host->io_pos) {
writel(TIFM_MS_SYS_FDIR
| readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
writel(host->io_word, sock->addr + SOCK_MS_DATA);
}
writel(TIFM_MS_SYS_FDIR
| readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
writel(0, sock->addr + SOCK_MS_DATA);
} else {
readl(sock->addr + SOCK_MS_DATA);
}
return length;
}
static int tifm_ms_issue_cmd(struct tifm_ms *host)
{
struct tifm_dev *sock = host->dev;
unsigned char *data;
unsigned int data_len, cmd, sys_param;
host->cmd_flags = 0;
host->block_pos = 0;
host->io_pos = 0;
host->io_word = 0;
host->cmd_flags = 0;
data = host->req->data;
host->use_dma = !no_dma;
if (host->req->long_data) {
data_len = host->req->sg.length;
if (!is_power_of_2(data_len))
host->use_dma = 0;
} else {
data_len = host->req->data_len;
host->use_dma = 0;
}
writel(TIFM_FIFO_INT_SETALL,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_CLEAR);
writel(TIFM_FIFO_ENABLE,
sock->addr + SOCK_FIFO_CONTROL);
if (host->use_dma) {
if (1 != tifm_map_sg(sock, &host->req->sg, 1,
host->req->data_dir == READ
? PCI_DMA_FROMDEVICE
: PCI_DMA_TODEVICE)) {
host->req->error = -ENOMEM;
return host->req->error;
}
data_len = sg_dma_len(&host->req->sg);
writel(ilog2(data_len) - 2,
sock->addr + SOCK_FIFO_PAGE_SIZE);
writel(TIFM_FIFO_INTMASK,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_SET);
sys_param = TIFM_DMA_EN | (1 << 8);
if (host->req->data_dir == WRITE)
sys_param |= TIFM_DMA_TX;
writel(TIFM_FIFO_INTMASK,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_SET);
writel(sg_dma_address(&host->req->sg),
sock->addr + SOCK_DMA_ADDRESS);
writel(sys_param, sock->addr + SOCK_DMA_CONTROL);
} else {
writel(host->mode_mask | TIFM_MS_SYS_FIFO,
sock->addr + SOCK_MS_SYSTEM);
writel(TIFM_FIFO_MORE,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_SET);
}
mod_timer(&host->timer, jiffies + host->timeout_jiffies);
writel(TIFM_CTRL_LED | readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
host->req->error = 0;
sys_param = readl(sock->addr + SOCK_MS_SYSTEM);
sys_param |= TIFM_MS_SYS_INTCLR;
if (host->use_dma)
sys_param |= TIFM_MS_SYS_DMA;
else
sys_param &= ~TIFM_MS_SYS_DMA;
writel(sys_param, sock->addr + SOCK_MS_SYSTEM);
cmd = (host->req->tpc & 0xf) << 12;
cmd |= data_len;
writel(cmd, sock->addr + SOCK_MS_COMMAND);
dev_dbg(&sock->dev, "executing TPC %x, %x\n", cmd, sys_param);
return 0;
}
static void tifm_ms_complete_cmd(struct tifm_ms *host)
{
struct tifm_dev *sock = host->dev;
struct memstick_host *msh = tifm_get_drvdata(sock);
int rc;
del_timer(&host->timer);
host->req->int_reg = readl(sock->addr + SOCK_MS_STATUS) & 0xff;
host->req->int_reg = (host->req->int_reg & 1)
| ((host->req->int_reg << 4) & 0xe0);
writel(TIFM_FIFO_INT_SETALL,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_CLEAR);
writel(TIFM_DMA_RESET, sock->addr + SOCK_DMA_CONTROL);
if (host->use_dma) {
tifm_unmap_sg(sock, &host->req->sg, 1,
host->req->data_dir == READ
? PCI_DMA_FROMDEVICE
: PCI_DMA_TODEVICE);
}
writel((~TIFM_CTRL_LED) & readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
dev_dbg(&sock->dev, "TPC complete\n");
do {
rc = memstick_next_req(msh, &host->req);
} while (!rc && tifm_ms_issue_cmd(host));
}
static int tifm_ms_check_status(struct tifm_ms *host)
{
if (!host->req->error) {
if (!(host->cmd_flags & CMD_READY))
return 1;
if (!(host->cmd_flags & FIFO_READY))
return 1;
if (host->req->need_card_int
&& !(host->cmd_flags & CARD_INT))
return 1;
}
return 0;
}
/* Called from interrupt handler */
static void tifm_ms_data_event(struct tifm_dev *sock)
{
struct tifm_ms *host;
unsigned int fifo_status = 0, host_status = 0;
int rc = 1;
spin_lock(&sock->lock);
host = memstick_priv((struct memstick_host *)tifm_get_drvdata(sock));
fifo_status = readl(sock->addr + SOCK_DMA_FIFO_STATUS);
host_status = readl(sock->addr + SOCK_MS_STATUS);
dev_dbg(&sock->dev,
"data event: fifo_status %x, host_status %x, flags %x\n",
fifo_status, host_status, host->cmd_flags);
if (host->req) {
if (host->use_dma && (fifo_status & 1)) {
host->cmd_flags |= FIFO_READY;
rc = tifm_ms_check_status(host);
}
if (!host->use_dma && (fifo_status & TIFM_FIFO_MORE)) {
if (!tifm_ms_transfer_data(host)) {
host->cmd_flags |= FIFO_READY;
rc = tifm_ms_check_status(host);
}
}
}
writel(fifo_status, sock->addr + SOCK_DMA_FIFO_STATUS);
if (!rc)
tifm_ms_complete_cmd(host);
spin_unlock(&sock->lock);
}
/* Called from interrupt handler */
static void tifm_ms_card_event(struct tifm_dev *sock)
{
struct tifm_ms *host;
unsigned int host_status = 0;
int rc = 1;
spin_lock(&sock->lock);
host = memstick_priv((struct memstick_host *)tifm_get_drvdata(sock));
host_status = readl(sock->addr + SOCK_MS_STATUS);
dev_dbg(&sock->dev, "host event: host_status %x, flags %x\n",
host_status, host->cmd_flags);
if (host->req) {
if (host_status & TIFM_MS_STAT_TOE)
host->req->error = -ETIME;
else if (host_status & TIFM_MS_STAT_CRC)
host->req->error = -EILSEQ;
if (host_status & TIFM_MS_STAT_RDY)
host->cmd_flags |= CMD_READY;
if (host_status & TIFM_MS_STAT_MSINT)
host->cmd_flags |= CARD_INT;
rc = tifm_ms_check_status(host);
}
writel(TIFM_MS_SYS_INTCLR | readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
if (!rc)
tifm_ms_complete_cmd(host);
spin_unlock(&sock->lock);
return;
}
static void tifm_ms_req_tasklet(unsigned long data)
{
struct memstick_host *msh = (struct memstick_host *)data;
struct tifm_ms *host = memstick_priv(msh);
struct tifm_dev *sock = host->dev;
unsigned long flags;
int rc;
spin_lock_irqsave(&sock->lock, flags);
if (!host->req) {
if (host->eject) {
do {
rc = memstick_next_req(msh, &host->req);
if (!rc)
host->req->error = -ETIME;
} while (!rc);
spin_unlock_irqrestore(&sock->lock, flags);
return;
}
do {
rc = memstick_next_req(msh, &host->req);
} while (!rc && tifm_ms_issue_cmd(host));
}
spin_unlock_irqrestore(&sock->lock, flags);
}
static void tifm_ms_dummy_submit(struct memstick_host *msh)
{
return;
}
static void tifm_ms_submit_req(struct memstick_host *msh)
{
struct tifm_ms *host = memstick_priv(msh);
tasklet_schedule(&host->notify);
}
static int tifm_ms_set_param(struct memstick_host *msh,
enum memstick_param param,
int value)
{
struct tifm_ms *host = memstick_priv(msh);
struct tifm_dev *sock = host->dev;
switch (param) {
case MEMSTICK_POWER:
/* also affected by media detection mechanism */
if (value == MEMSTICK_POWER_ON) {
host->mode_mask = TIFM_MS_SYS_SRAC | TIFM_MS_SYS_REI;
writel(TIFM_MS_SYS_RESET, sock->addr + SOCK_MS_SYSTEM);
writel(TIFM_MS_SYS_FCLR | TIFM_MS_SYS_INTCLR,
sock->addr + SOCK_MS_SYSTEM);
writel(0xffffffff, sock->addr + SOCK_MS_STATUS);
} else if (value == MEMSTICK_POWER_OFF) {
writel(TIFM_MS_SYS_FCLR | TIFM_MS_SYS_INTCLR,
sock->addr + SOCK_MS_SYSTEM);
writel(0xffffffff, sock->addr + SOCK_MS_STATUS);
} else
return -EINVAL;
break;
case MEMSTICK_INTERFACE:
if (value == MEMSTICK_SERIAL) {
host->mode_mask = TIFM_MS_SYS_SRAC | TIFM_MS_SYS_REI;
writel((~TIFM_CTRL_FAST_CLK)
& readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
} else if (value == MEMSTICK_PAR4) {
host->mode_mask = 0;
writel(TIFM_CTRL_FAST_CLK
| readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
} else
return -EINVAL;
break;
};
return 0;
}
static void tifm_ms_abort(unsigned long data)
{
struct tifm_ms *host = (struct tifm_ms *)data;
dev_dbg(&host->dev->dev, "status %x\n",
readl(host->dev->addr + SOCK_MS_STATUS));
printk(KERN_ERR
"%s : card failed to respond for a long period of time "
"(%x, %x)\n",
dev_name(&host->dev->dev), host->req ? host->req->tpc : 0,
host->cmd_flags);
tifm_eject(host->dev);
}
static int tifm_ms_probe(struct tifm_dev *sock)
{
struct memstick_host *msh;
struct tifm_ms *host;
int rc = -EIO;
if (!(TIFM_SOCK_STATE_OCCUPIED
& readl(sock->addr + SOCK_PRESENT_STATE))) {
printk(KERN_WARNING "%s : card gone, unexpectedly\n",
dev_name(&sock->dev));
return rc;
}
msh = memstick_alloc_host(sizeof(struct tifm_ms), &sock->dev);
if (!msh)
return -ENOMEM;
host = memstick_priv(msh);
tifm_set_drvdata(sock, msh);
host->dev = sock;
host->timeout_jiffies = msecs_to_jiffies(1000);
setup_timer(&host->timer, tifm_ms_abort, (unsigned long)host);
tasklet_init(&host->notify, tifm_ms_req_tasklet, (unsigned long)msh);
msh->request = tifm_ms_submit_req;
msh->set_param = tifm_ms_set_param;
sock->card_event = tifm_ms_card_event;
sock->data_event = tifm_ms_data_event;
if (tifm_has_ms_pif(sock))
msh->caps |= MEMSTICK_CAP_PAR4;
rc = memstick_add_host(msh);
if (!rc)
return 0;
memstick_free_host(msh);
return rc;
}
static void tifm_ms_remove(struct tifm_dev *sock)
{
struct memstick_host *msh = tifm_get_drvdata(sock);
struct tifm_ms *host = memstick_priv(msh);
int rc = 0;
unsigned long flags;
msh->request = tifm_ms_dummy_submit;
tasklet_kill(&host->notify);
spin_lock_irqsave(&sock->lock, flags);
host->eject = 1;
if (host->req) {
del_timer(&host->timer);
writel(TIFM_FIFO_INT_SETALL,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_CLEAR);
writel(TIFM_DMA_RESET, sock->addr + SOCK_DMA_CONTROL);
if (host->use_dma)
tifm_unmap_sg(sock, &host->req->sg, 1,
host->req->data_dir == READ
? PCI_DMA_TODEVICE
: PCI_DMA_FROMDEVICE);
host->req->error = -ETIME;
do {
rc = memstick_next_req(msh, &host->req);
if (!rc)
host->req->error = -ETIME;
} while (!rc);
}
spin_unlock_irqrestore(&sock->lock, flags);
memstick_remove_host(msh);
memstick_free_host(msh);
}
#ifdef CONFIG_PM
static int tifm_ms_suspend(struct tifm_dev *sock, pm_message_t state)
{
struct memstick_host *msh = tifm_get_drvdata(sock);
memstick_suspend_host(msh);
return 0;
}
static int tifm_ms_resume(struct tifm_dev *sock)
{
struct memstick_host *msh = tifm_get_drvdata(sock);
memstick_resume_host(msh);
return 0;
}
#else
#define tifm_ms_suspend NULL
#define tifm_ms_resume NULL
#endif /* CONFIG_PM */
static struct tifm_device_id tifm_ms_id_tbl[] = {
{ TIFM_TYPE_MS }, { 0 }
};
static struct tifm_driver tifm_ms_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE
},
.id_table = tifm_ms_id_tbl,
.probe = tifm_ms_probe,
.remove = tifm_ms_remove,
.suspend = tifm_ms_suspend,
.resume = tifm_ms_resume
};
static int __init tifm_ms_init(void)
{
return tifm_register_driver(&tifm_ms_driver);
}
static void __exit tifm_ms_exit(void)
{
tifm_unregister_driver(&tifm_ms_driver);
}
MODULE_AUTHOR("Alex Dubov");
MODULE_DESCRIPTION("TI FlashMedia MemoryStick driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(tifm, tifm_ms_id_tbl);
module_init(tifm_ms_init);
module_exit(tifm_ms_exit);
| gpl-2.0 |
thanhphat11/Kernel-Stock-A900-SLK | drivers/memstick/host/tifm_ms.c | 9626 | 17033 | /*
* TI FlashMedia driver
*
* Copyright (C) 2007 Alex Dubov <oakad@yahoo.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.
*
* Special thanks to Carlos Corbacho for providing various MemoryStick cards
* that made this driver possible.
*
*/
#include <linux/tifm.h>
#include <linux/memstick.h>
#include <linux/highmem.h>
#include <linux/scatterlist.h>
#include <linux/log2.h>
#include <linux/module.h>
#include <asm/io.h>
#define DRIVER_NAME "tifm_ms"
static bool no_dma;
module_param(no_dma, bool, 0644);
/*
* Some control bits of TIFM appear to conform to Sony's reference design,
* so I'm just assuming they all are.
*/
#define TIFM_MS_STAT_DRQ 0x04000
#define TIFM_MS_STAT_MSINT 0x02000
#define TIFM_MS_STAT_RDY 0x01000
#define TIFM_MS_STAT_CRC 0x00200
#define TIFM_MS_STAT_TOE 0x00100
#define TIFM_MS_STAT_EMP 0x00020
#define TIFM_MS_STAT_FUL 0x00010
#define TIFM_MS_STAT_CED 0x00008
#define TIFM_MS_STAT_ERR 0x00004
#define TIFM_MS_STAT_BRQ 0x00002
#define TIFM_MS_STAT_CNK 0x00001
#define TIFM_MS_SYS_DMA 0x10000
#define TIFM_MS_SYS_RESET 0x08000
#define TIFM_MS_SYS_SRAC 0x04000
#define TIFM_MS_SYS_INTEN 0x02000
#define TIFM_MS_SYS_NOCRC 0x01000
#define TIFM_MS_SYS_INTCLR 0x00800
#define TIFM_MS_SYS_MSIEN 0x00400
#define TIFM_MS_SYS_FCLR 0x00200
#define TIFM_MS_SYS_FDIR 0x00100
#define TIFM_MS_SYS_DAM 0x00080
#define TIFM_MS_SYS_DRM 0x00040
#define TIFM_MS_SYS_DRQSL 0x00020
#define TIFM_MS_SYS_REI 0x00010
#define TIFM_MS_SYS_REO 0x00008
#define TIFM_MS_SYS_BSY_MASK 0x00007
#define TIFM_MS_SYS_FIFO (TIFM_MS_SYS_INTEN | TIFM_MS_SYS_MSIEN \
| TIFM_MS_SYS_FCLR | TIFM_MS_SYS_BSY_MASK)
/* Hardware flags */
enum {
CMD_READY = 0x01,
FIFO_READY = 0x02,
CARD_INT = 0x04
};
struct tifm_ms {
struct tifm_dev *dev;
struct timer_list timer;
struct memstick_request *req;
struct tasklet_struct notify;
unsigned int mode_mask;
unsigned int block_pos;
unsigned long timeout_jiffies;
unsigned char eject:1,
use_dma:1;
unsigned char cmd_flags;
unsigned char io_pos;
unsigned int io_word;
};
static unsigned int tifm_ms_read_data(struct tifm_ms *host,
unsigned char *buf, unsigned int length)
{
struct tifm_dev *sock = host->dev;
unsigned int off = 0;
while (host->io_pos && length) {
buf[off++] = host->io_word & 0xff;
host->io_word >>= 8;
length--;
host->io_pos--;
}
if (!length)
return off;
while (!(TIFM_MS_STAT_EMP & readl(sock->addr + SOCK_MS_STATUS))) {
if (length < 4)
break;
*(unsigned int *)(buf + off) = __raw_readl(sock->addr
+ SOCK_MS_DATA);
length -= 4;
off += 4;
}
if (length
&& !(TIFM_MS_STAT_EMP & readl(sock->addr + SOCK_MS_STATUS))) {
host->io_word = readl(sock->addr + SOCK_MS_DATA);
for (host->io_pos = 4; host->io_pos; --host->io_pos) {
buf[off++] = host->io_word & 0xff;
host->io_word >>= 8;
length--;
if (!length)
break;
}
}
return off;
}
static unsigned int tifm_ms_write_data(struct tifm_ms *host,
unsigned char *buf, unsigned int length)
{
struct tifm_dev *sock = host->dev;
unsigned int off = 0;
if (host->io_pos) {
while (host->io_pos < 4 && length) {
host->io_word |= buf[off++] << (host->io_pos * 8);
host->io_pos++;
length--;
}
}
if (host->io_pos == 4
&& !(TIFM_MS_STAT_FUL & readl(sock->addr + SOCK_MS_STATUS))) {
writel(TIFM_MS_SYS_FDIR | readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
writel(host->io_word, sock->addr + SOCK_MS_DATA);
host->io_pos = 0;
host->io_word = 0;
} else if (host->io_pos) {
return off;
}
if (!length)
return off;
while (!(TIFM_MS_STAT_FUL & readl(sock->addr + SOCK_MS_STATUS))) {
if (length < 4)
break;
writel(TIFM_MS_SYS_FDIR | readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
__raw_writel(*(unsigned int *)(buf + off),
sock->addr + SOCK_MS_DATA);
length -= 4;
off += 4;
}
switch (length) {
case 3:
host->io_word |= buf[off + 2] << 16;
host->io_pos++;
case 2:
host->io_word |= buf[off + 1] << 8;
host->io_pos++;
case 1:
host->io_word |= buf[off];
host->io_pos++;
}
off += host->io_pos;
return off;
}
static unsigned int tifm_ms_transfer_data(struct tifm_ms *host)
{
struct tifm_dev *sock = host->dev;
unsigned int length;
unsigned int off;
unsigned int t_size, p_cnt;
unsigned char *buf;
struct page *pg;
unsigned long flags = 0;
if (host->req->long_data) {
length = host->req->sg.length - host->block_pos;
off = host->req->sg.offset + host->block_pos;
} else {
length = host->req->data_len - host->block_pos;
off = 0;
}
dev_dbg(&sock->dev, "fifo data transfer, %d, %d\n", length,
host->block_pos);
while (length) {
unsigned int uninitialized_var(p_off);
if (host->req->long_data) {
pg = nth_page(sg_page(&host->req->sg),
off >> PAGE_SHIFT);
p_off = offset_in_page(off);
p_cnt = PAGE_SIZE - p_off;
p_cnt = min(p_cnt, length);
local_irq_save(flags);
buf = kmap_atomic(pg) + p_off;
} else {
buf = host->req->data + host->block_pos;
p_cnt = host->req->data_len - host->block_pos;
}
t_size = host->req->data_dir == WRITE
? tifm_ms_write_data(host, buf, p_cnt)
: tifm_ms_read_data(host, buf, p_cnt);
if (host->req->long_data) {
kunmap_atomic(buf - p_off);
local_irq_restore(flags);
}
if (!t_size)
break;
host->block_pos += t_size;
length -= t_size;
off += t_size;
}
dev_dbg(&sock->dev, "fifo data transfer, %d remaining\n", length);
if (!length && (host->req->data_dir == WRITE)) {
if (host->io_pos) {
writel(TIFM_MS_SYS_FDIR
| readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
writel(host->io_word, sock->addr + SOCK_MS_DATA);
}
writel(TIFM_MS_SYS_FDIR
| readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
writel(0, sock->addr + SOCK_MS_DATA);
} else {
readl(sock->addr + SOCK_MS_DATA);
}
return length;
}
static int tifm_ms_issue_cmd(struct tifm_ms *host)
{
struct tifm_dev *sock = host->dev;
unsigned char *data;
unsigned int data_len, cmd, sys_param;
host->cmd_flags = 0;
host->block_pos = 0;
host->io_pos = 0;
host->io_word = 0;
host->cmd_flags = 0;
data = host->req->data;
host->use_dma = !no_dma;
if (host->req->long_data) {
data_len = host->req->sg.length;
if (!is_power_of_2(data_len))
host->use_dma = 0;
} else {
data_len = host->req->data_len;
host->use_dma = 0;
}
writel(TIFM_FIFO_INT_SETALL,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_CLEAR);
writel(TIFM_FIFO_ENABLE,
sock->addr + SOCK_FIFO_CONTROL);
if (host->use_dma) {
if (1 != tifm_map_sg(sock, &host->req->sg, 1,
host->req->data_dir == READ
? PCI_DMA_FROMDEVICE
: PCI_DMA_TODEVICE)) {
host->req->error = -ENOMEM;
return host->req->error;
}
data_len = sg_dma_len(&host->req->sg);
writel(ilog2(data_len) - 2,
sock->addr + SOCK_FIFO_PAGE_SIZE);
writel(TIFM_FIFO_INTMASK,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_SET);
sys_param = TIFM_DMA_EN | (1 << 8);
if (host->req->data_dir == WRITE)
sys_param |= TIFM_DMA_TX;
writel(TIFM_FIFO_INTMASK,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_SET);
writel(sg_dma_address(&host->req->sg),
sock->addr + SOCK_DMA_ADDRESS);
writel(sys_param, sock->addr + SOCK_DMA_CONTROL);
} else {
writel(host->mode_mask | TIFM_MS_SYS_FIFO,
sock->addr + SOCK_MS_SYSTEM);
writel(TIFM_FIFO_MORE,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_SET);
}
mod_timer(&host->timer, jiffies + host->timeout_jiffies);
writel(TIFM_CTRL_LED | readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
host->req->error = 0;
sys_param = readl(sock->addr + SOCK_MS_SYSTEM);
sys_param |= TIFM_MS_SYS_INTCLR;
if (host->use_dma)
sys_param |= TIFM_MS_SYS_DMA;
else
sys_param &= ~TIFM_MS_SYS_DMA;
writel(sys_param, sock->addr + SOCK_MS_SYSTEM);
cmd = (host->req->tpc & 0xf) << 12;
cmd |= data_len;
writel(cmd, sock->addr + SOCK_MS_COMMAND);
dev_dbg(&sock->dev, "executing TPC %x, %x\n", cmd, sys_param);
return 0;
}
static void tifm_ms_complete_cmd(struct tifm_ms *host)
{
struct tifm_dev *sock = host->dev;
struct memstick_host *msh = tifm_get_drvdata(sock);
int rc;
del_timer(&host->timer);
host->req->int_reg = readl(sock->addr + SOCK_MS_STATUS) & 0xff;
host->req->int_reg = (host->req->int_reg & 1)
| ((host->req->int_reg << 4) & 0xe0);
writel(TIFM_FIFO_INT_SETALL,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_CLEAR);
writel(TIFM_DMA_RESET, sock->addr + SOCK_DMA_CONTROL);
if (host->use_dma) {
tifm_unmap_sg(sock, &host->req->sg, 1,
host->req->data_dir == READ
? PCI_DMA_FROMDEVICE
: PCI_DMA_TODEVICE);
}
writel((~TIFM_CTRL_LED) & readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
dev_dbg(&sock->dev, "TPC complete\n");
do {
rc = memstick_next_req(msh, &host->req);
} while (!rc && tifm_ms_issue_cmd(host));
}
static int tifm_ms_check_status(struct tifm_ms *host)
{
if (!host->req->error) {
if (!(host->cmd_flags & CMD_READY))
return 1;
if (!(host->cmd_flags & FIFO_READY))
return 1;
if (host->req->need_card_int
&& !(host->cmd_flags & CARD_INT))
return 1;
}
return 0;
}
/* Called from interrupt handler */
static void tifm_ms_data_event(struct tifm_dev *sock)
{
struct tifm_ms *host;
unsigned int fifo_status = 0, host_status = 0;
int rc = 1;
spin_lock(&sock->lock);
host = memstick_priv((struct memstick_host *)tifm_get_drvdata(sock));
fifo_status = readl(sock->addr + SOCK_DMA_FIFO_STATUS);
host_status = readl(sock->addr + SOCK_MS_STATUS);
dev_dbg(&sock->dev,
"data event: fifo_status %x, host_status %x, flags %x\n",
fifo_status, host_status, host->cmd_flags);
if (host->req) {
if (host->use_dma && (fifo_status & 1)) {
host->cmd_flags |= FIFO_READY;
rc = tifm_ms_check_status(host);
}
if (!host->use_dma && (fifo_status & TIFM_FIFO_MORE)) {
if (!tifm_ms_transfer_data(host)) {
host->cmd_flags |= FIFO_READY;
rc = tifm_ms_check_status(host);
}
}
}
writel(fifo_status, sock->addr + SOCK_DMA_FIFO_STATUS);
if (!rc)
tifm_ms_complete_cmd(host);
spin_unlock(&sock->lock);
}
/* Called from interrupt handler */
static void tifm_ms_card_event(struct tifm_dev *sock)
{
struct tifm_ms *host;
unsigned int host_status = 0;
int rc = 1;
spin_lock(&sock->lock);
host = memstick_priv((struct memstick_host *)tifm_get_drvdata(sock));
host_status = readl(sock->addr + SOCK_MS_STATUS);
dev_dbg(&sock->dev, "host event: host_status %x, flags %x\n",
host_status, host->cmd_flags);
if (host->req) {
if (host_status & TIFM_MS_STAT_TOE)
host->req->error = -ETIME;
else if (host_status & TIFM_MS_STAT_CRC)
host->req->error = -EILSEQ;
if (host_status & TIFM_MS_STAT_RDY)
host->cmd_flags |= CMD_READY;
if (host_status & TIFM_MS_STAT_MSINT)
host->cmd_flags |= CARD_INT;
rc = tifm_ms_check_status(host);
}
writel(TIFM_MS_SYS_INTCLR | readl(sock->addr + SOCK_MS_SYSTEM),
sock->addr + SOCK_MS_SYSTEM);
if (!rc)
tifm_ms_complete_cmd(host);
spin_unlock(&sock->lock);
return;
}
static void tifm_ms_req_tasklet(unsigned long data)
{
struct memstick_host *msh = (struct memstick_host *)data;
struct tifm_ms *host = memstick_priv(msh);
struct tifm_dev *sock = host->dev;
unsigned long flags;
int rc;
spin_lock_irqsave(&sock->lock, flags);
if (!host->req) {
if (host->eject) {
do {
rc = memstick_next_req(msh, &host->req);
if (!rc)
host->req->error = -ETIME;
} while (!rc);
spin_unlock_irqrestore(&sock->lock, flags);
return;
}
do {
rc = memstick_next_req(msh, &host->req);
} while (!rc && tifm_ms_issue_cmd(host));
}
spin_unlock_irqrestore(&sock->lock, flags);
}
static void tifm_ms_dummy_submit(struct memstick_host *msh)
{
return;
}
static void tifm_ms_submit_req(struct memstick_host *msh)
{
struct tifm_ms *host = memstick_priv(msh);
tasklet_schedule(&host->notify);
}
static int tifm_ms_set_param(struct memstick_host *msh,
enum memstick_param param,
int value)
{
struct tifm_ms *host = memstick_priv(msh);
struct tifm_dev *sock = host->dev;
switch (param) {
case MEMSTICK_POWER:
/* also affected by media detection mechanism */
if (value == MEMSTICK_POWER_ON) {
host->mode_mask = TIFM_MS_SYS_SRAC | TIFM_MS_SYS_REI;
writel(TIFM_MS_SYS_RESET, sock->addr + SOCK_MS_SYSTEM);
writel(TIFM_MS_SYS_FCLR | TIFM_MS_SYS_INTCLR,
sock->addr + SOCK_MS_SYSTEM);
writel(0xffffffff, sock->addr + SOCK_MS_STATUS);
} else if (value == MEMSTICK_POWER_OFF) {
writel(TIFM_MS_SYS_FCLR | TIFM_MS_SYS_INTCLR,
sock->addr + SOCK_MS_SYSTEM);
writel(0xffffffff, sock->addr + SOCK_MS_STATUS);
} else
return -EINVAL;
break;
case MEMSTICK_INTERFACE:
if (value == MEMSTICK_SERIAL) {
host->mode_mask = TIFM_MS_SYS_SRAC | TIFM_MS_SYS_REI;
writel((~TIFM_CTRL_FAST_CLK)
& readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
} else if (value == MEMSTICK_PAR4) {
host->mode_mask = 0;
writel(TIFM_CTRL_FAST_CLK
| readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
} else
return -EINVAL;
break;
};
return 0;
}
static void tifm_ms_abort(unsigned long data)
{
struct tifm_ms *host = (struct tifm_ms *)data;
dev_dbg(&host->dev->dev, "status %x\n",
readl(host->dev->addr + SOCK_MS_STATUS));
printk(KERN_ERR
"%s : card failed to respond for a long period of time "
"(%x, %x)\n",
dev_name(&host->dev->dev), host->req ? host->req->tpc : 0,
host->cmd_flags);
tifm_eject(host->dev);
}
static int tifm_ms_probe(struct tifm_dev *sock)
{
struct memstick_host *msh;
struct tifm_ms *host;
int rc = -EIO;
if (!(TIFM_SOCK_STATE_OCCUPIED
& readl(sock->addr + SOCK_PRESENT_STATE))) {
printk(KERN_WARNING "%s : card gone, unexpectedly\n",
dev_name(&sock->dev));
return rc;
}
msh = memstick_alloc_host(sizeof(struct tifm_ms), &sock->dev);
if (!msh)
return -ENOMEM;
host = memstick_priv(msh);
tifm_set_drvdata(sock, msh);
host->dev = sock;
host->timeout_jiffies = msecs_to_jiffies(1000);
setup_timer(&host->timer, tifm_ms_abort, (unsigned long)host);
tasklet_init(&host->notify, tifm_ms_req_tasklet, (unsigned long)msh);
msh->request = tifm_ms_submit_req;
msh->set_param = tifm_ms_set_param;
sock->card_event = tifm_ms_card_event;
sock->data_event = tifm_ms_data_event;
if (tifm_has_ms_pif(sock))
msh->caps |= MEMSTICK_CAP_PAR4;
rc = memstick_add_host(msh);
if (!rc)
return 0;
memstick_free_host(msh);
return rc;
}
static void tifm_ms_remove(struct tifm_dev *sock)
{
struct memstick_host *msh = tifm_get_drvdata(sock);
struct tifm_ms *host = memstick_priv(msh);
int rc = 0;
unsigned long flags;
msh->request = tifm_ms_dummy_submit;
tasklet_kill(&host->notify);
spin_lock_irqsave(&sock->lock, flags);
host->eject = 1;
if (host->req) {
del_timer(&host->timer);
writel(TIFM_FIFO_INT_SETALL,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_CLEAR);
writel(TIFM_DMA_RESET, sock->addr + SOCK_DMA_CONTROL);
if (host->use_dma)
tifm_unmap_sg(sock, &host->req->sg, 1,
host->req->data_dir == READ
? PCI_DMA_TODEVICE
: PCI_DMA_FROMDEVICE);
host->req->error = -ETIME;
do {
rc = memstick_next_req(msh, &host->req);
if (!rc)
host->req->error = -ETIME;
} while (!rc);
}
spin_unlock_irqrestore(&sock->lock, flags);
memstick_remove_host(msh);
memstick_free_host(msh);
}
#ifdef CONFIG_PM
static int tifm_ms_suspend(struct tifm_dev *sock, pm_message_t state)
{
struct memstick_host *msh = tifm_get_drvdata(sock);
memstick_suspend_host(msh);
return 0;
}
static int tifm_ms_resume(struct tifm_dev *sock)
{
struct memstick_host *msh = tifm_get_drvdata(sock);
memstick_resume_host(msh);
return 0;
}
#else
#define tifm_ms_suspend NULL
#define tifm_ms_resume NULL
#endif /* CONFIG_PM */
static struct tifm_device_id tifm_ms_id_tbl[] = {
{ TIFM_TYPE_MS }, { 0 }
};
static struct tifm_driver tifm_ms_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE
},
.id_table = tifm_ms_id_tbl,
.probe = tifm_ms_probe,
.remove = tifm_ms_remove,
.suspend = tifm_ms_suspend,
.resume = tifm_ms_resume
};
static int __init tifm_ms_init(void)
{
return tifm_register_driver(&tifm_ms_driver);
}
static void __exit tifm_ms_exit(void)
{
tifm_unregister_driver(&tifm_ms_driver);
}
MODULE_AUTHOR("Alex Dubov");
MODULE_DESCRIPTION("TI FlashMedia MemoryStick driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(tifm, tifm_ms_id_tbl);
module_init(tifm_ms_init);
module_exit(tifm_ms_exit);
| gpl-2.0 |
SynerconTechnologies/FLA-Kernel | drivers/media/usb/pwc/pwc-misc.c | 9882 | 2909 | /* Linux driver for Philips webcam
Various miscellaneous functions and tables.
(C) 1999-2003 Nemosoft Unv.
(C) 2004-2006 Luc Saillard (luc@saillard.org)
NOTE: this version of pwc is an unofficial (modified) release of pwc & pcwx
driver and thus may have bugs that are not present in the original version.
Please send bug reports and support requests to <luc@saillard.org>.
The decompression routines have been implemented by reverse-engineering the
Nemosoft binary pwcx module. Caveat emptor.
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 "pwc.h"
const int pwc_image_sizes[PSZ_MAX][2] =
{
{ 128, 96 }, /* sqcif */
{ 160, 120 }, /* qsif */
{ 176, 144 }, /* qcif */
{ 320, 240 }, /* sif */
{ 352, 288 }, /* cif */
{ 640, 480 }, /* vga */
};
/* x,y -> PSZ_ */
int pwc_get_size(struct pwc_device *pdev, int width, int height)
{
int i;
/* Find the largest size supported by the camera that fits into the
requested size. */
for (i = PSZ_MAX - 1; i >= 0; i--) {
if (!(pdev->image_mask & (1 << i)))
continue;
if (pwc_image_sizes[i][0] <= width &&
pwc_image_sizes[i][1] <= height)
return i;
}
/* No mode found, return the smallest mode we have */
for (i = 0; i < PSZ_MAX; i++) {
if (pdev->image_mask & (1 << i))
return i;
}
/* Never reached there always is atleast one supported mode */
return 0;
}
/* initialize variables depending on type and decompressor */
void pwc_construct(struct pwc_device *pdev)
{
if (DEVICE_USE_CODEC1(pdev->type)) {
pdev->image_mask = 1 << PSZ_SQCIF | 1 << PSZ_QCIF | 1 << PSZ_CIF;
pdev->vcinterface = 2;
pdev->vendpoint = 4;
pdev->frame_header_size = 0;
pdev->frame_trailer_size = 0;
} else if (DEVICE_USE_CODEC3(pdev->type)) {
pdev->image_mask = 1 << PSZ_QSIF | 1 << PSZ_SIF | 1 << PSZ_VGA;
pdev->vcinterface = 3;
pdev->vendpoint = 5;
pdev->frame_header_size = TOUCAM_HEADER_SIZE;
pdev->frame_trailer_size = TOUCAM_TRAILER_SIZE;
} else /* if (DEVICE_USE_CODEC2(pdev->type)) */ {
pdev->image_mask = 1 << PSZ_SQCIF | 1 << PSZ_QSIF | 1 << PSZ_QCIF | 1 << PSZ_SIF | 1 << PSZ_CIF | 1 << PSZ_VGA;
pdev->vcinterface = 3;
pdev->vendpoint = 4;
pdev->frame_header_size = 0;
pdev->frame_trailer_size = 0;
}
}
| gpl-2.0 |
syhost/android_kernel_pantech_ef50l | drivers/mca/mca-proc.c | 9882 | 7280 | /* -*- mode: c; c-basic-offset: 8 -*- */
/*
* MCA bus support functions for the proc fs.
*
* NOTE: this code *requires* the legacy MCA api.
*
* Legacy API means the API that operates in terms of MCA slot number
*
* (C) 2002 James Bottomley <James.Bottomley@HansenPartnership.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/module.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/mca.h>
static int get_mca_info_helper(struct mca_device *mca_dev, char *page, int len)
{
int j;
for(j=0; j<8; j++)
len += sprintf(page+len, "%02x ",
mca_dev ? mca_dev->pos[j] : 0xff);
len += sprintf(page+len, " %s\n", mca_dev ? mca_dev->name : "");
return len;
}
static int get_mca_info(char *page, char **start, off_t off,
int count, int *eof, void *data)
{
int i, len = 0;
if(MCA_bus) {
struct mca_device *mca_dev;
/* Format POS registers of eight MCA slots */
for(i=0; i<MCA_MAX_SLOT_NR; i++) {
mca_dev = mca_find_device_by_slot(i);
len += sprintf(page+len, "Slot %d: ", i+1);
len = get_mca_info_helper(mca_dev, page, len);
}
/* Format POS registers of integrated video subsystem */
mca_dev = mca_find_device_by_slot(MCA_INTEGVIDEO);
len += sprintf(page+len, "Video : ");
len = get_mca_info_helper(mca_dev, page, len);
/* Format POS registers of integrated SCSI subsystem */
mca_dev = mca_find_device_by_slot(MCA_INTEGSCSI);
len += sprintf(page+len, "SCSI : ");
len = get_mca_info_helper(mca_dev, page, len);
/* Format POS registers of motherboard */
mca_dev = mca_find_device_by_slot(MCA_MOTHERBOARD);
len += sprintf(page+len, "Planar: ");
len = get_mca_info_helper(mca_dev, page, len);
} else {
/* Leave it empty if MCA not detected - this should *never*
* happen!
*/
}
if (len <= off+count) *eof = 1;
*start = page + off;
len -= off;
if (len>count) len = count;
if (len<0) len = 0;
return len;
}
/*--------------------------------------------------------------------*/
static int mca_default_procfn(char* buf, struct mca_device *mca_dev)
{
int len = 0, i;
int slot = mca_dev->slot;
/* Print out the basic information */
if(slot < MCA_MAX_SLOT_NR) {
len += sprintf(buf+len, "Slot: %d\n", slot+1);
} else if(slot == MCA_INTEGSCSI) {
len += sprintf(buf+len, "Integrated SCSI Adapter\n");
} else if(slot == MCA_INTEGVIDEO) {
len += sprintf(buf+len, "Integrated Video Adapter\n");
} else if(slot == MCA_MOTHERBOARD) {
len += sprintf(buf+len, "Motherboard\n");
}
if (mca_dev->name[0]) {
/* Drivers might register a name without /proc handler... */
len += sprintf(buf+len, "Adapter Name: %s\n",
mca_dev->name);
} else {
len += sprintf(buf+len, "Adapter Name: Unknown\n");
}
len += sprintf(buf+len, "Id: %02x%02x\n",
mca_dev->pos[1], mca_dev->pos[0]);
len += sprintf(buf+len, "Enabled: %s\nPOS: ",
mca_device_status(mca_dev) == MCA_ADAPTER_NORMAL ?
"Yes" : "No");
for(i=0; i<8; i++) {
len += sprintf(buf+len, "%02x ", mca_dev->pos[i]);
}
len += sprintf(buf+len, "\nDriver Installed: %s",
mca_device_claimed(mca_dev) ? "Yes" : "No");
buf[len++] = '\n';
buf[len] = 0;
return len;
} /* mca_default_procfn() */
static int get_mca_machine_info(char* page, char **start, off_t off,
int count, int *eof, void *data)
{
int len = 0;
len += sprintf(page+len, "Model Id: 0x%x\n", machine_id);
len += sprintf(page+len, "Submodel Id: 0x%x\n", machine_submodel_id);
len += sprintf(page+len, "BIOS Revision: 0x%x\n", BIOS_revision);
if (len <= off+count) *eof = 1;
*start = page + off;
len -= off;
if (len>count) len = count;
if (len<0) len = 0;
return len;
}
static int mca_read_proc(char *page, char **start, off_t off,
int count, int *eof, void *data)
{
struct mca_device *mca_dev = (struct mca_device *)data;
int len = 0;
/* Get the standard info */
len = mca_default_procfn(page, mca_dev);
/* Do any device-specific processing, if there is any */
if(mca_dev->procfn) {
len += mca_dev->procfn(page+len, mca_dev->slot,
mca_dev->proc_dev);
}
if (len <= off+count) *eof = 1;
*start = page + off;
len -= off;
if (len>count) len = count;
if (len<0) len = 0;
return len;
} /* mca_read_proc() */
/*--------------------------------------------------------------------*/
void __init mca_do_proc_init(void)
{
int i;
struct proc_dir_entry *proc_mca;
struct proc_dir_entry* node = NULL;
struct mca_device *mca_dev;
proc_mca = proc_mkdir("mca", NULL);
create_proc_read_entry("pos",0,proc_mca,get_mca_info,NULL);
create_proc_read_entry("machine",0,proc_mca,get_mca_machine_info,NULL);
/* Initialize /proc/mca entries for existing adapters */
for(i = 0; i < MCA_NUMADAPTERS; i++) {
enum MCA_AdapterStatus status;
mca_dev = mca_find_device_by_slot(i);
if(!mca_dev)
continue;
mca_dev->procfn = NULL;
if(i < MCA_MAX_SLOT_NR) sprintf(mca_dev->procname,"slot%d", i+1);
else if(i == MCA_INTEGVIDEO) sprintf(mca_dev->procname,"video");
else if(i == MCA_INTEGSCSI) sprintf(mca_dev->procname,"scsi");
else if(i == MCA_MOTHERBOARD) sprintf(mca_dev->procname,"planar");
status = mca_device_status(mca_dev);
if (status != MCA_ADAPTER_NORMAL &&
status != MCA_ADAPTER_DISABLED)
continue;
node = create_proc_read_entry(mca_dev->procname, 0, proc_mca,
mca_read_proc, (void *)mca_dev);
if(node == NULL) {
printk("Failed to allocate memory for MCA proc-entries!");
return;
}
}
} /* mca_do_proc_init() */
/**
* mca_set_adapter_procfn - Set the /proc callback
* @slot: slot to configure
* @procfn: callback function to call for /proc
* @dev: device information passed to the callback
*
* This sets up an information callback for /proc/mca/slot?. The
* function is called with the buffer, slot, and device pointer (or
* some equally informative context information, or nothing, if you
* prefer), and is expected to put useful information into the
* buffer. The adapter name, ID, and POS registers get printed
* before this is called though, so don't do it again.
*
* This should be called with a %NULL @procfn when a module
* unregisters, thus preventing kernel crashes and other such
* nastiness.
*/
void mca_set_adapter_procfn(int slot, MCA_ProcFn procfn, void* proc_dev)
{
struct mca_device *mca_dev = mca_find_device_by_slot(slot);
if(!mca_dev)
return;
mca_dev->procfn = procfn;
mca_dev->proc_dev = proc_dev;
}
EXPORT_SYMBOL(mca_set_adapter_procfn);
| gpl-2.0 |
cphelps76/DEMENTED_kernel_jf | drivers/net/ethernet/dec/tulip/21142.c | 10394 | 8242 | /*
drivers/net/ethernet/dec/tulip/21142.c
Copyright 2000,2001 The Linux Kernel Team
Written/copyright 1994-2001 by Donald Becker.
This software may be used and distributed according to the terms
of the GNU General Public License, incorporated herein by reference.
DC21143 manual "21143 PCI/CardBus 10/100Mb/s Ethernet LAN Controller
Hardware Reference Manual" is currently available at :
http://developer.intel.com/design/network/manuals/278074.htm
Please submit bugs to http://bugzilla.kernel.org/ .
*/
#include <linux/delay.h>
#include "tulip.h"
static u16 t21142_csr13[] = { 0x0001, 0x0009, 0x0009, 0x0000, 0x0001, };
u16 t21142_csr14[] = { 0xFFFF, 0x0705, 0x0705, 0x0000, 0x7F3D, };
static u16 t21142_csr15[] = { 0x0008, 0x0006, 0x000E, 0x0008, 0x0008, };
/* Handle the 21143 uniquely: do autoselect with NWay, not the EEPROM list
of available transceivers. */
void t21142_media_task(struct work_struct *work)
{
struct tulip_private *tp =
container_of(work, struct tulip_private, media_work);
struct net_device *dev = tp->dev;
void __iomem *ioaddr = tp->base_addr;
int csr12 = ioread32(ioaddr + CSR12);
int next_tick = 60*HZ;
int new_csr6 = 0;
int csr14 = ioread32(ioaddr + CSR14);
/* CSR12[LS10,LS100] are not reliable during autonegotiation */
if ((csr14 & 0x80) && (csr12 & 0x7000) != 0x5000)
csr12 |= 6;
if (tulip_debug > 2)
dev_info(&dev->dev, "21143 negotiation status %08x, %s\n",
csr12, medianame[dev->if_port]);
if (tulip_media_cap[dev->if_port] & MediaIsMII) {
if (tulip_check_duplex(dev) < 0) {
netif_carrier_off(dev);
next_tick = 3*HZ;
} else {
netif_carrier_on(dev);
next_tick = 60*HZ;
}
} else if (tp->nwayset) {
/* Don't screw up a negotiated session! */
if (tulip_debug > 1)
dev_info(&dev->dev,
"Using NWay-set %s media, csr12 %08x\n",
medianame[dev->if_port], csr12);
} else if (tp->medialock) {
;
} else if (dev->if_port == 3) {
if (csr12 & 2) { /* No 100mbps link beat, revert to 10mbps. */
if (tulip_debug > 1)
dev_info(&dev->dev,
"No 21143 100baseTx link beat, %08x, trying NWay\n",
csr12);
t21142_start_nway(dev);
next_tick = 3*HZ;
}
} else if ((csr12 & 0x7000) != 0x5000) {
/* Negotiation failed. Search media types. */
if (tulip_debug > 1)
dev_info(&dev->dev,
"21143 negotiation failed, status %08x\n",
csr12);
if (!(csr12 & 4)) { /* 10mbps link beat good. */
new_csr6 = 0x82420000;
dev->if_port = 0;
iowrite32(0, ioaddr + CSR13);
iowrite32(0x0003FFFF, ioaddr + CSR14);
iowrite16(t21142_csr15[dev->if_port], ioaddr + CSR15);
iowrite32(t21142_csr13[dev->if_port], ioaddr + CSR13);
} else {
/* Select 100mbps port to check for link beat. */
new_csr6 = 0x83860000;
dev->if_port = 3;
iowrite32(0, ioaddr + CSR13);
iowrite32(0x0003FFFF, ioaddr + CSR14);
iowrite16(8, ioaddr + CSR15);
iowrite32(1, ioaddr + CSR13);
}
if (tulip_debug > 1)
dev_info(&dev->dev, "Testing new 21143 media %s\n",
medianame[dev->if_port]);
if (new_csr6 != (tp->csr6 & ~0x00D5)) {
tp->csr6 &= 0x00D5;
tp->csr6 |= new_csr6;
iowrite32(0x0301, ioaddr + CSR12);
tulip_restart_rxtx(tp);
}
next_tick = 3*HZ;
}
/* mod_timer synchronizes us with potential add_timer calls
* from interrupts.
*/
mod_timer(&tp->timer, RUN_AT(next_tick));
}
void t21142_start_nway(struct net_device *dev)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
int csr14 = ((tp->sym_advertise & 0x0780) << 9) |
((tp->sym_advertise & 0x0020) << 1) | 0xffbf;
dev->if_port = 0;
tp->nway = tp->mediasense = 1;
tp->nwayset = tp->lpar = 0;
if (tulip_debug > 1)
netdev_dbg(dev, "Restarting 21143 autonegotiation, csr14=%08x\n",
csr14);
iowrite32(0x0001, ioaddr + CSR13);
udelay(100);
iowrite32(csr14, ioaddr + CSR14);
tp->csr6 = 0x82420000 | (tp->sym_advertise & 0x0040 ? FullDuplex : 0);
iowrite32(tp->csr6, ioaddr + CSR6);
if (tp->mtable && tp->mtable->csr15dir) {
iowrite32(tp->mtable->csr15dir, ioaddr + CSR15);
iowrite32(tp->mtable->csr15val, ioaddr + CSR15);
} else
iowrite16(0x0008, ioaddr + CSR15);
iowrite32(0x1301, ioaddr + CSR12); /* Trigger NWAY. */
}
void t21142_lnk_change(struct net_device *dev, int csr5)
{
struct tulip_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->base_addr;
int csr12 = ioread32(ioaddr + CSR12);
int csr14 = ioread32(ioaddr + CSR14);
/* CSR12[LS10,LS100] are not reliable during autonegotiation */
if ((csr14 & 0x80) && (csr12 & 0x7000) != 0x5000)
csr12 |= 6;
if (tulip_debug > 1)
dev_info(&dev->dev,
"21143 link status interrupt %08x, CSR5 %x, %08x\n",
csr12, csr5, csr14);
/* If NWay finished and we have a negotiated partner capability. */
if (tp->nway && !tp->nwayset && (csr12 & 0x7000) == 0x5000) {
int setup_done = 0;
int negotiated = tp->sym_advertise & (csr12 >> 16);
tp->lpar = csr12 >> 16;
tp->nwayset = 1;
/* If partner cannot negotiate, it is 10Mbps Half Duplex */
if (!(csr12 & 0x8000)) dev->if_port = 0;
else if (negotiated & 0x0100) dev->if_port = 5;
else if (negotiated & 0x0080) dev->if_port = 3;
else if (negotiated & 0x0040) dev->if_port = 4;
else if (negotiated & 0x0020) dev->if_port = 0;
else {
tp->nwayset = 0;
if ((csr12 & 2) == 0 && (tp->sym_advertise & 0x0180))
dev->if_port = 3;
}
tp->full_duplex = (tulip_media_cap[dev->if_port] & MediaAlwaysFD) ? 1:0;
if (tulip_debug > 1) {
if (tp->nwayset)
dev_info(&dev->dev,
"Switching to %s based on link negotiation %04x & %04x = %04x\n",
medianame[dev->if_port],
tp->sym_advertise, tp->lpar,
negotiated);
else
dev_info(&dev->dev,
"Autonegotiation failed, using %s, link beat status %04x\n",
medianame[dev->if_port], csr12);
}
if (tp->mtable) {
int i;
for (i = 0; i < tp->mtable->leafcount; i++)
if (tp->mtable->mleaf[i].media == dev->if_port) {
int startup = ! ((tp->chip_id == DC21143 && (tp->revision == 48 || tp->revision == 65)));
tp->cur_index = i;
tulip_select_media(dev, startup);
setup_done = 1;
break;
}
}
if ( ! setup_done) {
tp->csr6 = (dev->if_port & 1 ? 0x838E0000 : 0x82420000) | (tp->csr6 & 0x20ff);
if (tp->full_duplex)
tp->csr6 |= 0x0200;
iowrite32(1, ioaddr + CSR13);
}
#if 0 /* Restart shouldn't be needed. */
iowrite32(tp->csr6 | RxOn, ioaddr + CSR6);
if (tulip_debug > 2)
netdev_dbg(dev, " Restarting Tx and Rx, CSR5 is %08x\n",
ioread32(ioaddr + CSR5));
#endif
tulip_start_rxtx(tp);
if (tulip_debug > 2)
netdev_dbg(dev, " Setting CSR6 %08x/%x CSR12 %08x\n",
tp->csr6, ioread32(ioaddr + CSR6),
ioread32(ioaddr + CSR12));
} else if ((tp->nwayset && (csr5 & 0x08000000) &&
(dev->if_port == 3 || dev->if_port == 5) &&
(csr12 & 2) == 2) ||
(tp->nway && (csr5 & (TPLnkFail)))) {
/* Link blew? Maybe restart NWay. */
del_timer_sync(&tp->timer);
t21142_start_nway(dev);
tp->timer.expires = RUN_AT(3*HZ);
add_timer(&tp->timer);
} else if (dev->if_port == 3 || dev->if_port == 5) {
if (tulip_debug > 1)
dev_info(&dev->dev, "21143 %s link beat %s\n",
medianame[dev->if_port],
(csr12 & 2) ? "failed" : "good");
if ((csr12 & 2) && ! tp->medialock) {
del_timer_sync(&tp->timer);
t21142_start_nway(dev);
tp->timer.expires = RUN_AT(3*HZ);
add_timer(&tp->timer);
} else if (dev->if_port == 5)
iowrite32(csr14 & ~0x080, ioaddr + CSR14);
} else if (dev->if_port == 0 || dev->if_port == 4) {
if ((csr12 & 4) == 0)
dev_info(&dev->dev, "21143 10baseT link beat good\n");
} else if (!(csr12 & 4)) { /* 10mbps link beat good. */
if (tulip_debug)
dev_info(&dev->dev, "21143 10mbps sensed media\n");
dev->if_port = 0;
} else if (tp->nwayset) {
if (tulip_debug)
dev_info(&dev->dev, "21143 using NWay-set %s, csr6 %08x\n",
medianame[dev->if_port], tp->csr6);
} else { /* 100mbps link beat good. */
if (tulip_debug)
dev_info(&dev->dev, "21143 100baseTx sensed media\n");
dev->if_port = 3;
tp->csr6 = 0x838E0000 | (tp->csr6 & 0x20ff);
iowrite32(0x0003FF7F, ioaddr + CSR14);
iowrite32(0x0301, ioaddr + CSR12);
tulip_restart_rxtx(tp);
}
}
| gpl-2.0 |
kerneldevs/caf-kernel | sound/synth/emux/emux_nrpn.c | 14234 | 9938 | /*
* NRPN / SYSEX callbacks for Emu8k/Emu10k1
*
* Copyright (c) 1999-2000 Takashi Iwai <tiwai@suse.de>
*
* 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 "emux_voice.h"
#include <sound/asoundef.h>
/*
* conversion from NRPN/control parameters to Emu8000 raw parameters
*/
/* NRPN / CC -> Emu8000 parameter converter */
struct nrpn_conv_table {
int control;
int effect;
int (*convert)(int val);
};
/* effect sensitivity */
#define FX_CUTOFF 0
#define FX_RESONANCE 1
#define FX_ATTACK 2
#define FX_RELEASE 3
#define FX_VIBRATE 4
#define FX_VIBDEPTH 5
#define FX_VIBDELAY 6
#define FX_NUMS 7
/*
* convert NRPN/control values
*/
static int send_converted_effect(struct nrpn_conv_table *table, int num_tables,
struct snd_emux_port *port,
struct snd_midi_channel *chan,
int type, int val, int mode)
{
int i, cval;
for (i = 0; i < num_tables; i++) {
if (table[i].control == type) {
cval = table[i].convert(val);
snd_emux_send_effect(port, chan, table[i].effect,
cval, mode);
return 1;
}
}
return 0;
}
#define DEF_FX_CUTOFF 170
#define DEF_FX_RESONANCE 6
#define DEF_FX_ATTACK 50
#define DEF_FX_RELEASE 50
#define DEF_FX_VIBRATE 30
#define DEF_FX_VIBDEPTH 4
#define DEF_FX_VIBDELAY 1500
/* effect sensitivities for GS NRPN:
* adjusted for chaos 8MB soundfonts
*/
static int gs_sense[] =
{
DEF_FX_CUTOFF, DEF_FX_RESONANCE, DEF_FX_ATTACK, DEF_FX_RELEASE,
DEF_FX_VIBRATE, DEF_FX_VIBDEPTH, DEF_FX_VIBDELAY
};
/* effect sensitivies for XG controls:
* adjusted for chaos 8MB soundfonts
*/
static int xg_sense[] =
{
DEF_FX_CUTOFF, DEF_FX_RESONANCE, DEF_FX_ATTACK, DEF_FX_RELEASE,
DEF_FX_VIBRATE, DEF_FX_VIBDEPTH, DEF_FX_VIBDELAY
};
/*
* AWE32 NRPN effects
*/
static int fx_delay(int val);
static int fx_attack(int val);
static int fx_hold(int val);
static int fx_decay(int val);
static int fx_the_value(int val);
static int fx_twice_value(int val);
static int fx_conv_pitch(int val);
static int fx_conv_Q(int val);
/* function for each NRPN */ /* [range] units */
#define fx_env1_delay fx_delay /* [0,5900] 4msec */
#define fx_env1_attack fx_attack /* [0,5940] 1msec */
#define fx_env1_hold fx_hold /* [0,8191] 1msec */
#define fx_env1_decay fx_decay /* [0,5940] 4msec */
#define fx_env1_release fx_decay /* [0,5940] 4msec */
#define fx_env1_sustain fx_the_value /* [0,127] 0.75dB */
#define fx_env1_pitch fx_the_value /* [-127,127] 9.375cents */
#define fx_env1_cutoff fx_the_value /* [-127,127] 56.25cents */
#define fx_env2_delay fx_delay /* [0,5900] 4msec */
#define fx_env2_attack fx_attack /* [0,5940] 1msec */
#define fx_env2_hold fx_hold /* [0,8191] 1msec */
#define fx_env2_decay fx_decay /* [0,5940] 4msec */
#define fx_env2_release fx_decay /* [0,5940] 4msec */
#define fx_env2_sustain fx_the_value /* [0,127] 0.75dB */
#define fx_lfo1_delay fx_delay /* [0,5900] 4msec */
#define fx_lfo1_freq fx_twice_value /* [0,127] 84mHz */
#define fx_lfo1_volume fx_twice_value /* [0,127] 0.1875dB */
#define fx_lfo1_pitch fx_the_value /* [-127,127] 9.375cents */
#define fx_lfo1_cutoff fx_twice_value /* [-64,63] 56.25cents */
#define fx_lfo2_delay fx_delay /* [0,5900] 4msec */
#define fx_lfo2_freq fx_twice_value /* [0,127] 84mHz */
#define fx_lfo2_pitch fx_the_value /* [-127,127] 9.375cents */
#define fx_init_pitch fx_conv_pitch /* [-8192,8192] cents */
#define fx_chorus fx_the_value /* [0,255] -- */
#define fx_reverb fx_the_value /* [0,255] -- */
#define fx_cutoff fx_twice_value /* [0,127] 62Hz */
#define fx_filterQ fx_conv_Q /* [0,127] -- */
static int fx_delay(int val)
{
return (unsigned short)snd_sf_calc_parm_delay(val);
}
static int fx_attack(int val)
{
return (unsigned short)snd_sf_calc_parm_attack(val);
}
static int fx_hold(int val)
{
return (unsigned short)snd_sf_calc_parm_hold(val);
}
static int fx_decay(int val)
{
return (unsigned short)snd_sf_calc_parm_decay(val);
}
static int fx_the_value(int val)
{
return (unsigned short)(val & 0xff);
}
static int fx_twice_value(int val)
{
return (unsigned short)((val * 2) & 0xff);
}
static int fx_conv_pitch(int val)
{
return (short)(val * 4096 / 1200);
}
static int fx_conv_Q(int val)
{
return (unsigned short)((val / 8) & 0xff);
}
static struct nrpn_conv_table awe_effects[] =
{
{ 0, EMUX_FX_LFO1_DELAY, fx_lfo1_delay},
{ 1, EMUX_FX_LFO1_FREQ, fx_lfo1_freq},
{ 2, EMUX_FX_LFO2_DELAY, fx_lfo2_delay},
{ 3, EMUX_FX_LFO2_FREQ, fx_lfo2_freq},
{ 4, EMUX_FX_ENV1_DELAY, fx_env1_delay},
{ 5, EMUX_FX_ENV1_ATTACK,fx_env1_attack},
{ 6, EMUX_FX_ENV1_HOLD, fx_env1_hold},
{ 7, EMUX_FX_ENV1_DECAY, fx_env1_decay},
{ 8, EMUX_FX_ENV1_SUSTAIN, fx_env1_sustain},
{ 9, EMUX_FX_ENV1_RELEASE, fx_env1_release},
{10, EMUX_FX_ENV2_DELAY, fx_env2_delay},
{11, EMUX_FX_ENV2_ATTACK, fx_env2_attack},
{12, EMUX_FX_ENV2_HOLD, fx_env2_hold},
{13, EMUX_FX_ENV2_DECAY, fx_env2_decay},
{14, EMUX_FX_ENV2_SUSTAIN, fx_env2_sustain},
{15, EMUX_FX_ENV2_RELEASE, fx_env2_release},
{16, EMUX_FX_INIT_PITCH, fx_init_pitch},
{17, EMUX_FX_LFO1_PITCH, fx_lfo1_pitch},
{18, EMUX_FX_LFO2_PITCH, fx_lfo2_pitch},
{19, EMUX_FX_ENV1_PITCH, fx_env1_pitch},
{20, EMUX_FX_LFO1_VOLUME, fx_lfo1_volume},
{21, EMUX_FX_CUTOFF, fx_cutoff},
{22, EMUX_FX_FILTERQ, fx_filterQ},
{23, EMUX_FX_LFO1_CUTOFF, fx_lfo1_cutoff},
{24, EMUX_FX_ENV1_CUTOFF, fx_env1_cutoff},
{25, EMUX_FX_CHORUS, fx_chorus},
{26, EMUX_FX_REVERB, fx_reverb},
};
/*
* GS(SC88) NRPN effects; still experimental
*/
/* cutoff: quarter semitone step, max=255 */
static int gs_cutoff(int val)
{
return (val - 64) * gs_sense[FX_CUTOFF] / 50;
}
/* resonance: 0 to 15(max) */
static int gs_filterQ(int val)
{
return (val - 64) * gs_sense[FX_RESONANCE] / 50;
}
/* attack: */
static int gs_attack(int val)
{
return -(val - 64) * gs_sense[FX_ATTACK] / 50;
}
/* decay: */
static int gs_decay(int val)
{
return -(val - 64) * gs_sense[FX_RELEASE] / 50;
}
/* release: */
static int gs_release(int val)
{
return -(val - 64) * gs_sense[FX_RELEASE] / 50;
}
/* vibrato freq: 0.042Hz step, max=255 */
static int gs_vib_rate(int val)
{
return (val - 64) * gs_sense[FX_VIBRATE] / 50;
}
/* vibrato depth: max=127, 1 octave */
static int gs_vib_depth(int val)
{
return (val - 64) * gs_sense[FX_VIBDEPTH] / 50;
}
/* vibrato delay: -0.725msec step */
static int gs_vib_delay(int val)
{
return -(val - 64) * gs_sense[FX_VIBDELAY] / 50;
}
static struct nrpn_conv_table gs_effects[] =
{
{32, EMUX_FX_CUTOFF, gs_cutoff},
{33, EMUX_FX_FILTERQ, gs_filterQ},
{99, EMUX_FX_ENV2_ATTACK, gs_attack},
{100, EMUX_FX_ENV2_DECAY, gs_decay},
{102, EMUX_FX_ENV2_RELEASE, gs_release},
{8, EMUX_FX_LFO1_FREQ, gs_vib_rate},
{9, EMUX_FX_LFO1_VOLUME, gs_vib_depth},
{10, EMUX_FX_LFO1_DELAY, gs_vib_delay},
};
/*
* NRPN events
*/
void
snd_emux_nrpn(void *p, struct snd_midi_channel *chan,
struct snd_midi_channel_set *chset)
{
struct snd_emux_port *port;
port = p;
if (snd_BUG_ON(!port || !chan))
return;
if (chan->control[MIDI_CTL_NONREG_PARM_NUM_MSB] == 127 &&
chan->control[MIDI_CTL_NONREG_PARM_NUM_LSB] <= 26) {
int val;
/* Win/DOS AWE32 specific NRPNs */
/* both MSB/LSB necessary */
val = (chan->control[MIDI_CTL_MSB_DATA_ENTRY] << 7) |
chan->control[MIDI_CTL_LSB_DATA_ENTRY];
val -= 8192;
send_converted_effect
(awe_effects, ARRAY_SIZE(awe_effects),
port, chan, chan->control[MIDI_CTL_NONREG_PARM_NUM_LSB],
val, EMUX_FX_FLAG_SET);
return;
}
if (port->chset.midi_mode == SNDRV_MIDI_MODE_GS &&
chan->control[MIDI_CTL_NONREG_PARM_NUM_MSB] == 1) {
int val;
/* GS specific NRPNs */
/* only MSB is valid */
val = chan->control[MIDI_CTL_MSB_DATA_ENTRY];
send_converted_effect
(gs_effects, ARRAY_SIZE(gs_effects),
port, chan, chan->control[MIDI_CTL_NONREG_PARM_NUM_LSB],
val, EMUX_FX_FLAG_ADD);
return;
}
}
/*
* XG control effects; still experimental
*/
/* cutoff: quarter semitone step, max=255 */
static int xg_cutoff(int val)
{
return (val - 64) * xg_sense[FX_CUTOFF] / 64;
}
/* resonance: 0(open) to 15(most nasal) */
static int xg_filterQ(int val)
{
return (val - 64) * xg_sense[FX_RESONANCE] / 64;
}
/* attack: */
static int xg_attack(int val)
{
return -(val - 64) * xg_sense[FX_ATTACK] / 64;
}
/* release: */
static int xg_release(int val)
{
return -(val - 64) * xg_sense[FX_RELEASE] / 64;
}
static struct nrpn_conv_table xg_effects[] =
{
{71, EMUX_FX_CUTOFF, xg_cutoff},
{74, EMUX_FX_FILTERQ, xg_filterQ},
{72, EMUX_FX_ENV2_RELEASE, xg_release},
{73, EMUX_FX_ENV2_ATTACK, xg_attack},
};
int
snd_emux_xg_control(struct snd_emux_port *port, struct snd_midi_channel *chan,
int param)
{
return send_converted_effect(xg_effects, ARRAY_SIZE(xg_effects),
port, chan, param,
chan->control[param],
EMUX_FX_FLAG_ADD);
}
/*
* receive sysex
*/
void
snd_emux_sysex(void *p, unsigned char *buf, int len, int parsed,
struct snd_midi_channel_set *chset)
{
struct snd_emux_port *port;
struct snd_emux *emu;
port = p;
if (snd_BUG_ON(!port || !chset))
return;
emu = port->emu;
switch (parsed) {
case SNDRV_MIDI_SYSEX_GS_MASTER_VOLUME:
snd_emux_update_port(port, SNDRV_EMUX_UPDATE_VOLUME);
break;
default:
if (emu->ops.sysex)
emu->ops.sysex(emu, buf, len, parsed, chset);
break;
}
}
| gpl-2.0 |
ocoot/Xiaomi_Kernel_OpenSource | drivers/block/paride/epat.c | 15514 | 7137 | /*
epat.c (c) 1997-8 Grant R. Guenther <grant@torque.net>
Under the terms of the GNU General Public License.
This is the low level protocol driver for the EPAT parallel
to IDE adapter from Shuttle Technologies. This adapter is
used in many popular parallel port disk products such as the
SyQuest EZ drives, the Avatar Shark and the Imation SuperDisk.
*/
/* Changes:
1.01 GRG 1998.05.06 init_proto, release_proto
1.02 Joshua b. Jore CPP(renamed), epat_connect, epat_disconnect
*/
#define EPAT_VERSION "1.02"
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/wait.h>
#include <asm/io.h>
#include "paride.h"
#define j44(a,b) (((a>>4)&0x0f)+(b&0xf0))
#define j53(a,b) (((a>>3)&0x1f)+((b<<4)&0xe0))
static int epatc8;
module_param(epatc8, int, 0);
MODULE_PARM_DESC(epatc8, "support for the Shuttle EP1284 chip, "
"used in any recent Imation SuperDisk (LS-120) drive.");
/* cont = 0 IDE register file
cont = 1 IDE control registers
cont = 2 internal EPAT registers
*/
static int cont_map[3] = { 0x18, 0x10, 0 };
static void epat_write_regr( PIA *pi, int cont, int regr, int val)
{ int r;
r = regr + cont_map[cont];
switch (pi->mode) {
case 0:
case 1:
case 2: w0(0x60+r); w2(1); w0(val); w2(4);
break;
case 3:
case 4:
case 5: w3(0x40+r); w4(val);
break;
}
}
static int epat_read_regr( PIA *pi, int cont, int regr )
{ int a, b, r;
r = regr + cont_map[cont];
switch (pi->mode) {
case 0: w0(r); w2(1); w2(3);
a = r1(); w2(4); b = r1();
return j44(a,b);
case 1: w0(0x40+r); w2(1); w2(4);
a = r1(); b = r2(); w0(0xff);
return j53(a,b);
case 2: w0(0x20+r); w2(1); w2(0x25);
a = r0(); w2(4);
return a;
case 3:
case 4:
case 5: w3(r); w2(0x24); a = r4(); w2(4);
return a;
}
return -1; /* never gets here */
}
static void epat_read_block( PIA *pi, char * buf, int count )
{ int k, ph, a, b;
switch (pi->mode) {
case 0: w0(7); w2(1); w2(3); w0(0xff);
ph = 0;
for(k=0;k<count;k++) {
if (k == count-1) w0(0xfd);
w2(6+ph); a = r1();
if (a & 8) b = a;
else { w2(4+ph); b = r1(); }
buf[k] = j44(a,b);
ph = 1 - ph;
}
w0(0); w2(4);
break;
case 1: w0(0x47); w2(1); w2(5); w0(0xff);
ph = 0;
for(k=0;k<count;k++) {
if (k == count-1) w0(0xfd);
w2(4+ph);
a = r1(); b = r2();
buf[k] = j53(a,b);
ph = 1 - ph;
}
w0(0); w2(4);
break;
case 2: w0(0x27); w2(1); w2(0x25); w0(0);
ph = 0;
for(k=0;k<count-1;k++) {
w2(0x24+ph);
buf[k] = r0();
ph = 1 - ph;
}
w2(0x26); w2(0x27); buf[count-1] = r0();
w2(0x25); w2(4);
break;
case 3: w3(0x80); w2(0x24);
for(k=0;k<count-1;k++) buf[k] = r4();
w2(4); w3(0xa0); w2(0x24); buf[count-1] = r4();
w2(4);
break;
case 4: w3(0x80); w2(0x24);
for(k=0;k<(count/2)-1;k++) ((u16 *)buf)[k] = r4w();
buf[count-2] = r4();
w2(4); w3(0xa0); w2(0x24); buf[count-1] = r4();
w2(4);
break;
case 5: w3(0x80); w2(0x24);
for(k=0;k<(count/4)-1;k++) ((u32 *)buf)[k] = r4l();
for(k=count-4;k<count-1;k++) buf[k] = r4();
w2(4); w3(0xa0); w2(0x24); buf[count-1] = r4();
w2(4);
break;
}
}
static void epat_write_block( PIA *pi, char * buf, int count )
{ int ph, k;
switch (pi->mode) {
case 0:
case 1:
case 2: w0(0x67); w2(1); w2(5);
ph = 0;
for(k=0;k<count;k++) {
w0(buf[k]);
w2(4+ph);
ph = 1 - ph;
}
w2(7); w2(4);
break;
case 3: w3(0xc0);
for(k=0;k<count;k++) w4(buf[k]);
w2(4);
break;
case 4: w3(0xc0);
for(k=0;k<(count/2);k++) w4w(((u16 *)buf)[k]);
w2(4);
break;
case 5: w3(0xc0);
for(k=0;k<(count/4);k++) w4l(((u32 *)buf)[k]);
w2(4);
break;
}
}
/* these macros access the EPAT registers in native addressing */
#define WR(r,v) epat_write_regr(pi,2,r,v)
#define RR(r) (epat_read_regr(pi,2,r))
/* and these access the IDE task file */
#define WRi(r,v) epat_write_regr(pi,0,r,v)
#define RRi(r) (epat_read_regr(pi,0,r))
/* FIXME: the CPP stuff should be fixed to handle multiple EPATs on a chain */
#define CPP(x) w2(4);w0(0x22);w0(0xaa);w0(0x55);w0(0);w0(0xff);\
w0(0x87);w0(0x78);w0(x);w2(4);w2(5);w2(4);w0(0xff);
static void epat_connect ( PIA *pi )
{ pi->saved_r0 = r0();
pi->saved_r2 = r2();
/* Initialize the chip */
CPP(0);
if (epatc8) {
CPP(0x40);CPP(0xe0);
w0(0);w2(1);w2(4);
WR(0x8,0x12);WR(0xc,0x14);WR(0x12,0x10);
WR(0xe,0xf);WR(0xf,4);
/* WR(0xe,0xa);WR(0xf,4); */
WR(0xe,0xd);WR(0xf,0);
/* CPP(0x30); */
}
/* Connect to the chip */
CPP(0xe0);
w0(0);w2(1);w2(4); /* Idle into SPP */
if (pi->mode >= 3) {
w0(0);w2(1);w2(4);w2(0xc);
/* Request EPP */
w0(0x40);w2(6);w2(7);w2(4);w2(0xc);w2(4);
}
if (!epatc8) {
WR(8,0x10); WR(0xc,0x14); WR(0xa,0x38); WR(0x12,0x10);
}
}
static void epat_disconnect (PIA *pi)
{ CPP(0x30);
w0(pi->saved_r0);
w2(pi->saved_r2);
}
static int epat_test_proto( PIA *pi, char * scratch, int verbose )
{ int k, j, f, cc;
int e[2] = {0,0};
epat_connect(pi);
cc = RR(0xd);
epat_disconnect(pi);
epat_connect(pi);
for (j=0;j<2;j++) {
WRi(6,0xa0+j*0x10);
for (k=0;k<256;k++) {
WRi(2,k^0xaa);
WRi(3,k^0x55);
if (RRi(2) != (k^0xaa)) e[j]++;
}
}
epat_disconnect(pi);
f = 0;
epat_connect(pi);
WR(0x13,1); WR(0x13,0); WR(0xa,0x11);
epat_read_block(pi,scratch,512);
for (k=0;k<256;k++) {
if ((scratch[2*k] & 0xff) != k) f++;
if ((scratch[2*k+1] & 0xff) != (0xff-k)) f++;
}
epat_disconnect(pi);
if (verbose) {
printk("%s: epat: port 0x%x, mode %d, ccr %x, test=(%d,%d,%d)\n",
pi->device,pi->port,pi->mode,cc,e[0],e[1],f);
}
return (e[0] && e[1]) || f;
}
static void epat_log_adapter( PIA *pi, char * scratch, int verbose )
{ int ver;
char *mode_string[6] =
{"4-bit","5/3","8-bit","EPP-8","EPP-16","EPP-32"};
epat_connect(pi);
WR(0xa,0x38); /* read the version code */
ver = RR(0xb);
epat_disconnect(pi);
printk("%s: epat %s, Shuttle EPAT chip %x at 0x%x, ",
pi->device,EPAT_VERSION,ver,pi->port);
printk("mode %d (%s), delay %d\n",pi->mode,
mode_string[pi->mode],pi->delay);
}
static struct pi_protocol epat = {
.owner = THIS_MODULE,
.name = "epat",
.max_mode = 6,
.epp_first = 3,
.default_delay = 1,
.max_units = 1,
.write_regr = epat_write_regr,
.read_regr = epat_read_regr,
.write_block = epat_write_block,
.read_block = epat_read_block,
.connect = epat_connect,
.disconnect = epat_disconnect,
.test_proto = epat_test_proto,
.log_adapter = epat_log_adapter,
};
static int __init epat_init(void)
{
#ifdef CONFIG_PARIDE_EPATC8
epatc8 = 1;
#endif
return paride_register(&epat);
}
static void __exit epat_exit(void)
{
paride_unregister(&epat);
}
MODULE_LICENSE("GPL");
module_init(epat_init)
module_exit(epat_exit)
| gpl-2.0 |
EZchip/gdb | opcodes/m32r-opinst.c | 155 | 33716 | /* Semantic operand instances for m32r.
THIS FILE IS MACHINE GENERATED WITH CGEN.
Copyright 1996-2010 Free Software Foundation, Inc.
This file is part of the GNU Binutils and/or GDB, the GNU debugger.
This file 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 3, or (at your option)
any later version.
It 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 "sysdep.h"
#include "ansidecl.h"
#include "bfd.h"
#include "symcat.h"
#include "m32r-desc.h"
#include "m32r-opc.h"
/* Operand references. */
#define OP_ENT(op) M32R_OPERAND_##op
#define INPUT CGEN_OPINST_INPUT
#define OUTPUT CGEN_OPINST_OUTPUT
#define END CGEN_OPINST_END
#define COND_REF CGEN_OPINST_COND_REF
static const CGEN_OPINST sfmt_empty_ops[] ATTRIBUTE_UNUSED = {
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_add_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_add3_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "slo16", HW_H_SLO16, CGEN_MODE_INT, OP_ENT (SLO16), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_and3_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ INPUT, "uimm16", HW_H_UINT, CGEN_MODE_UINT, OP_ENT (UIMM16), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_or3_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ INPUT, "ulo16", HW_H_ULO16, CGEN_MODE_UINT, OP_ENT (ULO16), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_addi_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ INPUT, "simm8", HW_H_SINT, CGEN_MODE_INT, OP_ENT (SIMM8), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_addv_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_addv3_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "simm16", HW_H_SINT, CGEN_MODE_INT, OP_ENT (SIMM16), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_addx_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ INPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_bc8_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ INPUT, "disp8", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP8), 0, COND_REF },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, COND_REF },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_bc24_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ INPUT, "disp24", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP24), 0, COND_REF },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, COND_REF },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_beq_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "disp16", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP16), 0, COND_REF },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, COND_REF },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_beqz_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "disp16", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP16), 0, COND_REF },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, COND_REF },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_bl8_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "disp8", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP8), 0, 0 },
{ INPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ OUTPUT, "h_gr_SI_14", HW_H_GR, CGEN_MODE_SI, 0, 14, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_bl24_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "disp24", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP24), 0, 0 },
{ INPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ OUTPUT, "h_gr_SI_14", HW_H_GR, CGEN_MODE_SI, 0, 14, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_bcl8_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ INPUT, "disp8", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP8), 0, COND_REF },
{ INPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, COND_REF },
{ OUTPUT, "h_gr_SI_14", HW_H_GR, CGEN_MODE_SI, 0, 14, COND_REF },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, COND_REF },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_bcl24_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ INPUT, "disp24", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP24), 0, COND_REF },
{ INPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, COND_REF },
{ OUTPUT, "h_gr_SI_14", HW_H_GR, CGEN_MODE_SI, 0, 14, COND_REF },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, COND_REF },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_bra8_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "disp8", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP8), 0, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_bra24_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "disp24", HW_H_IADDR, CGEN_MODE_USI, OP_ENT (DISP24), 0, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_cmp_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_cmpi_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "simm16", HW_H_SINT, CGEN_MODE_INT, OP_ENT (SIMM16), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_cmpz_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_div_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, COND_REF },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, COND_REF },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_jc_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, COND_REF },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, COND_REF },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_jl_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "h_gr_SI_14", HW_H_GR, CGEN_MODE_SI, 0, 14, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_jmp_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ld_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_memory_SI_sr", HW_H_MEMORY, CGEN_MODE_SI, 0, 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ld_d_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_memory_SI_add__SI_sr_slo16", HW_H_MEMORY, CGEN_MODE_SI, 0, 0, 0 },
{ INPUT, "slo16", HW_H_SLO16, CGEN_MODE_INT, OP_ENT (SLO16), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ldb_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_memory_QI_sr", HW_H_MEMORY, CGEN_MODE_QI, 0, 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ldb_d_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_memory_QI_add__SI_sr_slo16", HW_H_MEMORY, CGEN_MODE_QI, 0, 0, 0 },
{ INPUT, "slo16", HW_H_SLO16, CGEN_MODE_INT, OP_ENT (SLO16), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ldh_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_memory_HI_sr", HW_H_MEMORY, CGEN_MODE_HI, 0, 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ldh_d_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_memory_HI_add__SI_sr_slo16", HW_H_MEMORY, CGEN_MODE_HI, 0, 0, 0 },
{ INPUT, "slo16", HW_H_SLO16, CGEN_MODE_INT, OP_ENT (SLO16), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ld_plus_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_memory_SI_sr", HW_H_MEMORY, CGEN_MODE_SI, 0, 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ OUTPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ld24_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "uimm24", HW_H_ADDR, CGEN_MODE_USI, OP_ENT (UIMM24), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ldi8_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "simm8", HW_H_SINT, CGEN_MODE_INT, OP_ENT (SIMM8), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_ldi16_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "slo16", HW_H_SLO16, CGEN_MODE_INT, OP_ENT (SLO16), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_lock_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_memory_SI_sr", HW_H_MEMORY, CGEN_MODE_SI, 0, 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ OUTPUT, "h_lock_BI", HW_H_LOCK, CGEN_MODE_BI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_machi_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "accum", HW_H_ACCUM, CGEN_MODE_DI, 0, 0, 0 },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "accum", HW_H_ACCUM, CGEN_MODE_DI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_machi_a_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "acc", HW_H_ACCUMS, CGEN_MODE_DI, OP_ENT (ACC), 0, 0 },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "acc", HW_H_ACCUMS, CGEN_MODE_DI, OP_ENT (ACC), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mulhi_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "accum", HW_H_ACCUM, CGEN_MODE_DI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mulhi_a_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "acc", HW_H_ACCUMS, CGEN_MODE_DI, OP_ENT (ACC), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mv_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mvfachi_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "accum", HW_H_ACCUM, CGEN_MODE_DI, 0, 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mvfachi_a_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "accs", HW_H_ACCUMS, CGEN_MODE_DI, OP_ENT (ACCS), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mvfc_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "scr", HW_H_CR, CGEN_MODE_USI, OP_ENT (SCR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mvtachi_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "accum", HW_H_ACCUM, CGEN_MODE_DI, 0, 0, 0 },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ OUTPUT, "accum", HW_H_ACCUM, CGEN_MODE_DI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mvtachi_a_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "accs", HW_H_ACCUMS, CGEN_MODE_DI, OP_ENT (ACCS), 0, 0 },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ OUTPUT, "accs", HW_H_ACCUMS, CGEN_MODE_DI, OP_ENT (ACCS), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mvtc_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dcr", HW_H_CR, CGEN_MODE_USI, OP_ENT (DCR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_nop_ops[] ATTRIBUTE_UNUSED = {
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_rac_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "accum", HW_H_ACCUM, CGEN_MODE_DI, 0, 0, 0 },
{ OUTPUT, "accum", HW_H_ACCUM, CGEN_MODE_DI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_rac_dsi_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "accs", HW_H_ACCUMS, CGEN_MODE_DI, OP_ENT (ACCS), 0, 0 },
{ INPUT, "imm1", HW_H_UINT, CGEN_MODE_UINT, OP_ENT (IMM1), 0, 0 },
{ OUTPUT, "accd", HW_H_ACCUMS, CGEN_MODE_DI, OP_ENT (ACCD), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_rte_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_bbpsw_UQI", HW_H_BBPSW, CGEN_MODE_UQI, 0, 0, 0 },
{ INPUT, "h_bpsw_UQI", HW_H_BPSW, CGEN_MODE_UQI, 0, 0, 0 },
{ INPUT, "h_cr_USI_14", HW_H_CR, CGEN_MODE_USI, 0, 14, 0 },
{ INPUT, "h_cr_USI_6", HW_H_CR, CGEN_MODE_USI, 0, 6, 0 },
{ OUTPUT, "h_bpsw_UQI", HW_H_BPSW, CGEN_MODE_UQI, 0, 0, 0 },
{ OUTPUT, "h_cr_USI_6", HW_H_CR, CGEN_MODE_USI, 0, 6, 0 },
{ OUTPUT, "h_psw_UQI", HW_H_PSW, CGEN_MODE_UQI, 0, 0, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_seth_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "hi16", HW_H_HI16, CGEN_MODE_UINT, OP_ENT (HI16), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_sll3_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "simm16", HW_H_SINT, CGEN_MODE_INT, OP_ENT (SIMM16), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_slli_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ INPUT, "uimm5", HW_H_UINT, CGEN_MODE_UINT, OP_ENT (UIMM5), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_st_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_memory_SI_src2", HW_H_MEMORY, CGEN_MODE_SI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_st_d_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "slo16", HW_H_SLO16, CGEN_MODE_INT, OP_ENT (SLO16), 0, 0 },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_memory_SI_add__SI_src2_slo16", HW_H_MEMORY, CGEN_MODE_SI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_stb_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_memory_QI_src2", HW_H_MEMORY, CGEN_MODE_QI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_stb_d_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "slo16", HW_H_SLO16, CGEN_MODE_INT, OP_ENT (SLO16), 0, 0 },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_memory_QI_add__SI_src2_slo16", HW_H_MEMORY, CGEN_MODE_QI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_sth_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_memory_HI_src2", HW_H_MEMORY, CGEN_MODE_HI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_sth_d_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "slo16", HW_H_SLO16, CGEN_MODE_INT, OP_ENT (SLO16), 0, 0 },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_memory_HI_add__SI_src2_slo16", HW_H_MEMORY, CGEN_MODE_HI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_st_plus_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_memory_SI_new_src2", HW_H_MEMORY, CGEN_MODE_SI, 0, 0, 0 },
{ OUTPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_sth_plus_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_memory_HI_new_src2", HW_H_MEMORY, CGEN_MODE_HI, 0, 0, 0 },
{ OUTPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_stb_plus_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_memory_QI_new_src2", HW_H_MEMORY, CGEN_MODE_QI, 0, 0, 0 },
{ OUTPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_trap_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_bpsw_UQI", HW_H_BPSW, CGEN_MODE_UQI, 0, 0, 0 },
{ INPUT, "h_cr_USI_6", HW_H_CR, CGEN_MODE_USI, 0, 6, 0 },
{ INPUT, "h_psw_UQI", HW_H_PSW, CGEN_MODE_UQI, 0, 0, 0 },
{ INPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ INPUT, "uimm4", HW_H_UINT, CGEN_MODE_UINT, OP_ENT (UIMM4), 0, 0 },
{ OUTPUT, "h_bbpsw_UQI", HW_H_BBPSW, CGEN_MODE_UQI, 0, 0, 0 },
{ OUTPUT, "h_bpsw_UQI", HW_H_BPSW, CGEN_MODE_UQI, 0, 0, 0 },
{ OUTPUT, "h_cr_USI_14", HW_H_CR, CGEN_MODE_USI, 0, 14, 0 },
{ OUTPUT, "h_cr_USI_6", HW_H_CR, CGEN_MODE_USI, 0, 6, 0 },
{ OUTPUT, "h_psw_UQI", HW_H_PSW, CGEN_MODE_UQI, 0, 0, 0 },
{ OUTPUT, "pc", HW_H_PC, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_unlock_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_lock_BI", HW_H_LOCK, CGEN_MODE_BI, 0, 0, 0 },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, COND_REF },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, COND_REF },
{ OUTPUT, "h_lock_BI", HW_H_LOCK, CGEN_MODE_BI, 0, 0, 0 },
{ OUTPUT, "h_memory_SI_src2", HW_H_MEMORY, CGEN_MODE_SI, 0, 0, COND_REF },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_satb_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_sat_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, COND_REF },
{ OUTPUT, "dr", HW_H_GR, CGEN_MODE_SI, OP_ENT (DR), 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_sadd_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_accums_DI_0", HW_H_ACCUMS, CGEN_MODE_DI, 0, 0, 0 },
{ INPUT, "h_accums_DI_1", HW_H_ACCUMS, CGEN_MODE_DI, 0, 1, 0 },
{ OUTPUT, "h_accums_DI_0", HW_H_ACCUMS, CGEN_MODE_DI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_macwu1_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_accums_DI_1", HW_H_ACCUMS, CGEN_MODE_DI, 0, 1, 0 },
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_accums_DI_1", HW_H_ACCUMS, CGEN_MODE_DI, 0, 1, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_mulwu1_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "src1", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC1), 0, 0 },
{ INPUT, "src2", HW_H_GR, CGEN_MODE_SI, OP_ENT (SRC2), 0, 0 },
{ OUTPUT, "h_accums_DI_1", HW_H_ACCUMS, CGEN_MODE_DI, 0, 1, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_sc_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_clrpsw_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_cr_USI_0", HW_H_CR, CGEN_MODE_USI, 0, 0, 0 },
{ INPUT, "uimm8", HW_H_UINT, CGEN_MODE_UINT, OP_ENT (UIMM8), 0, 0 },
{ OUTPUT, "h_cr_USI_0", HW_H_CR, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_setpsw_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "uimm8", HW_H_UINT, CGEN_MODE_UINT, OP_ENT (UIMM8), 0, 0 },
{ OUTPUT, "h_cr_USI_0", HW_H_CR, CGEN_MODE_USI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_bset_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "h_memory_QI_add__SI_sr_slo16", HW_H_MEMORY, CGEN_MODE_QI, 0, 0, 0 },
{ INPUT, "slo16", HW_H_SLO16, CGEN_MODE_INT, OP_ENT (SLO16), 0, 0 },
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ INPUT, "uimm3", HW_H_UINT, CGEN_MODE_UINT, OP_ENT (UIMM3), 0, 0 },
{ OUTPUT, "h_memory_QI_add__SI_sr_slo16", HW_H_MEMORY, CGEN_MODE_QI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
static const CGEN_OPINST sfmt_btst_ops[] ATTRIBUTE_UNUSED = {
{ INPUT, "sr", HW_H_GR, CGEN_MODE_SI, OP_ENT (SR), 0, 0 },
{ INPUT, "uimm3", HW_H_UINT, CGEN_MODE_UINT, OP_ENT (UIMM3), 0, 0 },
{ OUTPUT, "condbit", HW_H_COND, CGEN_MODE_BI, 0, 0, 0 },
{ END, (const char *)0, (enum cgen_hw_type)0, (enum cgen_mode)0, (enum cgen_operand_type)0, 0, 0 }
};
#undef OP_ENT
#undef INPUT
#undef OUTPUT
#undef END
#undef COND_REF
/* Operand instance lookup table. */
static const CGEN_OPINST *m32r_cgen_opinst_table[MAX_INSNS] = {
0,
& sfmt_add_ops[0],
& sfmt_add3_ops[0],
& sfmt_add_ops[0],
& sfmt_and3_ops[0],
& sfmt_add_ops[0],
& sfmt_or3_ops[0],
& sfmt_add_ops[0],
& sfmt_and3_ops[0],
& sfmt_addi_ops[0],
& sfmt_addv_ops[0],
& sfmt_addv3_ops[0],
& sfmt_addx_ops[0],
& sfmt_bc8_ops[0],
& sfmt_bc24_ops[0],
& sfmt_beq_ops[0],
& sfmt_beqz_ops[0],
& sfmt_beqz_ops[0],
& sfmt_beqz_ops[0],
& sfmt_beqz_ops[0],
& sfmt_beqz_ops[0],
& sfmt_beqz_ops[0],
& sfmt_bl8_ops[0],
& sfmt_bl24_ops[0],
& sfmt_bcl8_ops[0],
& sfmt_bcl24_ops[0],
& sfmt_bc8_ops[0],
& sfmt_bc24_ops[0],
& sfmt_beq_ops[0],
& sfmt_bra8_ops[0],
& sfmt_bra24_ops[0],
& sfmt_bcl8_ops[0],
& sfmt_bcl24_ops[0],
& sfmt_cmp_ops[0],
& sfmt_cmpi_ops[0],
& sfmt_cmp_ops[0],
& sfmt_cmpi_ops[0],
& sfmt_cmp_ops[0],
& sfmt_cmpz_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_div_ops[0],
& sfmt_jc_ops[0],
& sfmt_jc_ops[0],
& sfmt_jl_ops[0],
& sfmt_jmp_ops[0],
& sfmt_ld_ops[0],
& sfmt_ld_d_ops[0],
& sfmt_ldb_ops[0],
& sfmt_ldb_d_ops[0],
& sfmt_ldh_ops[0],
& sfmt_ldh_d_ops[0],
& sfmt_ldb_ops[0],
& sfmt_ldb_d_ops[0],
& sfmt_ldh_ops[0],
& sfmt_ldh_d_ops[0],
& sfmt_ld_plus_ops[0],
& sfmt_ld24_ops[0],
& sfmt_ldi8_ops[0],
& sfmt_ldi16_ops[0],
& sfmt_lock_ops[0],
& sfmt_machi_ops[0],
& sfmt_machi_a_ops[0],
& sfmt_machi_ops[0],
& sfmt_machi_a_ops[0],
& sfmt_machi_ops[0],
& sfmt_machi_a_ops[0],
& sfmt_machi_ops[0],
& sfmt_machi_a_ops[0],
& sfmt_add_ops[0],
& sfmt_mulhi_ops[0],
& sfmt_mulhi_a_ops[0],
& sfmt_mulhi_ops[0],
& sfmt_mulhi_a_ops[0],
& sfmt_mulhi_ops[0],
& sfmt_mulhi_a_ops[0],
& sfmt_mulhi_ops[0],
& sfmt_mulhi_a_ops[0],
& sfmt_mv_ops[0],
& sfmt_mvfachi_ops[0],
& sfmt_mvfachi_a_ops[0],
& sfmt_mvfachi_ops[0],
& sfmt_mvfachi_a_ops[0],
& sfmt_mvfachi_ops[0],
& sfmt_mvfachi_a_ops[0],
& sfmt_mvfc_ops[0],
& sfmt_mvtachi_ops[0],
& sfmt_mvtachi_a_ops[0],
& sfmt_mvtachi_ops[0],
& sfmt_mvtachi_a_ops[0],
& sfmt_mvtc_ops[0],
& sfmt_mv_ops[0],
& sfmt_nop_ops[0],
& sfmt_mv_ops[0],
& sfmt_rac_ops[0],
& sfmt_rac_dsi_ops[0],
& sfmt_rac_ops[0],
& sfmt_rac_dsi_ops[0],
& sfmt_rte_ops[0],
& sfmt_seth_ops[0],
& sfmt_add_ops[0],
& sfmt_sll3_ops[0],
& sfmt_slli_ops[0],
& sfmt_add_ops[0],
& sfmt_sll3_ops[0],
& sfmt_slli_ops[0],
& sfmt_add_ops[0],
& sfmt_sll3_ops[0],
& sfmt_slli_ops[0],
& sfmt_st_ops[0],
& sfmt_st_d_ops[0],
& sfmt_stb_ops[0],
& sfmt_stb_d_ops[0],
& sfmt_sth_ops[0],
& sfmt_sth_d_ops[0],
& sfmt_st_plus_ops[0],
& sfmt_sth_plus_ops[0],
& sfmt_stb_plus_ops[0],
& sfmt_st_plus_ops[0],
& sfmt_add_ops[0],
& sfmt_addv_ops[0],
& sfmt_addx_ops[0],
& sfmt_trap_ops[0],
& sfmt_unlock_ops[0],
& sfmt_satb_ops[0],
& sfmt_satb_ops[0],
& sfmt_sat_ops[0],
& sfmt_cmpz_ops[0],
& sfmt_sadd_ops[0],
& sfmt_macwu1_ops[0],
& sfmt_machi_ops[0],
& sfmt_mulwu1_ops[0],
& sfmt_macwu1_ops[0],
& sfmt_sc_ops[0],
& sfmt_sc_ops[0],
& sfmt_clrpsw_ops[0],
& sfmt_setpsw_ops[0],
& sfmt_bset_ops[0],
& sfmt_bset_ops[0],
& sfmt_btst_ops[0],
};
/* Function to call before using the operand instance table. */
void
m32r_cgen_init_opinst_table (cd)
CGEN_CPU_DESC cd;
{
int i;
const CGEN_OPINST **oi = & m32r_cgen_opinst_table[0];
CGEN_INSN *insns = (CGEN_INSN *) cd->insn_table.init_entries;
for (i = 0; i < MAX_INSNS; ++i)
insns[i].opinst = oi[i];
}
| gpl-2.0 |
bugralevent/linux | drivers/staging/media/omap4iss/iss_video.c | 411 | 34453 | /*
* TI OMAP4 ISS V4L2 Driver - Generic video node
*
* Copyright (C) 2012 Texas Instruments, Inc.
*
* Author: Sergio Aguirre <sergio.a.aguirre@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.
*/
#include <asm/cacheflush.h>
#include <linux/clk.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-ioctl.h>
#include "iss_video.h"
#include "iss.h"
/* -----------------------------------------------------------------------------
* Helper functions
*/
static struct iss_format_info formats[] = {
{ MEDIA_BUS_FMT_Y8_1X8, MEDIA_BUS_FMT_Y8_1X8,
MEDIA_BUS_FMT_Y8_1X8, MEDIA_BUS_FMT_Y8_1X8,
V4L2_PIX_FMT_GREY, 8, "Greyscale 8 bpp", },
{ MEDIA_BUS_FMT_Y10_1X10, MEDIA_BUS_FMT_Y10_1X10,
MEDIA_BUS_FMT_Y10_1X10, MEDIA_BUS_FMT_Y8_1X8,
V4L2_PIX_FMT_Y10, 10, "Greyscale 10 bpp", },
{ MEDIA_BUS_FMT_Y12_1X12, MEDIA_BUS_FMT_Y10_1X10,
MEDIA_BUS_FMT_Y12_1X12, MEDIA_BUS_FMT_Y8_1X8,
V4L2_PIX_FMT_Y12, 12, "Greyscale 12 bpp", },
{ MEDIA_BUS_FMT_SBGGR8_1X8, MEDIA_BUS_FMT_SBGGR8_1X8,
MEDIA_BUS_FMT_SBGGR8_1X8, MEDIA_BUS_FMT_SBGGR8_1X8,
V4L2_PIX_FMT_SBGGR8, 8, "BGGR Bayer 8 bpp", },
{ MEDIA_BUS_FMT_SGBRG8_1X8, MEDIA_BUS_FMT_SGBRG8_1X8,
MEDIA_BUS_FMT_SGBRG8_1X8, MEDIA_BUS_FMT_SGBRG8_1X8,
V4L2_PIX_FMT_SGBRG8, 8, "GBRG Bayer 8 bpp", },
{ MEDIA_BUS_FMT_SGRBG8_1X8, MEDIA_BUS_FMT_SGRBG8_1X8,
MEDIA_BUS_FMT_SGRBG8_1X8, MEDIA_BUS_FMT_SGRBG8_1X8,
V4L2_PIX_FMT_SGRBG8, 8, "GRBG Bayer 8 bpp", },
{ MEDIA_BUS_FMT_SRGGB8_1X8, MEDIA_BUS_FMT_SRGGB8_1X8,
MEDIA_BUS_FMT_SRGGB8_1X8, MEDIA_BUS_FMT_SRGGB8_1X8,
V4L2_PIX_FMT_SRGGB8, 8, "RGGB Bayer 8 bpp", },
{ MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8, MEDIA_BUS_FMT_SGRBG10_DPCM8_1X8,
MEDIA_BUS_FMT_SGRBG10_1X10, 0,
V4L2_PIX_FMT_SGRBG10DPCM8, 8, "GRBG Bayer 10 bpp DPCM8", },
{ MEDIA_BUS_FMT_SBGGR10_1X10, MEDIA_BUS_FMT_SBGGR10_1X10,
MEDIA_BUS_FMT_SBGGR10_1X10, MEDIA_BUS_FMT_SBGGR8_1X8,
V4L2_PIX_FMT_SBGGR10, 10, "BGGR Bayer 10 bpp", },
{ MEDIA_BUS_FMT_SGBRG10_1X10, MEDIA_BUS_FMT_SGBRG10_1X10,
MEDIA_BUS_FMT_SGBRG10_1X10, MEDIA_BUS_FMT_SGBRG8_1X8,
V4L2_PIX_FMT_SGBRG10, 10, "GBRG Bayer 10 bpp", },
{ MEDIA_BUS_FMT_SGRBG10_1X10, MEDIA_BUS_FMT_SGRBG10_1X10,
MEDIA_BUS_FMT_SGRBG10_1X10, MEDIA_BUS_FMT_SGRBG8_1X8,
V4L2_PIX_FMT_SGRBG10, 10, "GRBG Bayer 10 bpp", },
{ MEDIA_BUS_FMT_SRGGB10_1X10, MEDIA_BUS_FMT_SRGGB10_1X10,
MEDIA_BUS_FMT_SRGGB10_1X10, MEDIA_BUS_FMT_SRGGB8_1X8,
V4L2_PIX_FMT_SRGGB10, 10, "RGGB Bayer 10 bpp", },
{ MEDIA_BUS_FMT_SBGGR12_1X12, MEDIA_BUS_FMT_SBGGR10_1X10,
MEDIA_BUS_FMT_SBGGR12_1X12, MEDIA_BUS_FMT_SBGGR8_1X8,
V4L2_PIX_FMT_SBGGR12, 12, "BGGR Bayer 12 bpp", },
{ MEDIA_BUS_FMT_SGBRG12_1X12, MEDIA_BUS_FMT_SGBRG10_1X10,
MEDIA_BUS_FMT_SGBRG12_1X12, MEDIA_BUS_FMT_SGBRG8_1X8,
V4L2_PIX_FMT_SGBRG12, 12, "GBRG Bayer 12 bpp", },
{ MEDIA_BUS_FMT_SGRBG12_1X12, MEDIA_BUS_FMT_SGRBG10_1X10,
MEDIA_BUS_FMT_SGRBG12_1X12, MEDIA_BUS_FMT_SGRBG8_1X8,
V4L2_PIX_FMT_SGRBG12, 12, "GRBG Bayer 12 bpp", },
{ MEDIA_BUS_FMT_SRGGB12_1X12, MEDIA_BUS_FMT_SRGGB10_1X10,
MEDIA_BUS_FMT_SRGGB12_1X12, MEDIA_BUS_FMT_SRGGB8_1X8,
V4L2_PIX_FMT_SRGGB12, 12, "RGGB Bayer 12 bpp", },
{ MEDIA_BUS_FMT_UYVY8_1X16, MEDIA_BUS_FMT_UYVY8_1X16,
MEDIA_BUS_FMT_UYVY8_1X16, 0,
V4L2_PIX_FMT_UYVY, 16, "YUV 4:2:2 (UYVY)", },
{ MEDIA_BUS_FMT_YUYV8_1X16, MEDIA_BUS_FMT_YUYV8_1X16,
MEDIA_BUS_FMT_YUYV8_1X16, 0,
V4L2_PIX_FMT_YUYV, 16, "YUV 4:2:2 (YUYV)", },
{ MEDIA_BUS_FMT_YUYV8_1_5X8, MEDIA_BUS_FMT_YUYV8_1_5X8,
MEDIA_BUS_FMT_YUYV8_1_5X8, 0,
V4L2_PIX_FMT_NV12, 8, "YUV 4:2:0 (NV12)", },
};
const struct iss_format_info *
omap4iss_video_format_info(u32 code)
{
unsigned int i;
for (i = 0; i < ARRAY_SIZE(formats); ++i) {
if (formats[i].code == code)
return &formats[i];
}
return NULL;
}
/*
* iss_video_mbus_to_pix - Convert v4l2_mbus_framefmt to v4l2_pix_format
* @video: ISS video instance
* @mbus: v4l2_mbus_framefmt format (input)
* @pix: v4l2_pix_format format (output)
*
* Fill the output pix structure with information from the input mbus format.
* The bytesperline and sizeimage fields are computed from the requested bytes
* per line value in the pix format and information from the video instance.
*
* Return the number of padding bytes at end of line.
*/
static unsigned int iss_video_mbus_to_pix(const struct iss_video *video,
const struct v4l2_mbus_framefmt *mbus,
struct v4l2_pix_format *pix)
{
unsigned int bpl = pix->bytesperline;
unsigned int min_bpl;
unsigned int i;
memset(pix, 0, sizeof(*pix));
pix->width = mbus->width;
pix->height = mbus->height;
/* Skip the last format in the loop so that it will be selected if no
* match is found.
*/
for (i = 0; i < ARRAY_SIZE(formats) - 1; ++i) {
if (formats[i].code == mbus->code)
break;
}
min_bpl = pix->width * ALIGN(formats[i].bpp, 8) / 8;
/* Clamp the requested bytes per line value. If the maximum bytes per
* line value is zero, the module doesn't support user configurable line
* sizes. Override the requested value with the minimum in that case.
*/
if (video->bpl_max)
bpl = clamp(bpl, min_bpl, video->bpl_max);
else
bpl = min_bpl;
if (!video->bpl_zero_padding || bpl != min_bpl)
bpl = ALIGN(bpl, video->bpl_alignment);
pix->pixelformat = formats[i].pixelformat;
pix->bytesperline = bpl;
pix->sizeimage = pix->bytesperline * pix->height;
pix->colorspace = mbus->colorspace;
pix->field = mbus->field;
/* FIXME: Special case for NV12! We should make this nicer... */
if (pix->pixelformat == V4L2_PIX_FMT_NV12)
pix->sizeimage += (pix->bytesperline * pix->height) / 2;
return bpl - min_bpl;
}
static void iss_video_pix_to_mbus(const struct v4l2_pix_format *pix,
struct v4l2_mbus_framefmt *mbus)
{
unsigned int i;
memset(mbus, 0, sizeof(*mbus));
mbus->width = pix->width;
mbus->height = pix->height;
/* Skip the last format in the loop so that it will be selected if no
* match is found.
*/
for (i = 0; i < ARRAY_SIZE(formats) - 1; ++i) {
if (formats[i].pixelformat == pix->pixelformat)
break;
}
mbus->code = formats[i].code;
mbus->colorspace = pix->colorspace;
mbus->field = pix->field;
}
static struct v4l2_subdev *
iss_video_remote_subdev(struct iss_video *video, u32 *pad)
{
struct media_pad *remote;
remote = media_entity_remote_pad(&video->pad);
if (remote == NULL ||
media_entity_type(remote->entity) != MEDIA_ENT_T_V4L2_SUBDEV)
return NULL;
if (pad)
*pad = remote->index;
return media_entity_to_v4l2_subdev(remote->entity);
}
/* Return a pointer to the ISS video instance at the far end of the pipeline. */
static struct iss_video *
iss_video_far_end(struct iss_video *video)
{
struct media_entity_graph graph;
struct media_entity *entity = &video->video.entity;
struct media_device *mdev = entity->parent;
struct iss_video *far_end = NULL;
mutex_lock(&mdev->graph_mutex);
media_entity_graph_walk_start(&graph, entity);
while ((entity = media_entity_graph_walk_next(&graph))) {
if (entity == &video->video.entity)
continue;
if (media_entity_type(entity) != MEDIA_ENT_T_DEVNODE)
continue;
far_end = to_iss_video(media_entity_to_video_device(entity));
if (far_end->type != video->type)
break;
far_end = NULL;
}
mutex_unlock(&mdev->graph_mutex);
return far_end;
}
static int
__iss_video_get_format(struct iss_video *video,
struct v4l2_mbus_framefmt *format)
{
struct v4l2_subdev_format fmt;
struct v4l2_subdev *subdev;
u32 pad;
int ret;
subdev = iss_video_remote_subdev(video, &pad);
if (subdev == NULL)
return -EINVAL;
memset(&fmt, 0, sizeof(fmt));
fmt.pad = pad;
fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
mutex_lock(&video->mutex);
ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &fmt);
mutex_unlock(&video->mutex);
if (ret)
return ret;
*format = fmt.format;
return 0;
}
static int
iss_video_check_format(struct iss_video *video, struct iss_video_fh *vfh)
{
struct v4l2_mbus_framefmt format;
struct v4l2_pix_format pixfmt;
int ret;
ret = __iss_video_get_format(video, &format);
if (ret < 0)
return ret;
pixfmt.bytesperline = 0;
ret = iss_video_mbus_to_pix(video, &format, &pixfmt);
if (vfh->format.fmt.pix.pixelformat != pixfmt.pixelformat ||
vfh->format.fmt.pix.height != pixfmt.height ||
vfh->format.fmt.pix.width != pixfmt.width ||
vfh->format.fmt.pix.bytesperline != pixfmt.bytesperline ||
vfh->format.fmt.pix.sizeimage != pixfmt.sizeimage)
return -EINVAL;
return ret;
}
/* -----------------------------------------------------------------------------
* Video queue operations
*/
static int iss_video_queue_setup(struct vb2_queue *vq,
const struct v4l2_format *fmt,
unsigned int *count, unsigned int *num_planes,
unsigned int sizes[], void *alloc_ctxs[])
{
struct iss_video_fh *vfh = vb2_get_drv_priv(vq);
struct iss_video *video = vfh->video;
/* Revisit multi-planar support for NV12 */
*num_planes = 1;
sizes[0] = vfh->format.fmt.pix.sizeimage;
if (sizes[0] == 0)
return -EINVAL;
alloc_ctxs[0] = video->alloc_ctx;
*count = min(*count, video->capture_mem / PAGE_ALIGN(sizes[0]));
return 0;
}
static void iss_video_buf_cleanup(struct vb2_buffer *vb)
{
struct iss_buffer *buffer = container_of(vb, struct iss_buffer, vb);
if (buffer->iss_addr)
buffer->iss_addr = 0;
}
static int iss_video_buf_prepare(struct vb2_buffer *vb)
{
struct iss_video_fh *vfh = vb2_get_drv_priv(vb->vb2_queue);
struct iss_buffer *buffer = container_of(vb, struct iss_buffer, vb);
struct iss_video *video = vfh->video;
unsigned long size = vfh->format.fmt.pix.sizeimage;
dma_addr_t addr;
if (vb2_plane_size(vb, 0) < size)
return -ENOBUFS;
addr = vb2_dma_contig_plane_dma_addr(vb, 0);
if (!IS_ALIGNED(addr, 32)) {
dev_dbg(video->iss->dev,
"Buffer address must be aligned to 32 bytes boundary.\n");
return -EINVAL;
}
vb2_set_plane_payload(vb, 0, size);
buffer->iss_addr = addr;
return 0;
}
static void iss_video_buf_queue(struct vb2_buffer *vb)
{
struct iss_video_fh *vfh = vb2_get_drv_priv(vb->vb2_queue);
struct iss_video *video = vfh->video;
struct iss_buffer *buffer = container_of(vb, struct iss_buffer, vb);
struct iss_pipeline *pipe = to_iss_pipeline(&video->video.entity);
unsigned long flags;
bool empty;
spin_lock_irqsave(&video->qlock, flags);
/* Mark the buffer is faulty and give it back to the queue immediately
* if the video node has registered an error. vb2 will perform the same
* check when preparing the buffer, but that is inherently racy, so we
* need to handle the race condition with an authoritative check here.
*/
if (unlikely(video->error)) {
vb2_buffer_done(vb, VB2_BUF_STATE_ERROR);
spin_unlock_irqrestore(&video->qlock, flags);
return;
}
empty = list_empty(&video->dmaqueue);
list_add_tail(&buffer->list, &video->dmaqueue);
spin_unlock_irqrestore(&video->qlock, flags);
if (empty) {
enum iss_pipeline_state state;
unsigned int start;
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
state = ISS_PIPELINE_QUEUE_OUTPUT;
else
state = ISS_PIPELINE_QUEUE_INPUT;
spin_lock_irqsave(&pipe->lock, flags);
pipe->state |= state;
video->ops->queue(video, buffer);
video->dmaqueue_flags |= ISS_VIDEO_DMAQUEUE_QUEUED;
start = iss_pipeline_ready(pipe);
if (start)
pipe->state |= ISS_PIPELINE_STREAM;
spin_unlock_irqrestore(&pipe->lock, flags);
if (start)
omap4iss_pipeline_set_stream(pipe,
ISS_PIPELINE_STREAM_SINGLESHOT);
}
}
static const struct vb2_ops iss_video_vb2ops = {
.queue_setup = iss_video_queue_setup,
.buf_prepare = iss_video_buf_prepare,
.buf_queue = iss_video_buf_queue,
.buf_cleanup = iss_video_buf_cleanup,
};
/*
* omap4iss_video_buffer_next - Complete the current buffer and return the next
* @video: ISS video object
*
* Remove the current video buffer from the DMA queue and fill its timestamp,
* field count and state fields before waking up its completion handler.
*
* For capture video nodes, the buffer state is set to VB2_BUF_STATE_DONE if no
* error has been flagged in the pipeline, or to VB2_BUF_STATE_ERROR otherwise.
*
* The DMA queue is expected to contain at least one buffer.
*
* Return a pointer to the next buffer in the DMA queue, or NULL if the queue is
* empty.
*/
struct iss_buffer *omap4iss_video_buffer_next(struct iss_video *video)
{
struct iss_pipeline *pipe = to_iss_pipeline(&video->video.entity);
enum iss_pipeline_state state;
struct iss_buffer *buf;
unsigned long flags;
struct timespec ts;
spin_lock_irqsave(&video->qlock, flags);
if (WARN_ON(list_empty(&video->dmaqueue))) {
spin_unlock_irqrestore(&video->qlock, flags);
return NULL;
}
buf = list_first_entry(&video->dmaqueue, struct iss_buffer,
list);
list_del(&buf->list);
spin_unlock_irqrestore(&video->qlock, flags);
ktime_get_ts(&ts);
buf->vb.v4l2_buf.timestamp.tv_sec = ts.tv_sec;
buf->vb.v4l2_buf.timestamp.tv_usec = ts.tv_nsec / NSEC_PER_USEC;
/* Do frame number propagation only if this is the output video node.
* Frame number either comes from the CSI receivers or it gets
* incremented here if H3A is not active.
* Note: There is no guarantee that the output buffer will finish
* first, so the input number might lag behind by 1 in some cases.
*/
if (video == pipe->output && !pipe->do_propagation)
buf->vb.v4l2_buf.sequence =
atomic_inc_return(&pipe->frame_number);
else
buf->vb.v4l2_buf.sequence = atomic_read(&pipe->frame_number);
vb2_buffer_done(&buf->vb, pipe->error ?
VB2_BUF_STATE_ERROR : VB2_BUF_STATE_DONE);
pipe->error = false;
spin_lock_irqsave(&video->qlock, flags);
if (list_empty(&video->dmaqueue)) {
spin_unlock_irqrestore(&video->qlock, flags);
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
state = ISS_PIPELINE_QUEUE_OUTPUT
| ISS_PIPELINE_STREAM;
else
state = ISS_PIPELINE_QUEUE_INPUT
| ISS_PIPELINE_STREAM;
spin_lock_irqsave(&pipe->lock, flags);
pipe->state &= ~state;
if (video->pipe.stream_state == ISS_PIPELINE_STREAM_CONTINUOUS)
video->dmaqueue_flags |= ISS_VIDEO_DMAQUEUE_UNDERRUN;
spin_unlock_irqrestore(&pipe->lock, flags);
return NULL;
}
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && pipe->input != NULL) {
spin_lock(&pipe->lock);
pipe->state &= ~ISS_PIPELINE_STREAM;
spin_unlock(&pipe->lock);
}
buf = list_first_entry(&video->dmaqueue, struct iss_buffer,
list);
spin_unlock_irqrestore(&video->qlock, flags);
buf->vb.state = VB2_BUF_STATE_ACTIVE;
return buf;
}
/*
* omap4iss_video_cancel_stream - Cancel stream on a video node
* @video: ISS video object
*
* Cancelling a stream mark all buffers on the video node as erroneous and makes
* sure no new buffer can be queued.
*/
void omap4iss_video_cancel_stream(struct iss_video *video)
{
unsigned long flags;
spin_lock_irqsave(&video->qlock, flags);
while (!list_empty(&video->dmaqueue)) {
struct iss_buffer *buf;
buf = list_first_entry(&video->dmaqueue, struct iss_buffer,
list);
list_del(&buf->list);
vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
}
vb2_queue_error(video->queue);
video->error = true;
spin_unlock_irqrestore(&video->qlock, flags);
}
/* -----------------------------------------------------------------------------
* V4L2 ioctls
*/
static int
iss_video_querycap(struct file *file, void *fh, struct v4l2_capability *cap)
{
struct iss_video *video = video_drvdata(file);
strlcpy(cap->driver, ISS_VIDEO_DRIVER_NAME, sizeof(cap->driver));
strlcpy(cap->card, video->video.name, sizeof(cap->card));
strlcpy(cap->bus_info, "media", sizeof(cap->bus_info));
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
else
cap->device_caps = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING;
cap->capabilities = V4L2_CAP_DEVICE_CAPS | V4L2_CAP_STREAMING
| V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OUTPUT;
return 0;
}
static int
iss_video_enum_format(struct file *file, void *fh, struct v4l2_fmtdesc *f)
{
struct iss_video *video = video_drvdata(file);
struct v4l2_mbus_framefmt format;
unsigned int index = f->index;
unsigned int i;
int ret;
if (f->type != video->type)
return -EINVAL;
ret = __iss_video_get_format(video, &format);
if (ret < 0)
return ret;
for (i = 0; i < ARRAY_SIZE(formats); ++i) {
const struct iss_format_info *info = &formats[i];
if (format.code != info->code)
continue;
if (index == 0) {
f->pixelformat = info->pixelformat;
strlcpy(f->description, info->description,
sizeof(f->description));
return 0;
}
index--;
}
return -EINVAL;
}
static int
iss_video_get_format(struct file *file, void *fh, struct v4l2_format *format)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
if (format->type != video->type)
return -EINVAL;
mutex_lock(&video->mutex);
*format = vfh->format;
mutex_unlock(&video->mutex);
return 0;
}
static int
iss_video_set_format(struct file *file, void *fh, struct v4l2_format *format)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
struct v4l2_mbus_framefmt fmt;
if (format->type != video->type)
return -EINVAL;
mutex_lock(&video->mutex);
/* Fill the bytesperline and sizeimage fields by converting to media bus
* format and back to pixel format.
*/
iss_video_pix_to_mbus(&format->fmt.pix, &fmt);
iss_video_mbus_to_pix(video, &fmt, &format->fmt.pix);
vfh->format = *format;
mutex_unlock(&video->mutex);
return 0;
}
static int
iss_video_try_format(struct file *file, void *fh, struct v4l2_format *format)
{
struct iss_video *video = video_drvdata(file);
struct v4l2_subdev_format fmt;
struct v4l2_subdev *subdev;
u32 pad;
int ret;
if (format->type != video->type)
return -EINVAL;
subdev = iss_video_remote_subdev(video, &pad);
if (subdev == NULL)
return -EINVAL;
iss_video_pix_to_mbus(&format->fmt.pix, &fmt.format);
fmt.pad = pad;
fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE;
ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &fmt);
if (ret)
return ret;
iss_video_mbus_to_pix(video, &fmt.format, &format->fmt.pix);
return 0;
}
static int
iss_video_cropcap(struct file *file, void *fh, struct v4l2_cropcap *cropcap)
{
struct iss_video *video = video_drvdata(file);
struct v4l2_subdev *subdev;
int ret;
subdev = iss_video_remote_subdev(video, NULL);
if (subdev == NULL)
return -EINVAL;
mutex_lock(&video->mutex);
ret = v4l2_subdev_call(subdev, video, cropcap, cropcap);
mutex_unlock(&video->mutex);
return ret == -ENOIOCTLCMD ? -ENOTTY : ret;
}
static int
iss_video_get_crop(struct file *file, void *fh, struct v4l2_crop *crop)
{
struct iss_video *video = video_drvdata(file);
struct v4l2_subdev_format format;
struct v4l2_subdev *subdev;
u32 pad;
int ret;
subdev = iss_video_remote_subdev(video, &pad);
if (subdev == NULL)
return -EINVAL;
/* Try the get crop operation first and fallback to get format if not
* implemented.
*/
ret = v4l2_subdev_call(subdev, video, g_crop, crop);
if (ret != -ENOIOCTLCMD)
return ret;
format.pad = pad;
format.which = V4L2_SUBDEV_FORMAT_ACTIVE;
ret = v4l2_subdev_call(subdev, pad, get_fmt, NULL, &format);
if (ret < 0)
return ret == -ENOIOCTLCMD ? -ENOTTY : ret;
crop->c.left = 0;
crop->c.top = 0;
crop->c.width = format.format.width;
crop->c.height = format.format.height;
return 0;
}
static int
iss_video_set_crop(struct file *file, void *fh, const struct v4l2_crop *crop)
{
struct iss_video *video = video_drvdata(file);
struct v4l2_subdev *subdev;
int ret;
subdev = iss_video_remote_subdev(video, NULL);
if (subdev == NULL)
return -EINVAL;
mutex_lock(&video->mutex);
ret = v4l2_subdev_call(subdev, video, s_crop, crop);
mutex_unlock(&video->mutex);
return ret == -ENOIOCTLCMD ? -ENOTTY : ret;
}
static int
iss_video_get_param(struct file *file, void *fh, struct v4l2_streamparm *a)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
if (video->type != V4L2_BUF_TYPE_VIDEO_OUTPUT ||
video->type != a->type)
return -EINVAL;
memset(a, 0, sizeof(*a));
a->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
a->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
a->parm.output.timeperframe = vfh->timeperframe;
return 0;
}
static int
iss_video_set_param(struct file *file, void *fh, struct v4l2_streamparm *a)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
if (video->type != V4L2_BUF_TYPE_VIDEO_OUTPUT ||
video->type != a->type)
return -EINVAL;
if (a->parm.output.timeperframe.denominator == 0)
a->parm.output.timeperframe.denominator = 1;
vfh->timeperframe = a->parm.output.timeperframe;
return 0;
}
static int
iss_video_reqbufs(struct file *file, void *fh, struct v4l2_requestbuffers *rb)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_reqbufs(&vfh->queue, rb);
}
static int
iss_video_querybuf(struct file *file, void *fh, struct v4l2_buffer *b)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_querybuf(&vfh->queue, b);
}
static int
iss_video_qbuf(struct file *file, void *fh, struct v4l2_buffer *b)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_qbuf(&vfh->queue, b);
}
static int
iss_video_expbuf(struct file *file, void *fh, struct v4l2_exportbuffer *e)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_expbuf(&vfh->queue, e);
}
static int
iss_video_dqbuf(struct file *file, void *fh, struct v4l2_buffer *b)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
return vb2_dqbuf(&vfh->queue, b, file->f_flags & O_NONBLOCK);
}
/*
* Stream management
*
* Every ISS pipeline has a single input and a single output. The input can be
* either a sensor or a video node. The output is always a video node.
*
* As every pipeline has an output video node, the ISS video objects at the
* pipeline output stores the pipeline state. It tracks the streaming state of
* both the input and output, as well as the availability of buffers.
*
* In sensor-to-memory mode, frames are always available at the pipeline input.
* Starting the sensor usually requires I2C transfers and must be done in
* interruptible context. The pipeline is started and stopped synchronously
* to the stream on/off commands. All modules in the pipeline will get their
* subdev set stream handler called. The module at the end of the pipeline must
* delay starting the hardware until buffers are available at its output.
*
* In memory-to-memory mode, starting/stopping the stream requires
* synchronization between the input and output. ISS modules can't be stopped
* in the middle of a frame, and at least some of the modules seem to become
* busy as soon as they're started, even if they don't receive a frame start
* event. For that reason frames need to be processed in single-shot mode. The
* driver needs to wait until a frame is completely processed and written to
* memory before restarting the pipeline for the next frame. Pipelined
* processing might be possible but requires more testing.
*
* Stream start must be delayed until buffers are available at both the input
* and output. The pipeline must be started in the videobuf queue callback with
* the buffers queue spinlock held. The modules subdev set stream operation must
* not sleep.
*/
static int
iss_video_streamon(struct file *file, void *fh, enum v4l2_buf_type type)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
struct media_entity_graph graph;
struct media_entity *entity;
enum iss_pipeline_state state;
struct iss_pipeline *pipe;
struct iss_video *far_end;
unsigned long flags;
int ret;
if (type != video->type)
return -EINVAL;
mutex_lock(&video->stream_lock);
/* Start streaming on the pipeline. No link touching an entity in the
* pipeline can be activated or deactivated once streaming is started.
*/
pipe = video->video.entity.pipe
? to_iss_pipeline(&video->video.entity) : &video->pipe;
pipe->external = NULL;
pipe->external_rate = 0;
pipe->external_bpp = 0;
pipe->entities = 0;
if (video->iss->pdata->set_constraints)
video->iss->pdata->set_constraints(video->iss, true);
ret = media_entity_pipeline_start(&video->video.entity, &pipe->pipe);
if (ret < 0)
goto err_media_entity_pipeline_start;
entity = &video->video.entity;
media_entity_graph_walk_start(&graph, entity);
while ((entity = media_entity_graph_walk_next(&graph)))
pipe->entities |= 1 << entity->id;
/* Verify that the currently configured format matches the output of
* the connected subdev.
*/
ret = iss_video_check_format(video, vfh);
if (ret < 0)
goto err_iss_video_check_format;
video->bpl_padding = ret;
video->bpl_value = vfh->format.fmt.pix.bytesperline;
/* Find the ISS video node connected at the far end of the pipeline and
* update the pipeline.
*/
far_end = iss_video_far_end(video);
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
state = ISS_PIPELINE_STREAM_OUTPUT | ISS_PIPELINE_IDLE_OUTPUT;
pipe->input = far_end;
pipe->output = video;
} else {
if (far_end == NULL) {
ret = -EPIPE;
goto err_iss_video_check_format;
}
state = ISS_PIPELINE_STREAM_INPUT | ISS_PIPELINE_IDLE_INPUT;
pipe->input = video;
pipe->output = far_end;
}
spin_lock_irqsave(&pipe->lock, flags);
pipe->state &= ~ISS_PIPELINE_STREAM;
pipe->state |= state;
spin_unlock_irqrestore(&pipe->lock, flags);
/* Set the maximum time per frame as the value requested by userspace.
* This is a soft limit that can be overridden if the hardware doesn't
* support the request limit.
*/
if (video->type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
pipe->max_timeperframe = vfh->timeperframe;
video->queue = &vfh->queue;
INIT_LIST_HEAD(&video->dmaqueue);
video->error = false;
atomic_set(&pipe->frame_number, -1);
ret = vb2_streamon(&vfh->queue, type);
if (ret < 0)
goto err_iss_video_check_format;
/* In sensor-to-memory mode, the stream can be started synchronously
* to the stream on command. In memory-to-memory mode, it will be
* started when buffers are queued on both the input and output.
*/
if (pipe->input == NULL) {
unsigned long flags;
ret = omap4iss_pipeline_set_stream(pipe,
ISS_PIPELINE_STREAM_CONTINUOUS);
if (ret < 0)
goto err_omap4iss_set_stream;
spin_lock_irqsave(&video->qlock, flags);
if (list_empty(&video->dmaqueue))
video->dmaqueue_flags |= ISS_VIDEO_DMAQUEUE_UNDERRUN;
spin_unlock_irqrestore(&video->qlock, flags);
}
mutex_unlock(&video->stream_lock);
return 0;
err_omap4iss_set_stream:
vb2_streamoff(&vfh->queue, type);
err_iss_video_check_format:
media_entity_pipeline_stop(&video->video.entity);
err_media_entity_pipeline_start:
if (video->iss->pdata->set_constraints)
video->iss->pdata->set_constraints(video->iss, false);
video->queue = NULL;
mutex_unlock(&video->stream_lock);
return ret;
}
static int
iss_video_streamoff(struct file *file, void *fh, enum v4l2_buf_type type)
{
struct iss_video_fh *vfh = to_iss_video_fh(fh);
struct iss_video *video = video_drvdata(file);
struct iss_pipeline *pipe = to_iss_pipeline(&video->video.entity);
enum iss_pipeline_state state;
unsigned long flags;
if (type != video->type)
return -EINVAL;
mutex_lock(&video->stream_lock);
if (!vb2_is_streaming(&vfh->queue))
goto done;
/* Update the pipeline state. */
if (video->type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
state = ISS_PIPELINE_STREAM_OUTPUT
| ISS_PIPELINE_QUEUE_OUTPUT;
else
state = ISS_PIPELINE_STREAM_INPUT
| ISS_PIPELINE_QUEUE_INPUT;
spin_lock_irqsave(&pipe->lock, flags);
pipe->state &= ~state;
spin_unlock_irqrestore(&pipe->lock, flags);
/* Stop the stream. */
omap4iss_pipeline_set_stream(pipe, ISS_PIPELINE_STREAM_STOPPED);
vb2_streamoff(&vfh->queue, type);
video->queue = NULL;
if (video->iss->pdata->set_constraints)
video->iss->pdata->set_constraints(video->iss, false);
media_entity_pipeline_stop(&video->video.entity);
done:
mutex_unlock(&video->stream_lock);
return 0;
}
static int
iss_video_enum_input(struct file *file, void *fh, struct v4l2_input *input)
{
if (input->index > 0)
return -EINVAL;
strlcpy(input->name, "camera", sizeof(input->name));
input->type = V4L2_INPUT_TYPE_CAMERA;
return 0;
}
static int
iss_video_g_input(struct file *file, void *fh, unsigned int *input)
{
*input = 0;
return 0;
}
static int
iss_video_s_input(struct file *file, void *fh, unsigned int input)
{
return input == 0 ? 0 : -EINVAL;
}
static const struct v4l2_ioctl_ops iss_video_ioctl_ops = {
.vidioc_querycap = iss_video_querycap,
.vidioc_enum_fmt_vid_cap = iss_video_enum_format,
.vidioc_g_fmt_vid_cap = iss_video_get_format,
.vidioc_s_fmt_vid_cap = iss_video_set_format,
.vidioc_try_fmt_vid_cap = iss_video_try_format,
.vidioc_g_fmt_vid_out = iss_video_get_format,
.vidioc_s_fmt_vid_out = iss_video_set_format,
.vidioc_try_fmt_vid_out = iss_video_try_format,
.vidioc_cropcap = iss_video_cropcap,
.vidioc_g_crop = iss_video_get_crop,
.vidioc_s_crop = iss_video_set_crop,
.vidioc_g_parm = iss_video_get_param,
.vidioc_s_parm = iss_video_set_param,
.vidioc_reqbufs = iss_video_reqbufs,
.vidioc_querybuf = iss_video_querybuf,
.vidioc_qbuf = iss_video_qbuf,
.vidioc_expbuf = iss_video_expbuf,
.vidioc_dqbuf = iss_video_dqbuf,
.vidioc_streamon = iss_video_streamon,
.vidioc_streamoff = iss_video_streamoff,
.vidioc_enum_input = iss_video_enum_input,
.vidioc_g_input = iss_video_g_input,
.vidioc_s_input = iss_video_s_input,
};
/* -----------------------------------------------------------------------------
* V4L2 file operations
*/
static int iss_video_open(struct file *file)
{
struct iss_video *video = video_drvdata(file);
struct iss_video_fh *handle;
struct vb2_queue *q;
int ret = 0;
handle = kzalloc(sizeof(*handle), GFP_KERNEL);
if (handle == NULL)
return -ENOMEM;
v4l2_fh_init(&handle->vfh, &video->video);
v4l2_fh_add(&handle->vfh);
/* If this is the first user, initialise the pipeline. */
if (omap4iss_get(video->iss) == NULL) {
ret = -EBUSY;
goto done;
}
ret = omap4iss_pipeline_pm_use(&video->video.entity, 1);
if (ret < 0) {
omap4iss_put(video->iss);
goto done;
}
video->alloc_ctx = vb2_dma_contig_init_ctx(video->iss->dev);
if (IS_ERR(video->alloc_ctx)) {
ret = PTR_ERR(video->alloc_ctx);
omap4iss_put(video->iss);
goto done;
}
q = &handle->queue;
q->type = video->type;
q->io_modes = VB2_MMAP | VB2_DMABUF;
q->drv_priv = handle;
q->ops = &iss_video_vb2ops;
q->mem_ops = &vb2_dma_contig_memops;
q->buf_struct_size = sizeof(struct iss_buffer);
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
ret = vb2_queue_init(q);
if (ret) {
omap4iss_put(video->iss);
goto done;
}
memset(&handle->format, 0, sizeof(handle->format));
handle->format.type = video->type;
handle->timeperframe.denominator = 1;
handle->video = video;
file->private_data = &handle->vfh;
done:
if (ret < 0) {
v4l2_fh_del(&handle->vfh);
kfree(handle);
}
return ret;
}
static int iss_video_release(struct file *file)
{
struct iss_video *video = video_drvdata(file);
struct v4l2_fh *vfh = file->private_data;
struct iss_video_fh *handle = to_iss_video_fh(vfh);
/* Disable streaming and free the buffers queue resources. */
iss_video_streamoff(file, vfh, video->type);
omap4iss_pipeline_pm_use(&video->video.entity, 0);
/* Release the videobuf2 queue */
vb2_queue_release(&handle->queue);
/* Release the file handle. */
v4l2_fh_del(vfh);
kfree(handle);
file->private_data = NULL;
omap4iss_put(video->iss);
return 0;
}
static unsigned int iss_video_poll(struct file *file, poll_table *wait)
{
struct iss_video_fh *vfh = to_iss_video_fh(file->private_data);
return vb2_poll(&vfh->queue, file, wait);
}
static int iss_video_mmap(struct file *file, struct vm_area_struct *vma)
{
struct iss_video_fh *vfh = to_iss_video_fh(file->private_data);
return vb2_mmap(&vfh->queue, vma);
}
static struct v4l2_file_operations iss_video_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
.open = iss_video_open,
.release = iss_video_release,
.poll = iss_video_poll,
.mmap = iss_video_mmap,
};
/* -----------------------------------------------------------------------------
* ISS video core
*/
static const struct iss_video_operations iss_video_dummy_ops = {
};
int omap4iss_video_init(struct iss_video *video, const char *name)
{
const char *direction;
int ret;
switch (video->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
direction = "output";
video->pad.flags = MEDIA_PAD_FL_SINK;
break;
case V4L2_BUF_TYPE_VIDEO_OUTPUT:
direction = "input";
video->pad.flags = MEDIA_PAD_FL_SOURCE;
break;
default:
return -EINVAL;
}
ret = media_entity_init(&video->video.entity, 1, &video->pad, 0);
if (ret < 0)
return ret;
spin_lock_init(&video->qlock);
mutex_init(&video->mutex);
atomic_set(&video->active, 0);
spin_lock_init(&video->pipe.lock);
mutex_init(&video->stream_lock);
/* Initialize the video device. */
if (video->ops == NULL)
video->ops = &iss_video_dummy_ops;
video->video.fops = &iss_video_fops;
snprintf(video->video.name, sizeof(video->video.name),
"OMAP4 ISS %s %s", name, direction);
video->video.vfl_type = VFL_TYPE_GRABBER;
video->video.release = video_device_release_empty;
video->video.ioctl_ops = &iss_video_ioctl_ops;
video->pipe.stream_state = ISS_PIPELINE_STREAM_STOPPED;
video_set_drvdata(&video->video, video);
return 0;
}
void omap4iss_video_cleanup(struct iss_video *video)
{
media_entity_cleanup(&video->video.entity);
mutex_destroy(&video->stream_lock);
mutex_destroy(&video->mutex);
}
int omap4iss_video_register(struct iss_video *video, struct v4l2_device *vdev)
{
int ret;
video->video.v4l2_dev = vdev;
ret = video_register_device(&video->video, VFL_TYPE_GRABBER, -1);
if (ret < 0)
dev_err(video->iss->dev,
"could not register video device (%d)\n", ret);
return ret;
}
void omap4iss_video_unregister(struct iss_video *video)
{
video_unregister_device(&video->video);
}
| gpl-2.0 |
ArthySundaram/firstrepo | arch/x86/kernel/kprobes.c | 411 | 32117 | /*
* Kernel Probes (KProbes)
*
* 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.
*
* Copyright (C) IBM Corporation, 2002, 2004
*
* 2002-Oct Created by Vamsi Krishna S <vamsi_krishna@in.ibm.com> Kernel
* Probes initial implementation ( includes contributions from
* Rusty Russell).
* 2004-July Suparna Bhattacharya <suparna@in.ibm.com> added jumper probes
* interface to access function arguments.
* 2004-Oct Jim Keniston <jkenisto@us.ibm.com> and Prasanna S Panchamukhi
* <prasanna@in.ibm.com> adapted for x86_64 from i386.
* 2005-Mar Roland McGrath <roland@redhat.com>
* Fixed to handle %rip-relative addressing mode correctly.
* 2005-May Hien Nguyen <hien@us.ibm.com>, Jim Keniston
* <jkenisto@us.ibm.com> and Prasanna S Panchamukhi
* <prasanna@in.ibm.com> added function-return probes.
* 2005-May Rusty Lynch <rusty.lynch@intel.com>
* Added function return probes functionality
* 2006-Feb Masami Hiramatsu <hiramatu@sdl.hitachi.co.jp> added
* kprobe-booster and kretprobe-booster for i386.
* 2007-Dec Masami Hiramatsu <mhiramat@redhat.com> added kprobe-booster
* and kretprobe-booster for x86-64
* 2007-Dec Masami Hiramatsu <mhiramat@redhat.com>, Arjan van de Ven
* <arjan@infradead.org> and Jim Keniston <jkenisto@us.ibm.com>
* unified x86 kprobes code.
*/
#include <linux/kprobes.h>
#include <linux/ptrace.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/hardirq.h>
#include <linux/preempt.h>
#include <linux/module.h>
#include <linux/kdebug.h>
#include <asm/cacheflush.h>
#include <asm/desc.h>
#include <asm/pgtable.h>
#include <asm/uaccess.h>
#include <asm/alternative.h>
void jprobe_return_end(void);
DEFINE_PER_CPU(struct kprobe *, current_kprobe) = NULL;
DEFINE_PER_CPU(struct kprobe_ctlblk, kprobe_ctlblk);
#ifdef CONFIG_X86_64
#define stack_addr(regs) ((unsigned long *)regs->sp)
#else
/*
* "®s->sp" looks wrong, but it's correct for x86_32. x86_32 CPUs
* don't save the ss and esp registers if the CPU is already in kernel
* mode when it traps. So for kprobes, regs->sp and regs->ss are not
* the [nonexistent] saved stack pointer and ss register, but rather
* the top 8 bytes of the pre-int3 stack. So ®s->sp happens to
* point to the top of the pre-int3 stack.
*/
#define stack_addr(regs) ((unsigned long *)®s->sp)
#endif
#define W(row, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bb, bc, bd, be, bf)\
(((b0##UL << 0x0)|(b1##UL << 0x1)|(b2##UL << 0x2)|(b3##UL << 0x3) | \
(b4##UL << 0x4)|(b5##UL << 0x5)|(b6##UL << 0x6)|(b7##UL << 0x7) | \
(b8##UL << 0x8)|(b9##UL << 0x9)|(ba##UL << 0xa)|(bb##UL << 0xb) | \
(bc##UL << 0xc)|(bd##UL << 0xd)|(be##UL << 0xe)|(bf##UL << 0xf)) \
<< (row % 32))
/*
* Undefined/reserved opcodes, conditional jump, Opcode Extension
* Groups, and some special opcodes can not boost.
*/
static const u32 twobyte_is_boostable[256 / 32] = {
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/* ---------------------------------------------- */
W(0x00, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0) | /* 00 */
W(0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 10 */
W(0x20, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 20 */
W(0x30, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 30 */
W(0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 40 */
W(0x50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 50 */
W(0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1) | /* 60 */
W(0x70, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1) , /* 70 */
W(0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 80 */
W(0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 90 */
W(0xa0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) | /* a0 */
W(0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1) , /* b0 */
W(0xc0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1) | /* c0 */
W(0xd0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) , /* d0 */
W(0xe0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1) | /* e0 */
W(0xf0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0) /* f0 */
/* ----------------------------------------------- */
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
};
static const u32 onebyte_has_modrm[256 / 32] = {
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/* ----------------------------------------------- */
W(0x00, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0) | /* 00 */
W(0x10, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0) , /* 10 */
W(0x20, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0) | /* 20 */
W(0x30, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0) , /* 30 */
W(0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 40 */
W(0x50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 50 */
W(0x60, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0) | /* 60 */
W(0x70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 70 */
W(0x80, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 80 */
W(0x90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 90 */
W(0xa0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* a0 */
W(0xb0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* b0 */
W(0xc0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0) | /* c0 */
W(0xd0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1) , /* d0 */
W(0xe0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* e0 */
W(0xf0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1) /* f0 */
/* ----------------------------------------------- */
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
};
static const u32 twobyte_has_modrm[256 / 32] = {
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
/* ----------------------------------------------- */
W(0x00, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1) | /* 0f */
W(0x10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0) , /* 1f */
W(0x20, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1) | /* 2f */
W(0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) , /* 3f */
W(0x40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 4f */
W(0x50, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 5f */
W(0x60, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* 6f */
W(0x70, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1) , /* 7f */
W(0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) | /* 8f */
W(0x90, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* 9f */
W(0xa0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1) | /* af */
W(0xb0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1) , /* bf */
W(0xc0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0) | /* cf */
W(0xd0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) , /* df */
W(0xe0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) | /* ef */
W(0xf0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0) /* ff */
/* ----------------------------------------------- */
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
};
#undef W
struct kretprobe_blackpoint kretprobe_blacklist[] = {
{"__switch_to", }, /* This function switches only current task, but
doesn't switch kernel stack.*/
{NULL, NULL} /* Terminator */
};
const int kretprobe_blacklist_size = ARRAY_SIZE(kretprobe_blacklist);
/* Insert a jump instruction at address 'from', which jumps to address 'to'.*/
static void __kprobes set_jmp_op(void *from, void *to)
{
struct __arch_jmp_op {
char op;
s32 raddr;
} __attribute__((packed)) * jop;
jop = (struct __arch_jmp_op *)from;
jop->raddr = (s32)((long)(to) - ((long)(from) + 5));
jop->op = RELATIVEJUMP_INSTRUCTION;
}
/*
* Check for the REX prefix which can only exist on X86_64
* X86_32 always returns 0
*/
static int __kprobes is_REX_prefix(kprobe_opcode_t *insn)
{
#ifdef CONFIG_X86_64
if ((*insn & 0xf0) == 0x40)
return 1;
#endif
return 0;
}
/*
* Returns non-zero if opcode is boostable.
* RIP relative instructions are adjusted at copying time in 64 bits mode
*/
static int __kprobes can_boost(kprobe_opcode_t *opcodes)
{
kprobe_opcode_t opcode;
kprobe_opcode_t *orig_opcodes = opcodes;
if (search_exception_tables((unsigned long)opcodes))
return 0; /* Page fault may occur on this address. */
retry:
if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
return 0;
opcode = *(opcodes++);
/* 2nd-byte opcode */
if (opcode == 0x0f) {
if (opcodes - orig_opcodes > MAX_INSN_SIZE - 1)
return 0;
return test_bit(*opcodes,
(unsigned long *)twobyte_is_boostable);
}
switch (opcode & 0xf0) {
#ifdef CONFIG_X86_64
case 0x40:
goto retry; /* REX prefix is boostable */
#endif
case 0x60:
if (0x63 < opcode && opcode < 0x67)
goto retry; /* prefixes */
/* can't boost Address-size override and bound */
return (opcode != 0x62 && opcode != 0x67);
case 0x70:
return 0; /* can't boost conditional jump */
case 0xc0:
/* can't boost software-interruptions */
return (0xc1 < opcode && opcode < 0xcc) || opcode == 0xcf;
case 0xd0:
/* can boost AA* and XLAT */
return (opcode == 0xd4 || opcode == 0xd5 || opcode == 0xd7);
case 0xe0:
/* can boost in/out and absolute jmps */
return ((opcode & 0x04) || opcode == 0xea);
case 0xf0:
if ((opcode & 0x0c) == 0 && opcode != 0xf1)
goto retry; /* lock/rep(ne) prefix */
/* clear and set flags are boostable */
return (opcode == 0xf5 || (0xf7 < opcode && opcode < 0xfe));
default:
/* segment override prefixes are boostable */
if (opcode == 0x26 || opcode == 0x36 || opcode == 0x3e)
goto retry; /* prefixes */
/* CS override prefix and call are not boostable */
return (opcode != 0x2e && opcode != 0x9a);
}
}
/*
* Returns non-zero if opcode modifies the interrupt flag.
*/
static int __kprobes is_IF_modifier(kprobe_opcode_t *insn)
{
switch (*insn) {
case 0xfa: /* cli */
case 0xfb: /* sti */
case 0xcf: /* iret/iretd */
case 0x9d: /* popf/popfd */
return 1;
}
/*
* on X86_64, 0x40-0x4f are REX prefixes so we need to look
* at the next byte instead.. but of course not recurse infinitely
*/
if (is_REX_prefix(insn))
return is_IF_modifier(++insn);
return 0;
}
/*
* Adjust the displacement if the instruction uses the %rip-relative
* addressing mode.
* If it does, Return the address of the 32-bit displacement word.
* If not, return null.
* Only applicable to 64-bit x86.
*/
static void __kprobes fix_riprel(struct kprobe *p)
{
#ifdef CONFIG_X86_64
u8 *insn = p->ainsn.insn;
s64 disp;
int need_modrm;
/* Skip legacy instruction prefixes. */
while (1) {
switch (*insn) {
case 0x66:
case 0x67:
case 0x2e:
case 0x3e:
case 0x26:
case 0x64:
case 0x65:
case 0x36:
case 0xf0:
case 0xf3:
case 0xf2:
++insn;
continue;
}
break;
}
/* Skip REX instruction prefix. */
if (is_REX_prefix(insn))
++insn;
if (*insn == 0x0f) {
/* Two-byte opcode. */
++insn;
need_modrm = test_bit(*insn,
(unsigned long *)twobyte_has_modrm);
} else
/* One-byte opcode. */
need_modrm = test_bit(*insn,
(unsigned long *)onebyte_has_modrm);
if (need_modrm) {
u8 modrm = *++insn;
if ((modrm & 0xc7) == 0x05) {
/* %rip+disp32 addressing mode */
/* Displacement follows ModRM byte. */
++insn;
/*
* The copied instruction uses the %rip-relative
* addressing mode. Adjust the displacement for the
* difference between the original location of this
* instruction and the location of the copy that will
* actually be run. The tricky bit here is making sure
* that the sign extension happens correctly in this
* calculation, since we need a signed 32-bit result to
* be sign-extended to 64 bits when it's added to the
* %rip value and yield the same 64-bit result that the
* sign-extension of the original signed 32-bit
* displacement would have given.
*/
disp = (u8 *) p->addr + *((s32 *) insn) -
(u8 *) p->ainsn.insn;
BUG_ON((s64) (s32) disp != disp); /* Sanity check. */
*(s32 *)insn = (s32) disp;
}
}
#endif
}
static void __kprobes arch_copy_kprobe(struct kprobe *p)
{
memcpy(p->ainsn.insn, p->addr, MAX_INSN_SIZE * sizeof(kprobe_opcode_t));
fix_riprel(p);
if (can_boost(p->addr))
p->ainsn.boostable = 0;
else
p->ainsn.boostable = -1;
p->opcode = *p->addr;
}
int __kprobes arch_prepare_kprobe(struct kprobe *p)
{
/* insn: must be on special executable page on x86. */
p->ainsn.insn = get_insn_slot();
if (!p->ainsn.insn)
return -ENOMEM;
arch_copy_kprobe(p);
return 0;
}
void __kprobes arch_arm_kprobe(struct kprobe *p)
{
text_poke(p->addr, ((unsigned char []){BREAKPOINT_INSTRUCTION}), 1);
}
void __kprobes arch_disarm_kprobe(struct kprobe *p)
{
text_poke(p->addr, &p->opcode, 1);
}
void __kprobes arch_remove_kprobe(struct kprobe *p)
{
if (p->ainsn.insn) {
free_insn_slot(p->ainsn.insn, (p->ainsn.boostable == 1));
p->ainsn.insn = NULL;
}
}
static void __kprobes save_previous_kprobe(struct kprobe_ctlblk *kcb)
{
kcb->prev_kprobe.kp = kprobe_running();
kcb->prev_kprobe.status = kcb->kprobe_status;
kcb->prev_kprobe.old_flags = kcb->kprobe_old_flags;
kcb->prev_kprobe.saved_flags = kcb->kprobe_saved_flags;
}
static void __kprobes restore_previous_kprobe(struct kprobe_ctlblk *kcb)
{
__get_cpu_var(current_kprobe) = kcb->prev_kprobe.kp;
kcb->kprobe_status = kcb->prev_kprobe.status;
kcb->kprobe_old_flags = kcb->prev_kprobe.old_flags;
kcb->kprobe_saved_flags = kcb->prev_kprobe.saved_flags;
}
static void __kprobes set_current_kprobe(struct kprobe *p, struct pt_regs *regs,
struct kprobe_ctlblk *kcb)
{
__get_cpu_var(current_kprobe) = p;
kcb->kprobe_saved_flags = kcb->kprobe_old_flags
= (regs->flags & (X86_EFLAGS_TF | X86_EFLAGS_IF));
if (is_IF_modifier(p->ainsn.insn))
kcb->kprobe_saved_flags &= ~X86_EFLAGS_IF;
}
static void __kprobes clear_btf(void)
{
if (test_thread_flag(TIF_DEBUGCTLMSR))
update_debugctlmsr(0);
}
static void __kprobes restore_btf(void)
{
if (test_thread_flag(TIF_DEBUGCTLMSR))
update_debugctlmsr(current->thread.debugctlmsr);
}
static void __kprobes prepare_singlestep(struct kprobe *p, struct pt_regs *regs)
{
clear_btf();
regs->flags |= X86_EFLAGS_TF;
regs->flags &= ~X86_EFLAGS_IF;
/* single step inline if the instruction is an int3 */
if (p->opcode == BREAKPOINT_INSTRUCTION)
regs->ip = (unsigned long)p->addr;
else
regs->ip = (unsigned long)p->ainsn.insn;
}
void __kprobes arch_prepare_kretprobe(struct kretprobe_instance *ri,
struct pt_regs *regs)
{
unsigned long *sara = stack_addr(regs);
ri->ret_addr = (kprobe_opcode_t *) *sara;
/* Replace the return addr with trampoline addr */
*sara = (unsigned long) &kretprobe_trampoline;
}
static void __kprobes setup_singlestep(struct kprobe *p, struct pt_regs *regs,
struct kprobe_ctlblk *kcb)
{
#if !defined(CONFIG_PREEMPT) || defined(CONFIG_FREEZER)
if (p->ainsn.boostable == 1 && !p->post_handler) {
/* Boost up -- we can execute copied instructions directly */
reset_current_kprobe();
regs->ip = (unsigned long)p->ainsn.insn;
preempt_enable_no_resched();
return;
}
#endif
prepare_singlestep(p, regs);
kcb->kprobe_status = KPROBE_HIT_SS;
}
/*
* We have reentered the kprobe_handler(), since another probe was hit while
* within the handler. We save the original kprobes variables and just single
* step on the instruction of the new probe without calling any user handlers.
*/
static int __kprobes reenter_kprobe(struct kprobe *p, struct pt_regs *regs,
struct kprobe_ctlblk *kcb)
{
switch (kcb->kprobe_status) {
case KPROBE_HIT_SSDONE:
#ifdef CONFIG_X86_64
/* TODO: Provide re-entrancy from post_kprobes_handler() and
* avoid exception stack corruption while single-stepping on
* the instruction of the new probe.
*/
arch_disarm_kprobe(p);
regs->ip = (unsigned long)p->addr;
reset_current_kprobe();
preempt_enable_no_resched();
break;
#endif
case KPROBE_HIT_ACTIVE:
save_previous_kprobe(kcb);
set_current_kprobe(p, regs, kcb);
kprobes_inc_nmissed_count(p);
prepare_singlestep(p, regs);
kcb->kprobe_status = KPROBE_REENTER;
break;
case KPROBE_HIT_SS:
if (p == kprobe_running()) {
regs->flags &= ~X86_EFLAGS_TF;
regs->flags |= kcb->kprobe_saved_flags;
return 0;
} else {
/* A probe has been hit in the codepath leading up
* to, or just after, single-stepping of a probed
* instruction. This entire codepath should strictly
* reside in .kprobes.text section. Raise a warning
* to highlight this peculiar case.
*/
}
default:
/* impossible cases */
WARN_ON(1);
return 0;
}
return 1;
}
/*
* Interrupts are disabled on entry as trap3 is an interrupt gate and they
* remain disabled thorough out this function.
*/
static int __kprobes kprobe_handler(struct pt_regs *regs)
{
kprobe_opcode_t *addr;
struct kprobe *p;
struct kprobe_ctlblk *kcb;
addr = (kprobe_opcode_t *)(regs->ip - sizeof(kprobe_opcode_t));
if (*addr != BREAKPOINT_INSTRUCTION) {
/*
* The breakpoint instruction was removed right
* after we hit it. Another cpu has removed
* either a probepoint or a debugger breakpoint
* at this address. In either case, no further
* handling of this interrupt is appropriate.
* Back up over the (now missing) int3 and run
* the original instruction.
*/
regs->ip = (unsigned long)addr;
return 1;
}
/*
* We don't want to be preempted for the entire
* duration of kprobe processing. We conditionally
* re-enable preemption at the end of this function,
* and also in reenter_kprobe() and setup_singlestep().
*/
preempt_disable();
kcb = get_kprobe_ctlblk();
p = get_kprobe(addr);
if (p) {
if (kprobe_running()) {
if (reenter_kprobe(p, regs, kcb))
return 1;
} else {
set_current_kprobe(p, regs, kcb);
kcb->kprobe_status = KPROBE_HIT_ACTIVE;
/*
* If we have no pre-handler or it returned 0, we
* continue with normal processing. If we have a
* pre-handler and it returned non-zero, it prepped
* for calling the break_handler below on re-entry
* for jprobe processing, so get out doing nothing
* more here.
*/
if (!p->pre_handler || !p->pre_handler(p, regs))
setup_singlestep(p, regs, kcb);
return 1;
}
} else if (kprobe_running()) {
p = __get_cpu_var(current_kprobe);
if (p->break_handler && p->break_handler(p, regs)) {
setup_singlestep(p, regs, kcb);
return 1;
}
} /* else: not a kprobe fault; let the kernel handle it */
preempt_enable_no_resched();
return 0;
}
/*
* When a retprobed function returns, this code saves registers and
* calls trampoline_handler() runs, which calls the kretprobe's handler.
*/
static void __used __kprobes kretprobe_trampoline_holder(void)
{
asm volatile (
".global kretprobe_trampoline\n"
"kretprobe_trampoline: \n"
#ifdef CONFIG_X86_64
/* We don't bother saving the ss register */
" pushq %rsp\n"
" pushfq\n"
/*
* Skip cs, ip, orig_ax.
* trampoline_handler() will plug in these values
*/
" subq $24, %rsp\n"
" pushq %rdi\n"
" pushq %rsi\n"
" pushq %rdx\n"
" pushq %rcx\n"
" pushq %rax\n"
" pushq %r8\n"
" pushq %r9\n"
" pushq %r10\n"
" pushq %r11\n"
" pushq %rbx\n"
" pushq %rbp\n"
" pushq %r12\n"
" pushq %r13\n"
" pushq %r14\n"
" pushq %r15\n"
" movq %rsp, %rdi\n"
" call trampoline_handler\n"
/* Replace saved sp with true return address. */
" movq %rax, 152(%rsp)\n"
" popq %r15\n"
" popq %r14\n"
" popq %r13\n"
" popq %r12\n"
" popq %rbp\n"
" popq %rbx\n"
" popq %r11\n"
" popq %r10\n"
" popq %r9\n"
" popq %r8\n"
" popq %rax\n"
" popq %rcx\n"
" popq %rdx\n"
" popq %rsi\n"
" popq %rdi\n"
/* Skip orig_ax, ip, cs */
" addq $24, %rsp\n"
" popfq\n"
#else
" pushf\n"
/*
* Skip cs, ip, orig_ax and gs.
* trampoline_handler() will plug in these values
*/
" subl $16, %esp\n"
" pushl %fs\n"
" pushl %es\n"
" pushl %ds\n"
" pushl %eax\n"
" pushl %ebp\n"
" pushl %edi\n"
" pushl %esi\n"
" pushl %edx\n"
" pushl %ecx\n"
" pushl %ebx\n"
" movl %esp, %eax\n"
" call trampoline_handler\n"
/* Move flags to cs */
" movl 56(%esp), %edx\n"
" movl %edx, 52(%esp)\n"
/* Replace saved flags with true return address. */
" movl %eax, 56(%esp)\n"
" popl %ebx\n"
" popl %ecx\n"
" popl %edx\n"
" popl %esi\n"
" popl %edi\n"
" popl %ebp\n"
" popl %eax\n"
/* Skip ds, es, fs, gs, orig_ax and ip */
" addl $24, %esp\n"
" popf\n"
#endif
" ret\n");
}
/*
* Called from kretprobe_trampoline
*/
static __used __kprobes void *trampoline_handler(struct pt_regs *regs)
{
struct kretprobe_instance *ri = NULL;
struct hlist_head *head, empty_rp;
struct hlist_node *node, *tmp;
unsigned long flags, orig_ret_address = 0;
unsigned long trampoline_address = (unsigned long)&kretprobe_trampoline;
INIT_HLIST_HEAD(&empty_rp);
kretprobe_hash_lock(current, &head, &flags);
/* fixup registers */
#ifdef CONFIG_X86_64
regs->cs = __KERNEL_CS;
#else
regs->cs = __KERNEL_CS | get_kernel_rpl();
regs->gs = 0;
#endif
regs->ip = trampoline_address;
regs->orig_ax = ~0UL;
/*
* It is possible to have multiple instances associated with a given
* task either because multiple functions in the call path have
* return probes installed on them, and/or more than one
* return probe was registered for a target function.
*
* We can handle this because:
* - instances are always pushed into the head of the list
* - when multiple return probes are registered for the same
* function, the (chronologically) first instance's ret_addr
* will be the real return address, and all the rest will
* point to kretprobe_trampoline.
*/
hlist_for_each_entry_safe(ri, node, tmp, head, hlist) {
if (ri->task != current)
/* another task is sharing our hash bucket */
continue;
if (ri->rp && ri->rp->handler) {
__get_cpu_var(current_kprobe) = &ri->rp->kp;
get_kprobe_ctlblk()->kprobe_status = KPROBE_HIT_ACTIVE;
ri->rp->handler(ri, regs);
__get_cpu_var(current_kprobe) = NULL;
}
orig_ret_address = (unsigned long)ri->ret_addr;
recycle_rp_inst(ri, &empty_rp);
if (orig_ret_address != trampoline_address)
/*
* This is the real return address. Any other
* instances associated with this task are for
* other calls deeper on the call stack
*/
break;
}
kretprobe_assert(ri, orig_ret_address, trampoline_address);
kretprobe_hash_unlock(current, &flags);
hlist_for_each_entry_safe(ri, node, tmp, &empty_rp, hlist) {
hlist_del(&ri->hlist);
kfree(ri);
}
return (void *)orig_ret_address;
}
/*
* Called after single-stepping. p->addr is the address of the
* instruction whose first byte has been replaced by the "int 3"
* instruction. To avoid the SMP problems that can occur when we
* temporarily put back the original opcode to single-step, we
* single-stepped a copy of the instruction. The address of this
* copy is p->ainsn.insn.
*
* This function prepares to return from the post-single-step
* interrupt. We have to fix up the stack as follows:
*
* 0) Except in the case of absolute or indirect jump or call instructions,
* the new ip is relative to the copied instruction. We need to make
* it relative to the original instruction.
*
* 1) If the single-stepped instruction was pushfl, then the TF and IF
* flags are set in the just-pushed flags, and may need to be cleared.
*
* 2) If the single-stepped instruction was a call, the return address
* that is atop the stack is the address following the copied instruction.
* We need to make it the address following the original instruction.
*
* If this is the first time we've single-stepped the instruction at
* this probepoint, and the instruction is boostable, boost it: add a
* jump instruction after the copied instruction, that jumps to the next
* instruction after the probepoint.
*/
static void __kprobes resume_execution(struct kprobe *p,
struct pt_regs *regs, struct kprobe_ctlblk *kcb)
{
unsigned long *tos = stack_addr(regs);
unsigned long copy_ip = (unsigned long)p->ainsn.insn;
unsigned long orig_ip = (unsigned long)p->addr;
kprobe_opcode_t *insn = p->ainsn.insn;
/*skip the REX prefix*/
if (is_REX_prefix(insn))
insn++;
regs->flags &= ~X86_EFLAGS_TF;
switch (*insn) {
case 0x9c: /* pushfl */
*tos &= ~(X86_EFLAGS_TF | X86_EFLAGS_IF);
*tos |= kcb->kprobe_old_flags;
break;
case 0xc2: /* iret/ret/lret */
case 0xc3:
case 0xca:
case 0xcb:
case 0xcf:
case 0xea: /* jmp absolute -- ip is correct */
/* ip is already adjusted, no more changes required */
p->ainsn.boostable = 1;
goto no_change;
case 0xe8: /* call relative - Fix return addr */
*tos = orig_ip + (*tos - copy_ip);
break;
#ifdef CONFIG_X86_32
case 0x9a: /* call absolute -- same as call absolute, indirect */
*tos = orig_ip + (*tos - copy_ip);
goto no_change;
#endif
case 0xff:
if ((insn[1] & 0x30) == 0x10) {
/*
* call absolute, indirect
* Fix return addr; ip is correct.
* But this is not boostable
*/
*tos = orig_ip + (*tos - copy_ip);
goto no_change;
} else if (((insn[1] & 0x31) == 0x20) ||
((insn[1] & 0x31) == 0x21)) {
/*
* jmp near and far, absolute indirect
* ip is correct. And this is boostable
*/
p->ainsn.boostable = 1;
goto no_change;
}
default:
break;
}
if (p->ainsn.boostable == 0) {
if ((regs->ip > copy_ip) &&
(regs->ip - copy_ip) + 5 < MAX_INSN_SIZE) {
/*
* These instructions can be executed directly if it
* jumps back to correct address.
*/
set_jmp_op((void *)regs->ip,
(void *)orig_ip + (regs->ip - copy_ip));
p->ainsn.boostable = 1;
} else {
p->ainsn.boostable = -1;
}
}
regs->ip += orig_ip - copy_ip;
no_change:
restore_btf();
}
/*
* Interrupts are disabled on entry as trap1 is an interrupt gate and they
* remain disabled thoroughout this function.
*/
static int __kprobes post_kprobe_handler(struct pt_regs *regs)
{
struct kprobe *cur = kprobe_running();
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
if (!cur)
return 0;
resume_execution(cur, regs, kcb);
regs->flags |= kcb->kprobe_saved_flags;
if ((kcb->kprobe_status != KPROBE_REENTER) && cur->post_handler) {
kcb->kprobe_status = KPROBE_HIT_SSDONE;
cur->post_handler(cur, regs, 0);
}
/* Restore back the original saved kprobes variables and continue. */
if (kcb->kprobe_status == KPROBE_REENTER) {
restore_previous_kprobe(kcb);
goto out;
}
reset_current_kprobe();
out:
preempt_enable_no_resched();
/*
* if somebody else is singlestepping across a probe point, flags
* will have TF set, in which case, continue the remaining processing
* of do_debug, as if this is not a probe hit.
*/
if (regs->flags & X86_EFLAGS_TF)
return 0;
return 1;
}
int __kprobes kprobe_fault_handler(struct pt_regs *regs, int trapnr)
{
struct kprobe *cur = kprobe_running();
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
switch (kcb->kprobe_status) {
case KPROBE_HIT_SS:
case KPROBE_REENTER:
/*
* We are here because the instruction being single
* stepped caused a page fault. We reset the current
* kprobe and the ip points back to the probe address
* and allow the page fault handler to continue as a
* normal page fault.
*/
regs->ip = (unsigned long)cur->addr;
regs->flags |= kcb->kprobe_old_flags;
if (kcb->kprobe_status == KPROBE_REENTER)
restore_previous_kprobe(kcb);
else
reset_current_kprobe();
preempt_enable_no_resched();
break;
case KPROBE_HIT_ACTIVE:
case KPROBE_HIT_SSDONE:
/*
* We increment the nmissed count for accounting,
* we can also use npre/npostfault count for accounting
* these specific fault cases.
*/
kprobes_inc_nmissed_count(cur);
/*
* We come here because instructions in the pre/post
* handler caused the page_fault, this could happen
* if handler tries to access user space by
* copy_from_user(), get_user() etc. Let the
* user-specified handler try to fix it first.
*/
if (cur->fault_handler && cur->fault_handler(cur, regs, trapnr))
return 1;
/*
* In case the user-specified fault handler returned
* zero, try to fix up.
*/
if (fixup_exception(regs))
return 1;
/*
* fixup routine could not handle it,
* Let do_page_fault() fix it.
*/
break;
default:
break;
}
return 0;
}
/*
* Wrapper routine for handling exceptions.
*/
int __kprobes kprobe_exceptions_notify(struct notifier_block *self,
unsigned long val, void *data)
{
struct die_args *args = data;
int ret = NOTIFY_DONE;
if (args->regs && user_mode_vm(args->regs))
return ret;
switch (val) {
case DIE_INT3:
if (kprobe_handler(args->regs))
ret = NOTIFY_STOP;
break;
case DIE_DEBUG:
if (post_kprobe_handler(args->regs))
ret = NOTIFY_STOP;
break;
case DIE_GPF:
/*
* To be potentially processing a kprobe fault and to
* trust the result from kprobe_running(), we have
* be non-preemptible.
*/
if (!preemptible() && kprobe_running() &&
kprobe_fault_handler(args->regs, args->trapnr))
ret = NOTIFY_STOP;
break;
default:
break;
}
return ret;
}
int __kprobes setjmp_pre_handler(struct kprobe *p, struct pt_regs *regs)
{
struct jprobe *jp = container_of(p, struct jprobe, kp);
unsigned long addr;
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
kcb->jprobe_saved_regs = *regs;
kcb->jprobe_saved_sp = stack_addr(regs);
addr = (unsigned long)(kcb->jprobe_saved_sp);
/*
* As Linus pointed out, gcc assumes that the callee
* owns the argument space and could overwrite it, e.g.
* tailcall optimization. So, to be absolutely safe
* we also save and restore enough stack bytes to cover
* the argument area.
*/
memcpy(kcb->jprobes_stack, (kprobe_opcode_t *)addr,
MIN_STACK_SIZE(addr));
regs->flags &= ~X86_EFLAGS_IF;
trace_hardirqs_off();
regs->ip = (unsigned long)(jp->entry);
return 1;
}
void __kprobes jprobe_return(void)
{
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
asm volatile (
#ifdef CONFIG_X86_64
" xchg %%rbx,%%rsp \n"
#else
" xchgl %%ebx,%%esp \n"
#endif
" int3 \n"
" .globl jprobe_return_end\n"
" jprobe_return_end: \n"
" nop \n"::"b"
(kcb->jprobe_saved_sp):"memory");
}
int __kprobes longjmp_break_handler(struct kprobe *p, struct pt_regs *regs)
{
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
u8 *addr = (u8 *) (regs->ip - 1);
struct jprobe *jp = container_of(p, struct jprobe, kp);
if ((addr > (u8 *) jprobe_return) &&
(addr < (u8 *) jprobe_return_end)) {
if (stack_addr(regs) != kcb->jprobe_saved_sp) {
struct pt_regs *saved_regs = &kcb->jprobe_saved_regs;
printk(KERN_ERR
"current sp %p does not match saved sp %p\n",
stack_addr(regs), kcb->jprobe_saved_sp);
printk(KERN_ERR "Saved registers for jprobe %p\n", jp);
show_registers(saved_regs);
printk(KERN_ERR "Current registers\n");
show_registers(regs);
BUG();
}
*regs = kcb->jprobe_saved_regs;
memcpy((kprobe_opcode_t *)(kcb->jprobe_saved_sp),
kcb->jprobes_stack,
MIN_STACK_SIZE(kcb->jprobe_saved_sp));
preempt_enable_no_resched();
return 1;
}
return 0;
}
int __init arch_init_kprobes(void)
{
return 0;
}
int __kprobes arch_trampoline_kprobe(struct kprobe *p)
{
return 0;
}
| gpl-2.0 |
TeamHorizon/android_kernel_htc_endeavoru | drivers/gpio/gpio-74x164.c | 411 | 4045 | /*
* 74Hx164 - Generic serial-in/parallel-out 8-bits shift register GPIO driver
*
* Copyright (C) 2010 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2010 Miguel Gaio <miguel.gaio@efixo.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/init.h>
#include <linux/mutex.h>
#include <linux/spi/spi.h>
#include <linux/spi/74x164.h>
#include <linux/gpio.h>
#include <linux/slab.h>
struct gen_74x164_chip {
struct spi_device *spi;
struct gpio_chip gpio_chip;
struct mutex lock;
u8 port_config;
};
static struct gen_74x164_chip *gpio_to_74x164_chip(struct gpio_chip *gc)
{
return container_of(gc, struct gen_74x164_chip, gpio_chip);
}
static int __gen_74x164_write_config(struct gen_74x164_chip *chip)
{
return spi_write(chip->spi,
&chip->port_config, sizeof(chip->port_config));
}
static int gen_74x164_get_value(struct gpio_chip *gc, unsigned offset)
{
struct gen_74x164_chip *chip = gpio_to_74x164_chip(gc);
int ret;
mutex_lock(&chip->lock);
ret = (chip->port_config >> offset) & 0x1;
mutex_unlock(&chip->lock);
return ret;
}
static void gen_74x164_set_value(struct gpio_chip *gc,
unsigned offset, int val)
{
struct gen_74x164_chip *chip = gpio_to_74x164_chip(gc);
mutex_lock(&chip->lock);
if (val)
chip->port_config |= (1 << offset);
else
chip->port_config &= ~(1 << offset);
__gen_74x164_write_config(chip);
mutex_unlock(&chip->lock);
}
static int gen_74x164_direction_output(struct gpio_chip *gc,
unsigned offset, int val)
{
gen_74x164_set_value(gc, offset, val);
return 0;
}
static int __devinit gen_74x164_probe(struct spi_device *spi)
{
struct gen_74x164_chip *chip;
struct gen_74x164_chip_platform_data *pdata;
int ret;
pdata = spi->dev.platform_data;
if (!pdata || !pdata->base) {
dev_dbg(&spi->dev, "incorrect or missing platform data\n");
return -EINVAL;
}
/*
* bits_per_word cannot be configured in platform data
*/
spi->bits_per_word = 8;
ret = spi_setup(spi);
if (ret < 0)
return ret;
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
mutex_init(&chip->lock);
dev_set_drvdata(&spi->dev, chip);
chip->spi = spi;
chip->gpio_chip.label = spi->modalias;
chip->gpio_chip.direction_output = gen_74x164_direction_output;
chip->gpio_chip.get = gen_74x164_get_value;
chip->gpio_chip.set = gen_74x164_set_value;
chip->gpio_chip.base = pdata->base;
chip->gpio_chip.ngpio = 8;
chip->gpio_chip.can_sleep = 1;
chip->gpio_chip.dev = &spi->dev;
chip->gpio_chip.owner = THIS_MODULE;
ret = __gen_74x164_write_config(chip);
if (ret) {
dev_err(&spi->dev, "Failed writing: %d\n", ret);
goto exit_destroy;
}
ret = gpiochip_add(&chip->gpio_chip);
if (ret)
goto exit_destroy;
return ret;
exit_destroy:
dev_set_drvdata(&spi->dev, NULL);
mutex_destroy(&chip->lock);
kfree(chip);
return ret;
}
static int __devexit gen_74x164_remove(struct spi_device *spi)
{
struct gen_74x164_chip *chip;
int ret;
chip = dev_get_drvdata(&spi->dev);
if (chip == NULL)
return -ENODEV;
dev_set_drvdata(&spi->dev, NULL);
ret = gpiochip_remove(&chip->gpio_chip);
if (!ret) {
mutex_destroy(&chip->lock);
kfree(chip);
} else
dev_err(&spi->dev, "Failed to remove the GPIO controller: %d\n",
ret);
return ret;
}
static struct spi_driver gen_74x164_driver = {
.driver = {
.name = "74x164",
.owner = THIS_MODULE,
},
.probe = gen_74x164_probe,
.remove = __devexit_p(gen_74x164_remove),
};
static int __init gen_74x164_init(void)
{
return spi_register_driver(&gen_74x164_driver);
}
subsys_initcall(gen_74x164_init);
static void __exit gen_74x164_exit(void)
{
spi_unregister_driver(&gen_74x164_driver);
}
module_exit(gen_74x164_exit);
MODULE_AUTHOR("Gabor Juhos <juhosg@openwrt.org>");
MODULE_AUTHOR("Miguel Gaio <miguel.gaio@efixo.com>");
MODULE_DESCRIPTION("GPIO expander driver for 74X164 8-bits shift register");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
hackerspace/rpi-linux | arch/powerpc/platforms/powernv/opal-nvram.c | 1179 | 2049 | /*
* PowerNV nvram code.
*
* Copyright 2011 IBM Corp.
*
* 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.
*/
#define DEBUG
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/of.h>
#include <asm/opal.h>
#include <asm/nvram.h>
#include <asm/machdep.h>
static unsigned int nvram_size;
static ssize_t opal_nvram_size(void)
{
return nvram_size;
}
static ssize_t opal_nvram_read(char *buf, size_t count, loff_t *index)
{
s64 rc;
int off;
if (*index >= nvram_size)
return 0;
off = *index;
if ((off + count) > nvram_size)
count = nvram_size - off;
rc = opal_read_nvram(__pa(buf), count, off);
if (rc != OPAL_SUCCESS)
return -EIO;
*index += count;
return count;
}
static ssize_t opal_nvram_write(char *buf, size_t count, loff_t *index)
{
s64 rc = OPAL_BUSY;
int off;
if (*index >= nvram_size)
return 0;
off = *index;
if ((off + count) > nvram_size)
count = nvram_size - off;
while (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) {
rc = opal_write_nvram(__pa(buf), count, off);
if (rc == OPAL_BUSY_EVENT)
opal_poll_events(NULL);
}
*index += count;
return count;
}
static int __init opal_nvram_init_log_partitions(void)
{
/* Scan nvram for partitions */
nvram_scan_partitions();
nvram_init_oops_partition(0);
return 0;
}
machine_arch_initcall(powernv, opal_nvram_init_log_partitions);
void __init opal_nvram_init(void)
{
struct device_node *np;
const __be32 *nbytes_p;
np = of_find_compatible_node(NULL, NULL, "ibm,opal-nvram");
if (np == NULL)
return;
nbytes_p = of_get_property(np, "#bytes", NULL);
if (!nbytes_p) {
of_node_put(np);
return;
}
nvram_size = be32_to_cpup(nbytes_p);
pr_info("OPAL nvram setup, %u bytes\n", nvram_size);
of_node_put(np);
ppc_md.nvram_read = opal_nvram_read;
ppc_md.nvram_write = opal_nvram_write;
ppc_md.nvram_size = opal_nvram_size;
}
| gpl-2.0 |
Hani-K/H-Vitamin_trltedt | ipc/shm.c | 1179 | 32665 | /*
* linux/ipc/shm.c
* Copyright (C) 1992, 1993 Krishna Balasubramanian
* Many improvements/fixes by Bruno Haible.
* Replaced `struct shm_desc' by `struct vm_area_struct', July 1994.
* Fixed the shm swap deallocation (shm_unuse()), August 1998 Andrea Arcangeli.
*
* /proc/sysvipc/shm support (c) 1999 Dragos Acostachioaie <dragos@iname.com>
* BIGMEM support, Andrea Arcangeli <andrea@suse.de>
* SMP thread shm, Jean-Luc Boyard <jean-luc.boyard@siemens.fr>
* HIGHMEM support, Ingo Molnar <mingo@redhat.com>
* Make shmmax, shmall, shmmni sysctl'able, Christoph Rohland <cr@sap.com>
* Shared /dev/zero support, Kanoj Sarcar <kanoj@sgi.com>
* Move the mm functionality over to mm/shmem.c, Christoph Rohland <cr@sap.com>
*
* support for audit of ipc object properties and permission changes
* Dustin Kirkland <dustin.kirkland@us.ibm.com>
*
* namespaces support
* OpenVZ, SWsoft Inc.
* Pavel Emelianov <xemul@openvz.org>
*
* Better ipc lock (kern_ipc_perm.lock) handling
* Davidlohr Bueso <davidlohr.bueso@hp.com>, June 2013.
*/
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/hugetlb.h>
#include <linux/shm.h>
#include <linux/init.h>
#include <linux/file.h>
#include <linux/mman.h>
#include <linux/shmem_fs.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/audit.h>
#include <linux/capability.h>
#include <linux/ptrace.h>
#include <linux/seq_file.h>
#include <linux/rwsem.h>
#include <linux/nsproxy.h>
#include <linux/mount.h>
#include <linux/ipc_namespace.h>
#include <asm/uaccess.h>
#include "util.h"
struct shm_file_data {
int id;
struct ipc_namespace *ns;
struct file *file;
const struct vm_operations_struct *vm_ops;
};
#define shm_file_data(file) (*((struct shm_file_data **)&(file)->private_data))
static const struct file_operations shm_file_operations;
static const struct vm_operations_struct shm_vm_ops;
#define shm_ids(ns) ((ns)->ids[IPC_SHM_IDS])
#define shm_unlock(shp) \
ipc_unlock(&(shp)->shm_perm)
static int newseg(struct ipc_namespace *, struct ipc_params *);
static void shm_open(struct vm_area_struct *vma);
static void shm_close(struct vm_area_struct *vma);
static void shm_destroy (struct ipc_namespace *ns, struct shmid_kernel *shp);
#ifdef CONFIG_PROC_FS
static int sysvipc_shm_proc_show(struct seq_file *s, void *it);
#endif
void shm_init_ns(struct ipc_namespace *ns)
{
ns->shm_ctlmax = SHMMAX;
ns->shm_ctlall = SHMALL;
ns->shm_ctlmni = SHMMNI;
ns->shm_rmid_forced = 0;
ns->shm_tot = 0;
ipc_init_ids(&shm_ids(ns));
}
/*
* Called with shm_ids.rwsem (writer) and the shp structure locked.
* Only shm_ids.rwsem remains locked on exit.
*/
static void do_shm_rmid(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp)
{
struct shmid_kernel *shp;
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
if (shp->shm_nattch){
shp->shm_perm.mode |= SHM_DEST;
/* Do not find it any more */
shp->shm_perm.key = IPC_PRIVATE;
shm_unlock(shp);
} else
shm_destroy(ns, shp);
}
#ifdef CONFIG_IPC_NS
void shm_exit_ns(struct ipc_namespace *ns)
{
free_ipcs(ns, &shm_ids(ns), do_shm_rmid);
idr_destroy(&ns->ids[IPC_SHM_IDS].ipcs_idr);
}
#endif
static int __init ipc_ns_init(void)
{
shm_init_ns(&init_ipc_ns);
return 0;
}
pure_initcall(ipc_ns_init);
void __init shm_init (void)
{
ipc_init_proc_interface("sysvipc/shm",
#if BITS_PER_LONG <= 32
" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n",
#else
" key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n",
#endif
IPC_SHM_IDS, sysvipc_shm_proc_show);
}
static inline struct shmid_kernel *shm_obtain_object(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_obtain_object(&shm_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
static inline struct shmid_kernel *shm_obtain_object_check(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_obtain_object_check(&shm_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
/*
* shm_lock_(check_) routines are called in the paths where the rwsem
* is not necessarily held.
*/
static inline struct shmid_kernel *shm_lock(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_lock(&shm_ids(ns), id);
if (IS_ERR(ipcp))
return (struct shmid_kernel *)ipcp;
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
static inline void shm_lock_by_ptr(struct shmid_kernel *ipcp)
{
rcu_read_lock();
ipc_lock_object(&ipcp->shm_perm);
}
static void shm_rcu_free(struct rcu_head *head)
{
struct ipc_rcu *p = container_of(head, struct ipc_rcu, rcu);
struct shmid_kernel *shp = ipc_rcu_to_struct(p);
security_shm_free(shp);
ipc_rcu_free(head);
}
static inline void shm_rmid(struct ipc_namespace *ns, struct shmid_kernel *s)
{
ipc_rmid(&shm_ids(ns), &s->shm_perm);
}
/* This is called by fork, once for every shm attach. */
static void shm_open(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
struct shmid_kernel *shp;
shp = shm_lock(sfd->ns, sfd->id);
BUG_ON(IS_ERR(shp));
shp->shm_atim = get_seconds();
shp->shm_lprid = task_tgid_vnr(current);
shp->shm_nattch++;
shm_unlock(shp);
}
/*
* shm_destroy - free the struct shmid_kernel
*
* @ns: namespace
* @shp: struct to free
*
* It has to be called with shp and shm_ids.rwsem (writer) locked,
* but returns with shp unlocked and freed.
*/
static void shm_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)
{
struct file *shm_file;
shm_file = shp->shm_file;
shp->shm_file = NULL;
ns->shm_tot -= (shp->shm_segsz + PAGE_SIZE - 1) >> PAGE_SHIFT;
shm_rmid(ns, shp);
shm_unlock(shp);
if (!is_file_hugepages(shm_file))
shmem_lock(shm_file, 0, shp->mlock_user);
else if (shp->mlock_user)
user_shm_unlock(file_inode(shm_file)->i_size, shp->mlock_user);
fput(shm_file);
ipc_rcu_putref(shp, shm_rcu_free);
}
/*
* shm_may_destroy - identifies whether shm segment should be destroyed now
*
* Returns true if and only if there are no active users of the segment and
* one of the following is true:
*
* 1) shmctl(id, IPC_RMID, NULL) was called for this shp
*
* 2) sysctl kernel.shm_rmid_forced is set to 1.
*/
static bool shm_may_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)
{
return (shp->shm_nattch == 0) &&
(ns->shm_rmid_forced ||
(shp->shm_perm.mode & SHM_DEST));
}
/*
* remove the attach descriptor vma.
* free memory for segment if it is marked destroyed.
* The descriptor has already been removed from the current->mm->mmap list
* and will later be kfree()d.
*/
static void shm_close(struct vm_area_struct *vma)
{
struct file * file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
struct shmid_kernel *shp;
struct ipc_namespace *ns = sfd->ns;
down_write(&shm_ids(ns).rwsem);
/* remove from the list of attaches of the shm segment */
shp = shm_lock(ns, sfd->id);
BUG_ON(IS_ERR(shp));
shp->shm_lprid = task_tgid_vnr(current);
shp->shm_dtim = get_seconds();
shp->shm_nattch--;
if (shm_may_destroy(ns, shp))
shm_destroy(ns, shp);
else
shm_unlock(shp);
up_write(&shm_ids(ns).rwsem);
}
/* Called with ns->shm_ids(ns).rwsem locked */
static int shm_try_destroy_current(int id, void *p, void *data)
{
struct ipc_namespace *ns = data;
struct kern_ipc_perm *ipcp = p;
struct shmid_kernel *shp = container_of(ipcp, struct shmid_kernel, shm_perm);
if (shp->shm_creator != current)
return 0;
/*
* Mark it as orphaned to destroy the segment when
* kernel.shm_rmid_forced is changed.
* It is noop if the following shm_may_destroy() returns true.
*/
shp->shm_creator = NULL;
/*
* Don't even try to destroy it. If shm_rmid_forced=0 and IPC_RMID
* is not set, it shouldn't be deleted here.
*/
if (!ns->shm_rmid_forced)
return 0;
if (shm_may_destroy(ns, shp)) {
shm_lock_by_ptr(shp);
shm_destroy(ns, shp);
}
return 0;
}
/* Called with ns->shm_ids(ns).rwsem locked */
static int shm_try_destroy_orphaned(int id, void *p, void *data)
{
struct ipc_namespace *ns = data;
struct kern_ipc_perm *ipcp = p;
struct shmid_kernel *shp = container_of(ipcp, struct shmid_kernel, shm_perm);
/*
* We want to destroy segments without users and with already
* exit'ed originating process.
*
* As shp->* are changed under rwsem, it's safe to skip shp locking.
*/
if (shp->shm_creator != NULL)
return 0;
if (shm_may_destroy(ns, shp)) {
shm_lock_by_ptr(shp);
shm_destroy(ns, shp);
}
return 0;
}
void shm_destroy_orphaned(struct ipc_namespace *ns)
{
down_write(&shm_ids(ns).rwsem);
if (shm_ids(ns).in_use)
idr_for_each(&shm_ids(ns).ipcs_idr, &shm_try_destroy_orphaned, ns);
up_write(&shm_ids(ns).rwsem);
}
void exit_shm(struct task_struct *task)
{
struct ipc_namespace *ns = task->nsproxy->ipc_ns;
if (shm_ids(ns).in_use == 0)
return;
/* Destroy all already created segments, but not mapped yet */
down_write(&shm_ids(ns).rwsem);
if (shm_ids(ns).in_use)
idr_for_each(&shm_ids(ns).ipcs_idr, &shm_try_destroy_current, ns);
up_write(&shm_ids(ns).rwsem);
}
static int shm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
return sfd->vm_ops->fault(vma, vmf);
}
#ifdef CONFIG_NUMA
static int shm_set_policy(struct vm_area_struct *vma, struct mempolicy *new)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
int err = 0;
if (sfd->vm_ops->set_policy)
err = sfd->vm_ops->set_policy(vma, new);
return err;
}
static struct mempolicy *shm_get_policy(struct vm_area_struct *vma,
unsigned long addr)
{
struct file *file = vma->vm_file;
struct shm_file_data *sfd = shm_file_data(file);
struct mempolicy *pol = NULL;
if (sfd->vm_ops->get_policy)
pol = sfd->vm_ops->get_policy(vma, addr);
else if (vma->vm_policy)
pol = vma->vm_policy;
return pol;
}
#endif
static int shm_mmap(struct file * file, struct vm_area_struct * vma)
{
struct shm_file_data *sfd = shm_file_data(file);
int ret;
ret = sfd->file->f_op->mmap(sfd->file, vma);
if (ret != 0)
return ret;
sfd->vm_ops = vma->vm_ops;
#ifdef CONFIG_MMU
BUG_ON(!sfd->vm_ops->fault);
#endif
vma->vm_ops = &shm_vm_ops;
shm_open(vma);
return ret;
}
static int shm_release(struct inode *ino, struct file *file)
{
struct shm_file_data *sfd = shm_file_data(file);
put_ipc_ns(sfd->ns);
shm_file_data(file) = NULL;
kfree(sfd);
return 0;
}
static int shm_fsync(struct file *file, loff_t start, loff_t end, int datasync)
{
struct shm_file_data *sfd = shm_file_data(file);
if (!sfd->file->f_op->fsync)
return -EINVAL;
return sfd->file->f_op->fsync(sfd->file, start, end, datasync);
}
static long shm_fallocate(struct file *file, int mode, loff_t offset,
loff_t len)
{
struct shm_file_data *sfd = shm_file_data(file);
if (!sfd->file->f_op->fallocate)
return -EOPNOTSUPP;
return sfd->file->f_op->fallocate(file, mode, offset, len);
}
static unsigned long shm_get_unmapped_area(struct file *file,
unsigned long addr, unsigned long len, unsigned long pgoff,
unsigned long flags)
{
struct shm_file_data *sfd = shm_file_data(file);
return sfd->file->f_op->get_unmapped_area(sfd->file, addr, len,
pgoff, flags);
}
static const struct file_operations shm_file_operations = {
.mmap = shm_mmap,
.fsync = shm_fsync,
.release = shm_release,
#ifndef CONFIG_MMU
.get_unmapped_area = shm_get_unmapped_area,
#endif
.llseek = noop_llseek,
.fallocate = shm_fallocate,
};
static const struct file_operations shm_file_operations_huge = {
.mmap = shm_mmap,
.fsync = shm_fsync,
.release = shm_release,
.get_unmapped_area = shm_get_unmapped_area,
.llseek = noop_llseek,
.fallocate = shm_fallocate,
};
int is_file_shm_hugepages(struct file *file)
{
return file->f_op == &shm_file_operations_huge;
}
static const struct vm_operations_struct shm_vm_ops = {
.open = shm_open, /* callback for a new vm-area open */
.close = shm_close, /* callback for when the vm-area is released */
.fault = shm_fault,
#if defined(CONFIG_NUMA)
.set_policy = shm_set_policy,
.get_policy = shm_get_policy,
#endif
};
/**
* newseg - Create a new shared memory segment
* @ns: namespace
* @params: ptr to the structure that contains key, size and shmflg
*
* Called with shm_ids.rwsem held as a writer.
*/
static int newseg(struct ipc_namespace *ns, struct ipc_params *params)
{
key_t key = params->key;
int shmflg = params->flg;
size_t size = params->u.size;
int error;
struct shmid_kernel *shp;
size_t numpages = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
struct file * file;
char name[13];
int id;
vm_flags_t acctflag = 0;
if (size < SHMMIN || size > ns->shm_ctlmax)
return -EINVAL;
if (ns->shm_tot + numpages > ns->shm_ctlall)
return -ENOSPC;
shp = ipc_rcu_alloc(sizeof(*shp));
if (!shp)
return -ENOMEM;
shp->shm_perm.key = key;
shp->shm_perm.mode = (shmflg & S_IRWXUGO);
shp->mlock_user = NULL;
shp->shm_perm.security = NULL;
error = security_shm_alloc(shp);
if (error) {
ipc_rcu_putref(shp, ipc_rcu_free);
return error;
}
sprintf (name, "SYSV%08x", key);
if (shmflg & SHM_HUGETLB) {
struct hstate *hs = hstate_sizelog((shmflg >> SHM_HUGE_SHIFT)
& SHM_HUGE_MASK);
size_t hugesize;
if (!hs) {
error = -EINVAL;
goto no_file;
}
hugesize = ALIGN(size, huge_page_size(hs));
/* hugetlb_file_setup applies strict accounting */
if (shmflg & SHM_NORESERVE)
acctflag = VM_NORESERVE;
file = hugetlb_file_setup(name, hugesize, acctflag,
&shp->mlock_user, HUGETLB_SHMFS_INODE,
(shmflg >> SHM_HUGE_SHIFT) & SHM_HUGE_MASK);
} else {
/*
* Do not allow no accounting for OVERCOMMIT_NEVER, even
* if it's asked for.
*/
if ((shmflg & SHM_NORESERVE) &&
sysctl_overcommit_memory != OVERCOMMIT_NEVER)
acctflag = VM_NORESERVE;
file = shmem_file_setup(name, size, acctflag);
}
error = PTR_ERR(file);
if (IS_ERR(file))
goto no_file;
id = ipc_addid(&shm_ids(ns), &shp->shm_perm, ns->shm_ctlmni);
if (id < 0) {
error = id;
goto no_id;
}
shp->shm_cprid = task_tgid_vnr(current);
shp->shm_lprid = 0;
shp->shm_atim = shp->shm_dtim = 0;
shp->shm_ctim = get_seconds();
shp->shm_segsz = size;
shp->shm_nattch = 0;
shp->shm_file = file;
shp->shm_creator = current;
/*
* shmid gets reported as "inode#" in /proc/pid/maps.
* proc-ps tools use this. Changing this will break them.
*/
file_inode(file)->i_ino = shp->shm_perm.id;
ns->shm_tot += numpages;
error = shp->shm_perm.id;
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
return error;
no_id:
if (is_file_hugepages(file) && shp->mlock_user)
user_shm_unlock(size, shp->mlock_user);
fput(file);
no_file:
ipc_rcu_putref(shp, shm_rcu_free);
return error;
}
/*
* Called with shm_ids.rwsem and ipcp locked.
*/
static inline int shm_security(struct kern_ipc_perm *ipcp, int shmflg)
{
struct shmid_kernel *shp;
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
return security_shm_associate(shp, shmflg);
}
/*
* Called with shm_ids.rwsem and ipcp locked.
*/
static inline int shm_more_checks(struct kern_ipc_perm *ipcp,
struct ipc_params *params)
{
struct shmid_kernel *shp;
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
if (shp->shm_segsz < params->u.size)
return -EINVAL;
return 0;
}
SYSCALL_DEFINE3(shmget, key_t, key, size_t, size, int, shmflg)
{
struct ipc_namespace *ns;
struct ipc_ops shm_ops;
struct ipc_params shm_params;
ns = current->nsproxy->ipc_ns;
shm_ops.getnew = newseg;
shm_ops.associate = shm_security;
shm_ops.more_checks = shm_more_checks;
shm_params.key = key;
shm_params.flg = shmflg;
shm_params.u.size = size;
return ipcget(ns, &shm_ids(ns), &shm_ops, &shm_params);
}
static inline unsigned long copy_shmid_to_user(void __user *buf, struct shmid64_ds *in, int version)
{
switch(version) {
case IPC_64:
return copy_to_user(buf, in, sizeof(*in));
case IPC_OLD:
{
struct shmid_ds out;
memset(&out, 0, sizeof(out));
ipc64_perm_to_ipc_perm(&in->shm_perm, &out.shm_perm);
out.shm_segsz = in->shm_segsz;
out.shm_atime = in->shm_atime;
out.shm_dtime = in->shm_dtime;
out.shm_ctime = in->shm_ctime;
out.shm_cpid = in->shm_cpid;
out.shm_lpid = in->shm_lpid;
out.shm_nattch = in->shm_nattch;
return copy_to_user(buf, &out, sizeof(out));
}
default:
return -EINVAL;
}
}
static inline unsigned long
copy_shmid_from_user(struct shmid64_ds *out, void __user *buf, int version)
{
switch(version) {
case IPC_64:
if (copy_from_user(out, buf, sizeof(*out)))
return -EFAULT;
return 0;
case IPC_OLD:
{
struct shmid_ds tbuf_old;
if (copy_from_user(&tbuf_old, buf, sizeof(tbuf_old)))
return -EFAULT;
out->shm_perm.uid = tbuf_old.shm_perm.uid;
out->shm_perm.gid = tbuf_old.shm_perm.gid;
out->shm_perm.mode = tbuf_old.shm_perm.mode;
return 0;
}
default:
return -EINVAL;
}
}
static inline unsigned long copy_shminfo_to_user(void __user *buf, struct shminfo64 *in, int version)
{
switch(version) {
case IPC_64:
return copy_to_user(buf, in, sizeof(*in));
case IPC_OLD:
{
struct shminfo out;
if(in->shmmax > INT_MAX)
out.shmmax = INT_MAX;
else
out.shmmax = (int)in->shmmax;
out.shmmin = in->shmmin;
out.shmmni = in->shmmni;
out.shmseg = in->shmseg;
out.shmall = in->shmall;
return copy_to_user(buf, &out, sizeof(out));
}
default:
return -EINVAL;
}
}
/*
* Calculate and add used RSS and swap pages of a shm.
* Called with shm_ids.rwsem held as a reader
*/
static void shm_add_rss_swap(struct shmid_kernel *shp,
unsigned long *rss_add, unsigned long *swp_add)
{
struct inode *inode;
inode = file_inode(shp->shm_file);
if (is_file_hugepages(shp->shm_file)) {
struct address_space *mapping = inode->i_mapping;
struct hstate *h = hstate_file(shp->shm_file);
*rss_add += pages_per_huge_page(h) * mapping->nrpages;
} else {
#ifdef CONFIG_SHMEM
struct shmem_inode_info *info = SHMEM_I(inode);
spin_lock(&info->lock);
*rss_add += inode->i_mapping->nrpages;
*swp_add += info->swapped;
spin_unlock(&info->lock);
#else
*rss_add += inode->i_mapping->nrpages;
#endif
}
}
/*
* Called with shm_ids.rwsem held as a reader
*/
static void shm_get_stat(struct ipc_namespace *ns, unsigned long *rss,
unsigned long *swp)
{
int next_id;
int total, in_use;
*rss = 0;
*swp = 0;
in_use = shm_ids(ns).in_use;
for (total = 0, next_id = 0; total < in_use; next_id++) {
struct kern_ipc_perm *ipc;
struct shmid_kernel *shp;
ipc = idr_find(&shm_ids(ns).ipcs_idr, next_id);
if (ipc == NULL)
continue;
shp = container_of(ipc, struct shmid_kernel, shm_perm);
shm_add_rss_swap(shp, rss, swp);
total++;
}
}
/*
* This function handles some shmctl commands which require the rwsem
* to be held in write mode.
* NOTE: no locks must be held, the rwsem is taken inside this function.
*/
static int shmctl_down(struct ipc_namespace *ns, int shmid, int cmd,
struct shmid_ds __user *buf, int version)
{
struct kern_ipc_perm *ipcp;
struct shmid64_ds shmid64;
struct shmid_kernel *shp;
int err;
if (cmd == IPC_SET) {
if (copy_shmid_from_user(&shmid64, buf, version))
return -EFAULT;
}
down_write(&shm_ids(ns).rwsem);
rcu_read_lock();
ipcp = ipcctl_pre_down_nolock(ns, &shm_ids(ns), shmid, cmd,
&shmid64.shm_perm, 0);
if (IS_ERR(ipcp)) {
err = PTR_ERR(ipcp);
goto out_unlock1;
}
shp = container_of(ipcp, struct shmid_kernel, shm_perm);
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock1;
switch (cmd) {
case IPC_RMID:
ipc_lock_object(&shp->shm_perm);
/* do_shm_rmid unlocks the ipc object and rcu */
do_shm_rmid(ns, ipcp);
goto out_up;
case IPC_SET:
ipc_lock_object(&shp->shm_perm);
err = ipc_update_perm(&shmid64.shm_perm, ipcp);
if (err)
goto out_unlock0;
shp->shm_ctim = get_seconds();
break;
default:
err = -EINVAL;
goto out_unlock1;
}
out_unlock0:
ipc_unlock_object(&shp->shm_perm);
out_unlock1:
rcu_read_unlock();
out_up:
up_write(&shm_ids(ns).rwsem);
return err;
}
static int shmctl_nolock(struct ipc_namespace *ns, int shmid,
int cmd, int version, void __user *buf)
{
int err;
struct shmid_kernel *shp;
/* preliminary security checks for *_INFO */
if (cmd == IPC_INFO || cmd == SHM_INFO) {
err = security_shm_shmctl(NULL, cmd);
if (err)
return err;
}
switch (cmd) {
case IPC_INFO:
{
struct shminfo64 shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmmni = shminfo.shmseg = ns->shm_ctlmni;
shminfo.shmmax = ns->shm_ctlmax;
shminfo.shmall = ns->shm_ctlall;
shminfo.shmmin = SHMMIN;
if(copy_shminfo_to_user (buf, &shminfo, version))
return -EFAULT;
down_read(&shm_ids(ns).rwsem);
err = ipc_get_maxid(&shm_ids(ns));
up_read(&shm_ids(ns).rwsem);
if(err<0)
err = 0;
goto out;
}
case SHM_INFO:
{
struct shm_info shm_info;
memset(&shm_info, 0, sizeof(shm_info));
down_read(&shm_ids(ns).rwsem);
shm_info.used_ids = shm_ids(ns).in_use;
shm_get_stat (ns, &shm_info.shm_rss, &shm_info.shm_swp);
shm_info.shm_tot = ns->shm_tot;
shm_info.swap_attempts = 0;
shm_info.swap_successes = 0;
err = ipc_get_maxid(&shm_ids(ns));
up_read(&shm_ids(ns).rwsem);
if (copy_to_user(buf, &shm_info, sizeof(shm_info))) {
err = -EFAULT;
goto out;
}
err = err < 0 ? 0 : err;
goto out;
}
case SHM_STAT:
case IPC_STAT:
{
struct shmid64_ds tbuf;
int result;
rcu_read_lock();
if (cmd == SHM_STAT) {
shp = shm_obtain_object(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
result = shp->shm_perm.id;
} else {
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
result = 0;
}
err = -EACCES;
if (ipcperms(ns, &shp->shm_perm, S_IRUGO))
goto out_unlock;
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock;
memset(&tbuf, 0, sizeof(tbuf));
kernel_to_ipc64_perm(&shp->shm_perm, &tbuf.shm_perm);
tbuf.shm_segsz = shp->shm_segsz;
tbuf.shm_atime = shp->shm_atim;
tbuf.shm_dtime = shp->shm_dtim;
tbuf.shm_ctime = shp->shm_ctim;
tbuf.shm_cpid = shp->shm_cprid;
tbuf.shm_lpid = shp->shm_lprid;
tbuf.shm_nattch = shp->shm_nattch;
rcu_read_unlock();
if (copy_shmid_to_user(buf, &tbuf, version))
err = -EFAULT;
else
err = result;
goto out;
}
default:
return -EINVAL;
}
out_unlock:
rcu_read_unlock();
out:
return err;
}
SYSCALL_DEFINE3(shmctl, int, shmid, int, cmd, struct shmid_ds __user *, buf)
{
struct shmid_kernel *shp;
int err, version;
struct ipc_namespace *ns;
if (cmd < 0 || shmid < 0)
return -EINVAL;
version = ipc_parse_version(&cmd);
ns = current->nsproxy->ipc_ns;
switch (cmd) {
case IPC_INFO:
case SHM_INFO:
case SHM_STAT:
case IPC_STAT:
return shmctl_nolock(ns, shmid, cmd, version, buf);
case IPC_RMID:
case IPC_SET:
return shmctl_down(ns, shmid, cmd, buf, version);
case SHM_LOCK:
case SHM_UNLOCK:
{
struct file *shm_file;
rcu_read_lock();
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock1;
}
audit_ipc_obj(&(shp->shm_perm));
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock1;
ipc_lock_object(&shp->shm_perm);
if (!ns_capable(ns->user_ns, CAP_IPC_LOCK)) {
kuid_t euid = current_euid();
if (!uid_eq(euid, shp->shm_perm.uid) &&
!uid_eq(euid, shp->shm_perm.cuid)) {
err = -EPERM;
goto out_unlock0;
}
if (cmd == SHM_LOCK && !rlimit(RLIMIT_MEMLOCK)) {
err = -EPERM;
goto out_unlock0;
}
}
shm_file = shp->shm_file;
/* check if shm_destroy() is tearing down shp */
if (shm_file == NULL) {
err = -EIDRM;
goto out_unlock0;
}
if (is_file_hugepages(shm_file))
goto out_unlock0;
if (cmd == SHM_LOCK) {
struct user_struct *user = current_user();
err = shmem_lock(shm_file, 1, user);
if (!err && !(shp->shm_perm.mode & SHM_LOCKED)) {
shp->shm_perm.mode |= SHM_LOCKED;
shp->mlock_user = user;
}
goto out_unlock0;
}
/* SHM_UNLOCK */
if (!(shp->shm_perm.mode & SHM_LOCKED))
goto out_unlock0;
shmem_lock(shm_file, 0, shp->mlock_user);
shp->shm_perm.mode &= ~SHM_LOCKED;
shp->mlock_user = NULL;
get_file(shm_file);
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
shmem_unlock_mapping(shm_file->f_mapping);
fput(shm_file);
return err;
}
default:
return -EINVAL;
}
out_unlock0:
ipc_unlock_object(&shp->shm_perm);
out_unlock1:
rcu_read_unlock();
return err;
}
/*
* Fix shmaddr, allocate descriptor, map shm, add attach descriptor to lists.
*
* NOTE! Despite the name, this is NOT a direct system call entrypoint. The
* "raddr" thing points to kernel space, and there has to be a wrapper around
* this.
*/
long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr,
unsigned long shmlba)
{
struct shmid_kernel *shp;
unsigned long addr;
unsigned long size;
struct file * file;
int err;
unsigned long flags;
unsigned long prot;
int acc_mode;
struct ipc_namespace *ns;
struct shm_file_data *sfd;
struct path path;
fmode_t f_mode;
unsigned long populate = 0;
err = -EINVAL;
if (shmid < 0)
goto out;
else if ((addr = (ulong)shmaddr)) {
if (addr & (shmlba - 1)) {
if (shmflg & SHM_RND)
addr &= ~(shmlba - 1); /* round down */
else
#ifndef __ARCH_FORCE_SHMLBA
if (addr & ~PAGE_MASK)
#endif
goto out;
}
flags = MAP_SHARED | MAP_FIXED;
} else {
if ((shmflg & SHM_REMAP))
goto out;
flags = MAP_SHARED;
}
if (shmflg & SHM_RDONLY) {
prot = PROT_READ;
acc_mode = S_IRUGO;
f_mode = FMODE_READ;
} else {
prot = PROT_READ | PROT_WRITE;
acc_mode = S_IRUGO | S_IWUGO;
f_mode = FMODE_READ | FMODE_WRITE;
}
if (shmflg & SHM_EXEC) {
prot |= PROT_EXEC;
acc_mode |= S_IXUGO;
}
/*
* We cannot rely on the fs check since SYSV IPC does have an
* additional creator id...
*/
ns = current->nsproxy->ipc_ns;
rcu_read_lock();
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock;
}
err = -EACCES;
if (ipcperms(ns, &shp->shm_perm, acc_mode))
goto out_unlock;
err = security_shm_shmat(shp, shmaddr, shmflg);
if (err)
goto out_unlock;
ipc_lock_object(&shp->shm_perm);
/* check if shm_destroy() is tearing down shp */
if (shp->shm_file == NULL) {
ipc_unlock_object(&shp->shm_perm);
err = -EIDRM;
goto out_unlock;
}
path = shp->shm_file->f_path;
path_get(&path);
shp->shm_nattch++;
size = i_size_read(path.dentry->d_inode);
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
err = -ENOMEM;
sfd = kzalloc(sizeof(*sfd), GFP_KERNEL);
if (!sfd) {
path_put(&path);
goto out_nattch;
}
file = alloc_file(&path, f_mode,
is_file_hugepages(shp->shm_file) ?
&shm_file_operations_huge :
&shm_file_operations);
err = PTR_ERR(file);
if (IS_ERR(file)) {
kfree(sfd);
path_put(&path);
goto out_nattch;
}
file->private_data = sfd;
file->f_mapping = shp->shm_file->f_mapping;
sfd->id = shp->shm_perm.id;
sfd->ns = get_ipc_ns(ns);
sfd->file = shp->shm_file;
sfd->vm_ops = NULL;
err = security_mmap_file(file, prot, flags);
if (err)
goto out_fput;
down_write(¤t->mm->mmap_sem);
if (addr && !(shmflg & SHM_REMAP)) {
err = -EINVAL;
if (find_vma_intersection(current->mm, addr, addr + size))
goto invalid;
/*
* If shm segment goes below stack, make sure there is some
* space left for the stack to grow (at least 4 pages).
*/
if (addr < current->mm->start_stack &&
addr > current->mm->start_stack - size - PAGE_SIZE * 5)
goto invalid;
}
addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate);
*raddr = addr;
err = 0;
if (IS_ERR_VALUE(addr))
err = (long)addr;
invalid:
up_write(¤t->mm->mmap_sem);
if (populate)
mm_populate(addr, populate);
out_fput:
fput(file);
out_nattch:
down_write(&shm_ids(ns).rwsem);
shp = shm_lock(ns, shmid);
BUG_ON(IS_ERR(shp));
shp->shm_nattch--;
if (shm_may_destroy(ns, shp))
shm_destroy(ns, shp);
else
shm_unlock(shp);
up_write(&shm_ids(ns).rwsem);
return err;
out_unlock:
rcu_read_unlock();
out:
return err;
}
SYSCALL_DEFINE3(shmat, int, shmid, char __user *, shmaddr, int, shmflg)
{
unsigned long ret;
long err;
err = do_shmat(shmid, shmaddr, shmflg, &ret, SHMLBA);
if (err)
return err;
force_successful_syscall_return();
return (long)ret;
}
/*
* detach and kill segment if marked destroyed.
* The work is done in shm_close.
*/
SYSCALL_DEFINE1(shmdt, char __user *, shmaddr)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma;
unsigned long addr = (unsigned long)shmaddr;
int retval = -EINVAL;
#ifdef CONFIG_MMU
loff_t size = 0;
struct vm_area_struct *next;
#endif
if (addr & ~PAGE_MASK)
return retval;
down_write(&mm->mmap_sem);
/*
* This function tries to be smart and unmap shm segments that
* were modified by partial mlock or munmap calls:
* - It first determines the size of the shm segment that should be
* unmapped: It searches for a vma that is backed by shm and that
* started at address shmaddr. It records it's size and then unmaps
* it.
* - Then it unmaps all shm vmas that started at shmaddr and that
* are within the initially determined size.
* Errors from do_munmap are ignored: the function only fails if
* it's called with invalid parameters or if it's called to unmap
* a part of a vma. Both calls in this function are for full vmas,
* the parameters are directly copied from the vma itself and always
* valid - therefore do_munmap cannot fail. (famous last words?)
*/
/*
* If it had been mremap()'d, the starting address would not
* match the usual checks anyway. So assume all vma's are
* above the starting address given.
*/
vma = find_vma(mm, addr);
#ifdef CONFIG_MMU
while (vma) {
next = vma->vm_next;
/*
* Check if the starting address would match, i.e. it's
* a fragment created by mprotect() and/or munmap(), or it
* otherwise it starts at this address with no hassles.
*/
if ((vma->vm_ops == &shm_vm_ops) &&
(vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff) {
size = file_inode(vma->vm_file)->i_size;
do_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start);
/*
* We discovered the size of the shm segment, so
* break out of here and fall through to the next
* loop that uses the size information to stop
* searching for matching vma's.
*/
retval = 0;
vma = next;
break;
}
vma = next;
}
/*
* We need look no further than the maximum address a fragment
* could possibly have landed at. Also cast things to loff_t to
* prevent overflows and make comparisons vs. equal-width types.
*/
size = PAGE_ALIGN(size);
while (vma && (loff_t)(vma->vm_end - addr) <= size) {
next = vma->vm_next;
/* finding a matching vma now does not alter retval */
if ((vma->vm_ops == &shm_vm_ops) &&
(vma->vm_start - addr)/PAGE_SIZE == vma->vm_pgoff)
do_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start);
vma = next;
}
#else /* CONFIG_MMU */
/* under NOMMU conditions, the exact address to be destroyed must be
* given */
if (vma && vma->vm_start == addr && vma->vm_ops == &shm_vm_ops) {
do_munmap(mm, vma->vm_start, vma->vm_end - vma->vm_start);
retval = 0;
}
#endif
up_write(&mm->mmap_sem);
return retval;
}
#ifdef CONFIG_PROC_FS
static int sysvipc_shm_proc_show(struct seq_file *s, void *it)
{
struct user_namespace *user_ns = seq_user_ns(s);
struct shmid_kernel *shp = it;
unsigned long rss = 0, swp = 0;
shm_add_rss_swap(shp, &rss, &swp);
#if BITS_PER_LONG <= 32
#define SIZE_SPEC "%10lu"
#else
#define SIZE_SPEC "%21lu"
#endif
return seq_printf(s,
"%10d %10d %4o " SIZE_SPEC " %5u %5u "
"%5lu %5u %5u %5u %5u %10lu %10lu %10lu "
SIZE_SPEC " " SIZE_SPEC "\n",
shp->shm_perm.key,
shp->shm_perm.id,
shp->shm_perm.mode,
shp->shm_segsz,
shp->shm_cprid,
shp->shm_lprid,
shp->shm_nattch,
from_kuid_munged(user_ns, shp->shm_perm.uid),
from_kgid_munged(user_ns, shp->shm_perm.gid),
from_kuid_munged(user_ns, shp->shm_perm.cuid),
from_kgid_munged(user_ns, shp->shm_perm.cgid),
shp->shm_atim,
shp->shm_dtim,
shp->shm_ctim,
rss * PAGE_SIZE,
swp * PAGE_SIZE);
}
#endif
| gpl-2.0 |
Validus-Kernel/kernel_htc_flounder | sound/soc/samsung/smdk_wm8994.c | 2203 | 5622 | /*
* smdk_wm8994.c
*
* 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 "../codecs/wm8994.h"
#include <sound/pcm_params.h>
#include <linux/module.h>
#include <linux/of.h>
/*
* Default CFG switch settings to use this driver:
* SMDKV310: CFG5-1000, CFG7-111111
*/
/*
* Configure audio route as :-
* $ amixer sset 'DAC1' on,on
* $ amixer sset 'Right Headphone Mux' 'DAC'
* $ amixer sset 'Left Headphone Mux' 'DAC'
* $ amixer sset 'DAC1R Mixer AIF1.1' on
* $ amixer sset 'DAC1L Mixer AIF1.1' on
* $ amixer sset 'IN2L' on
* $ amixer sset 'IN2L PGA IN2LN' on
* $ amixer sset 'MIXINL IN2L' on
* $ amixer sset 'AIF1ADC1L Mixer ADC/DMIC' on
* $ amixer sset 'IN2R' on
* $ amixer sset 'IN2R PGA IN2RN' on
* $ amixer sset 'MIXINR IN2R' on
* $ amixer sset 'AIF1ADC1R Mixer ADC/DMIC' on
*/
/* SMDK has a 16.934MHZ crystal attached to WM8994 */
#define SMDK_WM8994_FREQ 16934000
static int smdk_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
unsigned int pll_out;
int ret;
/* AIF1CLK should be >=3MHz for optimal performance */
if (params_format(params) == SNDRV_PCM_FORMAT_S24_LE)
pll_out = params_rate(params) * 384;
else if (params_rate(params) == 8000 || params_rate(params) == 11025)
pll_out = params_rate(params) * 512;
else
pll_out = params_rate(params) * 256;
ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S
| SND_SOC_DAIFMT_NB_NF
| SND_SOC_DAIFMT_CBM_CFM);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S
| SND_SOC_DAIFMT_NB_NF
| SND_SOC_DAIFMT_CBM_CFM);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_pll(codec_dai, WM8994_FLL1, WM8994_FLL_SRC_MCLK1,
SMDK_WM8994_FREQ, pll_out);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_sysclk(codec_dai, WM8994_SYSCLK_FLL1,
pll_out, SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
return 0;
}
/*
* SMDK WM8994 DAI operations.
*/
static struct snd_soc_ops smdk_ops = {
.hw_params = smdk_hw_params,
};
static int smdk_wm8994_init_paiftx(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
/* HeadPhone */
snd_soc_dapm_enable_pin(dapm, "HPOUT1R");
snd_soc_dapm_enable_pin(dapm, "HPOUT1L");
/* MicIn */
snd_soc_dapm_enable_pin(dapm, "IN1LN");
snd_soc_dapm_enable_pin(dapm, "IN1RN");
/* LineIn */
snd_soc_dapm_enable_pin(dapm, "IN2LN");
snd_soc_dapm_enable_pin(dapm, "IN2RN");
/* Other pins NC */
snd_soc_dapm_nc_pin(dapm, "HPOUT2P");
snd_soc_dapm_nc_pin(dapm, "HPOUT2N");
snd_soc_dapm_nc_pin(dapm, "SPKOUTLN");
snd_soc_dapm_nc_pin(dapm, "SPKOUTLP");
snd_soc_dapm_nc_pin(dapm, "SPKOUTRP");
snd_soc_dapm_nc_pin(dapm, "SPKOUTRN");
snd_soc_dapm_nc_pin(dapm, "LINEOUT1N");
snd_soc_dapm_nc_pin(dapm, "LINEOUT1P");
snd_soc_dapm_nc_pin(dapm, "LINEOUT2N");
snd_soc_dapm_nc_pin(dapm, "LINEOUT2P");
snd_soc_dapm_nc_pin(dapm, "IN1LP");
snd_soc_dapm_nc_pin(dapm, "IN2LP:VXRN");
snd_soc_dapm_nc_pin(dapm, "IN1RP");
snd_soc_dapm_nc_pin(dapm, "IN2RP:VXRP");
return 0;
}
static struct snd_soc_dai_link smdk_dai[] = {
{ /* Primary DAI i/f */
.name = "WM8994 AIF1",
.stream_name = "Pri_Dai",
.cpu_dai_name = "samsung-i2s.0",
.codec_dai_name = "wm8994-aif1",
.platform_name = "samsung-i2s.0",
.codec_name = "wm8994-codec",
.init = smdk_wm8994_init_paiftx,
.ops = &smdk_ops,
}, { /* Sec_Fifo Playback i/f */
.name = "Sec_FIFO TX",
.stream_name = "Sec_Dai",
.cpu_dai_name = "samsung-i2s-sec",
.codec_dai_name = "wm8994-aif1",
.platform_name = "samsung-i2s-sec",
.codec_name = "wm8994-codec",
.ops = &smdk_ops,
},
};
static struct snd_soc_card smdk = {
.name = "SMDK-I2S",
.owner = THIS_MODULE,
.dai_link = smdk_dai,
.num_links = ARRAY_SIZE(smdk_dai),
};
static int smdk_audio_probe(struct platform_device *pdev)
{
int ret;
struct device_node *np = pdev->dev.of_node;
struct snd_soc_card *card = &smdk;
card->dev = &pdev->dev;
if (np) {
smdk_dai[0].cpu_dai_name = NULL;
smdk_dai[0].cpu_of_node = of_parse_phandle(np,
"samsung,i2s-controller", 0);
if (!smdk_dai[0].cpu_of_node) {
dev_err(&pdev->dev,
"Property 'samsung,i2s-controller' missing or invalid\n");
ret = -EINVAL;
}
smdk_dai[0].platform_name = NULL;
smdk_dai[0].platform_of_node = smdk_dai[0].cpu_of_node;
}
ret = snd_soc_register_card(card);
if (ret)
dev_err(&pdev->dev, "snd_soc_register_card() failed:%d\n", ret);
return ret;
}
static int smdk_audio_remove(struct platform_device *pdev)
{
struct snd_soc_card *card = platform_get_drvdata(pdev);
snd_soc_unregister_card(card);
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id samsung_wm8994_of_match[] = {
{ .compatible = "samsung,smdk-wm8994", },
{},
};
MODULE_DEVICE_TABLE(of, samsung_wm8994_of_match);
#endif /* CONFIG_OF */
static struct platform_driver smdk_audio_driver = {
.driver = {
.name = "smdk-audio",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(samsung_wm8994_of_match),
},
.probe = smdk_audio_probe,
.remove = smdk_audio_remove,
};
module_platform_driver(smdk_audio_driver);
MODULE_DESCRIPTION("ALSA SoC SMDK WM8994");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:smdk-audio");
| gpl-2.0 |
MikeC84/android_kernel_moto_shamu | block/blk-exec.c | 2203 | 3348 | /*
* Functions related to setting various queue properties from drivers
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/sched/sysctl.h>
#include "blk.h"
/*
* for max sense size
*/
#include <scsi/scsi_cmnd.h>
/**
* blk_end_sync_rq - executes a completion event on a request
* @rq: request to complete
* @error: end I/O status of the request
*/
static void blk_end_sync_rq(struct request *rq, int error)
{
struct completion *waiting = rq->end_io_data;
rq->end_io_data = NULL;
__blk_put_request(rq->q, rq);
/*
* complete last, if this is a stack request the process (and thus
* the rq pointer) could be invalid right after this complete()
*/
complete(waiting);
}
/**
* blk_execute_rq_nowait - insert a request into queue for execution
* @q: queue to insert the request in
* @bd_disk: matching gendisk
* @rq: request to insert
* @at_head: insert request at head or tail of queue
* @done: I/O completion handler
*
* Description:
* Insert a fully prepared request at the back of the I/O scheduler queue
* for execution. Don't wait for completion.
*
* Note:
* This function will invoke @done directly if the queue is dead.
*/
void blk_execute_rq_nowait(struct request_queue *q, struct gendisk *bd_disk,
struct request *rq, int at_head,
rq_end_io_fn *done)
{
int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
bool is_pm_resume;
WARN_ON(irqs_disabled());
rq->rq_disk = bd_disk;
rq->end_io = done;
/*
* need to check this before __blk_run_queue(), because rq can
* be freed before that returns.
*/
is_pm_resume = rq->cmd_type == REQ_TYPE_PM_RESUME;
spin_lock_irq(q->queue_lock);
if (unlikely(blk_queue_dying(q))) {
rq->errors = -ENXIO;
if (rq->end_io)
rq->end_io(rq, rq->errors);
spin_unlock_irq(q->queue_lock);
return;
}
__elv_add_request(q, rq, where);
__blk_run_queue(q);
/* the queue is stopped so it won't be run */
if (is_pm_resume)
__blk_run_queue_uncond(q);
spin_unlock_irq(q->queue_lock);
}
EXPORT_SYMBOL_GPL(blk_execute_rq_nowait);
/**
* blk_execute_rq - insert a request into queue for execution
* @q: queue to insert the request in
* @bd_disk: matching gendisk
* @rq: request to insert
* @at_head: insert request at head or tail of queue
*
* Description:
* Insert a fully prepared request at the back of the I/O scheduler queue
* for execution and wait for completion.
*/
int blk_execute_rq(struct request_queue *q, struct gendisk *bd_disk,
struct request *rq, int at_head)
{
DECLARE_COMPLETION_ONSTACK(wait);
char sense[SCSI_SENSE_BUFFERSIZE];
int err = 0;
unsigned long hang_check;
/*
* we need an extra reference to the request, so we can look at
* it after io completion
*/
rq->ref_count++;
if (!rq->sense) {
memset(sense, 0, sizeof(sense));
rq->sense = sense;
rq->sense_len = 0;
}
rq->end_io_data = &wait;
blk_execute_rq_nowait(q, bd_disk, rq, at_head, blk_end_sync_rq);
/* Prevent hang_check timer from firing at us during very long I/O */
hang_check = sysctl_hung_task_timeout_secs;
if (hang_check)
while (!wait_for_completion_io_timeout(&wait, hang_check * (HZ/2)));
else
wait_for_completion_io(&wait);
if (rq->errors)
err = -EIO;
return err;
}
EXPORT_SYMBOL(blk_execute_rq);
| gpl-2.0 |
GlitchKernel/Glitch-i9300 | drivers/acpi/acpica/utmisc.c | 3227 | 26816 | /*******************************************************************************
*
* Module Name: utmisc - common utility procedures
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2011, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <linux/module.h>
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_UTILITIES
ACPI_MODULE_NAME("utmisc")
/*******************************************************************************
*
* FUNCTION: acpi_ut_validate_exception
*
* PARAMETERS: Status - The acpi_status code to be formatted
*
* RETURN: A string containing the exception text. NULL if exception is
* not valid.
*
* DESCRIPTION: This function validates and translates an ACPI exception into
* an ASCII string.
*
******************************************************************************/
const char *acpi_ut_validate_exception(acpi_status status)
{
u32 sub_status;
const char *exception = NULL;
ACPI_FUNCTION_ENTRY();
/*
* Status is composed of two parts, a "type" and an actual code
*/
sub_status = (status & ~AE_CODE_MASK);
switch (status & AE_CODE_MASK) {
case AE_CODE_ENVIRONMENTAL:
if (sub_status <= AE_CODE_ENV_MAX) {
exception = acpi_gbl_exception_names_env[sub_status];
}
break;
case AE_CODE_PROGRAMMER:
if (sub_status <= AE_CODE_PGM_MAX) {
exception = acpi_gbl_exception_names_pgm[sub_status];
}
break;
case AE_CODE_ACPI_TABLES:
if (sub_status <= AE_CODE_TBL_MAX) {
exception = acpi_gbl_exception_names_tbl[sub_status];
}
break;
case AE_CODE_AML:
if (sub_status <= AE_CODE_AML_MAX) {
exception = acpi_gbl_exception_names_aml[sub_status];
}
break;
case AE_CODE_CONTROL:
if (sub_status <= AE_CODE_CTRL_MAX) {
exception = acpi_gbl_exception_names_ctrl[sub_status];
}
break;
default:
break;
}
return (ACPI_CAST_PTR(const char, exception));
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_is_pci_root_bridge
*
* PARAMETERS: Id - The HID/CID in string format
*
* RETURN: TRUE if the Id is a match for a PCI/PCI-Express Root Bridge
*
* DESCRIPTION: Determine if the input ID is a PCI Root Bridge ID.
*
******************************************************************************/
u8 acpi_ut_is_pci_root_bridge(char *id)
{
/*
* Check if this is a PCI root bridge.
* ACPI 3.0+: check for a PCI Express root also.
*/
if (!(ACPI_STRCMP(id,
PCI_ROOT_HID_STRING)) ||
!(ACPI_STRCMP(id, PCI_EXPRESS_ROOT_HID_STRING))) {
return (TRUE);
}
return (FALSE);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_is_aml_table
*
* PARAMETERS: Table - An ACPI table
*
* RETURN: TRUE if table contains executable AML; FALSE otherwise
*
* DESCRIPTION: Check ACPI Signature for a table that contains AML code.
* Currently, these are DSDT,SSDT,PSDT. All other table types are
* data tables that do not contain AML code.
*
******************************************************************************/
u8 acpi_ut_is_aml_table(struct acpi_table_header *table)
{
/* These are the only tables that contain executable AML */
if (ACPI_COMPARE_NAME(table->signature, ACPI_SIG_DSDT) ||
ACPI_COMPARE_NAME(table->signature, ACPI_SIG_PSDT) ||
ACPI_COMPARE_NAME(table->signature, ACPI_SIG_SSDT)) {
return (TRUE);
}
return (FALSE);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_allocate_owner_id
*
* PARAMETERS: owner_id - Where the new owner ID is returned
*
* RETURN: Status
*
* DESCRIPTION: Allocate a table or method owner ID. The owner ID is used to
* track objects created by the table or method, to be deleted
* when the method exits or the table is unloaded.
*
******************************************************************************/
acpi_status acpi_ut_allocate_owner_id(acpi_owner_id * owner_id)
{
u32 i;
u32 j;
u32 k;
acpi_status status;
ACPI_FUNCTION_TRACE(ut_allocate_owner_id);
/* Guard against multiple allocations of ID to the same location */
if (*owner_id) {
ACPI_ERROR((AE_INFO, "Owner ID [0x%2.2X] already exists",
*owner_id));
return_ACPI_STATUS(AE_ALREADY_EXISTS);
}
/* Mutex for the global ID mask */
status = acpi_ut_acquire_mutex(ACPI_MTX_CACHES);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/*
* Find a free owner ID, cycle through all possible IDs on repeated
* allocations. (ACPI_NUM_OWNERID_MASKS + 1) because first index may have
* to be scanned twice.
*/
for (i = 0, j = acpi_gbl_last_owner_id_index;
i < (ACPI_NUM_OWNERID_MASKS + 1); i++, j++) {
if (j >= ACPI_NUM_OWNERID_MASKS) {
j = 0; /* Wraparound to start of mask array */
}
for (k = acpi_gbl_next_owner_id_offset; k < 32; k++) {
if (acpi_gbl_owner_id_mask[j] == ACPI_UINT32_MAX) {
/* There are no free IDs in this mask */
break;
}
if (!(acpi_gbl_owner_id_mask[j] & (1 << k))) {
/*
* Found a free ID. The actual ID is the bit index plus one,
* making zero an invalid Owner ID. Save this as the last ID
* allocated and update the global ID mask.
*/
acpi_gbl_owner_id_mask[j] |= (1 << k);
acpi_gbl_last_owner_id_index = (u8) j;
acpi_gbl_next_owner_id_offset = (u8) (k + 1);
/*
* Construct encoded ID from the index and bit position
*
* Note: Last [j].k (bit 255) is never used and is marked
* permanently allocated (prevents +1 overflow)
*/
*owner_id =
(acpi_owner_id) ((k + 1) + ACPI_MUL_32(j));
ACPI_DEBUG_PRINT((ACPI_DB_VALUES,
"Allocated OwnerId: %2.2X\n",
(unsigned int)*owner_id));
goto exit;
}
}
acpi_gbl_next_owner_id_offset = 0;
}
/*
* All owner_ids have been allocated. This typically should
* not happen since the IDs are reused after deallocation. The IDs are
* allocated upon table load (one per table) and method execution, and
* they are released when a table is unloaded or a method completes
* execution.
*
* If this error happens, there may be very deep nesting of invoked control
* methods, or there may be a bug where the IDs are not released.
*/
status = AE_OWNER_ID_LIMIT;
ACPI_ERROR((AE_INFO,
"Could not allocate new OwnerId (255 max), AE_OWNER_ID_LIMIT"));
exit:
(void)acpi_ut_release_mutex(ACPI_MTX_CACHES);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_release_owner_id
*
* PARAMETERS: owner_id_ptr - Pointer to a previously allocated owner_iD
*
* RETURN: None. No error is returned because we are either exiting a
* control method or unloading a table. Either way, we would
* ignore any error anyway.
*
* DESCRIPTION: Release a table or method owner ID. Valid IDs are 1 - 255
*
******************************************************************************/
void acpi_ut_release_owner_id(acpi_owner_id * owner_id_ptr)
{
acpi_owner_id owner_id = *owner_id_ptr;
acpi_status status;
u32 index;
u32 bit;
ACPI_FUNCTION_TRACE_U32(ut_release_owner_id, owner_id);
/* Always clear the input owner_id (zero is an invalid ID) */
*owner_id_ptr = 0;
/* Zero is not a valid owner_iD */
if (owner_id == 0) {
ACPI_ERROR((AE_INFO, "Invalid OwnerId: 0x%2.2X", owner_id));
return_VOID;
}
/* Mutex for the global ID mask */
status = acpi_ut_acquire_mutex(ACPI_MTX_CACHES);
if (ACPI_FAILURE(status)) {
return_VOID;
}
/* Normalize the ID to zero */
owner_id--;
/* Decode ID to index/offset pair */
index = ACPI_DIV_32(owner_id);
bit = 1 << ACPI_MOD_32(owner_id);
/* Free the owner ID only if it is valid */
if (acpi_gbl_owner_id_mask[index] & bit) {
acpi_gbl_owner_id_mask[index] ^= bit;
} else {
ACPI_ERROR((AE_INFO,
"Release of non-allocated OwnerId: 0x%2.2X",
owner_id + 1));
}
(void)acpi_ut_release_mutex(ACPI_MTX_CACHES);
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_strupr (strupr)
*
* PARAMETERS: src_string - The source string to convert
*
* RETURN: None
*
* DESCRIPTION: Convert string to uppercase
*
* NOTE: This is not a POSIX function, so it appears here, not in utclib.c
*
******************************************************************************/
void acpi_ut_strupr(char *src_string)
{
char *string;
ACPI_FUNCTION_ENTRY();
if (!src_string) {
return;
}
/* Walk entire string, uppercasing the letters */
for (string = src_string; *string; string++) {
*string = (char)ACPI_TOUPPER(*string);
}
return;
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_print_string
*
* PARAMETERS: String - Null terminated ASCII string
* max_length - Maximum output length
*
* RETURN: None
*
* DESCRIPTION: Dump an ASCII string with support for ACPI-defined escape
* sequences.
*
******************************************************************************/
void acpi_ut_print_string(char *string, u8 max_length)
{
u32 i;
if (!string) {
acpi_os_printf("<\"NULL STRING PTR\">");
return;
}
acpi_os_printf("\"");
for (i = 0; string[i] && (i < max_length); i++) {
/* Escape sequences */
switch (string[i]) {
case 0x07:
acpi_os_printf("\\a"); /* BELL */
break;
case 0x08:
acpi_os_printf("\\b"); /* BACKSPACE */
break;
case 0x0C:
acpi_os_printf("\\f"); /* FORMFEED */
break;
case 0x0A:
acpi_os_printf("\\n"); /* LINEFEED */
break;
case 0x0D:
acpi_os_printf("\\r"); /* CARRIAGE RETURN */
break;
case 0x09:
acpi_os_printf("\\t"); /* HORIZONTAL TAB */
break;
case 0x0B:
acpi_os_printf("\\v"); /* VERTICAL TAB */
break;
case '\'': /* Single Quote */
case '\"': /* Double Quote */
case '\\': /* Backslash */
acpi_os_printf("\\%c", (int)string[i]);
break;
default:
/* Check for printable character or hex escape */
if (ACPI_IS_PRINT(string[i])) {
/* This is a normal character */
acpi_os_printf("%c", (int)string[i]);
} else {
/* All others will be Hex escapes */
acpi_os_printf("\\x%2.2X", (s32) string[i]);
}
break;
}
}
acpi_os_printf("\"");
if (i == max_length && string[i]) {
acpi_os_printf("...");
}
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_dword_byte_swap
*
* PARAMETERS: Value - Value to be converted
*
* RETURN: u32 integer with bytes swapped
*
* DESCRIPTION: Convert a 32-bit value to big-endian (swap the bytes)
*
******************************************************************************/
u32 acpi_ut_dword_byte_swap(u32 value)
{
union {
u32 value;
u8 bytes[4];
} out;
union {
u32 value;
u8 bytes[4];
} in;
ACPI_FUNCTION_ENTRY();
in.value = value;
out.bytes[0] = in.bytes[3];
out.bytes[1] = in.bytes[2];
out.bytes[2] = in.bytes[1];
out.bytes[3] = in.bytes[0];
return (out.value);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_set_integer_width
*
* PARAMETERS: Revision From DSDT header
*
* RETURN: None
*
* DESCRIPTION: Set the global integer bit width based upon the revision
* of the DSDT. For Revision 1 and 0, Integers are 32 bits.
* For Revision 2 and above, Integers are 64 bits. Yes, this
* makes a difference.
*
******************************************************************************/
void acpi_ut_set_integer_width(u8 revision)
{
if (revision < 2) {
/* 32-bit case */
acpi_gbl_integer_bit_width = 32;
acpi_gbl_integer_nybble_width = 8;
acpi_gbl_integer_byte_width = 4;
} else {
/* 64-bit case (ACPI 2.0+) */
acpi_gbl_integer_bit_width = 64;
acpi_gbl_integer_nybble_width = 16;
acpi_gbl_integer_byte_width = 8;
}
}
#ifdef ACPI_DEBUG_OUTPUT
/*******************************************************************************
*
* FUNCTION: acpi_ut_display_init_pathname
*
* PARAMETERS: Type - Object type of the node
* obj_handle - Handle whose pathname will be displayed
* Path - Additional path string to be appended.
* (NULL if no extra path)
*
* RETURN: acpi_status
*
* DESCRIPTION: Display full pathname of an object, DEBUG ONLY
*
******************************************************************************/
void
acpi_ut_display_init_pathname(u8 type,
struct acpi_namespace_node *obj_handle,
char *path)
{
acpi_status status;
struct acpi_buffer buffer;
ACPI_FUNCTION_ENTRY();
/* Only print the path if the appropriate debug level is enabled */
if (!(acpi_dbg_level & ACPI_LV_INIT_NAMES)) {
return;
}
/* Get the full pathname to the node */
buffer.length = ACPI_ALLOCATE_LOCAL_BUFFER;
status = acpi_ns_handle_to_pathname(obj_handle, &buffer);
if (ACPI_FAILURE(status)) {
return;
}
/* Print what we're doing */
switch (type) {
case ACPI_TYPE_METHOD:
acpi_os_printf("Executing ");
break;
default:
acpi_os_printf("Initializing ");
break;
}
/* Print the object type and pathname */
acpi_os_printf("%-12s %s",
acpi_ut_get_type_name(type), (char *)buffer.pointer);
/* Extra path is used to append names like _STA, _INI, etc. */
if (path) {
acpi_os_printf(".%s", path);
}
acpi_os_printf("\n");
ACPI_FREE(buffer.pointer);
}
#endif
/*******************************************************************************
*
* FUNCTION: acpi_ut_valid_acpi_char
*
* PARAMETERS: Char - The character to be examined
* Position - Byte position (0-3)
*
* RETURN: TRUE if the character is valid, FALSE otherwise
*
* DESCRIPTION: Check for a valid ACPI character. Must be one of:
* 1) Upper case alpha
* 2) numeric
* 3) underscore
*
* We allow a '!' as the last character because of the ASF! table
*
******************************************************************************/
u8 acpi_ut_valid_acpi_char(char character, u32 position)
{
if (!((character >= 'A' && character <= 'Z') ||
(character >= '0' && character <= '9') || (character == '_'))) {
/* Allow a '!' in the last position */
if (character == '!' && position == 3) {
return (TRUE);
}
return (FALSE);
}
return (TRUE);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_valid_acpi_name
*
* PARAMETERS: Name - The name to be examined
*
* RETURN: TRUE if the name is valid, FALSE otherwise
*
* DESCRIPTION: Check for a valid ACPI name. Each character must be one of:
* 1) Upper case alpha
* 2) numeric
* 3) underscore
*
******************************************************************************/
u8 acpi_ut_valid_acpi_name(u32 name)
{
u32 i;
ACPI_FUNCTION_ENTRY();
for (i = 0; i < ACPI_NAME_SIZE; i++) {
if (!acpi_ut_valid_acpi_char
((ACPI_CAST_PTR(char, &name))[i], i)) {
return (FALSE);
}
}
return (TRUE);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_repair_name
*
* PARAMETERS: Name - The ACPI name to be repaired
*
* RETURN: Repaired version of the name
*
* DESCRIPTION: Repair an ACPI name: Change invalid characters to '*' and
* return the new name.
*
******************************************************************************/
acpi_name acpi_ut_repair_name(char *name)
{
u32 i;
char new_name[ACPI_NAME_SIZE];
for (i = 0; i < ACPI_NAME_SIZE; i++) {
new_name[i] = name[i];
/*
* Replace a bad character with something printable, yet technically
* still invalid. This prevents any collisions with existing "good"
* names in the namespace.
*/
if (!acpi_ut_valid_acpi_char(name[i], i)) {
new_name[i] = '*';
}
}
return (*(u32 *) new_name);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_strtoul64
*
* PARAMETERS: String - Null terminated string
* Base - Radix of the string: 16 or ACPI_ANY_BASE;
* ACPI_ANY_BASE means 'in behalf of to_integer'
* ret_integer - Where the converted integer is returned
*
* RETURN: Status and Converted value
*
* DESCRIPTION: Convert a string into an unsigned value. Performs either a
* 32-bit or 64-bit conversion, depending on the current mode
* of the interpreter.
* NOTE: Does not support Octal strings, not needed.
*
******************************************************************************/
acpi_status acpi_ut_strtoul64(char *string, u32 base, u64 * ret_integer)
{
u32 this_digit = 0;
u64 return_value = 0;
u64 quotient;
u64 dividend;
u32 to_integer_op = (base == ACPI_ANY_BASE);
u32 mode32 = (acpi_gbl_integer_byte_width == 4);
u8 valid_digits = 0;
u8 sign_of0x = 0;
u8 term = 0;
ACPI_FUNCTION_TRACE_STR(ut_stroul64, string);
switch (base) {
case ACPI_ANY_BASE:
case 16:
break;
default:
/* Invalid Base */
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
if (!string) {
goto error_exit;
}
/* Skip over any white space in the buffer */
while ((*string) && (ACPI_IS_SPACE(*string) || *string == '\t')) {
string++;
}
if (to_integer_op) {
/*
* Base equal to ACPI_ANY_BASE means 'to_integer operation case'.
* We need to determine if it is decimal or hexadecimal.
*/
if ((*string == '0') && (ACPI_TOLOWER(*(string + 1)) == 'x')) {
sign_of0x = 1;
base = 16;
/* Skip over the leading '0x' */
string += 2;
} else {
base = 10;
}
}
/* Any string left? Check that '0x' is not followed by white space. */
if (!(*string) || ACPI_IS_SPACE(*string) || *string == '\t') {
if (to_integer_op) {
goto error_exit;
} else {
goto all_done;
}
}
/*
* Perform a 32-bit or 64-bit conversion, depending upon the current
* execution mode of the interpreter
*/
dividend = (mode32) ? ACPI_UINT32_MAX : ACPI_UINT64_MAX;
/* Main loop: convert the string to a 32- or 64-bit integer */
while (*string) {
if (ACPI_IS_DIGIT(*string)) {
/* Convert ASCII 0-9 to Decimal value */
this_digit = ((u8) * string) - '0';
} else if (base == 10) {
/* Digit is out of range; possible in to_integer case only */
term = 1;
} else {
this_digit = (u8) ACPI_TOUPPER(*string);
if (ACPI_IS_XDIGIT((char)this_digit)) {
/* Convert ASCII Hex char to value */
this_digit = this_digit - 'A' + 10;
} else {
term = 1;
}
}
if (term) {
if (to_integer_op) {
goto error_exit;
} else {
break;
}
} else if ((valid_digits == 0) && (this_digit == 0)
&& !sign_of0x) {
/* Skip zeros */
string++;
continue;
}
valid_digits++;
if (sign_of0x && ((valid_digits > 16)
|| ((valid_digits > 8) && mode32))) {
/*
* This is to_integer operation case.
* No any restrictions for string-to-integer conversion,
* see ACPI spec.
*/
goto error_exit;
}
/* Divide the digit into the correct position */
(void)acpi_ut_short_divide((dividend - (u64) this_digit),
base, "ient, NULL);
if (return_value > quotient) {
if (to_integer_op) {
goto error_exit;
} else {
break;
}
}
return_value *= base;
return_value += this_digit;
string++;
}
/* All done, normal exit */
all_done:
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "Converted value: %8.8X%8.8X\n",
ACPI_FORMAT_UINT64(return_value)));
*ret_integer = return_value;
return_ACPI_STATUS(AE_OK);
error_exit:
/* Base was set/validated above */
if (base == 10) {
return_ACPI_STATUS(AE_BAD_DECIMAL_CONSTANT);
} else {
return_ACPI_STATUS(AE_BAD_HEX_CONSTANT);
}
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_create_update_state_and_push
*
* PARAMETERS: Object - Object to be added to the new state
* Action - Increment/Decrement
* state_list - List the state will be added to
*
* RETURN: Status
*
* DESCRIPTION: Create a new state and push it
*
******************************************************************************/
acpi_status
acpi_ut_create_update_state_and_push(union acpi_operand_object *object,
u16 action,
union acpi_generic_state **state_list)
{
union acpi_generic_state *state;
ACPI_FUNCTION_ENTRY();
/* Ignore null objects; these are expected */
if (!object) {
return (AE_OK);
}
state = acpi_ut_create_update_state(object, action);
if (!state) {
return (AE_NO_MEMORY);
}
acpi_ut_push_generic_state(state_list, state);
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_walk_package_tree
*
* PARAMETERS: source_object - The package to walk
* target_object - Target object (if package is being copied)
* walk_callback - Called once for each package element
* Context - Passed to the callback function
*
* RETURN: Status
*
* DESCRIPTION: Walk through a package
*
******************************************************************************/
acpi_status
acpi_ut_walk_package_tree(union acpi_operand_object * source_object,
void *target_object,
acpi_pkg_callback walk_callback, void *context)
{
acpi_status status = AE_OK;
union acpi_generic_state *state_list = NULL;
union acpi_generic_state *state;
u32 this_index;
union acpi_operand_object *this_source_obj;
ACPI_FUNCTION_TRACE(ut_walk_package_tree);
state = acpi_ut_create_pkg_state(source_object, target_object, 0);
if (!state) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
while (state) {
/* Get one element of the package */
this_index = state->pkg.index;
this_source_obj = (union acpi_operand_object *)
state->pkg.source_object->package.elements[this_index];
/*
* Check for:
* 1) An uninitialized package element. It is completely
* legal to declare a package and leave it uninitialized
* 2) Not an internal object - can be a namespace node instead
* 3) Any type other than a package. Packages are handled in else
* case below.
*/
if ((!this_source_obj) ||
(ACPI_GET_DESCRIPTOR_TYPE(this_source_obj) !=
ACPI_DESC_TYPE_OPERAND)
|| (this_source_obj->common.type != ACPI_TYPE_PACKAGE)) {
status =
walk_callback(ACPI_COPY_TYPE_SIMPLE,
this_source_obj, state, context);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
state->pkg.index++;
while (state->pkg.index >=
state->pkg.source_object->package.count) {
/*
* We've handled all of the objects at this level, This means
* that we have just completed a package. That package may
* have contained one or more packages itself.
*
* Delete this state and pop the previous state (package).
*/
acpi_ut_delete_generic_state(state);
state = acpi_ut_pop_generic_state(&state_list);
/* Finished when there are no more states */
if (!state) {
/*
* We have handled all of the objects in the top level
* package just add the length of the package objects
* and exit
*/
return_ACPI_STATUS(AE_OK);
}
/*
* Go back up a level and move the index past the just
* completed package object.
*/
state->pkg.index++;
}
} else {
/* This is a subobject of type package */
status =
walk_callback(ACPI_COPY_TYPE_PACKAGE,
this_source_obj, state, context);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/*
* Push the current state and create a new one
* The callback above returned a new target package object.
*/
acpi_ut_push_generic_state(&state_list, state);
state = acpi_ut_create_pkg_state(this_source_obj,
state->pkg.
this_target_obj, 0);
if (!state) {
/* Free any stacked Update State objects */
while (state_list) {
state =
acpi_ut_pop_generic_state
(&state_list);
acpi_ut_delete_generic_state(state);
}
return_ACPI_STATUS(AE_NO_MEMORY);
}
}
}
/* We should never get here */
return_ACPI_STATUS(AE_AML_INTERNAL);
}
| gpl-2.0 |
snandlal/samsung_kernel | drivers/acpi/acpica/pswalk.c | 3227 | 3540 | /******************************************************************************
*
* Module Name: pswalk - Parser routines to walk parsed op tree(s)
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2011, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acparser.h"
#define _COMPONENT ACPI_PARSER
ACPI_MODULE_NAME("pswalk")
/*******************************************************************************
*
* FUNCTION: acpi_ps_delete_parse_tree
*
* PARAMETERS: subtree_root - Root of tree (or subtree) to delete
*
* RETURN: None
*
* DESCRIPTION: Delete a portion of or an entire parse tree.
*
******************************************************************************/
void acpi_ps_delete_parse_tree(union acpi_parse_object *subtree_root)
{
union acpi_parse_object *op = subtree_root;
union acpi_parse_object *next = NULL;
union acpi_parse_object *parent = NULL;
ACPI_FUNCTION_TRACE_PTR(ps_delete_parse_tree, subtree_root);
/* Visit all nodes in the subtree */
while (op) {
/* Check if we are not ascending */
if (op != parent) {
/* Look for an argument or child of the current op */
next = acpi_ps_get_arg(op, 0);
if (next) {
/* Still going downward in tree (Op is not completed yet) */
op = next;
continue;
}
}
/* No more children, this Op is complete. */
next = op->common.next;
parent = op->common.parent;
acpi_ps_free_op(op);
/* If we are back to the starting point, the walk is complete. */
if (op == subtree_root) {
return_VOID;
}
if (next) {
op = next;
} else {
op = parent;
}
}
return_VOID;
}
| gpl-2.0 |
EPDCenter/android_kernel_rockchip_mk908 | drivers/acpi/acpica/dsutils.c | 3227 | 25450 | /*******************************************************************************
*
* Module Name: dsutils - Dispatcher utilities
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2011, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acparser.h"
#include "amlcode.h"
#include "acdispat.h"
#include "acinterp.h"
#include "acnamesp.h"
#include "acdebug.h"
#define _COMPONENT ACPI_DISPATCHER
ACPI_MODULE_NAME("dsutils")
/*******************************************************************************
*
* FUNCTION: acpi_ds_clear_implicit_return
*
* PARAMETERS: walk_state - Current State
*
* RETURN: None.
*
* DESCRIPTION: Clear and remove a reference on an implicit return value. Used
* to delete "stale" return values (if enabled, the return value
* from every operator is saved at least momentarily, in case the
* parent method exits.)
*
******************************************************************************/
void acpi_ds_clear_implicit_return(struct acpi_walk_state *walk_state)
{
ACPI_FUNCTION_NAME(ds_clear_implicit_return);
/*
* Slack must be enabled for this feature
*/
if (!acpi_gbl_enable_interpreter_slack) {
return;
}
if (walk_state->implicit_return_obj) {
/*
* Delete any "stale" implicit return. However, in
* complex statements, the implicit return value can be
* bubbled up several levels.
*/
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Removing reference on stale implicit return obj %p\n",
walk_state->implicit_return_obj));
acpi_ut_remove_reference(walk_state->implicit_return_obj);
walk_state->implicit_return_obj = NULL;
}
}
#ifndef ACPI_NO_METHOD_EXECUTION
/*******************************************************************************
*
* FUNCTION: acpi_ds_do_implicit_return
*
* PARAMETERS: return_desc - The return value
* walk_state - Current State
* add_reference - True if a reference should be added to the
* return object
*
* RETURN: TRUE if implicit return enabled, FALSE otherwise
*
* DESCRIPTION: Implements the optional "implicit return". We save the result
* of every ASL operator and control method invocation in case the
* parent method exit. Before storing a new return value, we
* delete the previous return value.
*
******************************************************************************/
u8
acpi_ds_do_implicit_return(union acpi_operand_object *return_desc,
struct acpi_walk_state *walk_state, u8 add_reference)
{
ACPI_FUNCTION_NAME(ds_do_implicit_return);
/*
* Slack must be enabled for this feature, and we must
* have a valid return object
*/
if ((!acpi_gbl_enable_interpreter_slack) || (!return_desc)) {
return (FALSE);
}
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Result %p will be implicitly returned; Prev=%p\n",
return_desc, walk_state->implicit_return_obj));
/*
* Delete any "stale" implicit return value first. However, in
* complex statements, the implicit return value can be
* bubbled up several levels, so we don't clear the value if it
* is the same as the return_desc.
*/
if (walk_state->implicit_return_obj) {
if (walk_state->implicit_return_obj == return_desc) {
return (TRUE);
}
acpi_ds_clear_implicit_return(walk_state);
}
/* Save the implicit return value, add a reference if requested */
walk_state->implicit_return_obj = return_desc;
if (add_reference) {
acpi_ut_add_reference(return_desc);
}
return (TRUE);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_is_result_used
*
* PARAMETERS: Op - Current Op
* walk_state - Current State
*
* RETURN: TRUE if result is used, FALSE otherwise
*
* DESCRIPTION: Check if a result object will be used by the parent
*
******************************************************************************/
u8
acpi_ds_is_result_used(union acpi_parse_object * op,
struct acpi_walk_state * walk_state)
{
const struct acpi_opcode_info *parent_info;
ACPI_FUNCTION_TRACE_PTR(ds_is_result_used, op);
/* Must have both an Op and a Result Object */
if (!op) {
ACPI_ERROR((AE_INFO, "Null Op"));
return_UINT8(TRUE);
}
/*
* We know that this operator is not a
* Return() operator (would not come here.) The following code is the
* optional support for a so-called "implicit return". Some AML code
* assumes that the last value of the method is "implicitly" returned
* to the caller. Just save the last result as the return value.
* NOTE: this is optional because the ASL language does not actually
* support this behavior.
*/
(void)acpi_ds_do_implicit_return(walk_state->result_obj, walk_state,
TRUE);
/*
* Now determine if the parent will use the result
*
* If there is no parent, or the parent is a scope_op, we are executing
* at the method level. An executing method typically has no parent,
* since each method is parsed separately. A method invoked externally
* via execute_control_method has a scope_op as the parent.
*/
if ((!op->common.parent) ||
(op->common.parent->common.aml_opcode == AML_SCOPE_OP)) {
/* No parent, the return value cannot possibly be used */
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"At Method level, result of [%s] not used\n",
acpi_ps_get_opcode_name(op->common.
aml_opcode)));
return_UINT8(FALSE);
}
/* Get info on the parent. The root_op is AML_SCOPE */
parent_info =
acpi_ps_get_opcode_info(op->common.parent->common.aml_opcode);
if (parent_info->class == AML_CLASS_UNKNOWN) {
ACPI_ERROR((AE_INFO, "Unknown parent opcode Op=%p", op));
return_UINT8(FALSE);
}
/*
* Decide what to do with the result based on the parent. If
* the parent opcode will not use the result, delete the object.
* Otherwise leave it as is, it will be deleted when it is used
* as an operand later.
*/
switch (parent_info->class) {
case AML_CLASS_CONTROL:
switch (op->common.parent->common.aml_opcode) {
case AML_RETURN_OP:
/* Never delete the return value associated with a return opcode */
goto result_used;
case AML_IF_OP:
case AML_WHILE_OP:
/*
* If we are executing the predicate AND this is the predicate op,
* we will use the return value
*/
if ((walk_state->control_state->common.state ==
ACPI_CONTROL_PREDICATE_EXECUTING)
&& (walk_state->control_state->control.
predicate_op == op)) {
goto result_used;
}
break;
default:
/* Ignore other control opcodes */
break;
}
/* The general control opcode returns no result */
goto result_not_used;
case AML_CLASS_CREATE:
/*
* These opcodes allow term_arg(s) as operands and therefore
* the operands can be method calls. The result is used.
*/
goto result_used;
case AML_CLASS_NAMED_OBJECT:
if ((op->common.parent->common.aml_opcode == AML_REGION_OP) ||
(op->common.parent->common.aml_opcode == AML_DATA_REGION_OP)
|| (op->common.parent->common.aml_opcode == AML_PACKAGE_OP)
|| (op->common.parent->common.aml_opcode ==
AML_VAR_PACKAGE_OP)
|| (op->common.parent->common.aml_opcode == AML_BUFFER_OP)
|| (op->common.parent->common.aml_opcode ==
AML_INT_EVAL_SUBTREE_OP)
|| (op->common.parent->common.aml_opcode ==
AML_BANK_FIELD_OP)) {
/*
* These opcodes allow term_arg(s) as operands and therefore
* the operands can be method calls. The result is used.
*/
goto result_used;
}
goto result_not_used;
default:
/*
* In all other cases. the parent will actually use the return
* object, so keep it.
*/
goto result_used;
}
result_used:
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Result of [%s] used by Parent [%s] Op=%p\n",
acpi_ps_get_opcode_name(op->common.aml_opcode),
acpi_ps_get_opcode_name(op->common.parent->common.
aml_opcode), op));
return_UINT8(TRUE);
result_not_used:
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Result of [%s] not used by Parent [%s] Op=%p\n",
acpi_ps_get_opcode_name(op->common.aml_opcode),
acpi_ps_get_opcode_name(op->common.parent->common.
aml_opcode), op));
return_UINT8(FALSE);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_delete_result_if_not_used
*
* PARAMETERS: Op - Current parse Op
* result_obj - Result of the operation
* walk_state - Current state
*
* RETURN: Status
*
* DESCRIPTION: Used after interpretation of an opcode. If there is an internal
* result descriptor, check if the parent opcode will actually use
* this result. If not, delete the result now so that it will
* not become orphaned.
*
******************************************************************************/
void
acpi_ds_delete_result_if_not_used(union acpi_parse_object *op,
union acpi_operand_object *result_obj,
struct acpi_walk_state *walk_state)
{
union acpi_operand_object *obj_desc;
acpi_status status;
ACPI_FUNCTION_TRACE_PTR(ds_delete_result_if_not_used, result_obj);
if (!op) {
ACPI_ERROR((AE_INFO, "Null Op"));
return_VOID;
}
if (!result_obj) {
return_VOID;
}
if (!acpi_ds_is_result_used(op, walk_state)) {
/* Must pop the result stack (obj_desc should be equal to result_obj) */
status = acpi_ds_result_pop(&obj_desc, walk_state);
if (ACPI_SUCCESS(status)) {
acpi_ut_remove_reference(result_obj);
}
}
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_resolve_operands
*
* PARAMETERS: walk_state - Current walk state with operands on stack
*
* RETURN: Status
*
* DESCRIPTION: Resolve all operands to their values. Used to prepare
* arguments to a control method invocation (a call from one
* method to another.)
*
******************************************************************************/
acpi_status acpi_ds_resolve_operands(struct acpi_walk_state *walk_state)
{
u32 i;
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE_PTR(ds_resolve_operands, walk_state);
/*
* Attempt to resolve each of the valid operands
* Method arguments are passed by reference, not by value. This means
* that the actual objects are passed, not copies of the objects.
*/
for (i = 0; i < walk_state->num_operands; i++) {
status =
acpi_ex_resolve_to_value(&walk_state->operands[i],
walk_state);
if (ACPI_FAILURE(status)) {
break;
}
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_clear_operands
*
* PARAMETERS: walk_state - Current walk state with operands on stack
*
* RETURN: None
*
* DESCRIPTION: Clear all operands on the current walk state operand stack.
*
******************************************************************************/
void acpi_ds_clear_operands(struct acpi_walk_state *walk_state)
{
u32 i;
ACPI_FUNCTION_TRACE_PTR(ds_clear_operands, walk_state);
/* Remove a reference on each operand on the stack */
for (i = 0; i < walk_state->num_operands; i++) {
/*
* Remove a reference to all operands, including both
* "Arguments" and "Targets".
*/
acpi_ut_remove_reference(walk_state->operands[i]);
walk_state->operands[i] = NULL;
}
walk_state->num_operands = 0;
return_VOID;
}
#endif
/*******************************************************************************
*
* FUNCTION: acpi_ds_create_operand
*
* PARAMETERS: walk_state - Current walk state
* Arg - Parse object for the argument
* arg_index - Which argument (zero based)
*
* RETURN: Status
*
* DESCRIPTION: Translate a parse tree object that is an argument to an AML
* opcode to the equivalent interpreter object. This may include
* looking up a name or entering a new name into the internal
* namespace.
*
******************************************************************************/
acpi_status
acpi_ds_create_operand(struct acpi_walk_state *walk_state,
union acpi_parse_object *arg, u32 arg_index)
{
acpi_status status = AE_OK;
char *name_string;
u32 name_length;
union acpi_operand_object *obj_desc;
union acpi_parse_object *parent_op;
u16 opcode;
acpi_interpreter_mode interpreter_mode;
const struct acpi_opcode_info *op_info;
ACPI_FUNCTION_TRACE_PTR(ds_create_operand, arg);
/* A valid name must be looked up in the namespace */
if ((arg->common.aml_opcode == AML_INT_NAMEPATH_OP) &&
(arg->common.value.string) &&
!(arg->common.flags & ACPI_PARSEOP_IN_STACK)) {
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH, "Getting a name: Arg=%p\n",
arg));
/* Get the entire name string from the AML stream */
status =
acpi_ex_get_name_string(ACPI_TYPE_ANY,
arg->common.value.buffer,
&name_string, &name_length);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* All prefixes have been handled, and the name is in name_string */
/*
* Special handling for buffer_field declarations. This is a deferred
* opcode that unfortunately defines the field name as the last
* parameter instead of the first. We get here when we are performing
* the deferred execution, so the actual name of the field is already
* in the namespace. We don't want to attempt to look it up again
* because we may be executing in a different scope than where the
* actual opcode exists.
*/
if ((walk_state->deferred_node) &&
(walk_state->deferred_node->type == ACPI_TYPE_BUFFER_FIELD)
&& (arg_index ==
(u32) ((walk_state->opcode ==
AML_CREATE_FIELD_OP) ? 3 : 2))) {
obj_desc =
ACPI_CAST_PTR(union acpi_operand_object,
walk_state->deferred_node);
status = AE_OK;
} else { /* All other opcodes */
/*
* Differentiate between a namespace "create" operation
* versus a "lookup" operation (IMODE_LOAD_PASS2 vs.
* IMODE_EXECUTE) in order to support the creation of
* namespace objects during the execution of control methods.
*/
parent_op = arg->common.parent;
op_info =
acpi_ps_get_opcode_info(parent_op->common.
aml_opcode);
if ((op_info->flags & AML_NSNODE)
&& (parent_op->common.aml_opcode !=
AML_INT_METHODCALL_OP)
&& (parent_op->common.aml_opcode != AML_REGION_OP)
&& (parent_op->common.aml_opcode !=
AML_INT_NAMEPATH_OP)) {
/* Enter name into namespace if not found */
interpreter_mode = ACPI_IMODE_LOAD_PASS2;
} else {
/* Return a failure if name not found */
interpreter_mode = ACPI_IMODE_EXECUTE;
}
status =
acpi_ns_lookup(walk_state->scope_info, name_string,
ACPI_TYPE_ANY, interpreter_mode,
ACPI_NS_SEARCH_PARENT |
ACPI_NS_DONT_OPEN_SCOPE, walk_state,
ACPI_CAST_INDIRECT_PTR(struct
acpi_namespace_node,
&obj_desc));
/*
* The only case where we pass through (ignore) a NOT_FOUND
* error is for the cond_ref_of opcode.
*/
if (status == AE_NOT_FOUND) {
if (parent_op->common.aml_opcode ==
AML_COND_REF_OF_OP) {
/*
* For the Conditional Reference op, it's OK if
* the name is not found; We just need a way to
* indicate this to the interpreter, set the
* object to the root
*/
obj_desc = ACPI_CAST_PTR(union
acpi_operand_object,
acpi_gbl_root_node);
status = AE_OK;
} else {
/*
* We just plain didn't find it -- which is a
* very serious error at this point
*/
status = AE_AML_NAME_NOT_FOUND;
}
}
if (ACPI_FAILURE(status)) {
ACPI_ERROR_NAMESPACE(name_string, status);
}
}
/* Free the namestring created above */
ACPI_FREE(name_string);
/* Check status from the lookup */
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Put the resulting object onto the current object stack */
status = acpi_ds_obj_stack_push(obj_desc, walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
ACPI_DEBUGGER_EXEC(acpi_db_display_argument_object
(obj_desc, walk_state));
} else {
/* Check for null name case */
if ((arg->common.aml_opcode == AML_INT_NAMEPATH_OP) &&
!(arg->common.flags & ACPI_PARSEOP_IN_STACK)) {
/*
* If the name is null, this means that this is an
* optional result parameter that was not specified
* in the original ASL. Create a Zero Constant for a
* placeholder. (Store to a constant is a Noop.)
*/
opcode = AML_ZERO_OP; /* Has no arguments! */
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Null namepath: Arg=%p\n", arg));
} else {
opcode = arg->common.aml_opcode;
}
/* Get the object type of the argument */
op_info = acpi_ps_get_opcode_info(opcode);
if (op_info->object_type == ACPI_TYPE_INVALID) {
return_ACPI_STATUS(AE_NOT_IMPLEMENTED);
}
if ((op_info->flags & AML_HAS_RETVAL)
|| (arg->common.flags & ACPI_PARSEOP_IN_STACK)) {
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Argument previously created, already stacked\n"));
ACPI_DEBUGGER_EXEC(acpi_db_display_argument_object
(walk_state->
operands[walk_state->num_operands -
1], walk_state));
/*
* Use value that was already previously returned
* by the evaluation of this argument
*/
status = acpi_ds_result_pop(&obj_desc, walk_state);
if (ACPI_FAILURE(status)) {
/*
* Only error is underflow, and this indicates
* a missing or null operand!
*/
ACPI_EXCEPTION((AE_INFO, status,
"Missing or null operand"));
return_ACPI_STATUS(status);
}
} else {
/* Create an ACPI_INTERNAL_OBJECT for the argument */
obj_desc =
acpi_ut_create_internal_object(op_info->
object_type);
if (!obj_desc) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* Initialize the new object */
status =
acpi_ds_init_object_from_op(walk_state, arg, opcode,
&obj_desc);
if (ACPI_FAILURE(status)) {
acpi_ut_delete_object_desc(obj_desc);
return_ACPI_STATUS(status);
}
}
/* Put the operand object on the object stack */
status = acpi_ds_obj_stack_push(obj_desc, walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
ACPI_DEBUGGER_EXEC(acpi_db_display_argument_object
(obj_desc, walk_state));
}
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ds_create_operands
*
* PARAMETERS: walk_state - Current state
* first_arg - First argument of a parser argument tree
*
* RETURN: Status
*
* DESCRIPTION: Convert an operator's arguments from a parse tree format to
* namespace objects and place those argument object on the object
* stack in preparation for evaluation by the interpreter.
*
******************************************************************************/
acpi_status
acpi_ds_create_operands(struct acpi_walk_state *walk_state,
union acpi_parse_object *first_arg)
{
acpi_status status = AE_OK;
union acpi_parse_object *arg;
union acpi_parse_object *arguments[ACPI_OBJ_NUM_OPERANDS];
u32 arg_count = 0;
u32 index = walk_state->num_operands;
u32 i;
ACPI_FUNCTION_TRACE_PTR(ds_create_operands, first_arg);
/* Get all arguments in the list */
arg = first_arg;
while (arg) {
if (index >= ACPI_OBJ_NUM_OPERANDS) {
return_ACPI_STATUS(AE_BAD_DATA);
}
arguments[index] = arg;
walk_state->operands[index] = NULL;
/* Move on to next argument, if any */
arg = arg->common.next;
arg_count++;
index++;
}
index--;
/* It is the appropriate order to get objects from the Result stack */
for (i = 0; i < arg_count; i++) {
arg = arguments[index];
/* Force the filling of the operand stack in inverse order */
walk_state->operand_index = (u8) index;
status = acpi_ds_create_operand(walk_state, arg, index);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
index--;
ACPI_DEBUG_PRINT((ACPI_DB_DISPATCH,
"Arg #%u (%p) done, Arg1=%p\n", index, arg,
first_arg));
}
return_ACPI_STATUS(status);
cleanup:
/*
* We must undo everything done above; meaning that we must
* pop everything off of the operand stack and delete those
* objects
*/
acpi_ds_obj_stack_pop_and_delete(arg_count, walk_state);
ACPI_EXCEPTION((AE_INFO, status, "While creating Arg %u", index));
return_ACPI_STATUS(status);
}
/*****************************************************************************
*
* FUNCTION: acpi_ds_evaluate_name_path
*
* PARAMETERS: walk_state - Current state of the parse tree walk,
* the opcode of current operation should be
* AML_INT_NAMEPATH_OP
*
* RETURN: Status
*
* DESCRIPTION: Translate the -name_path- parse tree object to the equivalent
* interpreter object, convert it to value, if needed, duplicate
* it, if needed, and push it onto the current result stack.
*
****************************************************************************/
acpi_status acpi_ds_evaluate_name_path(struct acpi_walk_state *walk_state)
{
acpi_status status = AE_OK;
union acpi_parse_object *op = walk_state->op;
union acpi_operand_object **operand = &walk_state->operands[0];
union acpi_operand_object *new_obj_desc;
u8 type;
ACPI_FUNCTION_TRACE_PTR(ds_evaluate_name_path, walk_state);
if (!op->common.parent) {
/* This happens after certain exception processing */
goto exit;
}
if ((op->common.parent->common.aml_opcode == AML_PACKAGE_OP) ||
(op->common.parent->common.aml_opcode == AML_VAR_PACKAGE_OP) ||
(op->common.parent->common.aml_opcode == AML_REF_OF_OP)) {
/* TBD: Should we specify this feature as a bit of op_info->Flags of these opcodes? */
goto exit;
}
status = acpi_ds_create_operand(walk_state, op, 0);
if (ACPI_FAILURE(status)) {
goto exit;
}
if (op->common.flags & ACPI_PARSEOP_TARGET) {
new_obj_desc = *operand;
goto push_result;
}
type = (*operand)->common.type;
status = acpi_ex_resolve_to_value(operand, walk_state);
if (ACPI_FAILURE(status)) {
goto exit;
}
if (type == ACPI_TYPE_INTEGER) {
/* It was incremented by acpi_ex_resolve_to_value */
acpi_ut_remove_reference(*operand);
status =
acpi_ut_copy_iobject_to_iobject(*operand, &new_obj_desc,
walk_state);
if (ACPI_FAILURE(status)) {
goto exit;
}
} else {
/*
* The object either was anew created or is
* a Namespace node - don't decrement it.
*/
new_obj_desc = *operand;
}
/* Cleanup for name-path operand */
status = acpi_ds_obj_stack_pop(1, walk_state);
if (ACPI_FAILURE(status)) {
walk_state->result_obj = new_obj_desc;
goto exit;
}
push_result:
walk_state->result_obj = new_obj_desc;
status = acpi_ds_result_push(walk_state->result_obj, walk_state);
if (ACPI_SUCCESS(status)) {
/* Force to take it from stack */
op->common.flags |= ACPI_PARSEOP_IN_STACK;
}
exit:
return_ACPI_STATUS(status);
}
| gpl-2.0 |
Puri321/lge-kernel-bssq | fs/xfs/quota/xfs_qm_stats.c | 3483 | 2801 | /*
* Copyright (c) 2000-2003 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_alloc.h"
#include "xfs_quota.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_inode.h"
#include "xfs_itable.h"
#include "xfs_bmap.h"
#include "xfs_rtalloc.h"
#include "xfs_error.h"
#include "xfs_attr.h"
#include "xfs_buf_item.h"
#include "xfs_qm.h"
struct xqmstats xqmstats;
static int xqm_proc_show(struct seq_file *m, void *v)
{
/* maximum; incore; ratio free to inuse; freelist */
seq_printf(m, "%d\t%d\t%d\t%u\n",
ndquot,
xfs_Gqm? atomic_read(&xfs_Gqm->qm_totaldquots) : 0,
xfs_Gqm? xfs_Gqm->qm_dqfree_ratio : 0,
xfs_Gqm? xfs_Gqm->qm_dqfrlist_cnt : 0);
return 0;
}
static int xqm_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, xqm_proc_show, NULL);
}
static const struct file_operations xqm_proc_fops = {
.owner = THIS_MODULE,
.open = xqm_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int xqmstat_proc_show(struct seq_file *m, void *v)
{
/* quota performance statistics */
seq_printf(m, "qm %u %u %u %u %u %u %u %u\n",
xqmstats.xs_qm_dqreclaims,
xqmstats.xs_qm_dqreclaim_misses,
xqmstats.xs_qm_dquot_dups,
xqmstats.xs_qm_dqcachemisses,
xqmstats.xs_qm_dqcachehits,
xqmstats.xs_qm_dqwants,
xqmstats.xs_qm_dqshake_reclaims,
xqmstats.xs_qm_dqinact_reclaims);
return 0;
}
static int xqmstat_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, xqmstat_proc_show, NULL);
}
static const struct file_operations xqmstat_proc_fops = {
.owner = THIS_MODULE,
.open = xqmstat_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
void
xfs_qm_init_procfs(void)
{
proc_create("fs/xfs/xqmstat", 0, NULL, &xqmstat_proc_fops);
proc_create("fs/xfs/xqm", 0, NULL, &xqm_proc_fops);
}
void
xfs_qm_cleanup_procfs(void)
{
remove_proc_entry("fs/xfs/xqm", NULL);
remove_proc_entry("fs/xfs/xqmstat", NULL);
}
| gpl-2.0 |
arasilinux/kernel-3.2.0 | arch/sh/drivers/push-switch.c | 4763 | 3204 | /*
* Generic push-switch framework
*
* Copyright (C) 2006 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <asm/push-switch.h>
#define DRV_NAME "push-switch"
#define DRV_VERSION "0.1.1"
static ssize_t switch_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct push_switch_platform_info *psw_info = dev->platform_data;
return sprintf(buf, "%s\n", psw_info->name);
}
static DEVICE_ATTR(switch, S_IRUGO, switch_show, NULL);
static void switch_timer(unsigned long data)
{
struct push_switch *psw = (struct push_switch *)data;
schedule_work(&psw->work);
}
static void switch_work_handler(struct work_struct *work)
{
struct push_switch *psw = container_of(work, struct push_switch, work);
struct platform_device *pdev = psw->pdev;
psw->state = 0;
kobject_uevent(&pdev->dev.kobj, KOBJ_CHANGE);
}
static int switch_drv_probe(struct platform_device *pdev)
{
struct push_switch_platform_info *psw_info;
struct push_switch *psw;
int ret, irq;
psw = kzalloc(sizeof(struct push_switch), GFP_KERNEL);
if (unlikely(!psw))
return -ENOMEM;
irq = platform_get_irq(pdev, 0);
if (unlikely(irq < 0)) {
ret = -ENODEV;
goto err;
}
psw_info = pdev->dev.platform_data;
BUG_ON(!psw_info);
ret = request_irq(irq, psw_info->irq_handler,
psw_info->irq_flags,
psw_info->name ? psw_info->name : DRV_NAME, pdev);
if (unlikely(ret < 0))
goto err;
if (psw_info->name) {
ret = device_create_file(&pdev->dev, &dev_attr_switch);
if (unlikely(ret)) {
dev_err(&pdev->dev, "Failed creating device attrs\n");
ret = -EINVAL;
goto err_irq;
}
}
INIT_WORK(&psw->work, switch_work_handler);
init_timer(&psw->debounce);
psw->debounce.function = switch_timer;
psw->debounce.data = (unsigned long)psw;
/* Workqueue API brain-damage */
psw->pdev = pdev;
platform_set_drvdata(pdev, psw);
return 0;
err_irq:
free_irq(irq, pdev);
err:
kfree(psw);
return ret;
}
static int switch_drv_remove(struct platform_device *pdev)
{
struct push_switch *psw = platform_get_drvdata(pdev);
struct push_switch_platform_info *psw_info = pdev->dev.platform_data;
int irq = platform_get_irq(pdev, 0);
if (psw_info->name)
device_remove_file(&pdev->dev, &dev_attr_switch);
platform_set_drvdata(pdev, NULL);
flush_work_sync(&psw->work);
del_timer_sync(&psw->debounce);
free_irq(irq, pdev);
kfree(psw);
return 0;
}
static struct platform_driver switch_driver = {
.probe = switch_drv_probe,
.remove = switch_drv_remove,
.driver = {
.name = DRV_NAME,
},
};
static int __init switch_init(void)
{
printk(KERN_NOTICE DRV_NAME ": version %s loaded\n", DRV_VERSION);
return platform_driver_register(&switch_driver);
}
static void __exit switch_exit(void)
{
platform_driver_unregister(&switch_driver);
}
module_init(switch_init);
module_exit(switch_exit);
MODULE_VERSION(DRV_VERSION);
MODULE_AUTHOR("Paul Mundt");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
jgcaaprom/android_kernel_oneplus_msm8974 | arch/arm/mach-omap2/smartreflex-class3.c | 4763 | 1448 | /*
* Smart reflex Class 3 specific implementations
*
* Author: Thara Gopinath <thara@ti.com>
*
* Copyright (C) 2010 Texas Instruments, Inc.
* Thara Gopinath <thara@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include "smartreflex.h"
static int sr_class3_enable(struct voltagedomain *voltdm)
{
unsigned long volt = voltdm_get_voltage(voltdm);
if (!volt) {
pr_warning("%s: Curr voltage unknown. Cannot enable sr_%s\n",
__func__, voltdm->name);
return -ENODATA;
}
omap_vp_enable(voltdm);
return sr_enable(voltdm, volt);
}
static int sr_class3_disable(struct voltagedomain *voltdm, int is_volt_reset)
{
sr_disable_errgen(voltdm);
omap_vp_disable(voltdm);
sr_disable(voltdm);
if (is_volt_reset)
voltdm_reset(voltdm);
return 0;
}
static int sr_class3_configure(struct voltagedomain *voltdm)
{
return sr_configure_errgen(voltdm);
}
/* SR class3 structure */
static struct omap_sr_class_data class3_data = {
.enable = sr_class3_enable,
.disable = sr_class3_disable,
.configure = sr_class3_configure,
.class_type = SR_CLASS3,
};
/* Smartreflex Class3 init API to be called from board file */
static int __init sr_class3_init(void)
{
pr_info("SmartReflex Class3 initialized\n");
return sr_register_class(&class3_data);
}
late_initcall(sr_class3_init);
| gpl-2.0 |
philozheng/kernel-msm | drivers/uwb/est.c | 7323 | 13767 | /*
* Ultra Wide Band Radio Control
* Event Size Tables management
*
* Copyright (C) 2005-2006 Intel Corporation
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.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 Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*
* FIXME: docs
*
* Infrastructure, code and data tables for guessing the size of
* events received on the notification endpoints of UWB radio
* controllers.
*
* You define a table of events and for each, its size and how to get
* the extra size.
*
* ENTRY POINTS:
*
* uwb_est_{init/destroy}(): To initialize/release the EST subsystem.
*
* uwb_est_[u]register(): To un/register event size tables
* uwb_est_grow()
*
* uwb_est_find_size(): Get the size of an event
* uwb_est_get_size()
*/
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/export.h>
#include "uwb-internal.h"
struct uwb_est {
u16 type_event_high;
u16 vendor, product;
u8 entries;
const struct uwb_est_entry *entry;
};
static struct uwb_est *uwb_est;
static u8 uwb_est_size;
static u8 uwb_est_used;
static DEFINE_RWLOCK(uwb_est_lock);
/**
* WUSB Standard Event Size Table, HWA-RC interface
*
* Sizes for events and notifications type 0 (general), high nibble 0.
*/
static
struct uwb_est_entry uwb_est_00_00xx[] = {
[UWB_RC_EVT_IE_RCV] = {
.size = sizeof(struct uwb_rc_evt_ie_rcv),
.offset = 1 + offsetof(struct uwb_rc_evt_ie_rcv, wIELength),
},
[UWB_RC_EVT_BEACON] = {
.size = sizeof(struct uwb_rc_evt_beacon),
.offset = 1 + offsetof(struct uwb_rc_evt_beacon, wBeaconInfoLength),
},
[UWB_RC_EVT_BEACON_SIZE] = {
.size = sizeof(struct uwb_rc_evt_beacon_size),
},
[UWB_RC_EVT_BPOIE_CHANGE] = {
.size = sizeof(struct uwb_rc_evt_bpoie_change),
.offset = 1 + offsetof(struct uwb_rc_evt_bpoie_change,
wBPOIELength),
},
[UWB_RC_EVT_BP_SLOT_CHANGE] = {
.size = sizeof(struct uwb_rc_evt_bp_slot_change),
},
[UWB_RC_EVT_BP_SWITCH_IE_RCV] = {
.size = sizeof(struct uwb_rc_evt_bp_switch_ie_rcv),
.offset = 1 + offsetof(struct uwb_rc_evt_bp_switch_ie_rcv, wIELength),
},
[UWB_RC_EVT_DEV_ADDR_CONFLICT] = {
.size = sizeof(struct uwb_rc_evt_dev_addr_conflict),
},
[UWB_RC_EVT_DRP_AVAIL] = {
.size = sizeof(struct uwb_rc_evt_drp_avail)
},
[UWB_RC_EVT_DRP] = {
.size = sizeof(struct uwb_rc_evt_drp),
.offset = 1 + offsetof(struct uwb_rc_evt_drp, ie_length),
},
[UWB_RC_EVT_BP_SWITCH_STATUS] = {
.size = sizeof(struct uwb_rc_evt_bp_switch_status),
},
[UWB_RC_EVT_CMD_FRAME_RCV] = {
.size = sizeof(struct uwb_rc_evt_cmd_frame_rcv),
.offset = 1 + offsetof(struct uwb_rc_evt_cmd_frame_rcv, dataLength),
},
[UWB_RC_EVT_CHANNEL_CHANGE_IE_RCV] = {
.size = sizeof(struct uwb_rc_evt_channel_change_ie_rcv),
.offset = 1 + offsetof(struct uwb_rc_evt_channel_change_ie_rcv, wIELength),
},
[UWB_RC_CMD_CHANNEL_CHANGE] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_DEV_ADDR_MGMT] = {
.size = sizeof(struct uwb_rc_evt_dev_addr_mgmt) },
[UWB_RC_CMD_GET_IE] = {
.size = sizeof(struct uwb_rc_evt_get_ie),
.offset = 1 + offsetof(struct uwb_rc_evt_get_ie, wIELength),
},
[UWB_RC_CMD_RESET] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_SCAN] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_SET_BEACON_FILTER] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_SET_DRP_IE] = {
.size = sizeof(struct uwb_rc_evt_set_drp_ie),
},
[UWB_RC_CMD_SET_IE] = {
.size = sizeof(struct uwb_rc_evt_set_ie),
},
[UWB_RC_CMD_SET_NOTIFICATION_FILTER] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_SET_TX_POWER] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_SLEEP] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_START_BEACON] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_STOP_BEACON] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_BP_MERGE] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_SEND_COMMAND_FRAME] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
[UWB_RC_CMD_SET_ASIE_NOTIF] = {
.size = sizeof(struct uwb_rc_evt_confirm),
},
};
static
struct uwb_est_entry uwb_est_01_00xx[] = {
[UWB_RC_DAA_ENERGY_DETECTED] = {
.size = sizeof(struct uwb_rc_evt_daa_energy_detected),
},
[UWB_RC_SET_DAA_ENERGY_MASK] = {
.size = sizeof(struct uwb_rc_evt_set_daa_energy_mask),
},
[UWB_RC_SET_NOTIFICATION_FILTER_EX] = {
.size = sizeof(struct uwb_rc_evt_set_notification_filter_ex),
},
};
/**
* Initialize the EST subsystem
*
* Register the standard tables also.
*
* FIXME: tag init
*/
int uwb_est_create(void)
{
int result;
uwb_est_size = 2;
uwb_est_used = 0;
uwb_est = kcalloc(uwb_est_size, sizeof(uwb_est[0]), GFP_KERNEL);
if (uwb_est == NULL)
return -ENOMEM;
result = uwb_est_register(UWB_RC_CET_GENERAL, 0, 0xffff, 0xffff,
uwb_est_00_00xx, ARRAY_SIZE(uwb_est_00_00xx));
if (result < 0)
goto out;
result = uwb_est_register(UWB_RC_CET_EX_TYPE_1, 0, 0xffff, 0xffff,
uwb_est_01_00xx, ARRAY_SIZE(uwb_est_01_00xx));
out:
return result;
}
/** Clean it up */
void uwb_est_destroy(void)
{
kfree(uwb_est);
uwb_est = NULL;
uwb_est_size = uwb_est_used = 0;
}
/**
* Double the capacity of the EST table
*
* @returns 0 if ok, < 0 errno no error.
*/
static
int uwb_est_grow(void)
{
size_t actual_size = uwb_est_size * sizeof(uwb_est[0]);
void *new = kmalloc(2 * actual_size, GFP_ATOMIC);
if (new == NULL)
return -ENOMEM;
memcpy(new, uwb_est, actual_size);
memset(new + actual_size, 0, actual_size);
kfree(uwb_est);
uwb_est = new;
uwb_est_size *= 2;
return 0;
}
/**
* Register an event size table
*
* Makes room for it if the table is full, and then inserts it in the
* right position (entries are sorted by type, event_high, vendor and
* then product).
*
* @vendor: vendor code for matching against the device (0x0000 and
* 0xffff mean any); use 0x0000 to force all to match without
* checking possible vendor specific ones, 0xfffff to match
* after checking vendor specific ones.
*
* @product: product code from that vendor; same matching rules, use
* 0x0000 for not allowing vendor specific matches, 0xffff
* for allowing.
*
* This arragement just makes the tables sort differenty. Because the
* table is sorted by growing type-event_high-vendor-product, a zero
* vendor will match before than a 0x456a vendor, that will match
* before a 0xfffff vendor.
*
* @returns 0 if ok, < 0 errno on error (-ENOENT if not found).
*/
/* FIXME: add bus type to vendor/product code */
int uwb_est_register(u8 type, u8 event_high, u16 vendor, u16 product,
const struct uwb_est_entry *entry, size_t entries)
{
unsigned long flags;
unsigned itr;
u16 type_event_high;
int result = 0;
write_lock_irqsave(&uwb_est_lock, flags);
if (uwb_est_used == uwb_est_size) {
result = uwb_est_grow();
if (result < 0)
goto out;
}
/* Find the right spot to insert it in */
type_event_high = type << 8 | event_high;
for (itr = 0; itr < uwb_est_used; itr++)
if (uwb_est[itr].type_event_high < type
&& uwb_est[itr].vendor < vendor
&& uwb_est[itr].product < product)
break;
/* Shift others to make room for the new one? */
if (itr < uwb_est_used)
memmove(&uwb_est[itr+1], &uwb_est[itr], uwb_est_used - itr);
uwb_est[itr].type_event_high = type << 8 | event_high;
uwb_est[itr].vendor = vendor;
uwb_est[itr].product = product;
uwb_est[itr].entry = entry;
uwb_est[itr].entries = entries;
uwb_est_used++;
out:
write_unlock_irqrestore(&uwb_est_lock, flags);
return result;
}
EXPORT_SYMBOL_GPL(uwb_est_register);
/**
* Unregister an event size table
*
* This just removes the specified entry and moves the ones after it
* to fill in the gap. This is needed to keep the list sorted; no
* reallocation is done to reduce the size of the table.
*
* We unregister by all the data we used to register instead of by
* pointer to the @entry array because we might have used the same
* table for a bunch of IDs (for example).
*
* @returns 0 if ok, < 0 errno on error (-ENOENT if not found).
*/
int uwb_est_unregister(u8 type, u8 event_high, u16 vendor, u16 product,
const struct uwb_est_entry *entry, size_t entries)
{
unsigned long flags;
unsigned itr;
struct uwb_est est_cmp = {
.type_event_high = type << 8 | event_high,
.vendor = vendor,
.product = product,
.entry = entry,
.entries = entries
};
write_lock_irqsave(&uwb_est_lock, flags);
for (itr = 0; itr < uwb_est_used; itr++)
if (!memcmp(&uwb_est[itr], &est_cmp, sizeof(est_cmp)))
goto found;
write_unlock_irqrestore(&uwb_est_lock, flags);
return -ENOENT;
found:
if (itr < uwb_est_used - 1) /* Not last one? move ones above */
memmove(&uwb_est[itr], &uwb_est[itr+1], uwb_est_used - itr - 1);
uwb_est_used--;
write_unlock_irqrestore(&uwb_est_lock, flags);
return 0;
}
EXPORT_SYMBOL_GPL(uwb_est_unregister);
/**
* Get the size of an event from a table
*
* @rceb: pointer to the buffer with the event
* @rceb_size: size of the area pointed to by @rceb in bytes.
* @returns: > 0 Size of the event
* -ENOSPC An area big enough was not provided to look
* ahead into the event's guts and guess the size.
* -EINVAL Unknown event code (wEvent).
*
* This will look at the received RCEB and guess what is the total
* size. For variable sized events, it will look further ahead into
* their length field to see how much data should be read.
*
* Note this size is *not* final--the neh (Notification/Event Handle)
* might specificy an extra size to add.
*/
static
ssize_t uwb_est_get_size(struct uwb_rc *uwb_rc, struct uwb_est *est,
u8 event_low, const struct uwb_rceb *rceb,
size_t rceb_size)
{
unsigned offset;
ssize_t size;
struct device *dev = &uwb_rc->uwb_dev.dev;
const struct uwb_est_entry *entry;
size = -ENOENT;
if (event_low >= est->entries) { /* in range? */
dev_err(dev, "EST %p 0x%04x/%04x/%04x[%u]: event %u out of range\n",
est, est->type_event_high, est->vendor, est->product,
est->entries, event_low);
goto out;
}
size = -ENOENT;
entry = &est->entry[event_low];
if (entry->size == 0 && entry->offset == 0) { /* unknown? */
dev_err(dev, "EST %p 0x%04x/%04x/%04x[%u]: event %u unknown\n",
est, est->type_event_high, est->vendor, est->product,
est->entries, event_low);
goto out;
}
offset = entry->offset; /* extra fries with that? */
if (offset == 0)
size = entry->size;
else {
/* Ops, got an extra size field at 'offset'--read it */
const void *ptr = rceb;
size_t type_size = 0;
offset--;
size = -ENOSPC; /* enough data for more? */
switch (entry->type) {
case UWB_EST_16: type_size = sizeof(__le16); break;
case UWB_EST_8: type_size = sizeof(u8); break;
default: BUG();
}
if (offset + type_size > rceb_size) {
dev_err(dev, "EST %p 0x%04x/%04x/%04x[%u]: "
"not enough data to read extra size\n",
est, est->type_event_high, est->vendor,
est->product, est->entries);
goto out;
}
size = entry->size;
ptr += offset;
switch (entry->type) {
case UWB_EST_16: size += le16_to_cpu(*(__le16 *)ptr); break;
case UWB_EST_8: size += *(u8 *)ptr; break;
default: BUG();
}
}
out:
return size;
}
/**
* Guesses the size of a WA event
*
* @rceb: pointer to the buffer with the event
* @rceb_size: size of the area pointed to by @rceb in bytes.
* @returns: > 0 Size of the event
* -ENOSPC An area big enough was not provided to look
* ahead into the event's guts and guess the size.
* -EINVAL Unknown event code (wEvent).
*
* This will look at the received RCEB and guess what is the total
* size by checking all the tables registered with
* uwb_est_register(). For variable sized events, it will look further
* ahead into their length field to see how much data should be read.
*
* Note this size is *not* final--the neh (Notification/Event Handle)
* might specificy an extra size to add or replace.
*/
ssize_t uwb_est_find_size(struct uwb_rc *rc, const struct uwb_rceb *rceb,
size_t rceb_size)
{
/* FIXME: add vendor/product data */
ssize_t size;
struct device *dev = &rc->uwb_dev.dev;
unsigned long flags;
unsigned itr;
u16 type_event_high, event;
u8 *ptr = (u8 *) rceb;
read_lock_irqsave(&uwb_est_lock, flags);
size = -ENOSPC;
if (rceb_size < sizeof(*rceb))
goto out;
event = le16_to_cpu(rceb->wEvent);
type_event_high = rceb->bEventType << 8 | (event & 0xff00) >> 8;
for (itr = 0; itr < uwb_est_used; itr++) {
if (uwb_est[itr].type_event_high != type_event_high)
continue;
size = uwb_est_get_size(rc, &uwb_est[itr],
event & 0x00ff, rceb, rceb_size);
/* try more tables that might handle the same type */
if (size != -ENOENT)
goto out;
}
dev_dbg(dev, "event 0x%02x/%04x/%02x: no handlers available; "
"RCEB %02x %02x %02x %02x\n",
(unsigned) rceb->bEventType,
(unsigned) le16_to_cpu(rceb->wEvent),
(unsigned) rceb->bEventContext,
ptr[0], ptr[1], ptr[2], ptr[3]);
size = -ENOENT;
out:
read_unlock_irqrestore(&uwb_est_lock, flags);
return size;
}
EXPORT_SYMBOL_GPL(uwb_est_find_size);
| gpl-2.0 |
ChameleonOS/android_kernel_amazon_bowser-common | arch/sh/kernel/sh_ksyms_32.c | 8603 | 2668 | #include <linux/module.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <asm/checksum.h>
#include <asm/sections.h>
EXPORT_SYMBOL(memchr);
EXPORT_SYMBOL(memcpy);
EXPORT_SYMBOL(memset);
EXPORT_SYMBOL(memmove);
EXPORT_SYMBOL(__copy_user);
EXPORT_SYMBOL(__udelay);
EXPORT_SYMBOL(__ndelay);
EXPORT_SYMBOL(__const_udelay);
EXPORT_SYMBOL(strlen);
EXPORT_SYMBOL(csum_partial);
EXPORT_SYMBOL(csum_partial_copy_generic);
EXPORT_SYMBOL(copy_page);
EXPORT_SYMBOL(__clear_user);
EXPORT_SYMBOL(_ebss);
EXPORT_SYMBOL(empty_zero_page);
#define DECLARE_EXPORT(name) \
extern void name(void);EXPORT_SYMBOL(name)
DECLARE_EXPORT(__udivsi3);
DECLARE_EXPORT(__sdivsi3);
DECLARE_EXPORT(__lshrsi3);
DECLARE_EXPORT(__ashrsi3);
DECLARE_EXPORT(__ashlsi3);
DECLARE_EXPORT(__ashiftrt_r4_6);
DECLARE_EXPORT(__ashiftrt_r4_7);
DECLARE_EXPORT(__ashiftrt_r4_8);
DECLARE_EXPORT(__ashiftrt_r4_9);
DECLARE_EXPORT(__ashiftrt_r4_10);
DECLARE_EXPORT(__ashiftrt_r4_11);
DECLARE_EXPORT(__ashiftrt_r4_12);
DECLARE_EXPORT(__ashiftrt_r4_13);
DECLARE_EXPORT(__ashiftrt_r4_14);
DECLARE_EXPORT(__ashiftrt_r4_15);
DECLARE_EXPORT(__ashiftrt_r4_20);
DECLARE_EXPORT(__ashiftrt_r4_21);
DECLARE_EXPORT(__ashiftrt_r4_22);
DECLARE_EXPORT(__ashiftrt_r4_23);
DECLARE_EXPORT(__ashiftrt_r4_24);
DECLARE_EXPORT(__ashiftrt_r4_27);
DECLARE_EXPORT(__ashiftrt_r4_30);
DECLARE_EXPORT(__movstr);
DECLARE_EXPORT(__movstrSI8);
DECLARE_EXPORT(__movstrSI12);
DECLARE_EXPORT(__movstrSI16);
DECLARE_EXPORT(__movstrSI20);
DECLARE_EXPORT(__movstrSI24);
DECLARE_EXPORT(__movstrSI28);
DECLARE_EXPORT(__movstrSI32);
DECLARE_EXPORT(__movstrSI36);
DECLARE_EXPORT(__movstrSI40);
DECLARE_EXPORT(__movstrSI44);
DECLARE_EXPORT(__movstrSI48);
DECLARE_EXPORT(__movstrSI52);
DECLARE_EXPORT(__movstrSI56);
DECLARE_EXPORT(__movstrSI60);
DECLARE_EXPORT(__movstr_i4_even);
DECLARE_EXPORT(__movstr_i4_odd);
DECLARE_EXPORT(__movstrSI12_i4);
DECLARE_EXPORT(__movmem);
DECLARE_EXPORT(__movmemSI8);
DECLARE_EXPORT(__movmemSI12);
DECLARE_EXPORT(__movmemSI16);
DECLARE_EXPORT(__movmemSI20);
DECLARE_EXPORT(__movmemSI24);
DECLARE_EXPORT(__movmemSI28);
DECLARE_EXPORT(__movmemSI32);
DECLARE_EXPORT(__movmemSI36);
DECLARE_EXPORT(__movmemSI40);
DECLARE_EXPORT(__movmemSI44);
DECLARE_EXPORT(__movmemSI48);
DECLARE_EXPORT(__movmemSI52);
DECLARE_EXPORT(__movmemSI56);
DECLARE_EXPORT(__movmemSI60);
DECLARE_EXPORT(__movmem_i4_even);
DECLARE_EXPORT(__movmem_i4_odd);
DECLARE_EXPORT(__movmemSI12_i4);
DECLARE_EXPORT(__udiv_qrnnd_16);
DECLARE_EXPORT(__sdivsi3_i4);
DECLARE_EXPORT(__udivsi3_i4);
DECLARE_EXPORT(__sdivsi3_i4i);
DECLARE_EXPORT(__udivsi3_i4i);
#ifdef CONFIG_MCOUNT
DECLARE_EXPORT(mcount);
#endif
| gpl-2.0 |
iyahman/android_kernel_samsung_jf | drivers/net/wireless/wl1251/debugfs.c | 9883 | 17368 | /*
* This file is part of wl1251
*
* 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 "debugfs.h"
#include <linux/skbuff.h>
#include <linux/slab.h>
#include "wl1251.h"
#include "acx.h"
#include "ps.h"
/* ms */
#define WL1251_DEBUGFS_STATS_LIFETIME 1000
/* debugfs macros idea from mac80211 */
#define DEBUGFS_READONLY_FILE(name, buflen, fmt, value...) \
static ssize_t name## _read(struct file *file, char __user *userbuf, \
size_t count, loff_t *ppos) \
{ \
struct wl1251 *wl = file->private_data; \
char buf[buflen]; \
int res; \
\
res = scnprintf(buf, buflen, fmt "\n", ##value); \
return simple_read_from_buffer(userbuf, count, ppos, buf, res); \
} \
\
static const struct file_operations name## _ops = { \
.read = name## _read, \
.open = simple_open, \
.llseek = generic_file_llseek, \
};
#define DEBUGFS_ADD(name, parent) \
wl->debugfs.name = debugfs_create_file(#name, 0400, parent, \
wl, &name## _ops); \
if (IS_ERR(wl->debugfs.name)) { \
ret = PTR_ERR(wl->debugfs.name); \
wl->debugfs.name = NULL; \
goto out; \
}
#define DEBUGFS_DEL(name) \
do { \
debugfs_remove(wl->debugfs.name); \
wl->debugfs.name = NULL; \
} while (0)
#define DEBUGFS_FWSTATS_FILE(sub, name, buflen, fmt) \
static ssize_t sub## _ ##name## _read(struct file *file, \
char __user *userbuf, \
size_t count, loff_t *ppos) \
{ \
struct wl1251 *wl = file->private_data; \
char buf[buflen]; \
int res; \
\
wl1251_debugfs_update_stats(wl); \
\
res = scnprintf(buf, buflen, fmt "\n", \
wl->stats.fw_stats->sub.name); \
return simple_read_from_buffer(userbuf, count, ppos, buf, res); \
} \
\
static const struct file_operations sub## _ ##name## _ops = { \
.read = sub## _ ##name## _read, \
.open = simple_open, \
.llseek = generic_file_llseek, \
};
#define DEBUGFS_FWSTATS_ADD(sub, name) \
DEBUGFS_ADD(sub## _ ##name, wl->debugfs.fw_statistics)
#define DEBUGFS_FWSTATS_DEL(sub, name) \
DEBUGFS_DEL(sub## _ ##name)
static void wl1251_debugfs_update_stats(struct wl1251 *wl)
{
int ret;
mutex_lock(&wl->mutex);
ret = wl1251_ps_elp_wakeup(wl);
if (ret < 0)
goto out;
if (wl->state == WL1251_STATE_ON &&
time_after(jiffies, wl->stats.fw_stats_update +
msecs_to_jiffies(WL1251_DEBUGFS_STATS_LIFETIME))) {
wl1251_acx_statistics(wl, wl->stats.fw_stats);
wl->stats.fw_stats_update = jiffies;
}
wl1251_ps_elp_sleep(wl);
out:
mutex_unlock(&wl->mutex);
}
DEBUGFS_FWSTATS_FILE(tx, internal_desc_overflow, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, out_of_mem, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, hdr_overflow, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, hw_stuck, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, dropped, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, fcs_err, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, xfr_hint_trig, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, path_reset, 20, "%u");
DEBUGFS_FWSTATS_FILE(rx, reset_counter, 20, "%u");
DEBUGFS_FWSTATS_FILE(dma, rx_requested, 20, "%u");
DEBUGFS_FWSTATS_FILE(dma, rx_errors, 20, "%u");
DEBUGFS_FWSTATS_FILE(dma, tx_requested, 20, "%u");
DEBUGFS_FWSTATS_FILE(dma, tx_errors, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, cmd_cmplt, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, fiqs, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, rx_headers, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, rx_mem_overflow, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, rx_rdys, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, irqs, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, tx_procs, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, decrypt_done, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, dma0_done, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, dma1_done, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, tx_exch_complete, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, commands, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, rx_procs, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, hw_pm_mode_changes, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, host_acknowledges, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, pci_pm, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, wakeups, 20, "%u");
DEBUGFS_FWSTATS_FILE(isr, low_rssi, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, addr_key_count, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, default_key_count, 20, "%u");
/* skipping wep.reserved */
DEBUGFS_FWSTATS_FILE(wep, key_not_found, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, decrypt_fail, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, packets, 20, "%u");
DEBUGFS_FWSTATS_FILE(wep, interrupt, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, ps_enter, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, elp_enter, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, missing_bcns, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, wake_on_host, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, wake_on_timer_exp, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, tx_with_ps, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, tx_without_ps, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, rcvd_beacons, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, power_save_off, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, enable_ps, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, disable_ps, 20, "%u");
DEBUGFS_FWSTATS_FILE(pwr, fix_tsf_ps, 20, "%u");
/* skipping cont_miss_bcns_spread for now */
DEBUGFS_FWSTATS_FILE(pwr, rcvd_awake_beacons, 20, "%u");
DEBUGFS_FWSTATS_FILE(mic, rx_pkts, 20, "%u");
DEBUGFS_FWSTATS_FILE(mic, calc_failure, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, encrypt_fail, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, decrypt_fail, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, encrypt_packets, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, decrypt_packets, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, encrypt_interrupt, 20, "%u");
DEBUGFS_FWSTATS_FILE(aes, decrypt_interrupt, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, heart_beat, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, calibration, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, rx_mismatch, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, rx_mem_empty, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, rx_pool, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, oom_late, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, phy_transmit_error, 20, "%u");
DEBUGFS_FWSTATS_FILE(event, tx_stuck, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, pspoll_timeouts, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, upsd_timeouts, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, upsd_max_sptime, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, upsd_max_apturn, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, pspoll_max_apturn, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, pspoll_utilization, 20, "%u");
DEBUGFS_FWSTATS_FILE(ps, upsd_utilization, 20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, rx_prep_beacon_drop, 20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, descr_host_int_trig_rx_data, 20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, beacon_buffer_thres_host_int_trig_rx_data,
20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, missed_beacon_host_int_trig_rx_data, 20, "%u");
DEBUGFS_FWSTATS_FILE(rxpipe, tx_xfr_host_int_trig_rx_data, 20, "%u");
DEBUGFS_READONLY_FILE(retry_count, 20, "%u", wl->stats.retry_count);
DEBUGFS_READONLY_FILE(excessive_retries, 20, "%u",
wl->stats.excessive_retries);
static ssize_t tx_queue_len_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct wl1251 *wl = file->private_data;
u32 queue_len;
char buf[20];
int res;
queue_len = skb_queue_len(&wl->tx_queue);
res = scnprintf(buf, sizeof(buf), "%u\n", queue_len);
return simple_read_from_buffer(userbuf, count, ppos, buf, res);
}
static const struct file_operations tx_queue_len_ops = {
.read = tx_queue_len_read,
.open = simple_open,
.llseek = generic_file_llseek,
};
static ssize_t tx_queue_status_read(struct file *file, char __user *userbuf,
size_t count, loff_t *ppos)
{
struct wl1251 *wl = file->private_data;
char buf[3], status;
int len;
if (wl->tx_queue_stopped)
status = 's';
else
status = 'r';
len = scnprintf(buf, sizeof(buf), "%c\n", status);
return simple_read_from_buffer(userbuf, count, ppos, buf, len);
}
static const struct file_operations tx_queue_status_ops = {
.read = tx_queue_status_read,
.open = simple_open,
.llseek = generic_file_llseek,
};
static void wl1251_debugfs_delete_files(struct wl1251 *wl)
{
DEBUGFS_FWSTATS_DEL(tx, internal_desc_overflow);
DEBUGFS_FWSTATS_DEL(rx, out_of_mem);
DEBUGFS_FWSTATS_DEL(rx, hdr_overflow);
DEBUGFS_FWSTATS_DEL(rx, hw_stuck);
DEBUGFS_FWSTATS_DEL(rx, dropped);
DEBUGFS_FWSTATS_DEL(rx, fcs_err);
DEBUGFS_FWSTATS_DEL(rx, xfr_hint_trig);
DEBUGFS_FWSTATS_DEL(rx, path_reset);
DEBUGFS_FWSTATS_DEL(rx, reset_counter);
DEBUGFS_FWSTATS_DEL(dma, rx_requested);
DEBUGFS_FWSTATS_DEL(dma, rx_errors);
DEBUGFS_FWSTATS_DEL(dma, tx_requested);
DEBUGFS_FWSTATS_DEL(dma, tx_errors);
DEBUGFS_FWSTATS_DEL(isr, cmd_cmplt);
DEBUGFS_FWSTATS_DEL(isr, fiqs);
DEBUGFS_FWSTATS_DEL(isr, rx_headers);
DEBUGFS_FWSTATS_DEL(isr, rx_mem_overflow);
DEBUGFS_FWSTATS_DEL(isr, rx_rdys);
DEBUGFS_FWSTATS_DEL(isr, irqs);
DEBUGFS_FWSTATS_DEL(isr, tx_procs);
DEBUGFS_FWSTATS_DEL(isr, decrypt_done);
DEBUGFS_FWSTATS_DEL(isr, dma0_done);
DEBUGFS_FWSTATS_DEL(isr, dma1_done);
DEBUGFS_FWSTATS_DEL(isr, tx_exch_complete);
DEBUGFS_FWSTATS_DEL(isr, commands);
DEBUGFS_FWSTATS_DEL(isr, rx_procs);
DEBUGFS_FWSTATS_DEL(isr, hw_pm_mode_changes);
DEBUGFS_FWSTATS_DEL(isr, host_acknowledges);
DEBUGFS_FWSTATS_DEL(isr, pci_pm);
DEBUGFS_FWSTATS_DEL(isr, wakeups);
DEBUGFS_FWSTATS_DEL(isr, low_rssi);
DEBUGFS_FWSTATS_DEL(wep, addr_key_count);
DEBUGFS_FWSTATS_DEL(wep, default_key_count);
/* skipping wep.reserved */
DEBUGFS_FWSTATS_DEL(wep, key_not_found);
DEBUGFS_FWSTATS_DEL(wep, decrypt_fail);
DEBUGFS_FWSTATS_DEL(wep, packets);
DEBUGFS_FWSTATS_DEL(wep, interrupt);
DEBUGFS_FWSTATS_DEL(pwr, ps_enter);
DEBUGFS_FWSTATS_DEL(pwr, elp_enter);
DEBUGFS_FWSTATS_DEL(pwr, missing_bcns);
DEBUGFS_FWSTATS_DEL(pwr, wake_on_host);
DEBUGFS_FWSTATS_DEL(pwr, wake_on_timer_exp);
DEBUGFS_FWSTATS_DEL(pwr, tx_with_ps);
DEBUGFS_FWSTATS_DEL(pwr, tx_without_ps);
DEBUGFS_FWSTATS_DEL(pwr, rcvd_beacons);
DEBUGFS_FWSTATS_DEL(pwr, power_save_off);
DEBUGFS_FWSTATS_DEL(pwr, enable_ps);
DEBUGFS_FWSTATS_DEL(pwr, disable_ps);
DEBUGFS_FWSTATS_DEL(pwr, fix_tsf_ps);
/* skipping cont_miss_bcns_spread for now */
DEBUGFS_FWSTATS_DEL(pwr, rcvd_awake_beacons);
DEBUGFS_FWSTATS_DEL(mic, rx_pkts);
DEBUGFS_FWSTATS_DEL(mic, calc_failure);
DEBUGFS_FWSTATS_DEL(aes, encrypt_fail);
DEBUGFS_FWSTATS_DEL(aes, decrypt_fail);
DEBUGFS_FWSTATS_DEL(aes, encrypt_packets);
DEBUGFS_FWSTATS_DEL(aes, decrypt_packets);
DEBUGFS_FWSTATS_DEL(aes, encrypt_interrupt);
DEBUGFS_FWSTATS_DEL(aes, decrypt_interrupt);
DEBUGFS_FWSTATS_DEL(event, heart_beat);
DEBUGFS_FWSTATS_DEL(event, calibration);
DEBUGFS_FWSTATS_DEL(event, rx_mismatch);
DEBUGFS_FWSTATS_DEL(event, rx_mem_empty);
DEBUGFS_FWSTATS_DEL(event, rx_pool);
DEBUGFS_FWSTATS_DEL(event, oom_late);
DEBUGFS_FWSTATS_DEL(event, phy_transmit_error);
DEBUGFS_FWSTATS_DEL(event, tx_stuck);
DEBUGFS_FWSTATS_DEL(ps, pspoll_timeouts);
DEBUGFS_FWSTATS_DEL(ps, upsd_timeouts);
DEBUGFS_FWSTATS_DEL(ps, upsd_max_sptime);
DEBUGFS_FWSTATS_DEL(ps, upsd_max_apturn);
DEBUGFS_FWSTATS_DEL(ps, pspoll_max_apturn);
DEBUGFS_FWSTATS_DEL(ps, pspoll_utilization);
DEBUGFS_FWSTATS_DEL(ps, upsd_utilization);
DEBUGFS_FWSTATS_DEL(rxpipe, rx_prep_beacon_drop);
DEBUGFS_FWSTATS_DEL(rxpipe, descr_host_int_trig_rx_data);
DEBUGFS_FWSTATS_DEL(rxpipe, beacon_buffer_thres_host_int_trig_rx_data);
DEBUGFS_FWSTATS_DEL(rxpipe, missed_beacon_host_int_trig_rx_data);
DEBUGFS_FWSTATS_DEL(rxpipe, tx_xfr_host_int_trig_rx_data);
DEBUGFS_DEL(tx_queue_len);
DEBUGFS_DEL(tx_queue_status);
DEBUGFS_DEL(retry_count);
DEBUGFS_DEL(excessive_retries);
}
static int wl1251_debugfs_add_files(struct wl1251 *wl)
{
int ret = 0;
DEBUGFS_FWSTATS_ADD(tx, internal_desc_overflow);
DEBUGFS_FWSTATS_ADD(rx, out_of_mem);
DEBUGFS_FWSTATS_ADD(rx, hdr_overflow);
DEBUGFS_FWSTATS_ADD(rx, hw_stuck);
DEBUGFS_FWSTATS_ADD(rx, dropped);
DEBUGFS_FWSTATS_ADD(rx, fcs_err);
DEBUGFS_FWSTATS_ADD(rx, xfr_hint_trig);
DEBUGFS_FWSTATS_ADD(rx, path_reset);
DEBUGFS_FWSTATS_ADD(rx, reset_counter);
DEBUGFS_FWSTATS_ADD(dma, rx_requested);
DEBUGFS_FWSTATS_ADD(dma, rx_errors);
DEBUGFS_FWSTATS_ADD(dma, tx_requested);
DEBUGFS_FWSTATS_ADD(dma, tx_errors);
DEBUGFS_FWSTATS_ADD(isr, cmd_cmplt);
DEBUGFS_FWSTATS_ADD(isr, fiqs);
DEBUGFS_FWSTATS_ADD(isr, rx_headers);
DEBUGFS_FWSTATS_ADD(isr, rx_mem_overflow);
DEBUGFS_FWSTATS_ADD(isr, rx_rdys);
DEBUGFS_FWSTATS_ADD(isr, irqs);
DEBUGFS_FWSTATS_ADD(isr, tx_procs);
DEBUGFS_FWSTATS_ADD(isr, decrypt_done);
DEBUGFS_FWSTATS_ADD(isr, dma0_done);
DEBUGFS_FWSTATS_ADD(isr, dma1_done);
DEBUGFS_FWSTATS_ADD(isr, tx_exch_complete);
DEBUGFS_FWSTATS_ADD(isr, commands);
DEBUGFS_FWSTATS_ADD(isr, rx_procs);
DEBUGFS_FWSTATS_ADD(isr, hw_pm_mode_changes);
DEBUGFS_FWSTATS_ADD(isr, host_acknowledges);
DEBUGFS_FWSTATS_ADD(isr, pci_pm);
DEBUGFS_FWSTATS_ADD(isr, wakeups);
DEBUGFS_FWSTATS_ADD(isr, low_rssi);
DEBUGFS_FWSTATS_ADD(wep, addr_key_count);
DEBUGFS_FWSTATS_ADD(wep, default_key_count);
/* skipping wep.reserved */
DEBUGFS_FWSTATS_ADD(wep, key_not_found);
DEBUGFS_FWSTATS_ADD(wep, decrypt_fail);
DEBUGFS_FWSTATS_ADD(wep, packets);
DEBUGFS_FWSTATS_ADD(wep, interrupt);
DEBUGFS_FWSTATS_ADD(pwr, ps_enter);
DEBUGFS_FWSTATS_ADD(pwr, elp_enter);
DEBUGFS_FWSTATS_ADD(pwr, missing_bcns);
DEBUGFS_FWSTATS_ADD(pwr, wake_on_host);
DEBUGFS_FWSTATS_ADD(pwr, wake_on_timer_exp);
DEBUGFS_FWSTATS_ADD(pwr, tx_with_ps);
DEBUGFS_FWSTATS_ADD(pwr, tx_without_ps);
DEBUGFS_FWSTATS_ADD(pwr, rcvd_beacons);
DEBUGFS_FWSTATS_ADD(pwr, power_save_off);
DEBUGFS_FWSTATS_ADD(pwr, enable_ps);
DEBUGFS_FWSTATS_ADD(pwr, disable_ps);
DEBUGFS_FWSTATS_ADD(pwr, fix_tsf_ps);
/* skipping cont_miss_bcns_spread for now */
DEBUGFS_FWSTATS_ADD(pwr, rcvd_awake_beacons);
DEBUGFS_FWSTATS_ADD(mic, rx_pkts);
DEBUGFS_FWSTATS_ADD(mic, calc_failure);
DEBUGFS_FWSTATS_ADD(aes, encrypt_fail);
DEBUGFS_FWSTATS_ADD(aes, decrypt_fail);
DEBUGFS_FWSTATS_ADD(aes, encrypt_packets);
DEBUGFS_FWSTATS_ADD(aes, decrypt_packets);
DEBUGFS_FWSTATS_ADD(aes, encrypt_interrupt);
DEBUGFS_FWSTATS_ADD(aes, decrypt_interrupt);
DEBUGFS_FWSTATS_ADD(event, heart_beat);
DEBUGFS_FWSTATS_ADD(event, calibration);
DEBUGFS_FWSTATS_ADD(event, rx_mismatch);
DEBUGFS_FWSTATS_ADD(event, rx_mem_empty);
DEBUGFS_FWSTATS_ADD(event, rx_pool);
DEBUGFS_FWSTATS_ADD(event, oom_late);
DEBUGFS_FWSTATS_ADD(event, phy_transmit_error);
DEBUGFS_FWSTATS_ADD(event, tx_stuck);
DEBUGFS_FWSTATS_ADD(ps, pspoll_timeouts);
DEBUGFS_FWSTATS_ADD(ps, upsd_timeouts);
DEBUGFS_FWSTATS_ADD(ps, upsd_max_sptime);
DEBUGFS_FWSTATS_ADD(ps, upsd_max_apturn);
DEBUGFS_FWSTATS_ADD(ps, pspoll_max_apturn);
DEBUGFS_FWSTATS_ADD(ps, pspoll_utilization);
DEBUGFS_FWSTATS_ADD(ps, upsd_utilization);
DEBUGFS_FWSTATS_ADD(rxpipe, rx_prep_beacon_drop);
DEBUGFS_FWSTATS_ADD(rxpipe, descr_host_int_trig_rx_data);
DEBUGFS_FWSTATS_ADD(rxpipe, beacon_buffer_thres_host_int_trig_rx_data);
DEBUGFS_FWSTATS_ADD(rxpipe, missed_beacon_host_int_trig_rx_data);
DEBUGFS_FWSTATS_ADD(rxpipe, tx_xfr_host_int_trig_rx_data);
DEBUGFS_ADD(tx_queue_len, wl->debugfs.rootdir);
DEBUGFS_ADD(tx_queue_status, wl->debugfs.rootdir);
DEBUGFS_ADD(retry_count, wl->debugfs.rootdir);
DEBUGFS_ADD(excessive_retries, wl->debugfs.rootdir);
out:
if (ret < 0)
wl1251_debugfs_delete_files(wl);
return ret;
}
void wl1251_debugfs_reset(struct wl1251 *wl)
{
if (wl->stats.fw_stats != NULL)
memset(wl->stats.fw_stats, 0, sizeof(*wl->stats.fw_stats));
wl->stats.retry_count = 0;
wl->stats.excessive_retries = 0;
}
int wl1251_debugfs_init(struct wl1251 *wl)
{
int ret;
wl->debugfs.rootdir = debugfs_create_dir(KBUILD_MODNAME, NULL);
if (IS_ERR(wl->debugfs.rootdir)) {
ret = PTR_ERR(wl->debugfs.rootdir);
wl->debugfs.rootdir = NULL;
goto err;
}
wl->debugfs.fw_statistics = debugfs_create_dir("fw-statistics",
wl->debugfs.rootdir);
if (IS_ERR(wl->debugfs.fw_statistics)) {
ret = PTR_ERR(wl->debugfs.fw_statistics);
wl->debugfs.fw_statistics = NULL;
goto err_root;
}
wl->stats.fw_stats = kzalloc(sizeof(*wl->stats.fw_stats),
GFP_KERNEL);
if (!wl->stats.fw_stats) {
ret = -ENOMEM;
goto err_fw;
}
wl->stats.fw_stats_update = jiffies;
ret = wl1251_debugfs_add_files(wl);
if (ret < 0)
goto err_file;
return 0;
err_file:
kfree(wl->stats.fw_stats);
wl->stats.fw_stats = NULL;
err_fw:
debugfs_remove(wl->debugfs.fw_statistics);
wl->debugfs.fw_statistics = NULL;
err_root:
debugfs_remove(wl->debugfs.rootdir);
wl->debugfs.rootdir = NULL;
err:
return ret;
}
void wl1251_debugfs_exit(struct wl1251 *wl)
{
wl1251_debugfs_delete_files(wl);
kfree(wl->stats.fw_stats);
wl->stats.fw_stats = NULL;
debugfs_remove(wl->debugfs.fw_statistics);
wl->debugfs.fw_statistics = NULL;
debugfs_remove(wl->debugfs.rootdir);
wl->debugfs.rootdir = NULL;
}
| gpl-2.0 |
sycolon/lge_g3_kernel | arch/arm/mach-omap2/mux44xx.c | 9883 | 63046 | /*
* OMAP44xx ES1.0 pin mux definition
*
* Copyright (C) 2010 Texas Instruments, Inc.
*
* Benoit Cousson (b-cousson@ti.com)
*
* - Based on mux34xx.c done by Tony Lindgren <tony@atomide.com>
*
* This file is automatically generated from the OMAP hardware databases.
* We respectfully ask that any modifications to this file be coordinated
* with the public linux-omap@vger.kernel.org mailing list and the
* authors above to ensure that the autogeneration scripts are kept
* up-to-date with the file contents.
*
* 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/init.h>
#include "mux.h"
#ifdef CONFIG_OMAP_MUX
#define _OMAP4_MUXENTRY(M0, g, m0, m1, m2, m3, m4, m5, m6, m7) \
{ \
.reg_offset = (OMAP4_CTRL_MODULE_PAD_##M0##_OFFSET), \
.gpio = (g), \
.muxnames = { m0, m1, m2, m3, m4, m5, m6, m7 }, \
}
#else
#define _OMAP4_MUXENTRY(M0, g, m0, m1, m2, m3, m4, m5, m6, m7) \
{ \
.reg_offset = (OMAP4_CTRL_MODULE_PAD_##M0##_OFFSET), \
.gpio = (g), \
}
#endif
#define _OMAP4_BALLENTRY(M0, bb, bt) \
{ \
.reg_offset = (OMAP4_CTRL_MODULE_PAD_##M0##_OFFSET), \
.balls = { bb, bt }, \
}
/*
* Superset of all mux modes for omap4 ES1.0
*/
static struct omap_mux __initdata omap4_core_muxmodes[] = {
_OMAP4_MUXENTRY(GPMC_AD0, 0, "gpmc_ad0", "sdmmc2_dat0", NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD1, 0, "gpmc_ad1", "sdmmc2_dat1", NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD2, 0, "gpmc_ad2", "sdmmc2_dat2", NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD3, 0, "gpmc_ad3", "sdmmc2_dat3", NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD4, 0, "gpmc_ad4", "sdmmc2_dat4",
"sdmmc2_dir_dat0", NULL, NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD5, 0, "gpmc_ad5", "sdmmc2_dat5",
"sdmmc2_dir_dat1", NULL, NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD6, 0, "gpmc_ad6", "sdmmc2_dat6",
"sdmmc2_dir_cmd", NULL, NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD7, 0, "gpmc_ad7", "sdmmc2_dat7",
"sdmmc2_clk_fdbk", NULL, NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD8, 32, "gpmc_ad8", "kpd_row0", "c2c_data15",
"gpio_32", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD9, 33, "gpmc_ad9", "kpd_row1", "c2c_data14",
"gpio_33", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD10, 34, "gpmc_ad10", "kpd_row2", "c2c_data13",
"gpio_34", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD11, 35, "gpmc_ad11", "kpd_row3", "c2c_data12",
"gpio_35", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD12, 36, "gpmc_ad12", "kpd_col0", "c2c_data11",
"gpio_36", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD13, 37, "gpmc_ad13", "kpd_col1", "c2c_data10",
"gpio_37", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD14, 38, "gpmc_ad14", "kpd_col2", "c2c_data9",
"gpio_38", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD15, 39, "gpmc_ad15", "kpd_col3", "c2c_data8",
"gpio_39", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_A16, 40, "gpmc_a16", "kpd_row4", "c2c_datain0",
"gpio_40", "venc_656_data0", NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_A17, 41, "gpmc_a17", "kpd_row5", "c2c_datain1",
"gpio_41", "venc_656_data1", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_A18, 42, "gpmc_a18", "kpd_row6", "c2c_datain2",
"gpio_42", "venc_656_data2", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_A19, 43, "gpmc_a19", "kpd_row7", "c2c_datain3",
"gpio_43", "venc_656_data3", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_A20, 44, "gpmc_a20", "kpd_col4", "c2c_datain4",
"gpio_44", "venc_656_data4", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_A21, 45, "gpmc_a21", "kpd_col5", "c2c_datain5",
"gpio_45", "venc_656_data5", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_A22, 46, "gpmc_a22", "kpd_col6", "c2c_datain6",
"gpio_46", "venc_656_data6", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_A23, 47, "gpmc_a23", "kpd_col7", "c2c_datain7",
"gpio_47", "venc_656_data7", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_A24, 48, "gpmc_a24", NULL, "c2c_clkout0",
"gpio_48", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_A25, 49, "gpmc_a25", NULL, "c2c_clkout1",
"gpio_49", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_NCS0, 50, "gpmc_ncs0", NULL, NULL, "gpio_50",
"sys_ndmareq0", NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_NCS1, 51, "gpmc_ncs1", NULL, "c2c_dataout6",
"gpio_51", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_NCS2, 52, "gpmc_ncs2", NULL, "c2c_dataout7",
"gpio_52", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_NCS3, 53, "gpmc_ncs3", "gpmc_dir",
"c2c_dataout4", "gpio_53", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(GPMC_NWP, 54, "gpmc_nwp", "dsi1_te0", NULL, "gpio_54",
"sys_ndmareq1", NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_CLK, 55, "gpmc_clk", NULL, NULL, "gpio_55",
"sys_ndmareq2", NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_NADV_ALE, 56, "gpmc_nadv_ale", "dsi1_te1", NULL,
"gpio_56", "sys_ndmareq3", NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_NOE, 0, "gpmc_noe", "sdmmc2_clk", NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_NWE, 0, "gpmc_nwe", "sdmmc2_cmd", NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_NBE0_CLE, 59, "gpmc_nbe0_cle", "dsi2_te0", NULL,
"gpio_59", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_NBE1, 60, "gpmc_nbe1", NULL, "c2c_dataout5",
"gpio_60", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_WAIT0, 61, "gpmc_wait0", "dsi2_te1", NULL,
"gpio_61", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(GPMC_WAIT1, 62, "gpmc_wait1", NULL, "c2c_dataout2",
"gpio_62", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(C2C_DATA11, 100, "c2c_data11", "usbc1_icusb_txen",
"c2c_dataout3", "gpio_100", "sys_ndmareq0", NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(C2C_DATA12, 101, "c2c_data12", "dsi1_te0",
"c2c_clkin0", "gpio_101", "sys_ndmareq1", NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(C2C_DATA13, 102, "c2c_data13", "dsi1_te1",
"c2c_clkin1", "gpio_102", "sys_ndmareq2", NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(C2C_DATA14, 103, "c2c_data14", "dsi2_te0",
"c2c_dataout0", "gpio_103", "sys_ndmareq3", NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(C2C_DATA15, 104, "c2c_data15", "dsi2_te1",
"c2c_dataout1", "gpio_104", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(HDMI_HPD, 63, "hdmi_hpd", NULL, NULL, "gpio_63", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(HDMI_CEC, 64, "hdmi_cec", NULL, NULL, "gpio_64", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(HDMI_DDC_SCL, 65, "hdmi_ddc_scl", NULL, NULL,
"gpio_65", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(HDMI_DDC_SDA, 66, "hdmi_ddc_sda", NULL, NULL,
"gpio_66", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DX0, 0, "csi21_dx0", NULL, NULL, "gpi_67", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DY0, 0, "csi21_dy0", NULL, NULL, "gpi_68", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DX1, 0, "csi21_dx1", NULL, NULL, "gpi_69", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DY1, 0, "csi21_dy1", NULL, NULL, "gpi_70", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DX2, 0, "csi21_dx2", NULL, NULL, "gpi_71", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DY2, 0, "csi21_dy2", NULL, NULL, "gpi_72", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DX3, 0, "csi21_dx3", NULL, NULL, "gpi_73", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DY3, 0, "csi21_dy3", NULL, NULL, "gpi_74", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DX4, 0, "csi21_dx4", NULL, NULL, "gpi_75", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI21_DY4, 0, "csi21_dy4", NULL, NULL, "gpi_76", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI22_DX0, 0, "csi22_dx0", NULL, NULL, "gpi_77", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI22_DY0, 0, "csi22_dy0", NULL, NULL, "gpi_78", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI22_DX1, 0, "csi22_dx1", NULL, NULL, "gpi_79", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CSI22_DY1, 0, "csi22_dy1", NULL, NULL, "gpi_80", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CAM_SHUTTER, 81, "cam_shutter", NULL, NULL, "gpio_81",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CAM_STROBE, 82, "cam_strobe", NULL, NULL, "gpio_82",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(CAM_GLOBALRESET, 83, "cam_globalreset", NULL, NULL,
"gpio_83", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_CLK, 84, "usbb1_ulpitll_clk",
"hsi1_cawake", NULL, "gpio_84", "usbb1_ulpiphy_clk",
NULL, "hw_dbg20", "safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_STP, 85, "usbb1_ulpitll_stp",
"hsi1_cadata", "mcbsp4_clkr", "gpio_85",
"usbb1_ulpiphy_stp", "usbb1_mm_rxdp", "hw_dbg21",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DIR, 86, "usbb1_ulpitll_dir",
"hsi1_caflag", "mcbsp4_fsr", "gpio_86",
"usbb1_ulpiphy_dir", NULL, "hw_dbg22", "safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_NXT, 87, "usbb1_ulpitll_nxt",
"hsi1_acready", "mcbsp4_fsx", "gpio_87",
"usbb1_ulpiphy_nxt", "usbb1_mm_rxdm", "hw_dbg23",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT0, 88, "usbb1_ulpitll_dat0",
"hsi1_acwake", "mcbsp4_clkx", "gpio_88",
"usbb1_ulpiphy_dat0", "usbb1_mm_rxrcv", "hw_dbg24",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT1, 89, "usbb1_ulpitll_dat1",
"hsi1_acdata", "mcbsp4_dx", "gpio_89",
"usbb1_ulpiphy_dat1", "usbb1_mm_txse0", "hw_dbg25",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT2, 90, "usbb1_ulpitll_dat2",
"hsi1_acflag", "mcbsp4_dr", "gpio_90",
"usbb1_ulpiphy_dat2", "usbb1_mm_txdat", "hw_dbg26",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT3, 91, "usbb1_ulpitll_dat3",
"hsi1_caready", NULL, "gpio_91", "usbb1_ulpiphy_dat3",
"usbb1_mm_txen", "hw_dbg27", "safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT4, 92, "usbb1_ulpitll_dat4",
"dmtimer8_pwm_evt", "abe_mcbsp3_dr", "gpio_92",
"usbb1_ulpiphy_dat4", NULL, "hw_dbg28", "safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT5, 93, "usbb1_ulpitll_dat5",
"dmtimer9_pwm_evt", "abe_mcbsp3_dx", "gpio_93",
"usbb1_ulpiphy_dat5", NULL, "hw_dbg29", "safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT6, 94, "usbb1_ulpitll_dat6",
"dmtimer10_pwm_evt", "abe_mcbsp3_clkx", "gpio_94",
"usbb1_ulpiphy_dat6", "abe_dmic_din3", "hw_dbg30",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT7, 95, "usbb1_ulpitll_dat7",
"dmtimer11_pwm_evt", "abe_mcbsp3_fsx", "gpio_95",
"usbb1_ulpiphy_dat7", "abe_dmic_clk3", "hw_dbg31",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_HSIC_DATA, 96, "usbb1_hsic_data", NULL, NULL,
"gpio_96", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBB1_HSIC_STROBE, 97, "usbb1_hsic_strobe", NULL,
NULL, "gpio_97", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBC1_ICUSB_DP, 98, "usbc1_icusb_dp", NULL, NULL,
"gpio_98", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBC1_ICUSB_DM, 99, "usbc1_icusb_dm", NULL, NULL,
"gpio_99", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_CLK, 100, "sdmmc1_clk", NULL, "dpm_emu19",
"gpio_100", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_CMD, 101, "sdmmc1_cmd", NULL, "uart1_rx",
"gpio_101", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_DAT0, 102, "sdmmc1_dat0", NULL, "dpm_emu18",
"gpio_102", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_DAT1, 103, "sdmmc1_dat1", NULL, "dpm_emu17",
"gpio_103", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_DAT2, 104, "sdmmc1_dat2", NULL, "dpm_emu16",
"gpio_104", "jtag_tms_tmsc", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_DAT3, 105, "sdmmc1_dat3", NULL, "dpm_emu15",
"gpio_105", "jtag_tck", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_DAT4, 106, "sdmmc1_dat4", NULL, NULL,
"gpio_106", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_DAT5, 107, "sdmmc1_dat5", NULL, NULL,
"gpio_107", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_DAT6, 108, "sdmmc1_dat6", NULL, NULL,
"gpio_108", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC1_DAT7, 109, "sdmmc1_dat7", NULL, NULL,
"gpio_109", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_MCBSP2_CLKX, 110, "abe_mcbsp2_clkx", "mcspi2_clk",
"abe_mcasp_ahclkx", "gpio_110", "usbb2_mm_rxdm",
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_MCBSP2_DR, 111, "abe_mcbsp2_dr", "mcspi2_somi",
"abe_mcasp_axr", "gpio_111", "usbb2_mm_rxdp", NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_MCBSP2_DX, 112, "abe_mcbsp2_dx", "mcspi2_simo",
"abe_mcasp_amute", "gpio_112", "usbb2_mm_rxrcv", NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_MCBSP2_FSX, 113, "abe_mcbsp2_fsx", "mcspi2_cs0",
"abe_mcasp_afsx", "gpio_113", "usbb2_mm_txen", NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_MCBSP1_CLKX, 114, "abe_mcbsp1_clkx",
"abe_slimbus1_clock", NULL, "gpio_114", NULL, NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_MCBSP1_DR, 115, "abe_mcbsp1_dr",
"abe_slimbus1_data", NULL, "gpio_115", NULL, NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_MCBSP1_DX, 116, "abe_mcbsp1_dx", "sdmmc3_dat2",
"abe_mcasp_aclkx", "gpio_116", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(ABE_MCBSP1_FSX, 117, "abe_mcbsp1_fsx", "sdmmc3_dat3",
"abe_mcasp_amutein", "gpio_117", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(ABE_PDM_UL_DATA, 0, "abe_pdm_ul_data",
"abe_mcbsp3_dr", NULL, NULL, NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(ABE_PDM_DL_DATA, 0, "abe_pdm_dl_data",
"abe_mcbsp3_dx", NULL, NULL, NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(ABE_PDM_FRAME, 0, "abe_pdm_frame", "abe_mcbsp3_clkx",
NULL, NULL, NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_PDM_LB_CLK, 0, "abe_pdm_lb_clk", "abe_mcbsp3_fsx",
NULL, NULL, NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_CLKS, 118, "abe_clks", NULL, NULL, "gpio_118",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_DMIC_CLK1, 119, "abe_dmic_clk1", NULL, NULL,
"gpio_119", "usbb2_mm_txse0", NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(ABE_DMIC_DIN1, 120, "abe_dmic_din1", NULL, NULL,
"gpio_120", "usbb2_mm_txdat", NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(ABE_DMIC_DIN2, 121, "abe_dmic_din2", "slimbus2_clock",
NULL, "gpio_121", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_DMIC_DIN3, 122, "abe_dmic_din3", "slimbus2_data",
"abe_dmic_clk2", "gpio_122", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(UART2_CTS, 123, "uart2_cts", "sdmmc3_clk", NULL,
"gpio_123", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UART2_RTS, 124, "uart2_rts", "sdmmc3_cmd", NULL,
"gpio_124", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UART2_RX, 125, "uart2_rx", "sdmmc3_dat0", NULL,
"gpio_125", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UART2_TX, 126, "uart2_tx", "sdmmc3_dat1", NULL,
"gpio_126", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(HDQ_SIO, 127, "hdq_sio", "i2c3_sccb", "i2c2_sccb",
"gpio_127", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(I2C1_SCL, 0, "i2c1_scl", NULL, NULL, NULL, NULL, NULL,
NULL, NULL),
_OMAP4_MUXENTRY(I2C1_SDA, 0, "i2c1_sda", NULL, NULL, NULL, NULL, NULL,
NULL, NULL),
_OMAP4_MUXENTRY(I2C2_SCL, 128, "i2c2_scl", "uart1_rx", NULL,
"gpio_128", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(I2C2_SDA, 129, "i2c2_sda", "uart1_tx", NULL,
"gpio_129", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(I2C3_SCL, 130, "i2c3_scl", NULL, NULL, "gpio_130",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(I2C3_SDA, 131, "i2c3_sda", NULL, NULL, "gpio_131",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(I2C4_SCL, 132, "i2c4_scl", NULL, NULL, "gpio_132",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(I2C4_SDA, 133, "i2c4_sda", NULL, NULL, "gpio_133",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI1_CLK, 134, "mcspi1_clk", NULL, NULL, "gpio_134",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI1_SOMI, 135, "mcspi1_somi", NULL, NULL,
"gpio_135", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI1_SIMO, 136, "mcspi1_simo", NULL, NULL,
"gpio_136", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI1_CS0, 137, "mcspi1_cs0", NULL, NULL, "gpio_137",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI1_CS1, 138, "mcspi1_cs1", "uart1_rx", NULL,
"gpio_138", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI1_CS2, 139, "mcspi1_cs2", "uart1_cts",
"slimbus2_clock", "gpio_139", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(MCSPI1_CS3, 140, "mcspi1_cs3", "uart1_rts",
"slimbus2_data", "gpio_140", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(UART3_CTS_RCTX, 141, "uart3_cts_rctx", "uart1_tx",
NULL, "gpio_141", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UART3_RTS_SD, 142, "uart3_rts_sd", NULL, NULL,
"gpio_142", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UART3_RX_IRRX, 143, "uart3_rx_irrx",
"dmtimer8_pwm_evt", NULL, "gpio_143", NULL, NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(UART3_TX_IRTX, 144, "uart3_tx_irtx",
"dmtimer9_pwm_evt", NULL, "gpio_144", NULL, NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_CLK, 145, "sdmmc5_clk", "mcspi2_clk",
"usbc1_icusb_dp", "gpio_145", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_CMD, 146, "sdmmc5_cmd", "mcspi2_simo",
"usbc1_icusb_dm", "gpio_146", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_DAT0, 147, "sdmmc5_dat0", "mcspi2_somi",
"usbc1_icusb_rcv", "gpio_147", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_DAT1, 148, "sdmmc5_dat1", NULL,
"usbc1_icusb_txen", "gpio_148", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_DAT2, 149, "sdmmc5_dat2", "mcspi2_cs1", NULL,
"gpio_149", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_DAT3, 150, "sdmmc5_dat3", "mcspi2_cs0", NULL,
"gpio_150", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI4_CLK, 151, "mcspi4_clk", "sdmmc4_clk", NULL,
"gpio_151", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI4_SIMO, 152, "mcspi4_simo", "sdmmc4_cmd", NULL,
"gpio_152", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI4_SOMI, 153, "mcspi4_somi", "sdmmc4_dat0", NULL,
"gpio_153", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI4_CS0, 154, "mcspi4_cs0", "sdmmc4_dat3", NULL,
"gpio_154", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UART4_RX, 155, "uart4_rx", "sdmmc4_dat2", NULL,
"gpio_155", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UART4_TX, 156, "uart4_tx", "sdmmc4_dat1", NULL,
"gpio_156", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_CLK, 157, "usbb2_ulpitll_clk",
"usbb2_ulpiphy_clk", "sdmmc4_cmd", "gpio_157",
"hsi2_cawake", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_STP, 158, "usbb2_ulpitll_stp",
"usbb2_ulpiphy_stp", "sdmmc4_clk", "gpio_158",
"hsi2_cadata", "dispc2_data23", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DIR, 159, "usbb2_ulpitll_dir",
"usbb2_ulpiphy_dir", "sdmmc4_dat0", "gpio_159",
"hsi2_caflag", "dispc2_data22", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_NXT, 160, "usbb2_ulpitll_nxt",
"usbb2_ulpiphy_nxt", "sdmmc4_dat1", "gpio_160",
"hsi2_acready", "dispc2_data21", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT0, 161, "usbb2_ulpitll_dat0",
"usbb2_ulpiphy_dat0", "sdmmc4_dat2", "gpio_161",
"hsi2_acwake", "dispc2_data20", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT1, 162, "usbb2_ulpitll_dat1",
"usbb2_ulpiphy_dat1", "sdmmc4_dat3", "gpio_162",
"hsi2_acdata", "dispc2_data19", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT2, 163, "usbb2_ulpitll_dat2",
"usbb2_ulpiphy_dat2", "sdmmc3_dat2", "gpio_163",
"hsi2_acflag", "dispc2_data18", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT3, 164, "usbb2_ulpitll_dat3",
"usbb2_ulpiphy_dat3", "sdmmc3_dat1", "gpio_164",
"hsi2_caready", "dispc2_data15", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT4, 165, "usbb2_ulpitll_dat4",
"usbb2_ulpiphy_dat4", "sdmmc3_dat0", "gpio_165",
"mcspi3_somi", "dispc2_data14", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT5, 166, "usbb2_ulpitll_dat5",
"usbb2_ulpiphy_dat5", "sdmmc3_dat3", "gpio_166",
"mcspi3_cs0", "dispc2_data13", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT6, 167, "usbb2_ulpitll_dat6",
"usbb2_ulpiphy_dat6", "sdmmc3_cmd", "gpio_167",
"mcspi3_simo", "dispc2_data12", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT7, 168, "usbb2_ulpitll_dat7",
"usbb2_ulpiphy_dat7", "sdmmc3_clk", "gpio_168",
"mcspi3_clk", "dispc2_data11", NULL, "reserved"),
_OMAP4_MUXENTRY(USBB2_HSIC_DATA, 169, "usbb2_hsic_data", NULL, NULL,
"gpio_169", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBB2_HSIC_STROBE, 170, "usbb2_hsic_strobe", NULL,
NULL, "gpio_170", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_TX0, 171, "unipro_tx0", "kpd_col0", NULL,
"gpio_171", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_TY0, 172, "unipro_ty0", "kpd_col1", NULL,
"gpio_172", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_TX1, 173, "unipro_tx1", "kpd_col2", NULL,
"gpio_173", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_TY1, 174, "unipro_ty1", "kpd_col3", NULL,
"gpio_174", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_TX2, 0, "unipro_tx2", "kpd_col4", NULL,
"gpio_0", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_TY2, 1, "unipro_ty2", "kpd_col5", NULL,
"gpio_1", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_RX0, 0, "unipro_rx0", "kpd_row0", NULL,
"gpi_175", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_RY0, 0, "unipro_ry0", "kpd_row1", NULL,
"gpi_176", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_RX1, 0, "unipro_rx1", "kpd_row2", NULL,
"gpi_177", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_RY1, 0, "unipro_ry1", "kpd_row3", NULL,
"gpi_178", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_RX2, 0, "unipro_rx2", "kpd_row4", NULL,
"gpi_2", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UNIPRO_RY2, 0, "unipro_ry2", "kpd_row5", NULL,
"gpi_3", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBA0_OTG_CE, 0, "usba0_otg_ce", NULL, NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(USBA0_OTG_DP, 179, "usba0_otg_dp", "uart3_rx_irrx",
"uart2_rx", "gpio_179", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(USBA0_OTG_DM, 180, "usba0_otg_dm", "uart3_tx_irtx",
"uart2_tx", "gpio_180", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(FREF_CLK1_OUT, 181, "fref_clk1_out", NULL, NULL,
"gpio_181", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(FREF_CLK2_OUT, 182, "fref_clk2_out", NULL, NULL,
"gpio_182", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SYS_NIRQ1, 0, "sys_nirq1", NULL, NULL, NULL, NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SYS_NIRQ2, 183, "sys_nirq2", NULL, NULL, "gpio_183",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SYS_BOOT0, 184, "sys_boot0", NULL, NULL, "gpio_184",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SYS_BOOT1, 185, "sys_boot1", NULL, NULL, "gpio_185",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SYS_BOOT2, 186, "sys_boot2", NULL, NULL, "gpio_186",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SYS_BOOT3, 187, "sys_boot3", NULL, NULL, "gpio_187",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SYS_BOOT4, 188, "sys_boot4", NULL, NULL, "gpio_188",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SYS_BOOT5, 189, "sys_boot5", NULL, NULL, "gpio_189",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU0, 11, "dpm_emu0", NULL, NULL, "gpio_11", NULL,
NULL, "hw_dbg0", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU1, 12, "dpm_emu1", NULL, NULL, "gpio_12", NULL,
NULL, "hw_dbg1", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU2, 13, "dpm_emu2", "usba0_ulpiphy_clk", NULL,
"gpio_13", NULL, "dispc2_fid", "hw_dbg2", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU3, 14, "dpm_emu3", "usba0_ulpiphy_stp", NULL,
"gpio_14", NULL, "dispc2_data10", "hw_dbg3",
"reserved"),
_OMAP4_MUXENTRY(DPM_EMU4, 15, "dpm_emu4", "usba0_ulpiphy_dir", NULL,
"gpio_15", NULL, "dispc2_data9", "hw_dbg4",
"reserved"),
_OMAP4_MUXENTRY(DPM_EMU5, 16, "dpm_emu5", "usba0_ulpiphy_nxt", NULL,
"gpio_16", "rfbi_te_vsync0", "dispc2_data16",
"hw_dbg5", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU6, 17, "dpm_emu6", "usba0_ulpiphy_dat0",
"uart3_tx_irtx", "gpio_17", "rfbi_hsync0",
"dispc2_data17", "hw_dbg6", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU7, 18, "dpm_emu7", "usba0_ulpiphy_dat1",
"uart3_rx_irrx", "gpio_18", "rfbi_cs0",
"dispc2_hsync", "hw_dbg7", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU8, 19, "dpm_emu8", "usba0_ulpiphy_dat2",
"uart3_rts_sd", "gpio_19", "rfbi_re", "dispc2_pclk",
"hw_dbg8", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU9, 20, "dpm_emu9", "usba0_ulpiphy_dat3",
"uart3_cts_rctx", "gpio_20", "rfbi_we",
"dispc2_vsync", "hw_dbg9", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU10, 21, "dpm_emu10", "usba0_ulpiphy_dat4",
NULL, "gpio_21", "rfbi_a0", "dispc2_de", "hw_dbg10",
"reserved"),
_OMAP4_MUXENTRY(DPM_EMU11, 22, "dpm_emu11", "usba0_ulpiphy_dat5",
NULL, "gpio_22", "rfbi_data8", "dispc2_data8",
"hw_dbg11", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU12, 23, "dpm_emu12", "usba0_ulpiphy_dat6",
NULL, "gpio_23", "rfbi_data7", "dispc2_data7",
"hw_dbg12", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU13, 24, "dpm_emu13", "usba0_ulpiphy_dat7",
NULL, "gpio_24", "rfbi_data6", "dispc2_data6",
"hw_dbg13", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU14, 25, "dpm_emu14", "sys_drm_msecure",
"uart1_rx", "gpio_25", "rfbi_data5", "dispc2_data5",
"hw_dbg14", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU15, 26, "dpm_emu15", "sys_secure_indicator",
NULL, "gpio_26", "rfbi_data4", "dispc2_data4",
"hw_dbg15", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU16, 27, "dpm_emu16", "dmtimer8_pwm_evt",
"dsi1_te0", "gpio_27", "rfbi_data3", "dispc2_data3",
"hw_dbg16", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU17, 28, "dpm_emu17", "dmtimer9_pwm_evt",
"dsi1_te1", "gpio_28", "rfbi_data2", "dispc2_data2",
"hw_dbg17", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU18, 190, "dpm_emu18", "dmtimer10_pwm_evt",
"dsi2_te0", "gpio_190", "rfbi_data1", "dispc2_data1",
"hw_dbg18", "reserved"),
_OMAP4_MUXENTRY(DPM_EMU19, 191, "dpm_emu19", "dmtimer11_pwm_evt",
"dsi2_te1", "gpio_191", "rfbi_data0", "dispc2_data0",
"hw_dbg19", "reserved"),
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
/*
* Balls for 44XX CBL package
* 547-pin CBL ES1.0 S-FPGA-N547, 0.40mm Ball Pitch (Top),
* 0.40mm Ball Pitch (Bottom)
*/
#if defined(CONFIG_OMAP_MUX) && defined(CONFIG_DEBUG_FS) \
&& defined(CONFIG_OMAP_PACKAGE_CBL)
static struct omap_ball __initdata omap4_core_cbl_ball[] = {
_OMAP4_BALLENTRY(GPMC_AD0, "c12", NULL),
_OMAP4_BALLENTRY(GPMC_AD1, "d12", NULL),
_OMAP4_BALLENTRY(GPMC_AD2, "c13", NULL),
_OMAP4_BALLENTRY(GPMC_AD3, "d13", NULL),
_OMAP4_BALLENTRY(GPMC_AD4, "c15", NULL),
_OMAP4_BALLENTRY(GPMC_AD5, "d15", NULL),
_OMAP4_BALLENTRY(GPMC_AD6, "a16", NULL),
_OMAP4_BALLENTRY(GPMC_AD7, "b16", NULL),
_OMAP4_BALLENTRY(GPMC_AD8, "c16", NULL),
_OMAP4_BALLENTRY(GPMC_AD9, "d16", NULL),
_OMAP4_BALLENTRY(GPMC_AD10, "c17", NULL),
_OMAP4_BALLENTRY(GPMC_AD11, "d17", NULL),
_OMAP4_BALLENTRY(GPMC_AD12, "c18", NULL),
_OMAP4_BALLENTRY(GPMC_AD13, "d18", NULL),
_OMAP4_BALLENTRY(GPMC_AD14, "c19", NULL),
_OMAP4_BALLENTRY(GPMC_AD15, "d19", NULL),
_OMAP4_BALLENTRY(GPMC_A16, "b17", NULL),
_OMAP4_BALLENTRY(GPMC_A17, "a18", NULL),
_OMAP4_BALLENTRY(GPMC_A18, "b18", NULL),
_OMAP4_BALLENTRY(GPMC_A19, "a19", NULL),
_OMAP4_BALLENTRY(GPMC_A20, "b19", NULL),
_OMAP4_BALLENTRY(GPMC_A21, "b20", NULL),
_OMAP4_BALLENTRY(GPMC_A22, "a21", NULL),
_OMAP4_BALLENTRY(GPMC_A23, "b21", NULL),
_OMAP4_BALLENTRY(GPMC_A24, "c20", NULL),
_OMAP4_BALLENTRY(GPMC_A25, "d20", NULL),
_OMAP4_BALLENTRY(GPMC_NCS0, "b25", NULL),
_OMAP4_BALLENTRY(GPMC_NCS1, "c21", NULL),
_OMAP4_BALLENTRY(GPMC_NCS2, "d21", NULL),
_OMAP4_BALLENTRY(GPMC_NCS3, "c22", NULL),
_OMAP4_BALLENTRY(GPMC_NWP, "c25", NULL),
_OMAP4_BALLENTRY(GPMC_CLK, "b22", NULL),
_OMAP4_BALLENTRY(GPMC_NADV_ALE, "d25", NULL),
_OMAP4_BALLENTRY(GPMC_NOE, "b11", NULL),
_OMAP4_BALLENTRY(GPMC_NWE, "b12", NULL),
_OMAP4_BALLENTRY(GPMC_NBE0_CLE, "c23", NULL),
_OMAP4_BALLENTRY(GPMC_NBE1, "d22", NULL),
_OMAP4_BALLENTRY(GPMC_WAIT0, "b26", NULL),
_OMAP4_BALLENTRY(GPMC_WAIT1, "b23", NULL),
_OMAP4_BALLENTRY(C2C_DATA11, "d23", NULL),
_OMAP4_BALLENTRY(C2C_DATA12, "a24", NULL),
_OMAP4_BALLENTRY(C2C_DATA13, "b24", NULL),
_OMAP4_BALLENTRY(C2C_DATA14, "c24", NULL),
_OMAP4_BALLENTRY(C2C_DATA15, "d24", NULL),
_OMAP4_BALLENTRY(HDMI_HPD, "b9", NULL),
_OMAP4_BALLENTRY(HDMI_CEC, "b10", NULL),
_OMAP4_BALLENTRY(HDMI_DDC_SCL, "a8", NULL),
_OMAP4_BALLENTRY(HDMI_DDC_SDA, "b8", NULL),
_OMAP4_BALLENTRY(CSI21_DX0, "r26", NULL),
_OMAP4_BALLENTRY(CSI21_DY0, "r25", NULL),
_OMAP4_BALLENTRY(CSI21_DX1, "t26", NULL),
_OMAP4_BALLENTRY(CSI21_DY1, "t25", NULL),
_OMAP4_BALLENTRY(CSI21_DX2, "u26", NULL),
_OMAP4_BALLENTRY(CSI21_DY2, "u25", NULL),
_OMAP4_BALLENTRY(CSI21_DX3, "v26", NULL),
_OMAP4_BALLENTRY(CSI21_DY3, "v25", NULL),
_OMAP4_BALLENTRY(CSI21_DX4, "w26", NULL),
_OMAP4_BALLENTRY(CSI21_DY4, "w25", NULL),
_OMAP4_BALLENTRY(CSI22_DX0, "m26", NULL),
_OMAP4_BALLENTRY(CSI22_DY0, "m25", NULL),
_OMAP4_BALLENTRY(CSI22_DX1, "n26", NULL),
_OMAP4_BALLENTRY(CSI22_DY1, "n25", NULL),
_OMAP4_BALLENTRY(CAM_SHUTTER, "t27", NULL),
_OMAP4_BALLENTRY(CAM_STROBE, "u27", NULL),
_OMAP4_BALLENTRY(CAM_GLOBALRESET, "v27", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_CLK, "ae18", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_STP, "ag19", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DIR, "af19", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_NXT, "ae19", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT0, "af18", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT1, "ag18", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT2, "ae17", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT3, "af17", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT4, "ah17", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT5, "ae16", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT6, "af16", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT7, "ag16", NULL),
_OMAP4_BALLENTRY(USBB1_HSIC_DATA, "af14", NULL),
_OMAP4_BALLENTRY(USBB1_HSIC_STROBE, "ae14", NULL),
_OMAP4_BALLENTRY(USBC1_ICUSB_DP, "h2", NULL),
_OMAP4_BALLENTRY(USBC1_ICUSB_DM, "h3", NULL),
_OMAP4_BALLENTRY(SDMMC1_CLK, "d2", NULL),
_OMAP4_BALLENTRY(SDMMC1_CMD, "e3", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT0, "e4", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT1, "e2", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT2, "e1", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT3, "f4", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT4, "f3", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT5, "f1", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT6, "g4", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT7, "g3", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP2_CLKX, "ad27", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP2_DR, "ad26", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP2_DX, "ad25", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP2_FSX, "ac28", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP1_CLKX, "ac26", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP1_DR, "ac25", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP1_DX, "ab25", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP1_FSX, "ac27", NULL),
_OMAP4_BALLENTRY(ABE_PDM_UL_DATA, "ag25", NULL),
_OMAP4_BALLENTRY(ABE_PDM_DL_DATA, "af25", NULL),
_OMAP4_BALLENTRY(ABE_PDM_FRAME, "ae25", NULL),
_OMAP4_BALLENTRY(ABE_PDM_LB_CLK, "af26", NULL),
_OMAP4_BALLENTRY(ABE_CLKS, "ah26", NULL),
_OMAP4_BALLENTRY(ABE_DMIC_CLK1, "ae24", NULL),
_OMAP4_BALLENTRY(ABE_DMIC_DIN1, "af24", NULL),
_OMAP4_BALLENTRY(ABE_DMIC_DIN2, "ag24", NULL),
_OMAP4_BALLENTRY(ABE_DMIC_DIN3, "ah24", NULL),
_OMAP4_BALLENTRY(UART2_CTS, "ab26", NULL),
_OMAP4_BALLENTRY(UART2_RTS, "ab27", NULL),
_OMAP4_BALLENTRY(UART2_RX, "aa25", NULL),
_OMAP4_BALLENTRY(UART2_TX, "aa26", NULL),
_OMAP4_BALLENTRY(HDQ_SIO, "aa27", NULL),
_OMAP4_BALLENTRY(I2C1_SCL, "ae28", NULL),
_OMAP4_BALLENTRY(I2C1_SDA, "ae26", NULL),
_OMAP4_BALLENTRY(I2C2_SCL, "c26", NULL),
_OMAP4_BALLENTRY(I2C2_SDA, "d26", NULL),
_OMAP4_BALLENTRY(I2C3_SCL, "w27", NULL),
_OMAP4_BALLENTRY(I2C3_SDA, "y27", NULL),
_OMAP4_BALLENTRY(I2C4_SCL, "ag21", NULL),
_OMAP4_BALLENTRY(I2C4_SDA, "ah22", NULL),
_OMAP4_BALLENTRY(MCSPI1_CLK, "af22", NULL),
_OMAP4_BALLENTRY(MCSPI1_SOMI, "ae22", NULL),
_OMAP4_BALLENTRY(MCSPI1_SIMO, "ag22", NULL),
_OMAP4_BALLENTRY(MCSPI1_CS0, "ae23", NULL),
_OMAP4_BALLENTRY(MCSPI1_CS1, "af23", NULL),
_OMAP4_BALLENTRY(MCSPI1_CS2, "ag23", NULL),
_OMAP4_BALLENTRY(MCSPI1_CS3, "ah23", NULL),
_OMAP4_BALLENTRY(UART3_CTS_RCTX, "f27", NULL),
_OMAP4_BALLENTRY(UART3_RTS_SD, "f28", NULL),
_OMAP4_BALLENTRY(UART3_RX_IRRX, "g27", NULL),
_OMAP4_BALLENTRY(UART3_TX_IRTX, "g28", NULL),
_OMAP4_BALLENTRY(SDMMC5_CLK, "ae5", NULL),
_OMAP4_BALLENTRY(SDMMC5_CMD, "af5", NULL),
_OMAP4_BALLENTRY(SDMMC5_DAT0, "ae4", NULL),
_OMAP4_BALLENTRY(SDMMC5_DAT1, "af4", NULL),
_OMAP4_BALLENTRY(SDMMC5_DAT2, "ag3", NULL),
_OMAP4_BALLENTRY(SDMMC5_DAT3, "af3", NULL),
_OMAP4_BALLENTRY(MCSPI4_CLK, "ae21", NULL),
_OMAP4_BALLENTRY(MCSPI4_SIMO, "af20", NULL),
_OMAP4_BALLENTRY(MCSPI4_SOMI, "af21", NULL),
_OMAP4_BALLENTRY(MCSPI4_CS0, "ae20", NULL),
_OMAP4_BALLENTRY(UART4_RX, "ag20", NULL),
_OMAP4_BALLENTRY(UART4_TX, "ah19", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_CLK, "ag12", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_STP, "af12", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DIR, "ae12", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_NXT, "ag13", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT0, "ae11", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT1, "af11", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT2, "ag11", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT3, "ah11", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT4, "ae10", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT5, "af10", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT6, "ag10", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT7, "ae9", NULL),
_OMAP4_BALLENTRY(USBB2_HSIC_DATA, "af13", NULL),
_OMAP4_BALLENTRY(USBB2_HSIC_STROBE, "ae13", NULL),
_OMAP4_BALLENTRY(UNIPRO_TX0, "g26", NULL),
_OMAP4_BALLENTRY(UNIPRO_TY0, "g25", NULL),
_OMAP4_BALLENTRY(UNIPRO_TX1, "h26", NULL),
_OMAP4_BALLENTRY(UNIPRO_TY1, "h25", NULL),
_OMAP4_BALLENTRY(UNIPRO_TX2, "j27", NULL),
_OMAP4_BALLENTRY(UNIPRO_TY2, "h27", NULL),
_OMAP4_BALLENTRY(UNIPRO_RX0, "j26", NULL),
_OMAP4_BALLENTRY(UNIPRO_RY0, "j25", NULL),
_OMAP4_BALLENTRY(UNIPRO_RX1, "k26", NULL),
_OMAP4_BALLENTRY(UNIPRO_RY1, "k25", NULL),
_OMAP4_BALLENTRY(UNIPRO_RX2, "l27", NULL),
_OMAP4_BALLENTRY(UNIPRO_RY2, "k27", NULL),
_OMAP4_BALLENTRY(USBA0_OTG_CE, "c3", NULL),
_OMAP4_BALLENTRY(USBA0_OTG_DP, "b5", NULL),
_OMAP4_BALLENTRY(USBA0_OTG_DM, "b4", NULL),
_OMAP4_BALLENTRY(FREF_CLK1_OUT, "aa28", NULL),
_OMAP4_BALLENTRY(FREF_CLK2_OUT, "y28", NULL),
_OMAP4_BALLENTRY(SYS_NIRQ1, "ae6", NULL),
_OMAP4_BALLENTRY(SYS_NIRQ2, "af6", NULL),
_OMAP4_BALLENTRY(SYS_BOOT0, "f26", NULL),
_OMAP4_BALLENTRY(SYS_BOOT1, "e27", NULL),
_OMAP4_BALLENTRY(SYS_BOOT2, "e26", NULL),
_OMAP4_BALLENTRY(SYS_BOOT3, "e25", NULL),
_OMAP4_BALLENTRY(SYS_BOOT4, "d28", NULL),
_OMAP4_BALLENTRY(SYS_BOOT5, "d27", NULL),
_OMAP4_BALLENTRY(DPM_EMU0, "m2", NULL),
_OMAP4_BALLENTRY(DPM_EMU1, "n2", NULL),
_OMAP4_BALLENTRY(DPM_EMU2, "p2", NULL),
_OMAP4_BALLENTRY(DPM_EMU3, "v1", NULL),
_OMAP4_BALLENTRY(DPM_EMU4, "v2", NULL),
_OMAP4_BALLENTRY(DPM_EMU5, "w1", NULL),
_OMAP4_BALLENTRY(DPM_EMU6, "w2", NULL),
_OMAP4_BALLENTRY(DPM_EMU7, "w3", NULL),
_OMAP4_BALLENTRY(DPM_EMU8, "w4", NULL),
_OMAP4_BALLENTRY(DPM_EMU9, "y2", NULL),
_OMAP4_BALLENTRY(DPM_EMU10, "y3", NULL),
_OMAP4_BALLENTRY(DPM_EMU11, "y4", NULL),
_OMAP4_BALLENTRY(DPM_EMU12, "aa1", NULL),
_OMAP4_BALLENTRY(DPM_EMU13, "aa2", NULL),
_OMAP4_BALLENTRY(DPM_EMU14, "aa3", NULL),
_OMAP4_BALLENTRY(DPM_EMU15, "aa4", NULL),
_OMAP4_BALLENTRY(DPM_EMU16, "ab2", NULL),
_OMAP4_BALLENTRY(DPM_EMU17, "ab3", NULL),
_OMAP4_BALLENTRY(DPM_EMU18, "ab4", NULL),
_OMAP4_BALLENTRY(DPM_EMU19, "ac4", NULL),
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#else
#define omap4_core_cbl_ball NULL
#endif
/*
* Signals different on ES2.0 compared to superset
*/
static struct omap_mux __initdata omap4_es2_core_subset[] = {
_OMAP4_MUXENTRY(GPMC_AD8, 32, "gpmc_ad8", "kpd_row0", "c2c_data15",
"gpio_32", NULL, "sdmmc1_dat0", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD9, 33, "gpmc_ad9", "kpd_row1", "c2c_data14",
"gpio_33", NULL, "sdmmc1_dat1", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD10, 34, "gpmc_ad10", "kpd_row2", "c2c_data13",
"gpio_34", NULL, "sdmmc1_dat2", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD11, 35, "gpmc_ad11", "kpd_row3", "c2c_data12",
"gpio_35", NULL, "sdmmc1_dat3", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD12, 36, "gpmc_ad12", "kpd_col0", "c2c_data11",
"gpio_36", NULL, "sdmmc1_dat4", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD13, 37, "gpmc_ad13", "kpd_col1", "c2c_data10",
"gpio_37", NULL, "sdmmc1_dat5", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD14, 38, "gpmc_ad14", "kpd_col2", "c2c_data9",
"gpio_38", NULL, "sdmmc1_dat6", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_AD15, 39, "gpmc_ad15", "kpd_col3", "c2c_data8",
"gpio_39", NULL, "sdmmc1_dat7", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_A16, 40, "gpmc_a16", "kpd_row4", "c2c_datain0",
"gpio_40", "venc_656_data0", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_A24, 48, "gpmc_a24", "kpd_col8", "c2c_clkout0",
"gpio_48", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_NCS2, 52, "gpmc_ncs2", "kpd_row8",
"c2c_dataout7", "gpio_52", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(GPMC_CLK, 55, "gpmc_clk", NULL, NULL, "gpio_55",
"sys_ndmareq2", "sdmmc1_cmd", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_NADV_ALE, 56, "gpmc_nadv_ale", "dsi1_te1", NULL,
"gpio_56", "sys_ndmareq3", "sdmmc1_clk", NULL, NULL),
_OMAP4_MUXENTRY(GPMC_WAIT2, 100, "gpmc_wait2", "usbc1_icusb_txen",
"c2c_dataout3", "gpio_100", "sys_ndmareq0", NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_NCS4, 101, "gpmc_ncs4", "dsi1_te0", "c2c_clkin0",
"gpio_101", "sys_ndmareq1", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_NCS5, 102, "gpmc_ncs5", "dsi1_te1", "c2c_clkin1",
"gpio_102", "sys_ndmareq2", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_NCS6, 103, "gpmc_ncs6", "dsi2_te0",
"c2c_dataout0", "gpio_103", "sys_ndmareq3", NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(GPMC_NCS7, 104, "gpmc_ncs7", "dsi2_te1",
"c2c_dataout1", "gpio_104", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT0, 88, "usbb1_ulpitll_dat0",
"hsi1_acwake", "mcbsp4_clkx", "gpio_88",
"usbb1_ulpiphy_dat0", "usbb1_mm_txen", "hw_dbg24",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT1, 89, "usbb1_ulpitll_dat1",
"hsi1_acdata", "mcbsp4_dx", "gpio_89",
"usbb1_ulpiphy_dat1", "usbb1_mm_txdat", "hw_dbg25",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT2, 90, "usbb1_ulpitll_dat2",
"hsi1_acflag", "mcbsp4_dr", "gpio_90",
"usbb1_ulpiphy_dat2", "usbb1_mm_txse0", "hw_dbg26",
"safe_mode"),
_OMAP4_MUXENTRY(USBB1_ULPITLL_DAT3, 91, "usbb1_ulpitll_dat3",
"hsi1_caready", NULL, "gpio_91", "usbb1_ulpiphy_dat3",
"usbb1_mm_rxrcv", "hw_dbg27", "safe_mode"),
_OMAP4_MUXENTRY(ABE_DMIC_CLK1, 119, "abe_dmic_clk1", NULL, NULL,
"gpio_119", "usbb2_mm_txse0", "uart4_cts", NULL,
"safe_mode"),
_OMAP4_MUXENTRY(ABE_DMIC_DIN1, 120, "abe_dmic_din1", NULL, NULL,
"gpio_120", "usbb2_mm_txdat", "uart4_rts", NULL,
"safe_mode"),
_OMAP4_MUXENTRY(ABE_DMIC_DIN2, 121, "abe_dmic_din2", "slimbus2_clock",
"abe_mcasp_axr", "gpio_121", NULL,
"dmtimer11_pwm_evt", NULL, "safe_mode"),
_OMAP4_MUXENTRY(ABE_DMIC_DIN3, 122, "abe_dmic_din3", "slimbus2_data",
"abe_dmic_clk2", "gpio_122", NULL, "dmtimer9_pwm_evt",
NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_CLK, 145, "sdmmc5_clk", "mcspi2_clk",
"usbc1_icusb_dp", "gpio_145", NULL, "sdmmc2_clk",
NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_CMD, 146, "sdmmc5_cmd", "mcspi2_simo",
"usbc1_icusb_dm", "gpio_146", NULL, "sdmmc2_cmd",
NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_DAT0, 147, "sdmmc5_dat0", "mcspi2_somi",
"usbc1_icusb_rcv", "gpio_147", NULL, "sdmmc2_dat0",
NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_DAT1, 148, "sdmmc5_dat1", NULL,
"usbc1_icusb_txen", "gpio_148", NULL, "sdmmc2_dat1",
NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_DAT2, 149, "sdmmc5_dat2", "mcspi2_cs1", NULL,
"gpio_149", NULL, "sdmmc2_dat2", NULL, "safe_mode"),
_OMAP4_MUXENTRY(SDMMC5_DAT3, 150, "sdmmc5_dat3", "mcspi2_cs0", NULL,
"gpio_150", NULL, "sdmmc2_dat3", NULL, "safe_mode"),
_OMAP4_MUXENTRY(MCSPI4_CLK, 151, "mcspi4_clk", "sdmmc4_clk",
"kpd_col6", "gpio_151", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(MCSPI4_SIMO, 152, "mcspi4_simo", "sdmmc4_cmd",
"kpd_col7", "gpio_152", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(MCSPI4_SOMI, 153, "mcspi4_somi", "sdmmc4_dat0",
"kpd_row6", "gpio_153", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(MCSPI4_CS0, 154, "mcspi4_cs0", "sdmmc4_dat3",
"kpd_row7", "gpio_154", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(UART4_RX, 155, "uart4_rx", "sdmmc4_dat2", "kpd_row8",
"gpio_155", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(UART4_TX, 156, "uart4_tx", "sdmmc4_dat1", "kpd_col8",
"gpio_156", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_STP, 158, "usbb2_ulpitll_stp",
"usbb2_ulpiphy_stp", "sdmmc4_clk", "gpio_158",
"hsi2_cadata", "dispc2_data23", NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DIR, 159, "usbb2_ulpitll_dir",
"usbb2_ulpiphy_dir", "sdmmc4_dat0", "gpio_159",
"hsi2_caflag", "dispc2_data22", NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_NXT, 160, "usbb2_ulpitll_nxt",
"usbb2_ulpiphy_nxt", "sdmmc4_dat1", "gpio_160",
"hsi2_acready", "dispc2_data21", NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT0, 161, "usbb2_ulpitll_dat0",
"usbb2_ulpiphy_dat0", "sdmmc4_dat2", "gpio_161",
"hsi2_acwake", "dispc2_data20", "usbb2_mm_txen",
"safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT1, 162, "usbb2_ulpitll_dat1",
"usbb2_ulpiphy_dat1", "sdmmc4_dat3", "gpio_162",
"hsi2_acdata", "dispc2_data19", "usbb2_mm_txdat",
"safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT2, 163, "usbb2_ulpitll_dat2",
"usbb2_ulpiphy_dat2", "sdmmc3_dat2", "gpio_163",
"hsi2_acflag", "dispc2_data18", "usbb2_mm_txse0",
"safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT3, 164, "usbb2_ulpitll_dat3",
"usbb2_ulpiphy_dat3", "sdmmc3_dat1", "gpio_164",
"hsi2_caready", "dispc2_data15", "rfbi_data15",
"safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT4, 165, "usbb2_ulpitll_dat4",
"usbb2_ulpiphy_dat4", "sdmmc3_dat0", "gpio_165",
"mcspi3_somi", "dispc2_data14", "rfbi_data14",
"safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT5, 166, "usbb2_ulpitll_dat5",
"usbb2_ulpiphy_dat5", "sdmmc3_dat3", "gpio_166",
"mcspi3_cs0", "dispc2_data13", "rfbi_data13",
"safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT6, 167, "usbb2_ulpitll_dat6",
"usbb2_ulpiphy_dat6", "sdmmc3_cmd", "gpio_167",
"mcspi3_simo", "dispc2_data12", "rfbi_data12",
"safe_mode"),
_OMAP4_MUXENTRY(USBB2_ULPITLL_DAT7, 168, "usbb2_ulpitll_dat7",
"usbb2_ulpiphy_dat7", "sdmmc3_clk", "gpio_168",
"mcspi3_clk", "dispc2_data11", "rfbi_data11",
"safe_mode"),
_OMAP4_MUXENTRY(KPD_COL3, 171, "kpd_col3", "kpd_col0", NULL,
"gpio_171", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_COL4, 172, "kpd_col4", "kpd_col1", NULL,
"gpio_172", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_COL5, 173, "kpd_col5", "kpd_col2", NULL,
"gpio_173", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_COL0, 174, "kpd_col0", "kpd_col3", NULL,
"gpio_174", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_COL1, 0, "kpd_col1", "kpd_col4", NULL, "gpio_0",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_COL2, 1, "kpd_col2", "kpd_col5", NULL, "gpio_1",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_ROW3, 175, "kpd_row3", "kpd_row0", NULL,
"gpio_175", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_ROW4, 176, "kpd_row4", "kpd_row1", NULL,
"gpio_176", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_ROW5, 177, "kpd_row5", "kpd_row2", NULL,
"gpio_177", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_ROW0, 178, "kpd_row0", "kpd_row3", NULL,
"gpio_178", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_ROW1, 2, "kpd_row1", "kpd_row4", NULL, "gpio_2",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(KPD_ROW2, 3, "kpd_row2", "kpd_row5", NULL, "gpio_3",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBA0_OTG_DP, 0, "usba0_otg_dp", "uart3_rx_irrx",
"uart2_rx", NULL, NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(USBA0_OTG_DM, 0, "usba0_otg_dm", "uart3_tx_irtx",
"uart2_tx", NULL, NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU2, 13, "dpm_emu2", "usba0_ulpiphy_clk", NULL,
"gpio_13", NULL, "dispc2_fid", "hw_dbg2",
"safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU3, 14, "dpm_emu3", "usba0_ulpiphy_stp", NULL,
"gpio_14", "rfbi_data10", "dispc2_data10", "hw_dbg3",
"safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU4, 15, "dpm_emu4", "usba0_ulpiphy_dir", NULL,
"gpio_15", "rfbi_data9", "dispc2_data9", "hw_dbg4",
"safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU5, 16, "dpm_emu5", "usba0_ulpiphy_nxt", NULL,
"gpio_16", "rfbi_te_vsync0", "dispc2_data16",
"hw_dbg5", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU6, 17, "dpm_emu6", "usba0_ulpiphy_dat0",
"uart3_tx_irtx", "gpio_17", "rfbi_hsync0",
"dispc2_data17", "hw_dbg6", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU7, 18, "dpm_emu7", "usba0_ulpiphy_dat1",
"uart3_rx_irrx", "gpio_18", "rfbi_cs0",
"dispc2_hsync", "hw_dbg7", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU8, 19, "dpm_emu8", "usba0_ulpiphy_dat2",
"uart3_rts_sd", "gpio_19", "rfbi_re", "dispc2_pclk",
"hw_dbg8", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU9, 20, "dpm_emu9", "usba0_ulpiphy_dat3",
"uart3_cts_rctx", "gpio_20", "rfbi_we",
"dispc2_vsync", "hw_dbg9", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU10, 21, "dpm_emu10", "usba0_ulpiphy_dat4",
NULL, "gpio_21", "rfbi_a0", "dispc2_de", "hw_dbg10",
"safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU11, 22, "dpm_emu11", "usba0_ulpiphy_dat5",
NULL, "gpio_22", "rfbi_data8", "dispc2_data8",
"hw_dbg11", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU12, 23, "dpm_emu12", "usba0_ulpiphy_dat6",
NULL, "gpio_23", "rfbi_data7", "dispc2_data7",
"hw_dbg12", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU13, 24, "dpm_emu13", "usba0_ulpiphy_dat7",
NULL, "gpio_24", "rfbi_data6", "dispc2_data6",
"hw_dbg13", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU14, 25, "dpm_emu14", "sys_drm_msecure",
"uart1_rx", "gpio_25", "rfbi_data5", "dispc2_data5",
"hw_dbg14", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU15, 26, "dpm_emu15", "sys_secure_indicator",
NULL, "gpio_26", "rfbi_data4", "dispc2_data4",
"hw_dbg15", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU16, 27, "dpm_emu16", "dmtimer8_pwm_evt",
"dsi1_te0", "gpio_27", "rfbi_data3", "dispc2_data3",
"hw_dbg16", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU17, 28, "dpm_emu17", "dmtimer9_pwm_evt",
"dsi1_te1", "gpio_28", "rfbi_data2", "dispc2_data2",
"hw_dbg17", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU18, 190, "dpm_emu18", "dmtimer10_pwm_evt",
"dsi2_te0", "gpio_190", "rfbi_data1", "dispc2_data1",
"hw_dbg18", "safe_mode"),
_OMAP4_MUXENTRY(DPM_EMU19, 191, "dpm_emu19", "dmtimer11_pwm_evt",
"dsi2_te1", "gpio_191", "rfbi_data0", "dispc2_data0",
"hw_dbg19", "safe_mode"),
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
/*
* Balls for 44XX CBS package
* 547-pin CBL ES2.0 S-FPGA-N547, 0.40mm Ball Pitch (Top),
* 0.40mm Ball Pitch (Bottom)
*/
#if defined(CONFIG_OMAP_MUX) && defined(CONFIG_DEBUG_FS) \
&& defined(CONFIG_OMAP_PACKAGE_CBS)
static struct omap_ball __initdata omap4_core_cbs_ball[] = {
_OMAP4_BALLENTRY(GPMC_AD0, "c12", NULL),
_OMAP4_BALLENTRY(GPMC_AD1, "d12", NULL),
_OMAP4_BALLENTRY(GPMC_AD2, "c13", NULL),
_OMAP4_BALLENTRY(GPMC_AD3, "d13", NULL),
_OMAP4_BALLENTRY(GPMC_AD4, "c15", NULL),
_OMAP4_BALLENTRY(GPMC_AD5, "d15", NULL),
_OMAP4_BALLENTRY(GPMC_AD6, "a16", NULL),
_OMAP4_BALLENTRY(GPMC_AD7, "b16", NULL),
_OMAP4_BALLENTRY(GPMC_AD8, "c16", NULL),
_OMAP4_BALLENTRY(GPMC_AD9, "d16", NULL),
_OMAP4_BALLENTRY(GPMC_AD10, "c17", NULL),
_OMAP4_BALLENTRY(GPMC_AD11, "d17", NULL),
_OMAP4_BALLENTRY(GPMC_AD12, "c18", NULL),
_OMAP4_BALLENTRY(GPMC_AD13, "d18", NULL),
_OMAP4_BALLENTRY(GPMC_AD14, "c19", NULL),
_OMAP4_BALLENTRY(GPMC_AD15, "d19", NULL),
_OMAP4_BALLENTRY(GPMC_A16, "b17", NULL),
_OMAP4_BALLENTRY(GPMC_A17, "a18", NULL),
_OMAP4_BALLENTRY(GPMC_A18, "b18", NULL),
_OMAP4_BALLENTRY(GPMC_A19, "a19", NULL),
_OMAP4_BALLENTRY(GPMC_A20, "b19", NULL),
_OMAP4_BALLENTRY(GPMC_A21, "b20", NULL),
_OMAP4_BALLENTRY(GPMC_A22, "a21", NULL),
_OMAP4_BALLENTRY(GPMC_A23, "b21", NULL),
_OMAP4_BALLENTRY(GPMC_A24, "c20", NULL),
_OMAP4_BALLENTRY(GPMC_A25, "d20", NULL),
_OMAP4_BALLENTRY(GPMC_NCS0, "b25", NULL),
_OMAP4_BALLENTRY(GPMC_NCS1, "c21", NULL),
_OMAP4_BALLENTRY(GPMC_NCS2, "d21", NULL),
_OMAP4_BALLENTRY(GPMC_NCS3, "c22", NULL),
_OMAP4_BALLENTRY(GPMC_NWP, "c25", NULL),
_OMAP4_BALLENTRY(GPMC_CLK, "b22", NULL),
_OMAP4_BALLENTRY(GPMC_NADV_ALE, "d25", NULL),
_OMAP4_BALLENTRY(GPMC_NOE, "b11", NULL),
_OMAP4_BALLENTRY(GPMC_NWE, "b12", NULL),
_OMAP4_BALLENTRY(GPMC_NBE0_CLE, "c23", NULL),
_OMAP4_BALLENTRY(GPMC_NBE1, "d22", NULL),
_OMAP4_BALLENTRY(GPMC_WAIT0, "b26", NULL),
_OMAP4_BALLENTRY(GPMC_WAIT1, "b23", NULL),
_OMAP4_BALLENTRY(GPMC_WAIT2, "d23", NULL),
_OMAP4_BALLENTRY(GPMC_NCS4, "a24", NULL),
_OMAP4_BALLENTRY(GPMC_NCS5, "b24", NULL),
_OMAP4_BALLENTRY(GPMC_NCS6, "c24", NULL),
_OMAP4_BALLENTRY(GPMC_NCS7, "d24", NULL),
_OMAP4_BALLENTRY(HDMI_HPD, "b9", NULL),
_OMAP4_BALLENTRY(HDMI_CEC, "b10", NULL),
_OMAP4_BALLENTRY(HDMI_DDC_SCL, "a8", NULL),
_OMAP4_BALLENTRY(HDMI_DDC_SDA, "b8", NULL),
_OMAP4_BALLENTRY(CSI21_DX0, "r26", NULL),
_OMAP4_BALLENTRY(CSI21_DY0, "r25", NULL),
_OMAP4_BALLENTRY(CSI21_DX1, "t26", NULL),
_OMAP4_BALLENTRY(CSI21_DY1, "t25", NULL),
_OMAP4_BALLENTRY(CSI21_DX2, "u26", NULL),
_OMAP4_BALLENTRY(CSI21_DY2, "u25", NULL),
_OMAP4_BALLENTRY(CSI21_DX3, "v26", NULL),
_OMAP4_BALLENTRY(CSI21_DY3, "v25", NULL),
_OMAP4_BALLENTRY(CSI21_DX4, "w26", NULL),
_OMAP4_BALLENTRY(CSI21_DY4, "w25", NULL),
_OMAP4_BALLENTRY(CSI22_DX0, "m26", NULL),
_OMAP4_BALLENTRY(CSI22_DY0, "m25", NULL),
_OMAP4_BALLENTRY(CSI22_DX1, "n26", NULL),
_OMAP4_BALLENTRY(CSI22_DY1, "n25", NULL),
_OMAP4_BALLENTRY(CAM_SHUTTER, "t27", NULL),
_OMAP4_BALLENTRY(CAM_STROBE, "u27", NULL),
_OMAP4_BALLENTRY(CAM_GLOBALRESET, "v27", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_CLK, "ae18", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_STP, "ag19", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DIR, "af19", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_NXT, "ae19", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT0, "af18", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT1, "ag18", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT2, "ae17", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT3, "af17", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT4, "ah17", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT5, "ae16", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT6, "af16", NULL),
_OMAP4_BALLENTRY(USBB1_ULPITLL_DAT7, "ag16", NULL),
_OMAP4_BALLENTRY(USBB1_HSIC_DATA, "af14", NULL),
_OMAP4_BALLENTRY(USBB1_HSIC_STROBE, "ae14", NULL),
_OMAP4_BALLENTRY(USBC1_ICUSB_DP, "h2", NULL),
_OMAP4_BALLENTRY(USBC1_ICUSB_DM, "h3", NULL),
_OMAP4_BALLENTRY(SDMMC1_CLK, "d2", NULL),
_OMAP4_BALLENTRY(SDMMC1_CMD, "e3", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT0, "e4", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT1, "e2", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT2, "e1", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT3, "f4", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT4, "f3", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT5, "f1", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT6, "g4", NULL),
_OMAP4_BALLENTRY(SDMMC1_DAT7, "g3", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP2_CLKX, "ad27", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP2_DR, "ad26", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP2_DX, "ad25", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP2_FSX, "ac28", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP1_CLKX, "ac26", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP1_DR, "ac25", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP1_DX, "ab25", NULL),
_OMAP4_BALLENTRY(ABE_MCBSP1_FSX, "ac27", NULL),
_OMAP4_BALLENTRY(ABE_PDM_UL_DATA, "ag25", NULL),
_OMAP4_BALLENTRY(ABE_PDM_DL_DATA, "af25", NULL),
_OMAP4_BALLENTRY(ABE_PDM_FRAME, "ae25", NULL),
_OMAP4_BALLENTRY(ABE_PDM_LB_CLK, "af26", NULL),
_OMAP4_BALLENTRY(ABE_CLKS, "ah26", NULL),
_OMAP4_BALLENTRY(ABE_DMIC_CLK1, "ae24", NULL),
_OMAP4_BALLENTRY(ABE_DMIC_DIN1, "af24", NULL),
_OMAP4_BALLENTRY(ABE_DMIC_DIN2, "ag24", NULL),
_OMAP4_BALLENTRY(ABE_DMIC_DIN3, "ah24", NULL),
_OMAP4_BALLENTRY(UART2_CTS, "ab26", NULL),
_OMAP4_BALLENTRY(UART2_RTS, "ab27", NULL),
_OMAP4_BALLENTRY(UART2_RX, "aa25", NULL),
_OMAP4_BALLENTRY(UART2_TX, "aa26", NULL),
_OMAP4_BALLENTRY(HDQ_SIO, "aa27", NULL),
_OMAP4_BALLENTRY(I2C1_SCL, "ae28", NULL),
_OMAP4_BALLENTRY(I2C1_SDA, "ae26", NULL),
_OMAP4_BALLENTRY(I2C2_SCL, "c26", NULL),
_OMAP4_BALLENTRY(I2C2_SDA, "d26", NULL),
_OMAP4_BALLENTRY(I2C3_SCL, "w27", NULL),
_OMAP4_BALLENTRY(I2C3_SDA, "y27", NULL),
_OMAP4_BALLENTRY(I2C4_SCL, "ag21", NULL),
_OMAP4_BALLENTRY(I2C4_SDA, "ah22", NULL),
_OMAP4_BALLENTRY(MCSPI1_CLK, "af22", NULL),
_OMAP4_BALLENTRY(MCSPI1_SOMI, "ae22", NULL),
_OMAP4_BALLENTRY(MCSPI1_SIMO, "ag22", NULL),
_OMAP4_BALLENTRY(MCSPI1_CS0, "ae23", NULL),
_OMAP4_BALLENTRY(MCSPI1_CS1, "af23", NULL),
_OMAP4_BALLENTRY(MCSPI1_CS2, "ag23", NULL),
_OMAP4_BALLENTRY(MCSPI1_CS3, "ah23", NULL),
_OMAP4_BALLENTRY(UART3_CTS_RCTX, "f27", NULL),
_OMAP4_BALLENTRY(UART3_RTS_SD, "f28", NULL),
_OMAP4_BALLENTRY(UART3_RX_IRRX, "g27", NULL),
_OMAP4_BALLENTRY(UART3_TX_IRTX, "g28", NULL),
_OMAP4_BALLENTRY(SDMMC5_CLK, "ae5", NULL),
_OMAP4_BALLENTRY(SDMMC5_CMD, "af5", NULL),
_OMAP4_BALLENTRY(SDMMC5_DAT0, "ae4", NULL),
_OMAP4_BALLENTRY(SDMMC5_DAT1, "af4", NULL),
_OMAP4_BALLENTRY(SDMMC5_DAT2, "ag3", NULL),
_OMAP4_BALLENTRY(SDMMC5_DAT3, "af3", NULL),
_OMAP4_BALLENTRY(MCSPI4_CLK, "ae21", NULL),
_OMAP4_BALLENTRY(MCSPI4_SIMO, "af20", NULL),
_OMAP4_BALLENTRY(MCSPI4_SOMI, "af21", NULL),
_OMAP4_BALLENTRY(MCSPI4_CS0, "ae20", NULL),
_OMAP4_BALLENTRY(UART4_RX, "ag20", NULL),
_OMAP4_BALLENTRY(UART4_TX, "ah19", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_CLK, "ag12", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_STP, "af12", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DIR, "ae12", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_NXT, "ag13", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT0, "ae11", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT1, "af11", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT2, "ag11", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT3, "ah11", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT4, "ae10", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT5, "af10", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT6, "ag10", NULL),
_OMAP4_BALLENTRY(USBB2_ULPITLL_DAT7, "ae9", NULL),
_OMAP4_BALLENTRY(USBB2_HSIC_DATA, "af13", NULL),
_OMAP4_BALLENTRY(USBB2_HSIC_STROBE, "ae13", NULL),
_OMAP4_BALLENTRY(KPD_COL3, "g26", NULL),
_OMAP4_BALLENTRY(KPD_COL4, "g25", NULL),
_OMAP4_BALLENTRY(KPD_COL5, "h26", NULL),
_OMAP4_BALLENTRY(KPD_COL0, "h25", NULL),
_OMAP4_BALLENTRY(KPD_COL1, "j27", NULL),
_OMAP4_BALLENTRY(KPD_COL2, "h27", NULL),
_OMAP4_BALLENTRY(KPD_ROW3, "j26", NULL),
_OMAP4_BALLENTRY(KPD_ROW4, "j25", NULL),
_OMAP4_BALLENTRY(KPD_ROW5, "k26", NULL),
_OMAP4_BALLENTRY(KPD_ROW0, "k25", NULL),
_OMAP4_BALLENTRY(KPD_ROW1, "l27", NULL),
_OMAP4_BALLENTRY(KPD_ROW2, "k27", NULL),
_OMAP4_BALLENTRY(USBA0_OTG_CE, "c3", NULL),
_OMAP4_BALLENTRY(USBA0_OTG_DP, "b5", NULL),
_OMAP4_BALLENTRY(USBA0_OTG_DM, "b4", NULL),
_OMAP4_BALLENTRY(FREF_CLK1_OUT, "aa28", NULL),
_OMAP4_BALLENTRY(FREF_CLK2_OUT, "y28", NULL),
_OMAP4_BALLENTRY(SYS_NIRQ1, "ae6", NULL),
_OMAP4_BALLENTRY(SYS_NIRQ2, "af6", NULL),
_OMAP4_BALLENTRY(SYS_BOOT0, "f26", NULL),
_OMAP4_BALLENTRY(SYS_BOOT1, "e27", NULL),
_OMAP4_BALLENTRY(SYS_BOOT2, "e26", NULL),
_OMAP4_BALLENTRY(SYS_BOOT3, "e25", NULL),
_OMAP4_BALLENTRY(SYS_BOOT4, "d28", NULL),
_OMAP4_BALLENTRY(SYS_BOOT5, "d27", NULL),
_OMAP4_BALLENTRY(DPM_EMU0, "m2", NULL),
_OMAP4_BALLENTRY(DPM_EMU1, "n2", NULL),
_OMAP4_BALLENTRY(DPM_EMU2, "p2", NULL),
_OMAP4_BALLENTRY(DPM_EMU3, "v1", NULL),
_OMAP4_BALLENTRY(DPM_EMU4, "v2", NULL),
_OMAP4_BALLENTRY(DPM_EMU5, "w1", NULL),
_OMAP4_BALLENTRY(DPM_EMU6, "w2", NULL),
_OMAP4_BALLENTRY(DPM_EMU7, "w3", NULL),
_OMAP4_BALLENTRY(DPM_EMU8, "w4", NULL),
_OMAP4_BALLENTRY(DPM_EMU9, "y2", NULL),
_OMAP4_BALLENTRY(DPM_EMU10, "y3", NULL),
_OMAP4_BALLENTRY(DPM_EMU11, "y4", NULL),
_OMAP4_BALLENTRY(DPM_EMU12, "aa1", NULL),
_OMAP4_BALLENTRY(DPM_EMU13, "aa2", NULL),
_OMAP4_BALLENTRY(DPM_EMU14, "aa3", NULL),
_OMAP4_BALLENTRY(DPM_EMU15, "aa4", NULL),
_OMAP4_BALLENTRY(DPM_EMU16, "ab2", NULL),
_OMAP4_BALLENTRY(DPM_EMU17, "ab3", NULL),
_OMAP4_BALLENTRY(DPM_EMU18, "ab4", NULL),
_OMAP4_BALLENTRY(DPM_EMU19, "ac4", NULL),
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#else
#define omap4_core_cbs_ball NULL
#endif
/*
* Superset of all mux modes for omap4
*/
static struct omap_mux __initdata omap4_wkup_muxmodes[] = {
_OMAP4_MUXENTRY(SIM_IO, 0, "sim_io", NULL, NULL, "gpio_wk0", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SIM_CLK, 1, "sim_clk", NULL, NULL, "gpio_wk1", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SIM_RESET, 2, "sim_reset", NULL, NULL, "gpio_wk2",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SIM_CD, 3, "sim_cd", NULL, NULL, "gpio_wk3", NULL,
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SIM_PWRCTRL, 4, "sim_pwrctrl", NULL, NULL, "gpio_wk4",
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(SR_SCL, 0, "sr_scl", NULL, NULL, NULL, NULL, NULL,
NULL, NULL),
_OMAP4_MUXENTRY(SR_SDA, 0, "sr_sda", NULL, NULL, NULL, NULL, NULL,
NULL, NULL),
_OMAP4_MUXENTRY(FREF_XTAL_IN, 0, "fref_xtal_in", NULL, NULL, NULL,
"c2c_wakereqin", NULL, NULL, NULL),
_OMAP4_MUXENTRY(FREF_SLICER_IN, 0, "fref_slicer_in", NULL, NULL,
"gpi_wk5", "c2c_wakereqin", NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(FREF_CLK_IOREQ, 0, "fref_clk_ioreq", NULL, NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(FREF_CLK0_OUT, 6, "fref_clk0_out", "fref_clk1_req",
"sys_drm_msecure", "gpio_wk6", NULL, NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(FREF_CLK3_REQ, 30, "fref_clk3_req", "fref_clk1_req",
"sys_drm_msecure", "gpio_wk30", "c2c_wakereqin", NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(FREF_CLK3_OUT, 31, "fref_clk3_out", "fref_clk2_req",
"sys_secure_indicator", "gpio_wk31", "c2c_wakereqout",
NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(FREF_CLK4_REQ, 7, "fref_clk4_req", "fref_clk5_out",
NULL, "gpio_wk7", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(FREF_CLK4_OUT, 8, "fref_clk4_out", NULL, NULL,
"gpio_wk8", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(SYS_32K, 0, "sys_32k", NULL, NULL, NULL, NULL, NULL,
NULL, NULL),
_OMAP4_MUXENTRY(SYS_NRESPWRON, 0, "sys_nrespwron", NULL, NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(SYS_NRESWARM, 0, "sys_nreswarm", NULL, NULL, NULL,
NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(SYS_PWR_REQ, 0, "sys_pwr_req", NULL, NULL, NULL, NULL,
NULL, NULL, NULL),
_OMAP4_MUXENTRY(SYS_PWRON_RESET_OUT, 29, "sys_pwron_reset_out", NULL,
NULL, "gpio_wk29", NULL, NULL, NULL, NULL),
_OMAP4_MUXENTRY(SYS_BOOT6, 9, "sys_boot6", "dpm_emu18", NULL,
"gpio_wk9", "c2c_wakereqout", NULL, NULL,
"safe_mode"),
_OMAP4_MUXENTRY(SYS_BOOT7, 10, "sys_boot7", "dpm_emu19", NULL,
"gpio_wk10", NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(JTAG_NTRST, 0, "jtag_ntrst", NULL, NULL, NULL, NULL,
NULL, NULL, NULL),
_OMAP4_MUXENTRY(JTAG_TCK, 0, "jtag_tck", NULL, NULL, NULL, NULL, NULL,
NULL, "safe_mode"),
_OMAP4_MUXENTRY(JTAG_RTCK, 0, "jtag_rtck", NULL, NULL, NULL, NULL,
NULL, NULL, NULL),
_OMAP4_MUXENTRY(JTAG_TMS_TMSC, 0, "jtag_tms_tmsc", NULL, NULL, NULL,
NULL, NULL, NULL, "safe_mode"),
_OMAP4_MUXENTRY(JTAG_TDI, 0, "jtag_tdi", NULL, NULL, NULL, NULL, NULL,
NULL, NULL),
_OMAP4_MUXENTRY(JTAG_TDO, 0, "jtag_tdo", NULL, NULL, NULL, NULL, NULL,
NULL, NULL),
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
/*
* Balls for 44XX CBL & CBS package - wakeup partition
* 547-pin CBL ES1.0 S-FPGA-N547, 0.40mm Ball Pitch (Top),
* 0.40mm Ball Pitch (Bottom)
*/
#if defined(CONFIG_OMAP_MUX) && defined(CONFIG_DEBUG_FS) \
&& defined(CONFIG_OMAP_PACKAGE_CBL)
static struct omap_ball __initdata omap4_wkup_cbl_cbs_ball[] = {
_OMAP4_BALLENTRY(SIM_IO, "h4", NULL),
_OMAP4_BALLENTRY(SIM_CLK, "j2", NULL),
_OMAP4_BALLENTRY(SIM_RESET, "g2", NULL),
_OMAP4_BALLENTRY(SIM_CD, "j1", NULL),
_OMAP4_BALLENTRY(SIM_PWRCTRL, "k1", NULL),
_OMAP4_BALLENTRY(SR_SCL, "ag9", NULL),
_OMAP4_BALLENTRY(SR_SDA, "af9", NULL),
_OMAP4_BALLENTRY(FREF_XTAL_IN, "ah6", NULL),
_OMAP4_BALLENTRY(FREF_SLICER_IN, "ag8", NULL),
_OMAP4_BALLENTRY(FREF_CLK_IOREQ, "ad1", NULL),
_OMAP4_BALLENTRY(FREF_CLK0_OUT, "ad2", NULL),
_OMAP4_BALLENTRY(FREF_CLK3_REQ, "ad3", NULL),
_OMAP4_BALLENTRY(FREF_CLK3_OUT, "ad4", NULL),
_OMAP4_BALLENTRY(FREF_CLK4_REQ, "ac2", NULL),
_OMAP4_BALLENTRY(FREF_CLK4_OUT, "ac3", NULL),
_OMAP4_BALLENTRY(SYS_32K, "ag7", NULL),
_OMAP4_BALLENTRY(SYS_NRESPWRON, "ae7", NULL),
_OMAP4_BALLENTRY(SYS_NRESWARM, "af7", NULL),
_OMAP4_BALLENTRY(SYS_PWR_REQ, "ah7", NULL),
_OMAP4_BALLENTRY(SYS_PWRON_RESET_OUT, "ag6", NULL),
_OMAP4_BALLENTRY(SYS_BOOT6, "af8", NULL),
_OMAP4_BALLENTRY(SYS_BOOT7, "ae8", NULL),
_OMAP4_BALLENTRY(JTAG_NTRST, "ah2", NULL),
_OMAP4_BALLENTRY(JTAG_TCK, "ag1", NULL),
_OMAP4_BALLENTRY(JTAG_RTCK, "ae3", NULL),
_OMAP4_BALLENTRY(JTAG_TMS_TMSC, "ah1", NULL),
_OMAP4_BALLENTRY(JTAG_TDI, "ae1", NULL),
_OMAP4_BALLENTRY(JTAG_TDO, "ae2", NULL),
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#else
#define omap4_wkup_cbl_cbs_ball NULL
#endif
int __init omap4_mux_init(struct omap_board_mux *board_subset,
struct omap_board_mux *board_wkup_subset, int flags)
{
struct omap_ball *package_balls_core;
struct omap_ball *package_balls_wkup = omap4_wkup_cbl_cbs_ball;
struct omap_mux *core_muxmodes;
struct omap_mux *core_subset = NULL;
int ret;
switch (flags & OMAP_PACKAGE_MASK) {
case OMAP_PACKAGE_CBL:
pr_debug("%s: OMAP4430 ES1.0 -> OMAP_PACKAGE_CBL\n", __func__);
package_balls_core = omap4_core_cbl_ball;
core_muxmodes = omap4_core_muxmodes;
break;
case OMAP_PACKAGE_CBS:
pr_debug("%s: OMAP4430 ES2.X -> OMAP_PACKAGE_CBS\n", __func__);
package_balls_core = omap4_core_cbs_ball;
core_muxmodes = omap4_core_muxmodes;
core_subset = omap4_es2_core_subset;
break;
default:
pr_err("%s: Unknown omap package, mux disabled\n", __func__);
return -EINVAL;
}
ret = omap_mux_init("core",
OMAP_MUX_GPIO_IN_MODE3,
OMAP4_CTRL_MODULE_PAD_CORE_MUX_PBASE,
OMAP4_CTRL_MODULE_PAD_CORE_MUX_SIZE,
core_muxmodes, core_subset, board_subset,
package_balls_core);
if (ret)
return ret;
ret = omap_mux_init("wkup",
OMAP_MUX_GPIO_IN_MODE3,
OMAP4_CTRL_MODULE_PAD_WKUP_MUX_PBASE,
OMAP4_CTRL_MODULE_PAD_WKUP_MUX_SIZE,
omap4_wkup_muxmodes, NULL, board_wkup_subset,
package_balls_wkup);
return ret;
}
| gpl-2.0 |
arif8323/linux | drivers/sbus/char/jsflash.c | 10651 | 14482 | /*
* drivers/sbus/char/jsflash.c
*
* Copyright (C) 1991, 1992 Linus Torvalds (drivers/char/mem.c)
* Copyright (C) 1997 Eddie C. Dost (drivers/sbus/char/flash.c)
* Copyright (C) 1997-2000 Pavel Machek <pavel@ucw.cz> (drivers/block/nbd.c)
* Copyright (C) 1999-2000 Pete Zaitcev
*
* This driver is used to program OS into a Flash SIMM on
* Krups and Espresso platforms.
*
* TODO: do not allow erase/programming if file systems are mounted.
* TODO: Erase/program both banks of a 8MB SIMM.
*
* It is anticipated that programming an OS Flash will be a routine
* procedure. In the same time it is exceedingly dangerous because
* a user can program its OBP flash with OS image and effectively
* kill the machine.
*
* This driver uses an interface different from Eddie's flash.c
* as a silly safeguard.
*
* XXX The flash.c manipulates page caching characteristics in a certain
* dubious way; also it assumes that remap_pfn_range() can remap
* PCI bus locations, which may be false. ioremap() must be used
* instead. We should discuss this.
*/
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/genhd.h>
#include <linux/blkdev.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include <asm/io.h>
#include <asm/pcic.h>
#include <asm/oplib.h>
#include <asm/jsflash.h> /* ioctl arguments. <linux/> ?? */
#define JSFIDSZ (sizeof(struct jsflash_ident_arg))
#define JSFPRGSZ (sizeof(struct jsflash_program_arg))
/*
* Our device numbers have no business in system headers.
* The only thing a user knows is the device name /dev/jsflash.
*
* Block devices are laid out like this:
* minor+0 - Bootstrap, for 8MB SIMM 0x20400000[0x800000]
* minor+1 - Filesystem to mount, normally 0x20400400[0x7ffc00]
* minor+2 - Whole flash area for any case... 0x20000000[0x01000000]
* Total 3 minors per flash device.
*
* It is easier to have static size vectors, so we define
* a total minor range JSF_MAX, which must cover all minors.
*/
/* character device */
#define JSF_MINOR 178 /* 178 is registered with hpa */
/* block device */
#define JSF_MAX 3 /* 3 minors wasted total so far. */
#define JSF_NPART 3 /* 3 minors per flash device */
#define JSF_PART_BITS 2 /* 2 bits of minors to cover JSF_NPART */
#define JSF_PART_MASK 0x3 /* 2 bits mask */
static DEFINE_MUTEX(jsf_mutex);
/*
* Access functions.
* We could ioremap(), but it's easier this way.
*/
static unsigned int jsf_inl(unsigned long addr)
{
unsigned long retval;
__asm__ __volatile__("lda [%1] %2, %0\n\t" :
"=r" (retval) :
"r" (addr), "i" (ASI_M_BYPASS));
return retval;
}
static void jsf_outl(unsigned long addr, __u32 data)
{
__asm__ __volatile__("sta %0, [%1] %2\n\t" : :
"r" (data), "r" (addr), "i" (ASI_M_BYPASS) :
"memory");
}
/*
* soft carrier
*/
struct jsfd_part {
unsigned long dbase;
unsigned long dsize;
};
struct jsflash {
unsigned long base;
unsigned long size;
unsigned long busy; /* In use? */
struct jsflash_ident_arg id;
/* int mbase; */ /* Minor base, typically zero */
struct jsfd_part dv[JSF_NPART];
};
/*
* We do not map normal memory or obio as a safety precaution.
* But offsets are real, for ease of userland programming.
*/
#define JSF_BASE_TOP 0x30000000
#define JSF_BASE_ALL 0x20000000
#define JSF_BASE_JK 0x20400000
/*
*/
static struct gendisk *jsfd_disk[JSF_MAX];
/*
* Let's pretend we may have several of these...
*/
static struct jsflash jsf0;
/*
* Wait for AMD to finish its embedded algorithm.
* We use the Toggle bit DQ6 (0x40) because it does not
* depend on the data value as /DATA bit DQ7 does.
*
* XXX Do we need any timeout here? So far it never hanged, beware broken hw.
*/
static void jsf_wait(unsigned long p) {
unsigned int x1, x2;
for (;;) {
x1 = jsf_inl(p);
x2 = jsf_inl(p);
if ((x1 & 0x40404040) == (x2 & 0x40404040)) return;
}
}
/*
* Programming will only work if Flash is clean,
* we leave it to the programmer application.
*
* AMD must be programmed one byte at a time;
* thus, Simple Tech SIMM must be written 4 bytes at a time.
*
* Write waits for the chip to become ready after the write
* was finished. This is done so that application would read
* consistent data after the write is done.
*/
static void jsf_write4(unsigned long fa, u32 data) {
jsf_outl(fa, 0xAAAAAAAA); /* Unlock 1 Write 1 */
jsf_outl(fa, 0x55555555); /* Unlock 1 Write 2 */
jsf_outl(fa, 0xA0A0A0A0); /* Byte Program */
jsf_outl(fa, data);
jsf_wait(fa);
}
/*
*/
static void jsfd_read(char *buf, unsigned long p, size_t togo) {
union byte4 {
char s[4];
unsigned int n;
} b;
while (togo >= 4) {
togo -= 4;
b.n = jsf_inl(p);
memcpy(buf, b.s, 4);
p += 4;
buf += 4;
}
}
static void jsfd_do_request(struct request_queue *q)
{
struct request *req;
req = blk_fetch_request(q);
while (req) {
struct jsfd_part *jdp = req->rq_disk->private_data;
unsigned long offset = blk_rq_pos(req) << 9;
size_t len = blk_rq_cur_bytes(req);
int err = -EIO;
if ((offset + len) > jdp->dsize)
goto end;
if (rq_data_dir(req) != READ) {
printk(KERN_ERR "jsfd: write\n");
goto end;
}
if ((jdp->dbase & 0xff000000) != 0x20000000) {
printk(KERN_ERR "jsfd: bad base %x\n", (int)jdp->dbase);
goto end;
}
jsfd_read(req->buffer, jdp->dbase + offset, len);
err = 0;
end:
if (!__blk_end_request_cur(req, err))
req = blk_fetch_request(q);
}
}
/*
* The memory devices use the full 32/64 bits of the offset, and so we cannot
* check against negative addresses: they are ok. The return value is weird,
* though, in that case (0).
*
* also note that seeking relative to the "end of file" isn't supported:
* it has no meaning, so it returns -EINVAL.
*/
static loff_t jsf_lseek(struct file * file, loff_t offset, int orig)
{
loff_t ret;
mutex_lock(&jsf_mutex);
switch (orig) {
case 0:
file->f_pos = offset;
ret = file->f_pos;
break;
case 1:
file->f_pos += offset;
ret = file->f_pos;
break;
default:
ret = -EINVAL;
}
mutex_unlock(&jsf_mutex);
return ret;
}
/*
* OS SIMM Cannot be read in other size but a 32bits word.
*/
static ssize_t jsf_read(struct file * file, char __user * buf,
size_t togo, loff_t *ppos)
{
unsigned long p = *ppos;
char __user *tmp = buf;
union byte4 {
char s[4];
unsigned int n;
} b;
if (p < JSF_BASE_ALL || p >= JSF_BASE_TOP) {
return 0;
}
if ((p + togo) < p /* wrap */
|| (p + togo) >= JSF_BASE_TOP) {
togo = JSF_BASE_TOP - p;
}
if (p < JSF_BASE_ALL && togo != 0) {
#if 0 /* __bzero XXX */
size_t x = JSF_BASE_ALL - p;
if (x > togo) x = togo;
clear_user(tmp, x);
tmp += x;
p += x;
togo -= x;
#else
/*
* Implementation of clear_user() calls __bzero
* without regard to modversions,
* so we cannot build a module.
*/
return 0;
#endif
}
while (togo >= 4) {
togo -= 4;
b.n = jsf_inl(p);
if (copy_to_user(tmp, b.s, 4))
return -EFAULT;
tmp += 4;
p += 4;
}
/*
* XXX Small togo may remain if 1 byte is ordered.
* It would be nice if we did a word size read and unpacked it.
*/
*ppos = p;
return tmp-buf;
}
static ssize_t jsf_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
return -ENOSPC;
}
/*
*/
static int jsf_ioctl_erase(unsigned long arg)
{
unsigned long p;
/* p = jsf0.base; hits wrong bank */
p = 0x20400000;
jsf_outl(p, 0xAAAAAAAA); /* Unlock 1 Write 1 */
jsf_outl(p, 0x55555555); /* Unlock 1 Write 2 */
jsf_outl(p, 0x80808080); /* Erase setup */
jsf_outl(p, 0xAAAAAAAA); /* Unlock 2 Write 1 */
jsf_outl(p, 0x55555555); /* Unlock 2 Write 2 */
jsf_outl(p, 0x10101010); /* Chip erase */
#if 0
/*
* This code is ok, except that counter based timeout
* has no place in this world. Let's just drop timeouts...
*/
{
int i;
__u32 x;
for (i = 0; i < 1000000; i++) {
x = jsf_inl(p);
if ((x & 0x80808080) == 0x80808080) break;
}
if ((x & 0x80808080) != 0x80808080) {
printk("jsf0: erase timeout with 0x%08x\n", x);
} else {
printk("jsf0: erase done with 0x%08x\n", x);
}
}
#else
jsf_wait(p);
#endif
return 0;
}
/*
* Program a block of flash.
* Very simple because we can do it byte by byte anyway.
*/
static int jsf_ioctl_program(void __user *arg)
{
struct jsflash_program_arg abuf;
char __user *uptr;
unsigned long p;
unsigned int togo;
union {
unsigned int n;
char s[4];
} b;
if (copy_from_user(&abuf, arg, JSFPRGSZ))
return -EFAULT;
p = abuf.off;
togo = abuf.size;
if ((togo & 3) || (p & 3)) return -EINVAL;
uptr = (char __user *) (unsigned long) abuf.data;
while (togo != 0) {
togo -= 4;
if (copy_from_user(&b.s[0], uptr, 4))
return -EFAULT;
jsf_write4(p, b.n);
p += 4;
uptr += 4;
}
return 0;
}
static long jsf_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
mutex_lock(&jsf_mutex);
int error = -ENOTTY;
void __user *argp = (void __user *)arg;
if (!capable(CAP_SYS_ADMIN)) {
mutex_unlock(&jsf_mutex);
return -EPERM;
}
switch (cmd) {
case JSFLASH_IDENT:
if (copy_to_user(argp, &jsf0.id, JSFIDSZ)) {
mutex_unlock(&jsf_mutex);
return -EFAULT;
}
break;
case JSFLASH_ERASE:
error = jsf_ioctl_erase(arg);
break;
case JSFLASH_PROGRAM:
error = jsf_ioctl_program(argp);
break;
}
mutex_unlock(&jsf_mutex);
return error;
}
static int jsf_mmap(struct file * file, struct vm_area_struct * vma)
{
return -ENXIO;
}
static int jsf_open(struct inode * inode, struct file * filp)
{
mutex_lock(&jsf_mutex);
if (jsf0.base == 0) {
mutex_unlock(&jsf_mutex);
return -ENXIO;
}
if (test_and_set_bit(0, (void *)&jsf0.busy) != 0) {
mutex_unlock(&jsf_mutex);
return -EBUSY;
}
mutex_unlock(&jsf_mutex);
return 0; /* XXX What security? */
}
static int jsf_release(struct inode *inode, struct file *file)
{
jsf0.busy = 0;
return 0;
}
static const struct file_operations jsf_fops = {
.owner = THIS_MODULE,
.llseek = jsf_lseek,
.read = jsf_read,
.write = jsf_write,
.unlocked_ioctl = jsf_ioctl,
.mmap = jsf_mmap,
.open = jsf_open,
.release = jsf_release,
};
static struct miscdevice jsf_dev = { JSF_MINOR, "jsflash", &jsf_fops };
static const struct block_device_operations jsfd_fops = {
.owner = THIS_MODULE,
};
static int jsflash_init(void)
{
int rc;
struct jsflash *jsf;
phandle node;
char banner[128];
struct linux_prom_registers reg0;
node = prom_getchild(prom_root_node);
node = prom_searchsiblings(node, "flash-memory");
if (node != 0 && (s32)node != -1) {
if (prom_getproperty(node, "reg",
(char *)®0, sizeof(reg0)) == -1) {
printk("jsflash: no \"reg\" property\n");
return -ENXIO;
}
if (reg0.which_io != 0) {
printk("jsflash: bus number nonzero: 0x%x:%x\n",
reg0.which_io, reg0.phys_addr);
return -ENXIO;
}
/*
* Flash may be somewhere else, for instance on Ebus.
* So, don't do the following check for IIep flash space.
*/
#if 0
if ((reg0.phys_addr >> 24) != 0x20) {
printk("jsflash: suspicious address: 0x%x:%x\n",
reg0.which_io, reg0.phys_addr);
return -ENXIO;
}
#endif
if ((int)reg0.reg_size <= 0) {
printk("jsflash: bad size 0x%x\n", (int)reg0.reg_size);
return -ENXIO;
}
} else {
/* XXX Remove this code once PROLL ID12 got widespread */
printk("jsflash: no /flash-memory node, use PROLL >= 12\n");
prom_getproperty(prom_root_node, "banner-name", banner, 128);
if (strcmp (banner, "JavaStation-NC") != 0 &&
strcmp (banner, "JavaStation-E") != 0) {
return -ENXIO;
}
reg0.which_io = 0;
reg0.phys_addr = 0x20400000;
reg0.reg_size = 0x00800000;
}
/* Let us be really paranoid for modifications to probing code. */
/* extern enum sparc_cpu sparc_cpu_model; */ /* in <asm/system.h> */
if (sparc_cpu_model != sun4m) {
/* We must be on sun4m because we use MMU Bypass ASI. */
return -ENXIO;
}
if (jsf0.base == 0) {
jsf = &jsf0;
jsf->base = reg0.phys_addr;
jsf->size = reg0.reg_size;
/* XXX Redo the userland interface. */
jsf->id.off = JSF_BASE_ALL;
jsf->id.size = 0x01000000; /* 16M - all segments */
strcpy(jsf->id.name, "Krups_all");
jsf->dv[0].dbase = jsf->base;
jsf->dv[0].dsize = jsf->size;
jsf->dv[1].dbase = jsf->base + 1024;
jsf->dv[1].dsize = jsf->size - 1024;
jsf->dv[2].dbase = JSF_BASE_ALL;
jsf->dv[2].dsize = 0x01000000;
printk("Espresso Flash @0x%lx [%d MB]\n", jsf->base,
(int) (jsf->size / (1024*1024)));
}
if ((rc = misc_register(&jsf_dev)) != 0) {
printk(KERN_ERR "jsf: unable to get misc minor %d\n",
JSF_MINOR);
jsf0.base = 0;
return rc;
}
return 0;
}
static struct request_queue *jsf_queue;
static int jsfd_init(void)
{
static DEFINE_SPINLOCK(lock);
struct jsflash *jsf;
struct jsfd_part *jdp;
int err;
int i;
if (jsf0.base == 0)
return -ENXIO;
err = -ENOMEM;
for (i = 0; i < JSF_MAX; i++) {
struct gendisk *disk = alloc_disk(1);
if (!disk)
goto out;
jsfd_disk[i] = disk;
}
if (register_blkdev(JSFD_MAJOR, "jsfd")) {
err = -EIO;
goto out;
}
jsf_queue = blk_init_queue(jsfd_do_request, &lock);
if (!jsf_queue) {
err = -ENOMEM;
unregister_blkdev(JSFD_MAJOR, "jsfd");
goto out;
}
for (i = 0; i < JSF_MAX; i++) {
struct gendisk *disk = jsfd_disk[i];
if ((i & JSF_PART_MASK) >= JSF_NPART) continue;
jsf = &jsf0; /* actually, &jsfv[i >> JSF_PART_BITS] */
jdp = &jsf->dv[i&JSF_PART_MASK];
disk->major = JSFD_MAJOR;
disk->first_minor = i;
sprintf(disk->disk_name, "jsfd%d", i);
disk->fops = &jsfd_fops;
set_capacity(disk, jdp->dsize >> 9);
disk->private_data = jdp;
disk->queue = jsf_queue;
add_disk(disk);
set_disk_ro(disk, 1);
}
return 0;
out:
while (i--)
put_disk(jsfd_disk[i]);
return err;
}
MODULE_LICENSE("GPL");
static int __init jsflash_init_module(void) {
int rc;
if ((rc = jsflash_init()) == 0) {
jsfd_init();
return 0;
}
return rc;
}
static void __exit jsflash_cleanup_module(void)
{
int i;
for (i = 0; i < JSF_MAX; i++) {
if ((i & JSF_PART_MASK) >= JSF_NPART) continue;
del_gendisk(jsfd_disk[i]);
put_disk(jsfd_disk[i]);
}
if (jsf0.busy)
printk("jsf0: cleaning busy unit\n");
jsf0.base = 0;
jsf0.busy = 0;
misc_deregister(&jsf_dev);
unregister_blkdev(JSFD_MAJOR, "jsfd");
blk_cleanup_queue(jsf_queue);
}
module_init(jsflash_init_module);
module_exit(jsflash_cleanup_module);
| gpl-2.0 |
aidfarh/android_kernel_lge_palman | arch/powerpc/platforms/8xx/adder875.c | 12187 | 3142 | /* Analogue & Micro Adder MPC875 board support
*
* Author: Scott Wood <scottwood@freescale.com>
*
* Copyright (c) 2007 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/fs_enet_pd.h>
#include <linux/of_platform.h>
#include <asm/time.h>
#include <asm/machdep.h>
#include <asm/cpm1.h>
#include <asm/fs_pd.h>
#include <asm/udbg.h>
#include <asm/prom.h>
#include "mpc8xx.h"
struct cpm_pin {
int port, pin, flags;
};
static __initdata struct cpm_pin adder875_pins[] = {
/* SMC1 */
{CPM_PORTB, 24, CPM_PIN_INPUT}, /* RX */
{CPM_PORTB, 25, CPM_PIN_INPUT | CPM_PIN_SECONDARY}, /* TX */
/* MII1 */
{CPM_PORTA, 0, CPM_PIN_INPUT},
{CPM_PORTA, 1, CPM_PIN_INPUT},
{CPM_PORTA, 2, CPM_PIN_INPUT},
{CPM_PORTA, 3, CPM_PIN_INPUT},
{CPM_PORTA, 4, CPM_PIN_OUTPUT},
{CPM_PORTA, 10, CPM_PIN_OUTPUT},
{CPM_PORTA, 11, CPM_PIN_OUTPUT},
{CPM_PORTB, 19, CPM_PIN_INPUT},
{CPM_PORTB, 31, CPM_PIN_INPUT},
{CPM_PORTC, 12, CPM_PIN_INPUT},
{CPM_PORTC, 13, CPM_PIN_INPUT},
{CPM_PORTE, 30, CPM_PIN_OUTPUT},
{CPM_PORTE, 31, CPM_PIN_OUTPUT},
/* MII2 */
{CPM_PORTE, 14, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 15, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 16, CPM_PIN_OUTPUT},
{CPM_PORTE, 17, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 18, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 19, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 20, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 21, CPM_PIN_OUTPUT},
{CPM_PORTE, 22, CPM_PIN_OUTPUT},
{CPM_PORTE, 23, CPM_PIN_OUTPUT},
{CPM_PORTE, 24, CPM_PIN_OUTPUT},
{CPM_PORTE, 25, CPM_PIN_OUTPUT},
{CPM_PORTE, 26, CPM_PIN_OUTPUT},
{CPM_PORTE, 27, CPM_PIN_OUTPUT},
{CPM_PORTE, 28, CPM_PIN_OUTPUT},
{CPM_PORTE, 29, CPM_PIN_OUTPUT},
};
static void __init init_ioports(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(adder875_pins); i++) {
const struct cpm_pin *pin = &adder875_pins[i];
cpm1_set_pin(pin->port, pin->pin, pin->flags);
}
cpm1_clk_setup(CPM_CLK_SMC1, CPM_BRG1, CPM_CLK_RTX);
/* Set FEC1 and FEC2 to MII mode */
clrbits32(&mpc8xx_immr->im_cpm.cp_cptr, 0x00000180);
}
static void __init adder875_setup(void)
{
cpm_reset();
init_ioports();
}
static int __init adder875_probe(void)
{
unsigned long root = of_get_flat_dt_root();
return of_flat_dt_is_compatible(root, "analogue-and-micro,adder875");
}
static __initdata struct of_device_id of_bus_ids[] = {
{ .compatible = "simple-bus", },
{},
};
static int __init declare_of_platform_devices(void)
{
of_platform_bus_probe(NULL, of_bus_ids, NULL);
return 0;
}
machine_device_initcall(adder875, declare_of_platform_devices);
define_machine(adder875) {
.name = "Adder MPC875",
.probe = adder875_probe,
.setup_arch = adder875_setup,
.init_IRQ = mpc8xx_pics_init,
.get_irq = mpc8xx_get_irq,
.restart = mpc8xx_restart,
.calibrate_decr = generic_calibrate_decr,
.set_rtc_time = mpc8xx_set_rtc_time,
.get_rtc_time = mpc8xx_get_rtc_time,
.progress = udbg_progress,
};
| gpl-2.0 |
kumajaya/android_kernel_samsung_espresso10 | arch/powerpc/platforms/8xx/adder875.c | 12187 | 3142 | /* Analogue & Micro Adder MPC875 board support
*
* Author: Scott Wood <scottwood@freescale.com>
*
* Copyright (c) 2007 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/fs_enet_pd.h>
#include <linux/of_platform.h>
#include <asm/time.h>
#include <asm/machdep.h>
#include <asm/cpm1.h>
#include <asm/fs_pd.h>
#include <asm/udbg.h>
#include <asm/prom.h>
#include "mpc8xx.h"
struct cpm_pin {
int port, pin, flags;
};
static __initdata struct cpm_pin adder875_pins[] = {
/* SMC1 */
{CPM_PORTB, 24, CPM_PIN_INPUT}, /* RX */
{CPM_PORTB, 25, CPM_PIN_INPUT | CPM_PIN_SECONDARY}, /* TX */
/* MII1 */
{CPM_PORTA, 0, CPM_PIN_INPUT},
{CPM_PORTA, 1, CPM_PIN_INPUT},
{CPM_PORTA, 2, CPM_PIN_INPUT},
{CPM_PORTA, 3, CPM_PIN_INPUT},
{CPM_PORTA, 4, CPM_PIN_OUTPUT},
{CPM_PORTA, 10, CPM_PIN_OUTPUT},
{CPM_PORTA, 11, CPM_PIN_OUTPUT},
{CPM_PORTB, 19, CPM_PIN_INPUT},
{CPM_PORTB, 31, CPM_PIN_INPUT},
{CPM_PORTC, 12, CPM_PIN_INPUT},
{CPM_PORTC, 13, CPM_PIN_INPUT},
{CPM_PORTE, 30, CPM_PIN_OUTPUT},
{CPM_PORTE, 31, CPM_PIN_OUTPUT},
/* MII2 */
{CPM_PORTE, 14, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 15, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 16, CPM_PIN_OUTPUT},
{CPM_PORTE, 17, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 18, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 19, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 20, CPM_PIN_OUTPUT | CPM_PIN_SECONDARY},
{CPM_PORTE, 21, CPM_PIN_OUTPUT},
{CPM_PORTE, 22, CPM_PIN_OUTPUT},
{CPM_PORTE, 23, CPM_PIN_OUTPUT},
{CPM_PORTE, 24, CPM_PIN_OUTPUT},
{CPM_PORTE, 25, CPM_PIN_OUTPUT},
{CPM_PORTE, 26, CPM_PIN_OUTPUT},
{CPM_PORTE, 27, CPM_PIN_OUTPUT},
{CPM_PORTE, 28, CPM_PIN_OUTPUT},
{CPM_PORTE, 29, CPM_PIN_OUTPUT},
};
static void __init init_ioports(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(adder875_pins); i++) {
const struct cpm_pin *pin = &adder875_pins[i];
cpm1_set_pin(pin->port, pin->pin, pin->flags);
}
cpm1_clk_setup(CPM_CLK_SMC1, CPM_BRG1, CPM_CLK_RTX);
/* Set FEC1 and FEC2 to MII mode */
clrbits32(&mpc8xx_immr->im_cpm.cp_cptr, 0x00000180);
}
static void __init adder875_setup(void)
{
cpm_reset();
init_ioports();
}
static int __init adder875_probe(void)
{
unsigned long root = of_get_flat_dt_root();
return of_flat_dt_is_compatible(root, "analogue-and-micro,adder875");
}
static __initdata struct of_device_id of_bus_ids[] = {
{ .compatible = "simple-bus", },
{},
};
static int __init declare_of_platform_devices(void)
{
of_platform_bus_probe(NULL, of_bus_ids, NULL);
return 0;
}
machine_device_initcall(adder875, declare_of_platform_devices);
define_machine(adder875) {
.name = "Adder MPC875",
.probe = adder875_probe,
.setup_arch = adder875_setup,
.init_IRQ = mpc8xx_pics_init,
.get_irq = mpc8xx_get_irq,
.restart = mpc8xx_restart,
.calibrate_decr = generic_calibrate_decr,
.set_rtc_time = mpc8xx_set_rtc_time,
.get_rtc_time = mpc8xx_get_rtc_time,
.progress = udbg_progress,
};
| gpl-2.0 |
xuejian1354/attitude_adjustment | target/linux/s3c24xx/files-2.6.30/drivers/ar6000/htc/htc_services.c | 156 | 15342 | /*
*
* Copyright (c) 2007 Atheros Communications Inc.
* All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
*
*
*/
#include "htc_internal.h"
void HTCControlTxComplete(void *Context, HTC_PACKET *pPacket)
{
/* not implemented
* we do not send control TX frames during normal runtime, only during setup */
AR_DEBUG_ASSERT(FALSE);
}
/* callback when a control message arrives on this endpoint */
void HTCControlRecv(void *Context, HTC_PACKET *pPacket)
{
AR_DEBUG_ASSERT(pPacket->Endpoint == ENDPOINT_0);
/* the only control messages we are expecting are NULL messages (credit resports), which should
* never get here */
AR_DEBUG_PRINTF(ATH_DEBUG_ERR,
("HTCControlRecv, got message with length:%d \n",
pPacket->ActualLength + HTC_HDR_LENGTH));
/* dump header and message */
DebugDumpBytes(pPacket->pBuffer - HTC_HDR_LENGTH,
pPacket->ActualLength + HTC_HDR_LENGTH,
"Unexpected ENDPOINT 0 Message");
HTC_RECYCLE_RX_PKT((HTC_TARGET*)Context,pPacket);
}
A_STATUS HTCSendSetupComplete(HTC_TARGET *target)
{
HTC_PACKET *pSendPacket = NULL;
A_STATUS status;
HTC_SETUP_COMPLETE_MSG *pSetupComplete;
do {
/* allocate a packet to send to the target */
pSendPacket = HTC_ALLOC_CONTROL_TX(target);
if (NULL == pSendPacket) {
status = A_NO_MEMORY;
break;
}
/* assemble setup complete message */
pSetupComplete = (HTC_SETUP_COMPLETE_MSG *)pSendPacket->pBuffer;
A_MEMZERO(pSetupComplete,sizeof(HTC_SETUP_COMPLETE_MSG));
pSetupComplete->MessageID = HTC_MSG_SETUP_COMPLETE_ID;
SET_HTC_PACKET_INFO_TX(pSendPacket,
NULL,
(A_UINT8 *)pSetupComplete,
sizeof(HTC_SETUP_COMPLETE_MSG),
ENDPOINT_0,
HTC_SERVICE_TX_PACKET_TAG);
/* we want synchronous operation */
pSendPacket->Completion = NULL;
/* send the message */
status = HTCIssueSend(target,pSendPacket,0);
} while (FALSE);
if (pSendPacket != NULL) {
HTC_FREE_CONTROL_TX(target,pSendPacket);
}
return status;
}
A_STATUS HTCConnectService(HTC_HANDLE HTCHandle,
HTC_SERVICE_CONNECT_REQ *pConnectReq,
HTC_SERVICE_CONNECT_RESP *pConnectResp)
{
HTC_TARGET *target = GET_HTC_TARGET_FROM_HANDLE(HTCHandle);
A_STATUS status = A_OK;
HTC_PACKET *pRecvPacket = NULL;
HTC_PACKET *pSendPacket = NULL;
HTC_CONNECT_SERVICE_RESPONSE_MSG *pResponseMsg;
HTC_CONNECT_SERVICE_MSG *pConnectMsg;
HTC_ENDPOINT_ID assignedEndpoint = ENDPOINT_MAX;
HTC_ENDPOINT *pEndpoint;
int maxMsgSize = 0;
AR_DEBUG_PRINTF(ATH_DEBUG_TRC, ("+HTCConnectService, target:0x%X SvcID:0x%X \n",
(A_UINT32)target, pConnectReq->ServiceID));
do {
AR_DEBUG_ASSERT(pConnectReq->ServiceID != 0);
if (HTC_CTRL_RSVD_SVC == pConnectReq->ServiceID) {
/* special case for pseudo control service */
assignedEndpoint = ENDPOINT_0;
maxMsgSize = HTC_MAX_CONTROL_MESSAGE_LENGTH;
} else {
/* allocate a packet to send to the target */
pSendPacket = HTC_ALLOC_CONTROL_TX(target);
if (NULL == pSendPacket) {
AR_DEBUG_ASSERT(FALSE);
status = A_NO_MEMORY;
break;
}
/* assemble connect service message */
pConnectMsg = (HTC_CONNECT_SERVICE_MSG *)pSendPacket->pBuffer;
AR_DEBUG_ASSERT(pConnectMsg != NULL);
A_MEMZERO(pConnectMsg,sizeof(HTC_CONNECT_SERVICE_MSG));
pConnectMsg->MessageID = HTC_MSG_CONNECT_SERVICE_ID;
pConnectMsg->ServiceID = pConnectReq->ServiceID;
pConnectMsg->ConnectionFlags = pConnectReq->ConnectionFlags;
/* check caller if it wants to transfer meta data */
if ((pConnectReq->pMetaData != NULL) &&
(pConnectReq->MetaDataLength <= HTC_SERVICE_META_DATA_MAX_LENGTH)) {
/* copy meta data into message buffer (after header ) */
A_MEMCPY((A_UINT8 *)pConnectMsg + sizeof(HTC_CONNECT_SERVICE_MSG),
pConnectReq->pMetaData,
pConnectReq->MetaDataLength);
pConnectMsg->ServiceMetaLength = pConnectReq->MetaDataLength;
}
SET_HTC_PACKET_INFO_TX(pSendPacket,
NULL,
(A_UINT8 *)pConnectMsg,
sizeof(HTC_CONNECT_SERVICE_MSG) + pConnectMsg->ServiceMetaLength,
ENDPOINT_0,
HTC_SERVICE_TX_PACKET_TAG);
/* we want synchronous operation */
pSendPacket->Completion = NULL;
status = HTCIssueSend(target,pSendPacket,0);
if (A_FAILED(status)) {
break;
}
/* wait for response */
status = HTCWaitforControlMessage(target, &pRecvPacket);
if (A_FAILED(status)) {
break;
}
/* we controlled the buffer creation so it has to be properly aligned */
pResponseMsg = (HTC_CONNECT_SERVICE_RESPONSE_MSG *)pRecvPacket->pBuffer;
if ((pResponseMsg->MessageID != HTC_MSG_CONNECT_SERVICE_RESPONSE_ID) ||
(pRecvPacket->ActualLength < sizeof(HTC_CONNECT_SERVICE_RESPONSE_MSG))) {
/* this message is not valid */
AR_DEBUG_ASSERT(FALSE);
status = A_EPROTO;
break;
}
pConnectResp->ConnectRespCode = pResponseMsg->Status;
/* check response status */
if (pResponseMsg->Status != HTC_SERVICE_SUCCESS) {
AR_DEBUG_PRINTF(ATH_DEBUG_ERR,
(" Target failed service 0x%X connect request (status:%d)\n",
pResponseMsg->ServiceID, pResponseMsg->Status));
status = A_EPROTO;
break;
}
assignedEndpoint = pResponseMsg->EndpointID;
maxMsgSize = pResponseMsg->MaxMsgSize;
if ((pConnectResp->pMetaData != NULL) &&
(pResponseMsg->ServiceMetaLength > 0) &&
(pResponseMsg->ServiceMetaLength <= HTC_SERVICE_META_DATA_MAX_LENGTH)) {
/* caller supplied a buffer and the target responded with data */
int copyLength = min((int)pConnectResp->BufferLength, (int)pResponseMsg->ServiceMetaLength);
/* copy the meta data */
A_MEMCPY(pConnectResp->pMetaData,
((A_UINT8 *)pResponseMsg) + sizeof(HTC_CONNECT_SERVICE_RESPONSE_MSG),
copyLength);
pConnectResp->ActualLength = copyLength;
}
}
/* the rest of these are parameter checks so set the error status */
status = A_EPROTO;
if (assignedEndpoint >= ENDPOINT_MAX) {
AR_DEBUG_ASSERT(FALSE);
break;
}
if (0 == maxMsgSize) {
AR_DEBUG_ASSERT(FALSE);
break;
}
pEndpoint = &target->EndPoint[assignedEndpoint];
if (pEndpoint->ServiceID != 0) {
/* endpoint already in use! */
AR_DEBUG_ASSERT(FALSE);
break;
}
/* return assigned endpoint to caller */
pConnectResp->Endpoint = assignedEndpoint;
pConnectResp->MaxMsgLength = maxMsgSize;
/* setup the endpoint */
pEndpoint->ServiceID = pConnectReq->ServiceID; /* this marks the endpoint in use */
pEndpoint->MaxTxQueueDepth = pConnectReq->MaxSendQueueDepth;
pEndpoint->MaxMsgLength = maxMsgSize;
/* copy all the callbacks */
pEndpoint->EpCallBacks = pConnectReq->EpCallbacks;
INIT_HTC_PACKET_QUEUE(&pEndpoint->RxBuffers);
INIT_HTC_PACKET_QUEUE(&pEndpoint->TxQueue);
/* set the credit distribution info for this endpoint, this information is
* passed back to the credit distribution callback function */
pEndpoint->CreditDist.ServiceID = pConnectReq->ServiceID;
pEndpoint->CreditDist.pHTCReserved = pEndpoint;
pEndpoint->CreditDist.Endpoint = assignedEndpoint;
pEndpoint->CreditDist.TxCreditSize = target->TargetCreditSize;
pEndpoint->CreditDist.TxCreditsPerMaxMsg = maxMsgSize / target->TargetCreditSize;
if (0 == pEndpoint->CreditDist.TxCreditsPerMaxMsg) {
pEndpoint->CreditDist.TxCreditsPerMaxMsg = 1;
}
status = A_OK;
} while (FALSE);
if (pSendPacket != NULL) {
HTC_FREE_CONTROL_TX(target,pSendPacket);
}
if (pRecvPacket != NULL) {
HTC_FREE_CONTROL_RX(target,pRecvPacket);
}
AR_DEBUG_PRINTF(ATH_DEBUG_TRC, ("-HTCConnectService \n"));
return status;
}
static void AddToEndpointDistList(HTC_TARGET *target, HTC_ENDPOINT_CREDIT_DIST *pEpDist)
{
HTC_ENDPOINT_CREDIT_DIST *pCurEntry,*pLastEntry;
if (NULL == target->EpCreditDistributionListHead) {
target->EpCreditDistributionListHead = pEpDist;
pEpDist->pNext = NULL;
pEpDist->pPrev = NULL;
return;
}
/* queue to the end of the list, this does not have to be very
* fast since this list is built at startup time */
pCurEntry = target->EpCreditDistributionListHead;
while (pCurEntry) {
pLastEntry = pCurEntry;
pCurEntry = pCurEntry->pNext;
}
pLastEntry->pNext = pEpDist;
pEpDist->pPrev = pLastEntry;
pEpDist->pNext = NULL;
}
/* default credit init callback */
static void HTCDefaultCreditInit(void *Context,
HTC_ENDPOINT_CREDIT_DIST *pEPList,
int TotalCredits)
{
HTC_ENDPOINT_CREDIT_DIST *pCurEpDist;
int totalEps = 0;
int creditsPerEndpoint;
pCurEpDist = pEPList;
/* first run through the list and figure out how many endpoints we are dealing with */
while (pCurEpDist != NULL) {
pCurEpDist = pCurEpDist->pNext;
totalEps++;
}
/* even distribution */
creditsPerEndpoint = TotalCredits/totalEps;
pCurEpDist = pEPList;
/* run through the list and set minimum and normal credits and
* provide the endpoint with some credits to start */
while (pCurEpDist != NULL) {
if (creditsPerEndpoint < pCurEpDist->TxCreditsPerMaxMsg) {
/* too many endpoints and not enough credits */
AR_DEBUG_ASSERT(FALSE);
break;
}
/* our minimum is set for at least 1 max message */
pCurEpDist->TxCreditsMin = pCurEpDist->TxCreditsPerMaxMsg;
/* this value is ignored by our credit alg, since we do
* not dynamically adjust credits, this is the policy of
* the "default" credit distribution, something simple and easy */
pCurEpDist->TxCreditsNorm = 0xFFFF;
/* give the endpoint minimum credits */
pCurEpDist->TxCredits = creditsPerEndpoint;
pCurEpDist->TxCreditsAssigned = creditsPerEndpoint;
pCurEpDist = pCurEpDist->pNext;
}
}
/* default credit distribution callback, NOTE, this callback holds the TX lock */
void HTCDefaultCreditDist(void *Context,
HTC_ENDPOINT_CREDIT_DIST *pEPDistList,
HTC_CREDIT_DIST_REASON Reason)
{
HTC_ENDPOINT_CREDIT_DIST *pCurEpDist;
if (Reason == HTC_CREDIT_DIST_SEND_COMPLETE) {
pCurEpDist = pEPDistList;
/* simple distribution */
while (pCurEpDist != NULL) {
if (pCurEpDist->TxCreditsToDist > 0) {
/* just give the endpoint back the credits */
pCurEpDist->TxCredits += pCurEpDist->TxCreditsToDist;
pCurEpDist->TxCreditsToDist = 0;
}
pCurEpDist = pCurEpDist->pNext;
}
}
/* note we do not need to handle the other reason codes as this is a very
* simple distribution scheme, no need to seek for more credits or handle inactivity */
}
void HTCSetCreditDistribution(HTC_HANDLE HTCHandle,
void *pCreditDistContext,
HTC_CREDIT_DIST_CALLBACK CreditDistFunc,
HTC_CREDIT_INIT_CALLBACK CreditInitFunc,
HTC_SERVICE_ID ServicePriorityOrder[],
int ListLength)
{
HTC_TARGET *target = GET_HTC_TARGET_FROM_HANDLE(HTCHandle);
int i;
int ep;
if (CreditInitFunc != NULL) {
/* caller has supplied their own distribution functions */
target->InitCredits = CreditInitFunc;
AR_DEBUG_ASSERT(CreditDistFunc != NULL);
target->DistributeCredits = CreditDistFunc;
target->pCredDistContext = pCreditDistContext;
} else {
/* caller wants HTC to do distribution */
/* if caller wants service to handle distributions then
* it must set both of these to NULL! */
AR_DEBUG_ASSERT(CreditDistFunc == NULL);
target->InitCredits = HTCDefaultCreditInit;
target->DistributeCredits = HTCDefaultCreditDist;
target->pCredDistContext = target;
}
/* always add HTC control endpoint first, we only expose the list after the
* first one, this is added for TX queue checking */
AddToEndpointDistList(target, &target->EndPoint[ENDPOINT_0].CreditDist);
/* build the list of credit distribution structures in priority order
* supplied by the caller, these will follow endpoint 0 */
for (i = 0; i < ListLength; i++) {
/* match services with endpoints and add the endpoints to the distribution list
* in FIFO order */
for (ep = ENDPOINT_1; ep < ENDPOINT_MAX; ep++) {
if (target->EndPoint[ep].ServiceID == ServicePriorityOrder[i]) {
/* queue this one to the list */
AddToEndpointDistList(target, &target->EndPoint[ep].CreditDist);
break;
}
}
AR_DEBUG_ASSERT(ep < ENDPOINT_MAX);
}
}
| gpl-2.0 |
cminyard/linux-live-app-coredump | net/ipv4/netfilter/nf_tproxy_ipv4.c | 412 | 3862 | // SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) 2007-2008 BalaBit IT Ltd.
* Author: Krisztian Kovacs
*/
#include <net/netfilter/nf_tproxy.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <net/inet_sock.h>
#include <linux/ip.h>
#include <net/checksum.h>
#include <net/udp.h>
#include <net/tcp.h>
#include <linux/inetdevice.h>
struct sock *
nf_tproxy_handle_time_wait4(struct net *net, struct sk_buff *skb,
__be32 laddr, __be16 lport, struct sock *sk)
{
const struct iphdr *iph = ip_hdr(skb);
struct tcphdr _hdr, *hp;
hp = skb_header_pointer(skb, ip_hdrlen(skb), sizeof(_hdr), &_hdr);
if (hp == NULL) {
inet_twsk_put(inet_twsk(sk));
return NULL;
}
if (hp->syn && !hp->rst && !hp->ack && !hp->fin) {
/* SYN to a TIME_WAIT socket, we'd rather redirect it
* to a listener socket if there's one */
struct sock *sk2;
sk2 = nf_tproxy_get_sock_v4(net, skb, iph->protocol,
iph->saddr, laddr ? laddr : iph->daddr,
hp->source, lport ? lport : hp->dest,
skb->dev, NF_TPROXY_LOOKUP_LISTENER);
if (sk2) {
inet_twsk_deschedule_put(inet_twsk(sk));
sk = sk2;
}
}
return sk;
}
EXPORT_SYMBOL_GPL(nf_tproxy_handle_time_wait4);
__be32 nf_tproxy_laddr4(struct sk_buff *skb, __be32 user_laddr, __be32 daddr)
{
const struct in_ifaddr *ifa;
struct in_device *indev;
__be32 laddr;
if (user_laddr)
return user_laddr;
laddr = 0;
indev = __in_dev_get_rcu(skb->dev);
in_dev_for_each_ifa_rcu(ifa, indev) {
if (ifa->ifa_flags & IFA_F_SECONDARY)
continue;
laddr = ifa->ifa_local;
break;
}
return laddr ? laddr : daddr;
}
EXPORT_SYMBOL_GPL(nf_tproxy_laddr4);
struct sock *
nf_tproxy_get_sock_v4(struct net *net, struct sk_buff *skb,
const u8 protocol,
const __be32 saddr, const __be32 daddr,
const __be16 sport, const __be16 dport,
const struct net_device *in,
const enum nf_tproxy_lookup_t lookup_type)
{
struct sock *sk;
switch (protocol) {
case IPPROTO_TCP: {
struct tcphdr _hdr, *hp;
hp = skb_header_pointer(skb, ip_hdrlen(skb),
sizeof(struct tcphdr), &_hdr);
if (hp == NULL)
return NULL;
switch (lookup_type) {
case NF_TPROXY_LOOKUP_LISTENER:
sk = inet_lookup_listener(net, &tcp_hashinfo, skb,
ip_hdrlen(skb) +
__tcp_hdrlen(hp),
saddr, sport,
daddr, dport,
in->ifindex, 0);
if (sk && !refcount_inc_not_zero(&sk->sk_refcnt))
sk = NULL;
/* NOTE: we return listeners even if bound to
* 0.0.0.0, those are filtered out in
* xt_socket, since xt_TPROXY needs 0 bound
* listeners too
*/
break;
case NF_TPROXY_LOOKUP_ESTABLISHED:
sk = inet_lookup_established(net, &tcp_hashinfo,
saddr, sport, daddr, dport,
in->ifindex);
break;
default:
BUG();
}
break;
}
case IPPROTO_UDP:
sk = udp4_lib_lookup(net, saddr, sport, daddr, dport,
in->ifindex);
if (sk) {
int connected = (sk->sk_state == TCP_ESTABLISHED);
int wildcard = (inet_sk(sk)->inet_rcv_saddr == 0);
/* NOTE: we return listeners even if bound to
* 0.0.0.0, those are filtered out in
* xt_socket, since xt_TPROXY needs 0 bound
* listeners too
*/
if ((lookup_type == NF_TPROXY_LOOKUP_ESTABLISHED &&
(!connected || wildcard)) ||
(lookup_type == NF_TPROXY_LOOKUP_LISTENER && connected)) {
sock_put(sk);
sk = NULL;
}
}
break;
default:
WARN_ON(1);
sk = NULL;
}
pr_debug("tproxy socket lookup: proto %u %08x:%u -> %08x:%u, lookup type: %d, sock %p\n",
protocol, ntohl(saddr), ntohs(sport), ntohl(daddr), ntohs(dport), lookup_type, sk);
return sk;
}
EXPORT_SYMBOL_GPL(nf_tproxy_get_sock_v4);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Balazs Scheidler, Krisztian Kovacs");
MODULE_DESCRIPTION("Netfilter IPv4 transparent proxy support");
| gpl-2.0 |
DirtyUnicorns/android_kernel_samsung_tuna | arch/m68k/atari/config.c | 2972 | 18511 | /*
* linux/arch/m68k/atari/config.c
*
* Copyright (C) 1994 Bjoern Brauel
*
* 5/2/94 Roman Hodek:
* Added setting of time_adj to get a better clock.
*
* 5/14/94 Roman Hodek:
* gettod() for TT
*
* 5/15/94 Roman Hodek:
* hard_reset_now() for Atari (and others?)
*
* 94/12/30 Andreas Schwab:
* atari_sched_init fixed to get precise clock.
*
* 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.
*/
/*
* Miscellaneous atari stuff
*/
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/seq_file.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/vt_kern.h>
#include <linux/module.h>
#include <asm/bootinfo.h>
#include <asm/setup.h>
#include <asm/atarihw.h>
#include <asm/atariints.h>
#include <asm/atari_stram.h>
#include <asm/system.h>
#include <asm/machdep.h>
#include <asm/hwtest.h>
#include <asm/io.h>
u_long atari_mch_cookie;
EXPORT_SYMBOL(atari_mch_cookie);
u_long atari_mch_type;
EXPORT_SYMBOL(atari_mch_type);
struct atari_hw_present atari_hw_present;
EXPORT_SYMBOL(atari_hw_present);
u_long atari_switches;
EXPORT_SYMBOL(atari_switches);
int atari_dont_touch_floppy_select;
EXPORT_SYMBOL(atari_dont_touch_floppy_select);
int atari_rtc_year_offset;
/* local function prototypes */
static void atari_reset(void);
static void atari_get_model(char *model);
static void atari_get_hardware_list(struct seq_file *m);
/* atari specific irq functions */
extern void atari_init_IRQ (void);
extern void atari_mksound(unsigned int count, unsigned int ticks);
#ifdef CONFIG_HEARTBEAT
static void atari_heartbeat(int on);
#endif
/* atari specific timer functions (in time.c) */
extern void atari_sched_init(irq_handler_t);
extern unsigned long atari_gettimeoffset (void);
extern int atari_mste_hwclk (int, struct rtc_time *);
extern int atari_tt_hwclk (int, struct rtc_time *);
extern int atari_mste_set_clock_mmss (unsigned long);
extern int atari_tt_set_clock_mmss (unsigned long);
/* ++roman: This is a more elaborate test for an SCC chip, since the plain
* Medusa board generates DTACK at the SCC's standard addresses, but a SCC
* board in the Medusa is possible. Also, the addresses where the ST_ESCC
* resides generate DTACK without the chip, too.
* The method is to write values into the interrupt vector register, that
* should be readable without trouble (from channel A!).
*/
static int __init scc_test(volatile char *ctla)
{
if (!hwreg_present(ctla))
return 0;
MFPDELAY();
*ctla = 2;
MFPDELAY();
*ctla = 0x40;
MFPDELAY();
*ctla = 2;
MFPDELAY();
if (*ctla != 0x40)
return 0;
MFPDELAY();
*ctla = 2;
MFPDELAY();
*ctla = 0x60;
MFPDELAY();
*ctla = 2;
MFPDELAY();
if (*ctla != 0x60)
return 0;
return 1;
}
/*
* Parse an Atari-specific record in the bootinfo
*/
int __init atari_parse_bootinfo(const struct bi_record *record)
{
int unknown = 0;
const u_long *data = record->data;
switch (record->tag) {
case BI_ATARI_MCH_COOKIE:
atari_mch_cookie = *data;
break;
case BI_ATARI_MCH_TYPE:
atari_mch_type = *data;
break;
default:
unknown = 1;
break;
}
return unknown;
}
/* Parse the Atari-specific switches= option. */
static int __init atari_switches_setup(char *str)
{
char switches[strlen(str) + 1];
char *p;
int ovsc_shift;
char *args = switches;
if (!MACH_IS_ATARI)
return 0;
/* copy string to local array, strsep works destructively... */
strcpy(switches, str);
atari_switches = 0;
/* parse the options */
while ((p = strsep(&args, ",")) != NULL) {
if (!*p)
continue;
ovsc_shift = 0;
if (strncmp(p, "ov_", 3) == 0) {
p += 3;
ovsc_shift = ATARI_SWITCH_OVSC_SHIFT;
}
if (strcmp(p, "ikbd") == 0) {
/* RTS line of IKBD ACIA */
atari_switches |= ATARI_SWITCH_IKBD << ovsc_shift;
} else if (strcmp(p, "midi") == 0) {
/* RTS line of MIDI ACIA */
atari_switches |= ATARI_SWITCH_MIDI << ovsc_shift;
} else if (strcmp(p, "snd6") == 0) {
atari_switches |= ATARI_SWITCH_SND6 << ovsc_shift;
} else if (strcmp(p, "snd7") == 0) {
atari_switches |= ATARI_SWITCH_SND7 << ovsc_shift;
}
}
return 0;
}
early_param("switches", atari_switches_setup);
/*
* Setup the Atari configuration info
*/
void __init config_atari(void)
{
unsigned short tos_version;
memset(&atari_hw_present, 0, sizeof(atari_hw_present));
/* Change size of I/O space from 64KB to 4GB. */
ioport_resource.end = 0xFFFFFFFF;
mach_sched_init = atari_sched_init;
mach_init_IRQ = atari_init_IRQ;
mach_get_model = atari_get_model;
mach_get_hardware_list = atari_get_hardware_list;
mach_gettimeoffset = atari_gettimeoffset;
mach_reset = atari_reset;
mach_max_dma_address = 0xffffff;
#if defined(CONFIG_INPUT_M68K_BEEP) || defined(CONFIG_INPUT_M68K_BEEP_MODULE)
mach_beep = atari_mksound;
#endif
#ifdef CONFIG_HEARTBEAT
mach_heartbeat = atari_heartbeat;
#endif
/* Set switches as requested by the user */
if (atari_switches & ATARI_SWITCH_IKBD)
acia.key_ctrl = ACIA_DIV64 | ACIA_D8N1S | ACIA_RHTID;
if (atari_switches & ATARI_SWITCH_MIDI)
acia.mid_ctrl = ACIA_DIV16 | ACIA_D8N1S | ACIA_RHTID;
if (atari_switches & (ATARI_SWITCH_SND6|ATARI_SWITCH_SND7)) {
sound_ym.rd_data_reg_sel = 14;
sound_ym.wd_data = sound_ym.rd_data_reg_sel |
((atari_switches&ATARI_SWITCH_SND6) ? 0x40 : 0) |
((atari_switches&ATARI_SWITCH_SND7) ? 0x80 : 0);
}
/* ++bjoern:
* Determine hardware present
*/
printk("Atari hardware found: ");
if (MACH_IS_MEDUSA) {
/* There's no Atari video hardware on the Medusa, but all the
* addresses below generate a DTACK so no bus error occurs! */
} else if (hwreg_present(f030_xreg)) {
ATARIHW_SET(VIDEL_SHIFTER);
printk("VIDEL ");
/* This is a temporary hack: If there is Falcon video
* hardware, we assume that the ST-DMA serves SCSI instead of
* ACSI. In the future, there should be a better method for
* this...
*/
ATARIHW_SET(ST_SCSI);
printk("STDMA-SCSI ");
} else if (hwreg_present(tt_palette)) {
ATARIHW_SET(TT_SHIFTER);
printk("TT_SHIFTER ");
} else if (hwreg_present(&shifter.bas_hi)) {
if (hwreg_present(&shifter.bas_lo) &&
(shifter.bas_lo = 0x0aau, shifter.bas_lo == 0x0aau)) {
ATARIHW_SET(EXTD_SHIFTER);
printk("EXTD_SHIFTER ");
} else {
ATARIHW_SET(STND_SHIFTER);
printk("STND_SHIFTER ");
}
}
if (hwreg_present(&st_mfp.par_dt_reg)) {
ATARIHW_SET(ST_MFP);
printk("ST_MFP ");
}
if (hwreg_present(&tt_mfp.par_dt_reg)) {
ATARIHW_SET(TT_MFP);
printk("TT_MFP ");
}
if (hwreg_present(&tt_scsi_dma.dma_addr_hi)) {
ATARIHW_SET(SCSI_DMA);
printk("TT_SCSI_DMA ");
}
/*
* The ST-DMA address registers aren't readable
* on all Medusas, so the test below may fail
*/
if (MACH_IS_MEDUSA ||
(hwreg_present(&st_dma.dma_vhi) &&
(st_dma.dma_vhi = 0x55) && (st_dma.dma_hi = 0xaa) &&
st_dma.dma_vhi == 0x55 && st_dma.dma_hi == 0xaa &&
(st_dma.dma_vhi = 0xaa) && (st_dma.dma_hi = 0x55) &&
st_dma.dma_vhi == 0xaa && st_dma.dma_hi == 0x55)) {
ATARIHW_SET(EXTD_DMA);
printk("EXTD_DMA ");
}
if (hwreg_present(&tt_scsi.scsi_data)) {
ATARIHW_SET(TT_SCSI);
printk("TT_SCSI ");
}
if (hwreg_present(&sound_ym.rd_data_reg_sel)) {
ATARIHW_SET(YM_2149);
printk("YM2149 ");
}
if (!MACH_IS_MEDUSA && hwreg_present(&tt_dmasnd.ctrl)) {
ATARIHW_SET(PCM_8BIT);
printk("PCM ");
}
if (hwreg_present(&falcon_codec.unused5)) {
ATARIHW_SET(CODEC);
printk("CODEC ");
}
if (hwreg_present(&dsp56k_host_interface.icr)) {
ATARIHW_SET(DSP56K);
printk("DSP56K ");
}
if (hwreg_present(&tt_scc_dma.dma_ctrl) &&
#if 0
/* This test sucks! Who knows some better? */
(tt_scc_dma.dma_ctrl = 0x01, (tt_scc_dma.dma_ctrl & 1) == 1) &&
(tt_scc_dma.dma_ctrl = 0x00, (tt_scc_dma.dma_ctrl & 1) == 0)
#else
!MACH_IS_MEDUSA
#endif
) {
ATARIHW_SET(SCC_DMA);
printk("SCC_DMA ");
}
if (scc_test(&atari_scc.cha_a_ctrl)) {
ATARIHW_SET(SCC);
printk("SCC ");
}
if (scc_test(&st_escc.cha_b_ctrl)) {
ATARIHW_SET(ST_ESCC);
printk("ST_ESCC ");
}
if (hwreg_present(&tt_scu.sys_mask)) {
ATARIHW_SET(SCU);
/* Assume a VME bus if there's a SCU */
ATARIHW_SET(VME);
printk("VME SCU ");
}
if (hwreg_present((void *)(0xffff9210))) {
ATARIHW_SET(ANALOG_JOY);
printk("ANALOG_JOY ");
}
if (hwreg_present(blitter.halftone)) {
ATARIHW_SET(BLITTER);
printk("BLITTER ");
}
if (hwreg_present((void *)0xfff00039)) {
ATARIHW_SET(IDE);
printk("IDE ");
}
#if 1 /* This maybe wrong */
if (!MACH_IS_MEDUSA && hwreg_present(&tt_microwire.data) &&
hwreg_present(&tt_microwire.mask) &&
(tt_microwire.mask = 0x7ff,
udelay(1),
tt_microwire.data = MW_LM1992_PSG_HIGH | MW_LM1992_ADDR,
udelay(1),
tt_microwire.data != 0)) {
ATARIHW_SET(MICROWIRE);
while (tt_microwire.mask != 0x7ff)
;
printk("MICROWIRE ");
}
#endif
if (hwreg_present(&tt_rtc.regsel)) {
ATARIHW_SET(TT_CLK);
printk("TT_CLK ");
mach_hwclk = atari_tt_hwclk;
mach_set_clock_mmss = atari_tt_set_clock_mmss;
}
if (hwreg_present(&mste_rtc.sec_ones)) {
ATARIHW_SET(MSTE_CLK);
printk("MSTE_CLK ");
mach_hwclk = atari_mste_hwclk;
mach_set_clock_mmss = atari_mste_set_clock_mmss;
}
if (!MACH_IS_MEDUSA && hwreg_present(&dma_wd.fdc_speed) &&
hwreg_write(&dma_wd.fdc_speed, 0)) {
ATARIHW_SET(FDCSPEED);
printk("FDC_SPEED ");
}
if (!ATARIHW_PRESENT(ST_SCSI)) {
ATARIHW_SET(ACSI);
printk("ACSI ");
}
printk("\n");
if (CPU_IS_040_OR_060)
/* Now it seems to be safe to turn of the tt0 transparent
* translation (the one that must not be turned off in
* head.S...)
*/
asm volatile ("\n"
" moveq #0,%%d0\n"
" .chip 68040\n"
" movec %%d0,%%itt0\n"
" movec %%d0,%%dtt0\n"
" .chip 68k"
: /* no outputs */
: /* no inputs */
: "d0");
/* allocator for memory that must reside in st-ram */
atari_stram_init();
/* Set up a mapping for the VMEbus address region:
*
* VME is either at phys. 0xfexxxxxx (TT) or 0xa00000..0xdfffff
* (MegaSTE) In both cases, the whole 16 MB chunk is mapped at
* 0xfe000000 virt., because this can be done with a single
* transparent translation. On the 68040, lots of often unused
* page tables would be needed otherwise. On a MegaSTE or similar,
* the highest byte is stripped off by hardware due to the 24 bit
* design of the bus.
*/
if (CPU_IS_020_OR_030) {
unsigned long tt1_val;
tt1_val = 0xfe008543; /* Translate 0xfexxxxxx, enable, cache
* inhibit, read and write, FDC mask = 3,
* FDC val = 4 -> Supervisor only */
asm volatile ("\n"
" .chip 68030\n"
" pmove %0@,%/tt1\n"
" .chip 68k"
: : "a" (&tt1_val));
} else {
asm volatile ("\n"
" .chip 68040\n"
" movec %0,%%itt1\n"
" movec %0,%%dtt1\n"
" .chip 68k"
:
: "d" (0xfe00a040)); /* Translate 0xfexxxxxx, enable,
* supervisor only, non-cacheable/
* serialized, writable */
}
/* Fetch tos version at Physical 2 */
/*
* We my not be able to access this address if the kernel is
* loaded to st ram, since the first page is unmapped. On the
* Medusa this is always the case and there is nothing we can do
* about this, so we just assume the smaller offset. For the TT
* we use the fact that in head.S we have set up a mapping
* 0xFFxxxxxx -> 0x00xxxxxx, so that the first 16MB is accessible
* in the last 16MB of the address space.
*/
tos_version = (MACH_IS_MEDUSA) ?
0xfff : *(unsigned short *)0xff000002;
atari_rtc_year_offset = (tos_version < 0x306) ? 70 : 68;
}
#ifdef CONFIG_HEARTBEAT
static void atari_heartbeat(int on)
{
unsigned char tmp;
unsigned long flags;
if (atari_dont_touch_floppy_select)
return;
local_irq_save(flags);
sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
tmp = sound_ym.rd_data_reg_sel;
sound_ym.wd_data = on ? (tmp & ~0x02) : (tmp | 0x02);
local_irq_restore(flags);
}
#endif
/* ++roman:
*
* This function does a reset on machines that lack the ability to
* assert the processor's _RESET signal somehow via hardware. It is
* based on the fact that you can find the initial SP and PC values
* after a reset at physical addresses 0 and 4. This works pretty well
* for Atari machines, since the lowest 8 bytes of physical memory are
* really ROM (mapped by hardware). For other 680x0 machines: don't
* know if it works...
*
* To get the values at addresses 0 and 4, the MMU better is turned
* off first. After that, we have to jump into physical address space
* (the PC before the pmove statement points to the virtual address of
* the code). Getting that physical address is not hard, but the code
* becomes a bit complex since I've tried to ensure that the jump
* statement after the pmove is in the cache already (otherwise the
* processor can't fetch it!). For that, the code first jumps to the
* jump statement with the (virtual) address of the pmove section in
* an address register . The jump statement is surely in the cache
* now. After that, that physical address of the reset code is loaded
* into the same address register, pmove is done and the same jump
* statements goes to the reset code. Since there are not many
* statements between the two jumps, I hope it stays in the cache.
*
* The C code makes heavy use of the GCC features that you can get the
* address of a C label. No hope to compile this with another compiler
* than GCC!
*/
/* ++andreas: no need for complicated code, just depend on prefetch */
static void atari_reset(void)
{
long tc_val = 0;
long reset_addr;
/*
* On the Medusa, phys. 0x4 may contain garbage because it's no
* ROM. See above for explanation why we cannot use PTOV(4).
*/
reset_addr = MACH_IS_MEDUSA || MACH_IS_AB40 ? 0xe00030 :
*(unsigned long *) 0xff000004;
/* reset ACIA for switch off OverScan, if it's active */
if (atari_switches & ATARI_SWITCH_OVSC_IKBD)
acia.key_ctrl = ACIA_RESET;
if (atari_switches & ATARI_SWITCH_OVSC_MIDI)
acia.mid_ctrl = ACIA_RESET;
/* processor independent: turn off interrupts and reset the VBR;
* the caches must be left enabled, else prefetching the final jump
* instruction doesn't work.
*/
local_irq_disable();
asm volatile ("movec %0,%%vbr"
: : "d" (0));
if (CPU_IS_040_OR_060) {
unsigned long jmp_addr040 = virt_to_phys(&&jmp_addr_label040);
if (CPU_IS_060) {
/* 68060: clear PCR to turn off superscalar operation */
asm volatile ("\n"
" .chip 68060\n"
" movec %0,%%pcr\n"
" .chip 68k"
: : "d" (0));
}
asm volatile ("\n"
" move.l %0,%%d0\n"
" and.l #0xff000000,%%d0\n"
" or.w #0xe020,%%d0\n" /* map 16 MB, enable, cacheable */
" .chip 68040\n"
" movec %%d0,%%itt0\n"
" movec %%d0,%%dtt0\n"
" .chip 68k\n"
" jmp %0@"
: : "a" (jmp_addr040)
: "d0");
jmp_addr_label040:
asm volatile ("\n"
" moveq #0,%%d0\n"
" nop\n"
" .chip 68040\n"
" cinva %%bc\n"
" nop\n"
" pflusha\n"
" nop\n"
" movec %%d0,%%tc\n"
" nop\n"
/* the following setup of transparent translations is needed on the
* Afterburner040 to successfully reboot. Other machines shouldn't
* care about a different tt regs setup, they also didn't care in
* the past that the regs weren't turned off. */
" move.l #0xffc000,%%d0\n" /* whole insn space cacheable */
" movec %%d0,%%itt0\n"
" movec %%d0,%%itt1\n"
" or.w #0x40,%/d0\n" /* whole data space non-cacheable/ser. */
" movec %%d0,%%dtt0\n"
" movec %%d0,%%dtt1\n"
" .chip 68k\n"
" jmp %0@"
: /* no outputs */
: "a" (reset_addr)
: "d0");
} else
asm volatile ("\n"
" pmove %0@,%%tc\n"
" jmp %1@"
: /* no outputs */
: "a" (&tc_val), "a" (reset_addr));
}
static void atari_get_model(char *model)
{
strcpy(model, "Atari ");
switch (atari_mch_cookie >> 16) {
case ATARI_MCH_ST:
if (ATARIHW_PRESENT(MSTE_CLK))
strcat(model, "Mega ST");
else
strcat(model, "ST");
break;
case ATARI_MCH_STE:
if (MACH_IS_MSTE)
strcat(model, "Mega STE");
else
strcat(model, "STE");
break;
case ATARI_MCH_TT:
if (MACH_IS_MEDUSA)
/* Medusa has TT _MCH cookie */
strcat(model, "Medusa");
else
strcat(model, "TT");
break;
case ATARI_MCH_FALCON:
strcat(model, "Falcon");
if (MACH_IS_AB40)
strcat(model, " (with Afterburner040)");
break;
default:
sprintf(model + strlen(model), "(unknown mach cookie 0x%lx)",
atari_mch_cookie);
break;
}
}
static void atari_get_hardware_list(struct seq_file *m)
{
int i;
for (i = 0; i < m68k_num_memory; i++)
seq_printf(m, "\t%3ld MB at 0x%08lx (%s)\n",
m68k_memory[i].size >> 20, m68k_memory[i].addr,
(m68k_memory[i].addr & 0xff000000 ?
"alternate RAM" : "ST-RAM"));
#define ATARIHW_ANNOUNCE(name, str) \
if (ATARIHW_PRESENT(name)) \
seq_printf(m, "\t%s\n", str)
seq_printf(m, "Detected hardware:\n");
ATARIHW_ANNOUNCE(STND_SHIFTER, "ST Shifter");
ATARIHW_ANNOUNCE(EXTD_SHIFTER, "STe Shifter");
ATARIHW_ANNOUNCE(TT_SHIFTER, "TT Shifter");
ATARIHW_ANNOUNCE(VIDEL_SHIFTER, "Falcon Shifter");
ATARIHW_ANNOUNCE(YM_2149, "Programmable Sound Generator");
ATARIHW_ANNOUNCE(PCM_8BIT, "PCM 8 Bit Sound");
ATARIHW_ANNOUNCE(CODEC, "CODEC Sound");
ATARIHW_ANNOUNCE(TT_SCSI, "SCSI Controller NCR5380 (TT style)");
ATARIHW_ANNOUNCE(ST_SCSI, "SCSI Controller NCR5380 (Falcon style)");
ATARIHW_ANNOUNCE(ACSI, "ACSI Interface");
ATARIHW_ANNOUNCE(IDE, "IDE Interface");
ATARIHW_ANNOUNCE(FDCSPEED, "8/16 Mhz Switch for FDC");
ATARIHW_ANNOUNCE(ST_MFP, "Multi Function Peripheral MFP 68901");
ATARIHW_ANNOUNCE(TT_MFP, "Second Multi Function Peripheral MFP 68901");
ATARIHW_ANNOUNCE(SCC, "Serial Communications Controller SCC 8530");
ATARIHW_ANNOUNCE(ST_ESCC, "Extended Serial Communications Controller SCC 85230");
ATARIHW_ANNOUNCE(ANALOG_JOY, "Paddle Interface");
ATARIHW_ANNOUNCE(MICROWIRE, "MICROWIRE(tm) Interface");
ATARIHW_ANNOUNCE(STND_DMA, "DMA Controller (24 bit)");
ATARIHW_ANNOUNCE(EXTD_DMA, "DMA Controller (32 bit)");
ATARIHW_ANNOUNCE(SCSI_DMA, "DMA Controller for NCR5380");
ATARIHW_ANNOUNCE(SCC_DMA, "DMA Controller for SCC");
ATARIHW_ANNOUNCE(TT_CLK, "Clock Chip MC146818A");
ATARIHW_ANNOUNCE(MSTE_CLK, "Clock Chip RP5C15");
ATARIHW_ANNOUNCE(SCU, "System Control Unit");
ATARIHW_ANNOUNCE(BLITTER, "Blitter");
ATARIHW_ANNOUNCE(VME, "VME Bus");
ATARIHW_ANNOUNCE(DSP56K, "DSP56001 processor");
}
| gpl-2.0 |
EPDCenterSpain/bq-DC-v1 | drivers/net/fsl_pq_mdio.c | 2972 | 11718 | /*
* Freescale PowerQUICC Ethernet Driver -- MIIM bus implementation
* Provides Bus interface for MIIM regs
*
* Author: Andy Fleming <afleming@freescale.com>
* Modifier: Sandeep Gopalpet <sandeep.kumar@freescale.com>
*
* Copyright 2002-2004, 2008-2009 Freescale Semiconductor, Inc.
*
* Based on gianfar_mii.c and ucc_geth_mii.c (Li Yang, Kim Phillips)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/unistd.h>
#include <linux/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/mm.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/crc32.h>
#include <linux/mii.h>
#include <linux/phy.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_mdio.h>
#include <linux/of_platform.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <asm/ucc.h>
#include "gianfar.h"
#include "fsl_pq_mdio.h"
struct fsl_pq_mdio_priv {
void __iomem *map;
struct fsl_pq_mdio __iomem *regs;
};
/*
* Write value to the PHY at mii_id at register regnum,
* on the bus attached to the local interface, which may be different from the
* generic mdio bus (tied to a single interface), waiting until the write is
* done before returning. This is helpful in programming interfaces like
* the TBI which control interfaces like onchip SERDES and are always tied to
* the local mdio pins, which may not be the same as system mdio bus, used for
* controlling the external PHYs, for example.
*/
int fsl_pq_local_mdio_write(struct fsl_pq_mdio __iomem *regs, int mii_id,
int regnum, u16 value)
{
/* Set the PHY address and the register address we want to write */
out_be32(®s->miimadd, (mii_id << 8) | regnum);
/* Write out the value we want */
out_be32(®s->miimcon, value);
/* Wait for the transaction to finish */
while (in_be32(®s->miimind) & MIIMIND_BUSY)
cpu_relax();
return 0;
}
/*
* Read the bus for PHY at addr mii_id, register regnum, and
* return the value. Clears miimcom first. All PHY operation
* done on the bus attached to the local interface,
* which may be different from the generic mdio bus
* This is helpful in programming interfaces like
* the TBI which, in turn, control interfaces like onchip SERDES
* and are always tied to the local mdio pins, which may not be the
* same as system mdio bus, used for controlling the external PHYs, for eg.
*/
int fsl_pq_local_mdio_read(struct fsl_pq_mdio __iomem *regs,
int mii_id, int regnum)
{
u16 value;
/* Set the PHY address and the register address we want to read */
out_be32(®s->miimadd, (mii_id << 8) | regnum);
/* Clear miimcom, and then initiate a read */
out_be32(®s->miimcom, 0);
out_be32(®s->miimcom, MII_READ_COMMAND);
/* Wait for the transaction to finish */
while (in_be32(®s->miimind) & (MIIMIND_NOTVALID | MIIMIND_BUSY))
cpu_relax();
/* Grab the value of the register from miimstat */
value = in_be32(®s->miimstat);
return value;
}
static struct fsl_pq_mdio __iomem *fsl_pq_mdio_get_regs(struct mii_bus *bus)
{
struct fsl_pq_mdio_priv *priv = bus->priv;
return priv->regs;
}
/*
* Write value to the PHY at mii_id at register regnum,
* on the bus, waiting until the write is done before returning.
*/
int fsl_pq_mdio_write(struct mii_bus *bus, int mii_id, int regnum, u16 value)
{
struct fsl_pq_mdio __iomem *regs = fsl_pq_mdio_get_regs(bus);
/* Write to the local MII regs */
return fsl_pq_local_mdio_write(regs, mii_id, regnum, value);
}
/*
* Read the bus for PHY at addr mii_id, register regnum, and
* return the value. Clears miimcom first.
*/
int fsl_pq_mdio_read(struct mii_bus *bus, int mii_id, int regnum)
{
struct fsl_pq_mdio __iomem *regs = fsl_pq_mdio_get_regs(bus);
/* Read the local MII regs */
return fsl_pq_local_mdio_read(regs, mii_id, regnum);
}
/* Reset the MIIM registers, and wait for the bus to free */
static int fsl_pq_mdio_reset(struct mii_bus *bus)
{
struct fsl_pq_mdio __iomem *regs = fsl_pq_mdio_get_regs(bus);
int timeout = PHY_INIT_TIMEOUT;
mutex_lock(&bus->mdio_lock);
/* Reset the management interface */
out_be32(®s->miimcfg, MIIMCFG_RESET);
/* Setup the MII Mgmt clock speed */
out_be32(®s->miimcfg, MIIMCFG_INIT_VALUE);
/* Wait until the bus is free */
while ((in_be32(®s->miimind) & MIIMIND_BUSY) && timeout--)
cpu_relax();
mutex_unlock(&bus->mdio_lock);
if (timeout < 0) {
printk(KERN_ERR "%s: The MII Bus is stuck!\n",
bus->name);
return -EBUSY;
}
return 0;
}
void fsl_pq_mdio_bus_name(char *name, struct device_node *np)
{
const u32 *addr;
u64 taddr = OF_BAD_ADDR;
addr = of_get_address(np, 0, NULL, NULL);
if (addr)
taddr = of_translate_address(np, addr);
snprintf(name, MII_BUS_ID_SIZE, "%s@%llx", np->name,
(unsigned long long)taddr);
}
EXPORT_SYMBOL_GPL(fsl_pq_mdio_bus_name);
/* Scan the bus in reverse, looking for an empty spot */
static int fsl_pq_mdio_find_free(struct mii_bus *new_bus)
{
int i;
for (i = PHY_MAX_ADDR; i > 0; i--) {
u32 phy_id;
if (get_phy_id(new_bus, i, &phy_id))
return -1;
if (phy_id == 0xffffffff)
break;
}
return i;
}
#if defined(CONFIG_GIANFAR) || defined(CONFIG_GIANFAR_MODULE)
static u32 __iomem *get_gfar_tbipa(struct fsl_pq_mdio __iomem *regs, struct device_node *np)
{
struct gfar __iomem *enet_regs;
/*
* This is mildly evil, but so is our hardware for doing this.
* Also, we have to cast back to struct gfar because of
* definition weirdness done in gianfar.h.
*/
if(of_device_is_compatible(np, "fsl,gianfar-mdio") ||
of_device_is_compatible(np, "fsl,gianfar-tbi") ||
of_device_is_compatible(np, "gianfar")) {
enet_regs = (struct gfar __iomem *)regs;
return &enet_regs->tbipa;
} else if (of_device_is_compatible(np, "fsl,etsec2-mdio") ||
of_device_is_compatible(np, "fsl,etsec2-tbi")) {
return of_iomap(np, 1);
} else
return NULL;
}
#endif
#if defined(CONFIG_UCC_GETH) || defined(CONFIG_UCC_GETH_MODULE)
static int get_ucc_id_for_range(u64 start, u64 end, u32 *ucc_id)
{
struct device_node *np = NULL;
int err = 0;
for_each_compatible_node(np, NULL, "ucc_geth") {
struct resource tempres;
err = of_address_to_resource(np, 0, &tempres);
if (err)
continue;
/* if our mdio regs fall within this UCC regs range */
if ((start >= tempres.start) && (end <= tempres.end)) {
/* Find the id of the UCC */
const u32 *id;
id = of_get_property(np, "cell-index", NULL);
if (!id) {
id = of_get_property(np, "device-id", NULL);
if (!id)
continue;
}
*ucc_id = *id;
return 0;
}
}
if (err)
return err;
else
return -EINVAL;
}
#endif
static int fsl_pq_mdio_probe(struct platform_device *ofdev)
{
struct device_node *np = ofdev->dev.of_node;
struct device_node *tbi;
struct fsl_pq_mdio_priv *priv;
struct fsl_pq_mdio __iomem *regs = NULL;
void __iomem *map;
u32 __iomem *tbipa;
struct mii_bus *new_bus;
int tbiaddr = -1;
const u32 *addrp;
u64 addr = 0, size = 0;
int err;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
new_bus = mdiobus_alloc();
if (!new_bus) {
err = -ENOMEM;
goto err_free_priv;
}
new_bus->name = "Freescale PowerQUICC MII Bus",
new_bus->read = &fsl_pq_mdio_read,
new_bus->write = &fsl_pq_mdio_write,
new_bus->reset = &fsl_pq_mdio_reset,
new_bus->priv = priv;
fsl_pq_mdio_bus_name(new_bus->id, np);
addrp = of_get_address(np, 0, &size, NULL);
if (!addrp) {
err = -EINVAL;
goto err_free_bus;
}
/* Set the PHY base address */
addr = of_translate_address(np, addrp);
if (addr == OF_BAD_ADDR) {
err = -EINVAL;
goto err_free_bus;
}
map = ioremap(addr, size);
if (!map) {
err = -ENOMEM;
goto err_free_bus;
}
priv->map = map;
if (of_device_is_compatible(np, "fsl,gianfar-mdio") ||
of_device_is_compatible(np, "fsl,gianfar-tbi") ||
of_device_is_compatible(np, "fsl,ucc-mdio") ||
of_device_is_compatible(np, "ucc_geth_phy"))
map -= offsetof(struct fsl_pq_mdio, miimcfg);
regs = map;
priv->regs = regs;
new_bus->irq = kcalloc(PHY_MAX_ADDR, sizeof(int), GFP_KERNEL);
if (NULL == new_bus->irq) {
err = -ENOMEM;
goto err_unmap_regs;
}
new_bus->parent = &ofdev->dev;
dev_set_drvdata(&ofdev->dev, new_bus);
if (of_device_is_compatible(np, "fsl,gianfar-mdio") ||
of_device_is_compatible(np, "fsl,gianfar-tbi") ||
of_device_is_compatible(np, "fsl,etsec2-mdio") ||
of_device_is_compatible(np, "fsl,etsec2-tbi") ||
of_device_is_compatible(np, "gianfar")) {
#if defined(CONFIG_GIANFAR) || defined(CONFIG_GIANFAR_MODULE)
tbipa = get_gfar_tbipa(regs, np);
if (!tbipa) {
err = -EINVAL;
goto err_free_irqs;
}
#else
err = -ENODEV;
goto err_free_irqs;
#endif
} else if (of_device_is_compatible(np, "fsl,ucc-mdio") ||
of_device_is_compatible(np, "ucc_geth_phy")) {
#if defined(CONFIG_UCC_GETH) || defined(CONFIG_UCC_GETH_MODULE)
u32 id;
static u32 mii_mng_master;
tbipa = ®s->utbipar;
if ((err = get_ucc_id_for_range(addr, addr + size, &id)))
goto err_free_irqs;
if (!mii_mng_master) {
mii_mng_master = id;
ucc_set_qe_mux_mii_mng(id - 1);
}
#else
err = -ENODEV;
goto err_free_irqs;
#endif
} else {
err = -ENODEV;
goto err_free_irqs;
}
for_each_child_of_node(np, tbi) {
if (!strncmp(tbi->type, "tbi-phy", 8))
break;
}
if (tbi) {
const u32 *prop = of_get_property(tbi, "reg", NULL);
if (prop)
tbiaddr = *prop;
}
if (tbiaddr == -1) {
out_be32(tbipa, 0);
tbiaddr = fsl_pq_mdio_find_free(new_bus);
}
/*
* We define TBIPA at 0 to be illegal, opting to fail for boards that
* have PHYs at 1-31, rather than change tbipa and rescan.
*/
if (tbiaddr == 0) {
err = -EBUSY;
goto err_free_irqs;
}
out_be32(tbipa, tbiaddr);
err = of_mdiobus_register(new_bus, np);
if (err) {
printk (KERN_ERR "%s: Cannot register as MDIO bus\n",
new_bus->name);
goto err_free_irqs;
}
return 0;
err_free_irqs:
kfree(new_bus->irq);
err_unmap_regs:
iounmap(priv->map);
err_free_bus:
kfree(new_bus);
err_free_priv:
kfree(priv);
return err;
}
static int fsl_pq_mdio_remove(struct platform_device *ofdev)
{
struct device *device = &ofdev->dev;
struct mii_bus *bus = dev_get_drvdata(device);
struct fsl_pq_mdio_priv *priv = bus->priv;
mdiobus_unregister(bus);
dev_set_drvdata(device, NULL);
iounmap(priv->map);
bus->priv = NULL;
mdiobus_free(bus);
kfree(priv);
return 0;
}
static struct of_device_id fsl_pq_mdio_match[] = {
{
.type = "mdio",
.compatible = "ucc_geth_phy",
},
{
.type = "mdio",
.compatible = "gianfar",
},
{
.compatible = "fsl,ucc-mdio",
},
{
.compatible = "fsl,gianfar-tbi",
},
{
.compatible = "fsl,gianfar-mdio",
},
{
.compatible = "fsl,etsec2-tbi",
},
{
.compatible = "fsl,etsec2-mdio",
},
{},
};
MODULE_DEVICE_TABLE(of, fsl_pq_mdio_match);
static struct platform_driver fsl_pq_mdio_driver = {
.driver = {
.name = "fsl-pq_mdio",
.owner = THIS_MODULE,
.of_match_table = fsl_pq_mdio_match,
},
.probe = fsl_pq_mdio_probe,
.remove = fsl_pq_mdio_remove,
};
int __init fsl_pq_mdio_init(void)
{
return platform_driver_register(&fsl_pq_mdio_driver);
}
module_init(fsl_pq_mdio_init);
void fsl_pq_mdio_exit(void)
{
platform_driver_unregister(&fsl_pq_mdio_driver);
}
module_exit(fsl_pq_mdio_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
sloanyang/android_kernel_zte_u950 | arch/sh/kernel/hw_breakpoint.c | 3996 | 8797 | /*
* arch/sh/kernel/hw_breakpoint.c
*
* Unified kernel/user-space hardware breakpoint facility for the on-chip UBC.
*
* Copyright (C) 2009 - 2010 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/perf_event.h>
#include <linux/hw_breakpoint.h>
#include <linux/percpu.h>
#include <linux/kallsyms.h>
#include <linux/notifier.h>
#include <linux/kprobes.h>
#include <linux/kdebug.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <asm/hw_breakpoint.h>
#include <asm/mmu_context.h>
#include <asm/ptrace.h>
/*
* Stores the breakpoints currently in use on each breakpoint address
* register for each cpus
*/
static DEFINE_PER_CPU(struct perf_event *, bp_per_reg[HBP_NUM]);
/*
* A dummy placeholder for early accesses until the CPUs get a chance to
* register their UBCs later in the boot process.
*/
static struct sh_ubc ubc_dummy = { .num_events = 0 };
static struct sh_ubc *sh_ubc __read_mostly = &ubc_dummy;
/*
* Install a perf counter breakpoint.
*
* We seek a free UBC channel and use it for this breakpoint.
*
* Atomic: we hold the counter->ctx->lock and we only handle variables
* and registers local to this cpu.
*/
int arch_install_hw_breakpoint(struct perf_event *bp)
{
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
int i;
for (i = 0; i < sh_ubc->num_events; i++) {
struct perf_event **slot = &__get_cpu_var(bp_per_reg[i]);
if (!*slot) {
*slot = bp;
break;
}
}
if (WARN_ONCE(i == sh_ubc->num_events, "Can't find any breakpoint slot"))
return -EBUSY;
clk_enable(sh_ubc->clk);
sh_ubc->enable(info, i);
return 0;
}
/*
* Uninstall the breakpoint contained in the given counter.
*
* First we search the debug address register it uses and then we disable
* it.
*
* Atomic: we hold the counter->ctx->lock and we only handle variables
* and registers local to this cpu.
*/
void arch_uninstall_hw_breakpoint(struct perf_event *bp)
{
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
int i;
for (i = 0; i < sh_ubc->num_events; i++) {
struct perf_event **slot = &__get_cpu_var(bp_per_reg[i]);
if (*slot == bp) {
*slot = NULL;
break;
}
}
if (WARN_ONCE(i == sh_ubc->num_events, "Can't find any breakpoint slot"))
return;
sh_ubc->disable(info, i);
clk_disable(sh_ubc->clk);
}
static int get_hbp_len(u16 hbp_len)
{
unsigned int len_in_bytes = 0;
switch (hbp_len) {
case SH_BREAKPOINT_LEN_1:
len_in_bytes = 1;
break;
case SH_BREAKPOINT_LEN_2:
len_in_bytes = 2;
break;
case SH_BREAKPOINT_LEN_4:
len_in_bytes = 4;
break;
case SH_BREAKPOINT_LEN_8:
len_in_bytes = 8;
break;
}
return len_in_bytes;
}
/*
* Check for virtual address in kernel space.
*/
int arch_check_bp_in_kernelspace(struct perf_event *bp)
{
unsigned int len;
unsigned long va;
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
va = info->address;
len = get_hbp_len(info->len);
return (va >= TASK_SIZE) && ((va + len - 1) >= TASK_SIZE);
}
int arch_bp_generic_fields(int sh_len, int sh_type,
int *gen_len, int *gen_type)
{
/* Len */
switch (sh_len) {
case SH_BREAKPOINT_LEN_1:
*gen_len = HW_BREAKPOINT_LEN_1;
break;
case SH_BREAKPOINT_LEN_2:
*gen_len = HW_BREAKPOINT_LEN_2;
break;
case SH_BREAKPOINT_LEN_4:
*gen_len = HW_BREAKPOINT_LEN_4;
break;
case SH_BREAKPOINT_LEN_8:
*gen_len = HW_BREAKPOINT_LEN_8;
break;
default:
return -EINVAL;
}
/* Type */
switch (sh_type) {
case SH_BREAKPOINT_READ:
*gen_type = HW_BREAKPOINT_R;
case SH_BREAKPOINT_WRITE:
*gen_type = HW_BREAKPOINT_W;
break;
case SH_BREAKPOINT_RW:
*gen_type = HW_BREAKPOINT_W | HW_BREAKPOINT_R;
break;
default:
return -EINVAL;
}
return 0;
}
static int arch_build_bp_info(struct perf_event *bp)
{
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
info->address = bp->attr.bp_addr;
/* Len */
switch (bp->attr.bp_len) {
case HW_BREAKPOINT_LEN_1:
info->len = SH_BREAKPOINT_LEN_1;
break;
case HW_BREAKPOINT_LEN_2:
info->len = SH_BREAKPOINT_LEN_2;
break;
case HW_BREAKPOINT_LEN_4:
info->len = SH_BREAKPOINT_LEN_4;
break;
case HW_BREAKPOINT_LEN_8:
info->len = SH_BREAKPOINT_LEN_8;
break;
default:
return -EINVAL;
}
/* Type */
switch (bp->attr.bp_type) {
case HW_BREAKPOINT_R:
info->type = SH_BREAKPOINT_READ;
break;
case HW_BREAKPOINT_W:
info->type = SH_BREAKPOINT_WRITE;
break;
case HW_BREAKPOINT_W | HW_BREAKPOINT_R:
info->type = SH_BREAKPOINT_RW;
break;
default:
return -EINVAL;
}
return 0;
}
/*
* Validate the arch-specific HW Breakpoint register settings
*/
int arch_validate_hwbkpt_settings(struct perf_event *bp)
{
struct arch_hw_breakpoint *info = counter_arch_bp(bp);
unsigned int align;
int ret;
ret = arch_build_bp_info(bp);
if (ret)
return ret;
ret = -EINVAL;
switch (info->len) {
case SH_BREAKPOINT_LEN_1:
align = 0;
break;
case SH_BREAKPOINT_LEN_2:
align = 1;
break;
case SH_BREAKPOINT_LEN_4:
align = 3;
break;
case SH_BREAKPOINT_LEN_8:
align = 7;
break;
default:
return ret;
}
/*
* For kernel-addresses, either the address or symbol name can be
* specified.
*/
if (info->name)
info->address = (unsigned long)kallsyms_lookup_name(info->name);
/*
* Check that the low-order bits of the address are appropriate
* for the alignment implied by len.
*/
if (info->address & align)
return -EINVAL;
return 0;
}
/*
* Release the user breakpoints used by ptrace
*/
void flush_ptrace_hw_breakpoint(struct task_struct *tsk)
{
int i;
struct thread_struct *t = &tsk->thread;
for (i = 0; i < sh_ubc->num_events; i++) {
unregister_hw_breakpoint(t->ptrace_bps[i]);
t->ptrace_bps[i] = NULL;
}
}
static int __kprobes hw_breakpoint_handler(struct die_args *args)
{
int cpu, i, rc = NOTIFY_STOP;
struct perf_event *bp;
unsigned int cmf, resume_mask;
/*
* Do an early return if none of the channels triggered.
*/
cmf = sh_ubc->triggered_mask();
if (unlikely(!cmf))
return NOTIFY_DONE;
/*
* By default, resume all of the active channels.
*/
resume_mask = sh_ubc->active_mask();
/*
* Disable breakpoints during exception handling.
*/
sh_ubc->disable_all();
cpu = get_cpu();
for (i = 0; i < sh_ubc->num_events; i++) {
unsigned long event_mask = (1 << i);
if (likely(!(cmf & event_mask)))
continue;
/*
* The counter may be concurrently released but that can only
* occur from a call_rcu() path. We can then safely fetch
* the breakpoint, use its callback, touch its counter
* while we are in an rcu_read_lock() path.
*/
rcu_read_lock();
bp = per_cpu(bp_per_reg[i], cpu);
if (bp)
rc = NOTIFY_DONE;
/*
* Reset the condition match flag to denote completion of
* exception handling.
*/
sh_ubc->clear_triggered_mask(event_mask);
/*
* bp can be NULL due to concurrent perf counter
* removing.
*/
if (!bp) {
rcu_read_unlock();
break;
}
/*
* Don't restore the channel if the breakpoint is from
* ptrace, as it always operates in one-shot mode.
*/
if (bp->overflow_handler == ptrace_triggered)
resume_mask &= ~(1 << i);
perf_bp_event(bp, args->regs);
/* Deliver the signal to userspace */
if (!arch_check_bp_in_kernelspace(bp)) {
siginfo_t info;
info.si_signo = args->signr;
info.si_errno = notifier_to_errno(rc);
info.si_code = TRAP_HWBKPT;
force_sig_info(args->signr, &info, current);
}
rcu_read_unlock();
}
if (cmf == 0)
rc = NOTIFY_DONE;
sh_ubc->enable_all(resume_mask);
put_cpu();
return rc;
}
BUILD_TRAP_HANDLER(breakpoint)
{
unsigned long ex = lookup_exception_vector();
TRAP_HANDLER_DECL;
notify_die(DIE_BREAKPOINT, "breakpoint", regs, 0, ex, SIGTRAP);
}
/*
* Handle debug exception notifications.
*/
int __kprobes hw_breakpoint_exceptions_notify(struct notifier_block *unused,
unsigned long val, void *data)
{
struct die_args *args = data;
if (val != DIE_BREAKPOINT)
return NOTIFY_DONE;
/*
* If the breakpoint hasn't been triggered by the UBC, it's
* probably from a debugger, so don't do anything more here.
*
* This also permits the UBC interface clock to remain off for
* non-UBC breakpoints, as we don't need to check the triggered
* or active channel masks.
*/
if (args->trapnr != sh_ubc->trap_nr)
return NOTIFY_DONE;
return hw_breakpoint_handler(data);
}
void hw_breakpoint_pmu_read(struct perf_event *bp)
{
/* TODO */
}
int register_sh_ubc(struct sh_ubc *ubc)
{
/* Bail if it's already assigned */
if (sh_ubc != &ubc_dummy)
return -EBUSY;
sh_ubc = ubc;
pr_info("HW Breakpoints: %s UBC support registered\n", ubc->name);
WARN_ON(ubc->num_events > HBP_NUM);
return 0;
}
| gpl-2.0 |
skybosi/linux | arch/arm/mach-ixp4xx/ixp4xx_npe.c | 4764 | 21755 | /*
* Intel IXP4xx Network Processor Engine driver for Linux
*
* Copyright (C) 2007 Krzysztof Halasa <khc@pm.waw.pl>
*
* 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.
*
* The code is based on publicly available information:
* - Intel IXP4xx Developer's Manual and other e-papers
* - Intel IXP400 Access Library Software (BSD license)
* - previous works by Christian Hohnstaedt <chohnstaedt@innominate.com>
* Thanks, Christian.
*/
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/firmware.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <mach/npe.h>
#define DEBUG_MSG 0
#define DEBUG_FW 0
#define NPE_COUNT 3
#define MAX_RETRIES 1000 /* microseconds */
#define NPE_42X_DATA_SIZE 0x800 /* in dwords */
#define NPE_46X_DATA_SIZE 0x1000
#define NPE_A_42X_INSTR_SIZE 0x1000
#define NPE_B_AND_C_42X_INSTR_SIZE 0x800
#define NPE_46X_INSTR_SIZE 0x1000
#define REGS_SIZE 0x1000
#define NPE_PHYS_REG 32
#define FW_MAGIC 0xFEEDF00D
#define FW_BLOCK_TYPE_INSTR 0x0
#define FW_BLOCK_TYPE_DATA 0x1
#define FW_BLOCK_TYPE_EOF 0xF
/* NPE exec status (read) and command (write) */
#define CMD_NPE_STEP 0x01
#define CMD_NPE_START 0x02
#define CMD_NPE_STOP 0x03
#define CMD_NPE_CLR_PIPE 0x04
#define CMD_CLR_PROFILE_CNT 0x0C
#define CMD_RD_INS_MEM 0x10 /* instruction memory */
#define CMD_WR_INS_MEM 0x11
#define CMD_RD_DATA_MEM 0x12 /* data memory */
#define CMD_WR_DATA_MEM 0x13
#define CMD_RD_ECS_REG 0x14 /* exec access register */
#define CMD_WR_ECS_REG 0x15
#define STAT_RUN 0x80000000
#define STAT_STOP 0x40000000
#define STAT_CLEAR 0x20000000
#define STAT_ECS_K 0x00800000 /* pipeline clean */
#define NPE_STEVT 0x1B
#define NPE_STARTPC 0x1C
#define NPE_REGMAP 0x1E
#define NPE_CINDEX 0x1F
#define INSTR_WR_REG_SHORT 0x0000C000
#define INSTR_WR_REG_BYTE 0x00004000
#define INSTR_RD_FIFO 0x0F888220
#define INSTR_RESET_MBOX 0x0FAC8210
#define ECS_BG_CTXT_REG_0 0x00 /* Background Executing Context */
#define ECS_BG_CTXT_REG_1 0x01 /* Stack level */
#define ECS_BG_CTXT_REG_2 0x02
#define ECS_PRI_1_CTXT_REG_0 0x04 /* Priority 1 Executing Context */
#define ECS_PRI_1_CTXT_REG_1 0x05 /* Stack level */
#define ECS_PRI_1_CTXT_REG_2 0x06
#define ECS_PRI_2_CTXT_REG_0 0x08 /* Priority 2 Executing Context */
#define ECS_PRI_2_CTXT_REG_1 0x09 /* Stack level */
#define ECS_PRI_2_CTXT_REG_2 0x0A
#define ECS_DBG_CTXT_REG_0 0x0C /* Debug Executing Context */
#define ECS_DBG_CTXT_REG_1 0x0D /* Stack level */
#define ECS_DBG_CTXT_REG_2 0x0E
#define ECS_INSTRUCT_REG 0x11 /* NPE Instruction Register */
#define ECS_REG_0_ACTIVE 0x80000000 /* all levels */
#define ECS_REG_0_NEXTPC_MASK 0x1FFF0000 /* BG/PRI1/PRI2 levels */
#define ECS_REG_0_LDUR_BITS 8
#define ECS_REG_0_LDUR_MASK 0x00000700 /* all levels */
#define ECS_REG_1_CCTXT_BITS 16
#define ECS_REG_1_CCTXT_MASK 0x000F0000 /* all levels */
#define ECS_REG_1_SELCTXT_BITS 0
#define ECS_REG_1_SELCTXT_MASK 0x0000000F /* all levels */
#define ECS_DBG_REG_2_IF 0x00100000 /* debug level */
#define ECS_DBG_REG_2_IE 0x00080000 /* debug level */
/* NPE watchpoint_fifo register bit */
#define WFIFO_VALID 0x80000000
/* NPE messaging_status register bit definitions */
#define MSGSTAT_OFNE 0x00010000 /* OutFifoNotEmpty */
#define MSGSTAT_IFNF 0x00020000 /* InFifoNotFull */
#define MSGSTAT_OFNF 0x00040000 /* OutFifoNotFull */
#define MSGSTAT_IFNE 0x00080000 /* InFifoNotEmpty */
#define MSGSTAT_MBINT 0x00100000 /* Mailbox interrupt */
#define MSGSTAT_IFINT 0x00200000 /* InFifo interrupt */
#define MSGSTAT_OFINT 0x00400000 /* OutFifo interrupt */
#define MSGSTAT_WFINT 0x00800000 /* WatchFifo interrupt */
/* NPE messaging_control register bit definitions */
#define MSGCTL_OUT_FIFO 0x00010000 /* enable output FIFO */
#define MSGCTL_IN_FIFO 0x00020000 /* enable input FIFO */
#define MSGCTL_OUT_FIFO_WRITE 0x01000000 /* enable FIFO + WRITE */
#define MSGCTL_IN_FIFO_WRITE 0x02000000
/* NPE mailbox_status value for reset */
#define RESET_MBOX_STAT 0x0000F0F0
#define NPE_A_FIRMWARE "NPE-A"
#define NPE_B_FIRMWARE "NPE-B"
#define NPE_C_FIRMWARE "NPE-C"
const char *npe_names[] = { NPE_A_FIRMWARE, NPE_B_FIRMWARE, NPE_C_FIRMWARE };
#define print_npe(pri, npe, fmt, ...) \
printk(pri "%s: " fmt, npe_name(npe), ## __VA_ARGS__)
#if DEBUG_MSG
#define debug_msg(npe, fmt, ...) \
print_npe(KERN_DEBUG, npe, fmt, ## __VA_ARGS__)
#else
#define debug_msg(npe, fmt, ...)
#endif
static struct {
u32 reg, val;
} ecs_reset[] = {
{ ECS_BG_CTXT_REG_0, 0xA0000000 },
{ ECS_BG_CTXT_REG_1, 0x01000000 },
{ ECS_BG_CTXT_REG_2, 0x00008000 },
{ ECS_PRI_1_CTXT_REG_0, 0x20000080 },
{ ECS_PRI_1_CTXT_REG_1, 0x01000000 },
{ ECS_PRI_1_CTXT_REG_2, 0x00008000 },
{ ECS_PRI_2_CTXT_REG_0, 0x20000080 },
{ ECS_PRI_2_CTXT_REG_1, 0x01000000 },
{ ECS_PRI_2_CTXT_REG_2, 0x00008000 },
{ ECS_DBG_CTXT_REG_0, 0x20000000 },
{ ECS_DBG_CTXT_REG_1, 0x00000000 },
{ ECS_DBG_CTXT_REG_2, 0x001E0000 },
{ ECS_INSTRUCT_REG, 0x1003C00F },
};
static struct npe npe_tab[NPE_COUNT] = {
{
.id = 0,
.regs = (struct npe_regs __iomem *)IXP4XX_NPEA_BASE_VIRT,
.regs_phys = IXP4XX_NPEA_BASE_PHYS,
}, {
.id = 1,
.regs = (struct npe_regs __iomem *)IXP4XX_NPEB_BASE_VIRT,
.regs_phys = IXP4XX_NPEB_BASE_PHYS,
}, {
.id = 2,
.regs = (struct npe_regs __iomem *)IXP4XX_NPEC_BASE_VIRT,
.regs_phys = IXP4XX_NPEC_BASE_PHYS,
}
};
int npe_running(struct npe *npe)
{
return (__raw_readl(&npe->regs->exec_status_cmd) & STAT_RUN) != 0;
}
static void npe_cmd_write(struct npe *npe, u32 addr, int cmd, u32 data)
{
__raw_writel(data, &npe->regs->exec_data);
__raw_writel(addr, &npe->regs->exec_addr);
__raw_writel(cmd, &npe->regs->exec_status_cmd);
}
static u32 npe_cmd_read(struct npe *npe, u32 addr, int cmd)
{
__raw_writel(addr, &npe->regs->exec_addr);
__raw_writel(cmd, &npe->regs->exec_status_cmd);
/* Iintroduce extra read cycles after issuing read command to NPE
so that we read the register after the NPE has updated it.
This is to overcome race condition between XScale and NPE */
__raw_readl(&npe->regs->exec_data);
__raw_readl(&npe->regs->exec_data);
return __raw_readl(&npe->regs->exec_data);
}
static void npe_clear_active(struct npe *npe, u32 reg)
{
u32 val = npe_cmd_read(npe, reg, CMD_RD_ECS_REG);
npe_cmd_write(npe, reg, CMD_WR_ECS_REG, val & ~ECS_REG_0_ACTIVE);
}
static void npe_start(struct npe *npe)
{
/* ensure only Background Context Stack Level is active */
npe_clear_active(npe, ECS_PRI_1_CTXT_REG_0);
npe_clear_active(npe, ECS_PRI_2_CTXT_REG_0);
npe_clear_active(npe, ECS_DBG_CTXT_REG_0);
__raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd);
__raw_writel(CMD_NPE_START, &npe->regs->exec_status_cmd);
}
static void npe_stop(struct npe *npe)
{
__raw_writel(CMD_NPE_STOP, &npe->regs->exec_status_cmd);
__raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd); /*FIXME?*/
}
static int __must_check npe_debug_instr(struct npe *npe, u32 instr, u32 ctx,
u32 ldur)
{
u32 wc;
int i;
/* set the Active bit, and the LDUR, in the debug level */
npe_cmd_write(npe, ECS_DBG_CTXT_REG_0, CMD_WR_ECS_REG,
ECS_REG_0_ACTIVE | (ldur << ECS_REG_0_LDUR_BITS));
/* set CCTXT at ECS DEBUG L3 to specify in which context to execute
the instruction, and set SELCTXT at ECS DEBUG Level to specify
which context store to access.
Debug ECS Level Reg 1 has form 0x000n000n, where n = context number
*/
npe_cmd_write(npe, ECS_DBG_CTXT_REG_1, CMD_WR_ECS_REG,
(ctx << ECS_REG_1_CCTXT_BITS) |
(ctx << ECS_REG_1_SELCTXT_BITS));
/* clear the pipeline */
__raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd);
/* load NPE instruction into the instruction register */
npe_cmd_write(npe, ECS_INSTRUCT_REG, CMD_WR_ECS_REG, instr);
/* we need this value later to wait for completion of NPE execution
step */
wc = __raw_readl(&npe->regs->watch_count);
/* issue a Step One command via the Execution Control register */
__raw_writel(CMD_NPE_STEP, &npe->regs->exec_status_cmd);
/* Watch Count register increments when NPE completes an instruction */
for (i = 0; i < MAX_RETRIES; i++) {
if (wc != __raw_readl(&npe->regs->watch_count))
return 0;
udelay(1);
}
print_npe(KERN_ERR, npe, "reset: npe_debug_instr(): timeout\n");
return -ETIMEDOUT;
}
static int __must_check npe_logical_reg_write8(struct npe *npe, u32 addr,
u8 val, u32 ctx)
{
/* here we build the NPE assembler instruction: mov8 d0, #0 */
u32 instr = INSTR_WR_REG_BYTE | /* OpCode */
addr << 9 | /* base Operand */
(val & 0x1F) << 4 | /* lower 5 bits to immediate data */
(val & ~0x1F) << (18 - 5);/* higher 3 bits to CoProc instr. */
return npe_debug_instr(npe, instr, ctx, 1); /* execute it */
}
static int __must_check npe_logical_reg_write16(struct npe *npe, u32 addr,
u16 val, u32 ctx)
{
/* here we build the NPE assembler instruction: mov16 d0, #0 */
u32 instr = INSTR_WR_REG_SHORT | /* OpCode */
addr << 9 | /* base Operand */
(val & 0x1F) << 4 | /* lower 5 bits to immediate data */
(val & ~0x1F) << (18 - 5);/* higher 11 bits to CoProc instr. */
return npe_debug_instr(npe, instr, ctx, 1); /* execute it */
}
static int __must_check npe_logical_reg_write32(struct npe *npe, u32 addr,
u32 val, u32 ctx)
{
/* write in 16 bit steps first the high and then the low value */
if (npe_logical_reg_write16(npe, addr, val >> 16, ctx))
return -ETIMEDOUT;
return npe_logical_reg_write16(npe, addr + 2, val & 0xFFFF, ctx);
}
static int npe_reset(struct npe *npe)
{
u32 val, ctl, exec_count, ctx_reg2;
int i;
ctl = (__raw_readl(&npe->regs->messaging_control) | 0x3F000000) &
0x3F3FFFFF;
/* disable parity interrupt */
__raw_writel(ctl & 0x3F00FFFF, &npe->regs->messaging_control);
/* pre exec - debug instruction */
/* turn off the halt bit by clearing Execution Count register. */
exec_count = __raw_readl(&npe->regs->exec_count);
__raw_writel(0, &npe->regs->exec_count);
/* ensure that IF and IE are on (temporarily), so that we don't end up
stepping forever */
ctx_reg2 = npe_cmd_read(npe, ECS_DBG_CTXT_REG_2, CMD_RD_ECS_REG);
npe_cmd_write(npe, ECS_DBG_CTXT_REG_2, CMD_WR_ECS_REG, ctx_reg2 |
ECS_DBG_REG_2_IF | ECS_DBG_REG_2_IE);
/* clear the FIFOs */
while (__raw_readl(&npe->regs->watchpoint_fifo) & WFIFO_VALID)
;
while (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_OFNE)
/* read from the outFIFO until empty */
print_npe(KERN_DEBUG, npe, "npe_reset: read FIFO = 0x%X\n",
__raw_readl(&npe->regs->in_out_fifo));
while (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNE)
/* step execution of the NPE intruction to read inFIFO using
the Debug Executing Context stack */
if (npe_debug_instr(npe, INSTR_RD_FIFO, 0, 0))
return -ETIMEDOUT;
/* reset the mailbox reg from the XScale side */
__raw_writel(RESET_MBOX_STAT, &npe->regs->mailbox_status);
/* from NPE side */
if (npe_debug_instr(npe, INSTR_RESET_MBOX, 0, 0))
return -ETIMEDOUT;
/* Reset the physical registers in the NPE register file */
for (val = 0; val < NPE_PHYS_REG; val++) {
if (npe_logical_reg_write16(npe, NPE_REGMAP, val >> 1, 0))
return -ETIMEDOUT;
/* address is either 0 or 4 */
if (npe_logical_reg_write32(npe, (val & 1) * 4, 0, 0))
return -ETIMEDOUT;
}
/* Reset the context store = each context's Context Store registers */
/* Context 0 has no STARTPC. Instead, this value is used to set NextPC
for Background ECS, to set where NPE starts executing code */
val = npe_cmd_read(npe, ECS_BG_CTXT_REG_0, CMD_RD_ECS_REG);
val &= ~ECS_REG_0_NEXTPC_MASK;
val |= (0 /* NextPC */ << 16) & ECS_REG_0_NEXTPC_MASK;
npe_cmd_write(npe, ECS_BG_CTXT_REG_0, CMD_WR_ECS_REG, val);
for (i = 0; i < 16; i++) {
if (i) { /* Context 0 has no STEVT nor STARTPC */
/* STEVT = off, 0x80 */
if (npe_logical_reg_write8(npe, NPE_STEVT, 0x80, i))
return -ETIMEDOUT;
if (npe_logical_reg_write16(npe, NPE_STARTPC, 0, i))
return -ETIMEDOUT;
}
/* REGMAP = d0->p0, d8->p2, d16->p4 */
if (npe_logical_reg_write16(npe, NPE_REGMAP, 0x820, i))
return -ETIMEDOUT;
if (npe_logical_reg_write8(npe, NPE_CINDEX, 0, i))
return -ETIMEDOUT;
}
/* post exec */
/* clear active bit in debug level */
npe_cmd_write(npe, ECS_DBG_CTXT_REG_0, CMD_WR_ECS_REG, 0);
/* clear the pipeline */
__raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd);
/* restore previous values */
__raw_writel(exec_count, &npe->regs->exec_count);
npe_cmd_write(npe, ECS_DBG_CTXT_REG_2, CMD_WR_ECS_REG, ctx_reg2);
/* write reset values to Execution Context Stack registers */
for (val = 0; val < ARRAY_SIZE(ecs_reset); val++)
npe_cmd_write(npe, ecs_reset[val].reg, CMD_WR_ECS_REG,
ecs_reset[val].val);
/* clear the profile counter */
__raw_writel(CMD_CLR_PROFILE_CNT, &npe->regs->exec_status_cmd);
__raw_writel(0, &npe->regs->exec_count);
__raw_writel(0, &npe->regs->action_points[0]);
__raw_writel(0, &npe->regs->action_points[1]);
__raw_writel(0, &npe->regs->action_points[2]);
__raw_writel(0, &npe->regs->action_points[3]);
__raw_writel(0, &npe->regs->watch_count);
val = ixp4xx_read_feature_bits();
/* reset the NPE */
ixp4xx_write_feature_bits(val &
~(IXP4XX_FEATURE_RESET_NPEA << npe->id));
/* deassert reset */
ixp4xx_write_feature_bits(val |
(IXP4XX_FEATURE_RESET_NPEA << npe->id));
for (i = 0; i < MAX_RETRIES; i++) {
if (ixp4xx_read_feature_bits() &
(IXP4XX_FEATURE_RESET_NPEA << npe->id))
break; /* NPE is back alive */
udelay(1);
}
if (i == MAX_RETRIES)
return -ETIMEDOUT;
npe_stop(npe);
/* restore NPE configuration bus Control Register - parity settings */
__raw_writel(ctl, &npe->regs->messaging_control);
return 0;
}
int npe_send_message(struct npe *npe, const void *msg, const char *what)
{
const u32 *send = msg;
int cycles = 0;
debug_msg(npe, "Trying to send message %s [%08X:%08X]\n",
what, send[0], send[1]);
if (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNE) {
debug_msg(npe, "NPE input FIFO not empty\n");
return -EIO;
}
__raw_writel(send[0], &npe->regs->in_out_fifo);
if (!(__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNF)) {
debug_msg(npe, "NPE input FIFO full\n");
return -EIO;
}
__raw_writel(send[1], &npe->regs->in_out_fifo);
while ((cycles < MAX_RETRIES) &&
(__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNE)) {
udelay(1);
cycles++;
}
if (cycles == MAX_RETRIES) {
debug_msg(npe, "Timeout sending message\n");
return -ETIMEDOUT;
}
#if DEBUG_MSG > 1
debug_msg(npe, "Sending a message took %i cycles\n", cycles);
#endif
return 0;
}
int npe_recv_message(struct npe *npe, void *msg, const char *what)
{
u32 *recv = msg;
int cycles = 0, cnt = 0;
debug_msg(npe, "Trying to receive message %s\n", what);
while (cycles < MAX_RETRIES) {
if (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_OFNE) {
recv[cnt++] = __raw_readl(&npe->regs->in_out_fifo);
if (cnt == 2)
break;
} else {
udelay(1);
cycles++;
}
}
switch(cnt) {
case 1:
debug_msg(npe, "Received [%08X]\n", recv[0]);
break;
case 2:
debug_msg(npe, "Received [%08X:%08X]\n", recv[0], recv[1]);
break;
}
if (cycles == MAX_RETRIES) {
debug_msg(npe, "Timeout waiting for message\n");
return -ETIMEDOUT;
}
#if DEBUG_MSG > 1
debug_msg(npe, "Receiving a message took %i cycles\n", cycles);
#endif
return 0;
}
int npe_send_recv_message(struct npe *npe, void *msg, const char *what)
{
int result;
u32 *send = msg, recv[2];
if ((result = npe_send_message(npe, msg, what)) != 0)
return result;
if ((result = npe_recv_message(npe, recv, what)) != 0)
return result;
if ((recv[0] != send[0]) || (recv[1] != send[1])) {
debug_msg(npe, "Message %s: unexpected message received\n",
what);
return -EIO;
}
return 0;
}
int npe_load_firmware(struct npe *npe, const char *name, struct device *dev)
{
const struct firmware *fw_entry;
struct dl_block {
u32 type;
u32 offset;
} *blk;
struct dl_image {
u32 magic;
u32 id;
u32 size;
union {
u32 data[0];
struct dl_block blocks[0];
};
} *image;
struct dl_codeblock {
u32 npe_addr;
u32 size;
u32 data[0];
} *cb;
int i, j, err, data_size, instr_size, blocks, table_end;
u32 cmd;
if ((err = request_firmware(&fw_entry, name, dev)) != 0)
return err;
err = -EINVAL;
if (fw_entry->size < sizeof(struct dl_image)) {
print_npe(KERN_ERR, npe, "incomplete firmware file\n");
goto err;
}
image = (struct dl_image*)fw_entry->data;
#if DEBUG_FW
print_npe(KERN_DEBUG, npe, "firmware: %08X %08X %08X (0x%X bytes)\n",
image->magic, image->id, image->size, image->size * 4);
#endif
if (image->magic == swab32(FW_MAGIC)) { /* swapped file */
image->id = swab32(image->id);
image->size = swab32(image->size);
} else if (image->magic != FW_MAGIC) {
print_npe(KERN_ERR, npe, "bad firmware file magic: 0x%X\n",
image->magic);
goto err;
}
if ((image->size * 4 + sizeof(struct dl_image)) != fw_entry->size) {
print_npe(KERN_ERR, npe,
"inconsistent size of firmware file\n");
goto err;
}
if (((image->id >> 24) & 0xF /* NPE ID */) != npe->id) {
print_npe(KERN_ERR, npe, "firmware file NPE ID mismatch\n");
goto err;
}
if (image->magic == swab32(FW_MAGIC))
for (i = 0; i < image->size; i++)
image->data[i] = swab32(image->data[i]);
if (cpu_is_ixp42x() && ((image->id >> 28) & 0xF /* device ID */)) {
print_npe(KERN_INFO, npe, "IXP43x/IXP46x firmware ignored on "
"IXP42x\n");
goto err;
}
if (npe_running(npe)) {
print_npe(KERN_INFO, npe, "unable to load firmware, NPE is "
"already running\n");
err = -EBUSY;
goto err;
}
#if 0
npe_stop(npe);
npe_reset(npe);
#endif
print_npe(KERN_INFO, npe, "firmware functionality 0x%X, "
"revision 0x%X:%X\n", (image->id >> 16) & 0xFF,
(image->id >> 8) & 0xFF, image->id & 0xFF);
if (cpu_is_ixp42x()) {
if (!npe->id)
instr_size = NPE_A_42X_INSTR_SIZE;
else
instr_size = NPE_B_AND_C_42X_INSTR_SIZE;
data_size = NPE_42X_DATA_SIZE;
} else {
instr_size = NPE_46X_INSTR_SIZE;
data_size = NPE_46X_DATA_SIZE;
}
for (blocks = 0; blocks * sizeof(struct dl_block) / 4 < image->size;
blocks++)
if (image->blocks[blocks].type == FW_BLOCK_TYPE_EOF)
break;
if (blocks * sizeof(struct dl_block) / 4 >= image->size) {
print_npe(KERN_INFO, npe, "firmware EOF block marker not "
"found\n");
goto err;
}
#if DEBUG_FW
print_npe(KERN_DEBUG, npe, "%i firmware blocks found\n", blocks);
#endif
table_end = blocks * sizeof(struct dl_block) / 4 + 1 /* EOF marker */;
for (i = 0, blk = image->blocks; i < blocks; i++, blk++) {
if (blk->offset > image->size - sizeof(struct dl_codeblock) / 4
|| blk->offset < table_end) {
print_npe(KERN_INFO, npe, "invalid offset 0x%X of "
"firmware block #%i\n", blk->offset, i);
goto err;
}
cb = (struct dl_codeblock*)&image->data[blk->offset];
if (blk->type == FW_BLOCK_TYPE_INSTR) {
if (cb->npe_addr + cb->size > instr_size)
goto too_big;
cmd = CMD_WR_INS_MEM;
} else if (blk->type == FW_BLOCK_TYPE_DATA) {
if (cb->npe_addr + cb->size > data_size)
goto too_big;
cmd = CMD_WR_DATA_MEM;
} else {
print_npe(KERN_INFO, npe, "invalid firmware block #%i "
"type 0x%X\n", i, blk->type);
goto err;
}
if (blk->offset + sizeof(*cb) / 4 + cb->size > image->size) {
print_npe(KERN_INFO, npe, "firmware block #%i doesn't "
"fit in firmware image: type %c, start 0x%X,"
" length 0x%X\n", i,
blk->type == FW_BLOCK_TYPE_INSTR ? 'I' : 'D',
cb->npe_addr, cb->size);
goto err;
}
for (j = 0; j < cb->size; j++)
npe_cmd_write(npe, cb->npe_addr + j, cmd, cb->data[j]);
}
npe_start(npe);
if (!npe_running(npe))
print_npe(KERN_ERR, npe, "unable to start\n");
release_firmware(fw_entry);
return 0;
too_big:
print_npe(KERN_INFO, npe, "firmware block #%i doesn't fit in NPE "
"memory: type %c, start 0x%X, length 0x%X\n", i,
blk->type == FW_BLOCK_TYPE_INSTR ? 'I' : 'D',
cb->npe_addr, cb->size);
err:
release_firmware(fw_entry);
return err;
}
struct npe *npe_request(unsigned id)
{
if (id < NPE_COUNT)
if (npe_tab[id].valid)
if (try_module_get(THIS_MODULE))
return &npe_tab[id];
return NULL;
}
void npe_release(struct npe *npe)
{
module_put(THIS_MODULE);
}
static int __init npe_init_module(void)
{
int i, found = 0;
for (i = 0; i < NPE_COUNT; i++) {
struct npe *npe = &npe_tab[i];
if (!(ixp4xx_read_feature_bits() &
(IXP4XX_FEATURE_RESET_NPEA << i)))
continue; /* NPE already disabled or not present */
if (!(npe->mem_res = request_mem_region(npe->regs_phys,
REGS_SIZE,
npe_name(npe)))) {
print_npe(KERN_ERR, npe,
"failed to request memory region\n");
continue;
}
if (npe_reset(npe))
continue;
npe->valid = 1;
found++;
}
if (!found)
return -ENODEV;
return 0;
}
static void __exit npe_cleanup_module(void)
{
int i;
for (i = 0; i < NPE_COUNT; i++)
if (npe_tab[i].mem_res) {
npe_reset(&npe_tab[i]);
release_resource(npe_tab[i].mem_res);
}
}
module_init(npe_init_module);
module_exit(npe_cleanup_module);
MODULE_AUTHOR("Krzysztof Halasa");
MODULE_LICENSE("GPL v2");
MODULE_FIRMWARE(NPE_A_FIRMWARE);
MODULE_FIRMWARE(NPE_B_FIRMWARE);
MODULE_FIRMWARE(NPE_C_FIRMWARE);
EXPORT_SYMBOL(npe_names);
EXPORT_SYMBOL(npe_running);
EXPORT_SYMBOL(npe_request);
EXPORT_SYMBOL(npe_release);
EXPORT_SYMBOL(npe_load_firmware);
EXPORT_SYMBOL(npe_send_message);
EXPORT_SYMBOL(npe_recv_message);
EXPORT_SYMBOL(npe_send_recv_message);
| gpl-2.0 |
intel-linux-graphics/drm-intel | arch/arm/mach-ixp4xx/ixp4xx_npe.c | 4764 | 21755 | /*
* Intel IXP4xx Network Processor Engine driver for Linux
*
* Copyright (C) 2007 Krzysztof Halasa <khc@pm.waw.pl>
*
* 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.
*
* The code is based on publicly available information:
* - Intel IXP4xx Developer's Manual and other e-papers
* - Intel IXP400 Access Library Software (BSD license)
* - previous works by Christian Hohnstaedt <chohnstaedt@innominate.com>
* Thanks, Christian.
*/
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/firmware.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <mach/npe.h>
#define DEBUG_MSG 0
#define DEBUG_FW 0
#define NPE_COUNT 3
#define MAX_RETRIES 1000 /* microseconds */
#define NPE_42X_DATA_SIZE 0x800 /* in dwords */
#define NPE_46X_DATA_SIZE 0x1000
#define NPE_A_42X_INSTR_SIZE 0x1000
#define NPE_B_AND_C_42X_INSTR_SIZE 0x800
#define NPE_46X_INSTR_SIZE 0x1000
#define REGS_SIZE 0x1000
#define NPE_PHYS_REG 32
#define FW_MAGIC 0xFEEDF00D
#define FW_BLOCK_TYPE_INSTR 0x0
#define FW_BLOCK_TYPE_DATA 0x1
#define FW_BLOCK_TYPE_EOF 0xF
/* NPE exec status (read) and command (write) */
#define CMD_NPE_STEP 0x01
#define CMD_NPE_START 0x02
#define CMD_NPE_STOP 0x03
#define CMD_NPE_CLR_PIPE 0x04
#define CMD_CLR_PROFILE_CNT 0x0C
#define CMD_RD_INS_MEM 0x10 /* instruction memory */
#define CMD_WR_INS_MEM 0x11
#define CMD_RD_DATA_MEM 0x12 /* data memory */
#define CMD_WR_DATA_MEM 0x13
#define CMD_RD_ECS_REG 0x14 /* exec access register */
#define CMD_WR_ECS_REG 0x15
#define STAT_RUN 0x80000000
#define STAT_STOP 0x40000000
#define STAT_CLEAR 0x20000000
#define STAT_ECS_K 0x00800000 /* pipeline clean */
#define NPE_STEVT 0x1B
#define NPE_STARTPC 0x1C
#define NPE_REGMAP 0x1E
#define NPE_CINDEX 0x1F
#define INSTR_WR_REG_SHORT 0x0000C000
#define INSTR_WR_REG_BYTE 0x00004000
#define INSTR_RD_FIFO 0x0F888220
#define INSTR_RESET_MBOX 0x0FAC8210
#define ECS_BG_CTXT_REG_0 0x00 /* Background Executing Context */
#define ECS_BG_CTXT_REG_1 0x01 /* Stack level */
#define ECS_BG_CTXT_REG_2 0x02
#define ECS_PRI_1_CTXT_REG_0 0x04 /* Priority 1 Executing Context */
#define ECS_PRI_1_CTXT_REG_1 0x05 /* Stack level */
#define ECS_PRI_1_CTXT_REG_2 0x06
#define ECS_PRI_2_CTXT_REG_0 0x08 /* Priority 2 Executing Context */
#define ECS_PRI_2_CTXT_REG_1 0x09 /* Stack level */
#define ECS_PRI_2_CTXT_REG_2 0x0A
#define ECS_DBG_CTXT_REG_0 0x0C /* Debug Executing Context */
#define ECS_DBG_CTXT_REG_1 0x0D /* Stack level */
#define ECS_DBG_CTXT_REG_2 0x0E
#define ECS_INSTRUCT_REG 0x11 /* NPE Instruction Register */
#define ECS_REG_0_ACTIVE 0x80000000 /* all levels */
#define ECS_REG_0_NEXTPC_MASK 0x1FFF0000 /* BG/PRI1/PRI2 levels */
#define ECS_REG_0_LDUR_BITS 8
#define ECS_REG_0_LDUR_MASK 0x00000700 /* all levels */
#define ECS_REG_1_CCTXT_BITS 16
#define ECS_REG_1_CCTXT_MASK 0x000F0000 /* all levels */
#define ECS_REG_1_SELCTXT_BITS 0
#define ECS_REG_1_SELCTXT_MASK 0x0000000F /* all levels */
#define ECS_DBG_REG_2_IF 0x00100000 /* debug level */
#define ECS_DBG_REG_2_IE 0x00080000 /* debug level */
/* NPE watchpoint_fifo register bit */
#define WFIFO_VALID 0x80000000
/* NPE messaging_status register bit definitions */
#define MSGSTAT_OFNE 0x00010000 /* OutFifoNotEmpty */
#define MSGSTAT_IFNF 0x00020000 /* InFifoNotFull */
#define MSGSTAT_OFNF 0x00040000 /* OutFifoNotFull */
#define MSGSTAT_IFNE 0x00080000 /* InFifoNotEmpty */
#define MSGSTAT_MBINT 0x00100000 /* Mailbox interrupt */
#define MSGSTAT_IFINT 0x00200000 /* InFifo interrupt */
#define MSGSTAT_OFINT 0x00400000 /* OutFifo interrupt */
#define MSGSTAT_WFINT 0x00800000 /* WatchFifo interrupt */
/* NPE messaging_control register bit definitions */
#define MSGCTL_OUT_FIFO 0x00010000 /* enable output FIFO */
#define MSGCTL_IN_FIFO 0x00020000 /* enable input FIFO */
#define MSGCTL_OUT_FIFO_WRITE 0x01000000 /* enable FIFO + WRITE */
#define MSGCTL_IN_FIFO_WRITE 0x02000000
/* NPE mailbox_status value for reset */
#define RESET_MBOX_STAT 0x0000F0F0
#define NPE_A_FIRMWARE "NPE-A"
#define NPE_B_FIRMWARE "NPE-B"
#define NPE_C_FIRMWARE "NPE-C"
const char *npe_names[] = { NPE_A_FIRMWARE, NPE_B_FIRMWARE, NPE_C_FIRMWARE };
#define print_npe(pri, npe, fmt, ...) \
printk(pri "%s: " fmt, npe_name(npe), ## __VA_ARGS__)
#if DEBUG_MSG
#define debug_msg(npe, fmt, ...) \
print_npe(KERN_DEBUG, npe, fmt, ## __VA_ARGS__)
#else
#define debug_msg(npe, fmt, ...)
#endif
static struct {
u32 reg, val;
} ecs_reset[] = {
{ ECS_BG_CTXT_REG_0, 0xA0000000 },
{ ECS_BG_CTXT_REG_1, 0x01000000 },
{ ECS_BG_CTXT_REG_2, 0x00008000 },
{ ECS_PRI_1_CTXT_REG_0, 0x20000080 },
{ ECS_PRI_1_CTXT_REG_1, 0x01000000 },
{ ECS_PRI_1_CTXT_REG_2, 0x00008000 },
{ ECS_PRI_2_CTXT_REG_0, 0x20000080 },
{ ECS_PRI_2_CTXT_REG_1, 0x01000000 },
{ ECS_PRI_2_CTXT_REG_2, 0x00008000 },
{ ECS_DBG_CTXT_REG_0, 0x20000000 },
{ ECS_DBG_CTXT_REG_1, 0x00000000 },
{ ECS_DBG_CTXT_REG_2, 0x001E0000 },
{ ECS_INSTRUCT_REG, 0x1003C00F },
};
static struct npe npe_tab[NPE_COUNT] = {
{
.id = 0,
.regs = (struct npe_regs __iomem *)IXP4XX_NPEA_BASE_VIRT,
.regs_phys = IXP4XX_NPEA_BASE_PHYS,
}, {
.id = 1,
.regs = (struct npe_regs __iomem *)IXP4XX_NPEB_BASE_VIRT,
.regs_phys = IXP4XX_NPEB_BASE_PHYS,
}, {
.id = 2,
.regs = (struct npe_regs __iomem *)IXP4XX_NPEC_BASE_VIRT,
.regs_phys = IXP4XX_NPEC_BASE_PHYS,
}
};
int npe_running(struct npe *npe)
{
return (__raw_readl(&npe->regs->exec_status_cmd) & STAT_RUN) != 0;
}
static void npe_cmd_write(struct npe *npe, u32 addr, int cmd, u32 data)
{
__raw_writel(data, &npe->regs->exec_data);
__raw_writel(addr, &npe->regs->exec_addr);
__raw_writel(cmd, &npe->regs->exec_status_cmd);
}
static u32 npe_cmd_read(struct npe *npe, u32 addr, int cmd)
{
__raw_writel(addr, &npe->regs->exec_addr);
__raw_writel(cmd, &npe->regs->exec_status_cmd);
/* Iintroduce extra read cycles after issuing read command to NPE
so that we read the register after the NPE has updated it.
This is to overcome race condition between XScale and NPE */
__raw_readl(&npe->regs->exec_data);
__raw_readl(&npe->regs->exec_data);
return __raw_readl(&npe->regs->exec_data);
}
static void npe_clear_active(struct npe *npe, u32 reg)
{
u32 val = npe_cmd_read(npe, reg, CMD_RD_ECS_REG);
npe_cmd_write(npe, reg, CMD_WR_ECS_REG, val & ~ECS_REG_0_ACTIVE);
}
static void npe_start(struct npe *npe)
{
/* ensure only Background Context Stack Level is active */
npe_clear_active(npe, ECS_PRI_1_CTXT_REG_0);
npe_clear_active(npe, ECS_PRI_2_CTXT_REG_0);
npe_clear_active(npe, ECS_DBG_CTXT_REG_0);
__raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd);
__raw_writel(CMD_NPE_START, &npe->regs->exec_status_cmd);
}
static void npe_stop(struct npe *npe)
{
__raw_writel(CMD_NPE_STOP, &npe->regs->exec_status_cmd);
__raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd); /*FIXME?*/
}
static int __must_check npe_debug_instr(struct npe *npe, u32 instr, u32 ctx,
u32 ldur)
{
u32 wc;
int i;
/* set the Active bit, and the LDUR, in the debug level */
npe_cmd_write(npe, ECS_DBG_CTXT_REG_0, CMD_WR_ECS_REG,
ECS_REG_0_ACTIVE | (ldur << ECS_REG_0_LDUR_BITS));
/* set CCTXT at ECS DEBUG L3 to specify in which context to execute
the instruction, and set SELCTXT at ECS DEBUG Level to specify
which context store to access.
Debug ECS Level Reg 1 has form 0x000n000n, where n = context number
*/
npe_cmd_write(npe, ECS_DBG_CTXT_REG_1, CMD_WR_ECS_REG,
(ctx << ECS_REG_1_CCTXT_BITS) |
(ctx << ECS_REG_1_SELCTXT_BITS));
/* clear the pipeline */
__raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd);
/* load NPE instruction into the instruction register */
npe_cmd_write(npe, ECS_INSTRUCT_REG, CMD_WR_ECS_REG, instr);
/* we need this value later to wait for completion of NPE execution
step */
wc = __raw_readl(&npe->regs->watch_count);
/* issue a Step One command via the Execution Control register */
__raw_writel(CMD_NPE_STEP, &npe->regs->exec_status_cmd);
/* Watch Count register increments when NPE completes an instruction */
for (i = 0; i < MAX_RETRIES; i++) {
if (wc != __raw_readl(&npe->regs->watch_count))
return 0;
udelay(1);
}
print_npe(KERN_ERR, npe, "reset: npe_debug_instr(): timeout\n");
return -ETIMEDOUT;
}
static int __must_check npe_logical_reg_write8(struct npe *npe, u32 addr,
u8 val, u32 ctx)
{
/* here we build the NPE assembler instruction: mov8 d0, #0 */
u32 instr = INSTR_WR_REG_BYTE | /* OpCode */
addr << 9 | /* base Operand */
(val & 0x1F) << 4 | /* lower 5 bits to immediate data */
(val & ~0x1F) << (18 - 5);/* higher 3 bits to CoProc instr. */
return npe_debug_instr(npe, instr, ctx, 1); /* execute it */
}
static int __must_check npe_logical_reg_write16(struct npe *npe, u32 addr,
u16 val, u32 ctx)
{
/* here we build the NPE assembler instruction: mov16 d0, #0 */
u32 instr = INSTR_WR_REG_SHORT | /* OpCode */
addr << 9 | /* base Operand */
(val & 0x1F) << 4 | /* lower 5 bits to immediate data */
(val & ~0x1F) << (18 - 5);/* higher 11 bits to CoProc instr. */
return npe_debug_instr(npe, instr, ctx, 1); /* execute it */
}
static int __must_check npe_logical_reg_write32(struct npe *npe, u32 addr,
u32 val, u32 ctx)
{
/* write in 16 bit steps first the high and then the low value */
if (npe_logical_reg_write16(npe, addr, val >> 16, ctx))
return -ETIMEDOUT;
return npe_logical_reg_write16(npe, addr + 2, val & 0xFFFF, ctx);
}
static int npe_reset(struct npe *npe)
{
u32 val, ctl, exec_count, ctx_reg2;
int i;
ctl = (__raw_readl(&npe->regs->messaging_control) | 0x3F000000) &
0x3F3FFFFF;
/* disable parity interrupt */
__raw_writel(ctl & 0x3F00FFFF, &npe->regs->messaging_control);
/* pre exec - debug instruction */
/* turn off the halt bit by clearing Execution Count register. */
exec_count = __raw_readl(&npe->regs->exec_count);
__raw_writel(0, &npe->regs->exec_count);
/* ensure that IF and IE are on (temporarily), so that we don't end up
stepping forever */
ctx_reg2 = npe_cmd_read(npe, ECS_DBG_CTXT_REG_2, CMD_RD_ECS_REG);
npe_cmd_write(npe, ECS_DBG_CTXT_REG_2, CMD_WR_ECS_REG, ctx_reg2 |
ECS_DBG_REG_2_IF | ECS_DBG_REG_2_IE);
/* clear the FIFOs */
while (__raw_readl(&npe->regs->watchpoint_fifo) & WFIFO_VALID)
;
while (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_OFNE)
/* read from the outFIFO until empty */
print_npe(KERN_DEBUG, npe, "npe_reset: read FIFO = 0x%X\n",
__raw_readl(&npe->regs->in_out_fifo));
while (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNE)
/* step execution of the NPE intruction to read inFIFO using
the Debug Executing Context stack */
if (npe_debug_instr(npe, INSTR_RD_FIFO, 0, 0))
return -ETIMEDOUT;
/* reset the mailbox reg from the XScale side */
__raw_writel(RESET_MBOX_STAT, &npe->regs->mailbox_status);
/* from NPE side */
if (npe_debug_instr(npe, INSTR_RESET_MBOX, 0, 0))
return -ETIMEDOUT;
/* Reset the physical registers in the NPE register file */
for (val = 0; val < NPE_PHYS_REG; val++) {
if (npe_logical_reg_write16(npe, NPE_REGMAP, val >> 1, 0))
return -ETIMEDOUT;
/* address is either 0 or 4 */
if (npe_logical_reg_write32(npe, (val & 1) * 4, 0, 0))
return -ETIMEDOUT;
}
/* Reset the context store = each context's Context Store registers */
/* Context 0 has no STARTPC. Instead, this value is used to set NextPC
for Background ECS, to set where NPE starts executing code */
val = npe_cmd_read(npe, ECS_BG_CTXT_REG_0, CMD_RD_ECS_REG);
val &= ~ECS_REG_0_NEXTPC_MASK;
val |= (0 /* NextPC */ << 16) & ECS_REG_0_NEXTPC_MASK;
npe_cmd_write(npe, ECS_BG_CTXT_REG_0, CMD_WR_ECS_REG, val);
for (i = 0; i < 16; i++) {
if (i) { /* Context 0 has no STEVT nor STARTPC */
/* STEVT = off, 0x80 */
if (npe_logical_reg_write8(npe, NPE_STEVT, 0x80, i))
return -ETIMEDOUT;
if (npe_logical_reg_write16(npe, NPE_STARTPC, 0, i))
return -ETIMEDOUT;
}
/* REGMAP = d0->p0, d8->p2, d16->p4 */
if (npe_logical_reg_write16(npe, NPE_REGMAP, 0x820, i))
return -ETIMEDOUT;
if (npe_logical_reg_write8(npe, NPE_CINDEX, 0, i))
return -ETIMEDOUT;
}
/* post exec */
/* clear active bit in debug level */
npe_cmd_write(npe, ECS_DBG_CTXT_REG_0, CMD_WR_ECS_REG, 0);
/* clear the pipeline */
__raw_writel(CMD_NPE_CLR_PIPE, &npe->regs->exec_status_cmd);
/* restore previous values */
__raw_writel(exec_count, &npe->regs->exec_count);
npe_cmd_write(npe, ECS_DBG_CTXT_REG_2, CMD_WR_ECS_REG, ctx_reg2);
/* write reset values to Execution Context Stack registers */
for (val = 0; val < ARRAY_SIZE(ecs_reset); val++)
npe_cmd_write(npe, ecs_reset[val].reg, CMD_WR_ECS_REG,
ecs_reset[val].val);
/* clear the profile counter */
__raw_writel(CMD_CLR_PROFILE_CNT, &npe->regs->exec_status_cmd);
__raw_writel(0, &npe->regs->exec_count);
__raw_writel(0, &npe->regs->action_points[0]);
__raw_writel(0, &npe->regs->action_points[1]);
__raw_writel(0, &npe->regs->action_points[2]);
__raw_writel(0, &npe->regs->action_points[3]);
__raw_writel(0, &npe->regs->watch_count);
val = ixp4xx_read_feature_bits();
/* reset the NPE */
ixp4xx_write_feature_bits(val &
~(IXP4XX_FEATURE_RESET_NPEA << npe->id));
/* deassert reset */
ixp4xx_write_feature_bits(val |
(IXP4XX_FEATURE_RESET_NPEA << npe->id));
for (i = 0; i < MAX_RETRIES; i++) {
if (ixp4xx_read_feature_bits() &
(IXP4XX_FEATURE_RESET_NPEA << npe->id))
break; /* NPE is back alive */
udelay(1);
}
if (i == MAX_RETRIES)
return -ETIMEDOUT;
npe_stop(npe);
/* restore NPE configuration bus Control Register - parity settings */
__raw_writel(ctl, &npe->regs->messaging_control);
return 0;
}
int npe_send_message(struct npe *npe, const void *msg, const char *what)
{
const u32 *send = msg;
int cycles = 0;
debug_msg(npe, "Trying to send message %s [%08X:%08X]\n",
what, send[0], send[1]);
if (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNE) {
debug_msg(npe, "NPE input FIFO not empty\n");
return -EIO;
}
__raw_writel(send[0], &npe->regs->in_out_fifo);
if (!(__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNF)) {
debug_msg(npe, "NPE input FIFO full\n");
return -EIO;
}
__raw_writel(send[1], &npe->regs->in_out_fifo);
while ((cycles < MAX_RETRIES) &&
(__raw_readl(&npe->regs->messaging_status) & MSGSTAT_IFNE)) {
udelay(1);
cycles++;
}
if (cycles == MAX_RETRIES) {
debug_msg(npe, "Timeout sending message\n");
return -ETIMEDOUT;
}
#if DEBUG_MSG > 1
debug_msg(npe, "Sending a message took %i cycles\n", cycles);
#endif
return 0;
}
int npe_recv_message(struct npe *npe, void *msg, const char *what)
{
u32 *recv = msg;
int cycles = 0, cnt = 0;
debug_msg(npe, "Trying to receive message %s\n", what);
while (cycles < MAX_RETRIES) {
if (__raw_readl(&npe->regs->messaging_status) & MSGSTAT_OFNE) {
recv[cnt++] = __raw_readl(&npe->regs->in_out_fifo);
if (cnt == 2)
break;
} else {
udelay(1);
cycles++;
}
}
switch(cnt) {
case 1:
debug_msg(npe, "Received [%08X]\n", recv[0]);
break;
case 2:
debug_msg(npe, "Received [%08X:%08X]\n", recv[0], recv[1]);
break;
}
if (cycles == MAX_RETRIES) {
debug_msg(npe, "Timeout waiting for message\n");
return -ETIMEDOUT;
}
#if DEBUG_MSG > 1
debug_msg(npe, "Receiving a message took %i cycles\n", cycles);
#endif
return 0;
}
int npe_send_recv_message(struct npe *npe, void *msg, const char *what)
{
int result;
u32 *send = msg, recv[2];
if ((result = npe_send_message(npe, msg, what)) != 0)
return result;
if ((result = npe_recv_message(npe, recv, what)) != 0)
return result;
if ((recv[0] != send[0]) || (recv[1] != send[1])) {
debug_msg(npe, "Message %s: unexpected message received\n",
what);
return -EIO;
}
return 0;
}
int npe_load_firmware(struct npe *npe, const char *name, struct device *dev)
{
const struct firmware *fw_entry;
struct dl_block {
u32 type;
u32 offset;
} *blk;
struct dl_image {
u32 magic;
u32 id;
u32 size;
union {
u32 data[0];
struct dl_block blocks[0];
};
} *image;
struct dl_codeblock {
u32 npe_addr;
u32 size;
u32 data[0];
} *cb;
int i, j, err, data_size, instr_size, blocks, table_end;
u32 cmd;
if ((err = request_firmware(&fw_entry, name, dev)) != 0)
return err;
err = -EINVAL;
if (fw_entry->size < sizeof(struct dl_image)) {
print_npe(KERN_ERR, npe, "incomplete firmware file\n");
goto err;
}
image = (struct dl_image*)fw_entry->data;
#if DEBUG_FW
print_npe(KERN_DEBUG, npe, "firmware: %08X %08X %08X (0x%X bytes)\n",
image->magic, image->id, image->size, image->size * 4);
#endif
if (image->magic == swab32(FW_MAGIC)) { /* swapped file */
image->id = swab32(image->id);
image->size = swab32(image->size);
} else if (image->magic != FW_MAGIC) {
print_npe(KERN_ERR, npe, "bad firmware file magic: 0x%X\n",
image->magic);
goto err;
}
if ((image->size * 4 + sizeof(struct dl_image)) != fw_entry->size) {
print_npe(KERN_ERR, npe,
"inconsistent size of firmware file\n");
goto err;
}
if (((image->id >> 24) & 0xF /* NPE ID */) != npe->id) {
print_npe(KERN_ERR, npe, "firmware file NPE ID mismatch\n");
goto err;
}
if (image->magic == swab32(FW_MAGIC))
for (i = 0; i < image->size; i++)
image->data[i] = swab32(image->data[i]);
if (cpu_is_ixp42x() && ((image->id >> 28) & 0xF /* device ID */)) {
print_npe(KERN_INFO, npe, "IXP43x/IXP46x firmware ignored on "
"IXP42x\n");
goto err;
}
if (npe_running(npe)) {
print_npe(KERN_INFO, npe, "unable to load firmware, NPE is "
"already running\n");
err = -EBUSY;
goto err;
}
#if 0
npe_stop(npe);
npe_reset(npe);
#endif
print_npe(KERN_INFO, npe, "firmware functionality 0x%X, "
"revision 0x%X:%X\n", (image->id >> 16) & 0xFF,
(image->id >> 8) & 0xFF, image->id & 0xFF);
if (cpu_is_ixp42x()) {
if (!npe->id)
instr_size = NPE_A_42X_INSTR_SIZE;
else
instr_size = NPE_B_AND_C_42X_INSTR_SIZE;
data_size = NPE_42X_DATA_SIZE;
} else {
instr_size = NPE_46X_INSTR_SIZE;
data_size = NPE_46X_DATA_SIZE;
}
for (blocks = 0; blocks * sizeof(struct dl_block) / 4 < image->size;
blocks++)
if (image->blocks[blocks].type == FW_BLOCK_TYPE_EOF)
break;
if (blocks * sizeof(struct dl_block) / 4 >= image->size) {
print_npe(KERN_INFO, npe, "firmware EOF block marker not "
"found\n");
goto err;
}
#if DEBUG_FW
print_npe(KERN_DEBUG, npe, "%i firmware blocks found\n", blocks);
#endif
table_end = blocks * sizeof(struct dl_block) / 4 + 1 /* EOF marker */;
for (i = 0, blk = image->blocks; i < blocks; i++, blk++) {
if (blk->offset > image->size - sizeof(struct dl_codeblock) / 4
|| blk->offset < table_end) {
print_npe(KERN_INFO, npe, "invalid offset 0x%X of "
"firmware block #%i\n", blk->offset, i);
goto err;
}
cb = (struct dl_codeblock*)&image->data[blk->offset];
if (blk->type == FW_BLOCK_TYPE_INSTR) {
if (cb->npe_addr + cb->size > instr_size)
goto too_big;
cmd = CMD_WR_INS_MEM;
} else if (blk->type == FW_BLOCK_TYPE_DATA) {
if (cb->npe_addr + cb->size > data_size)
goto too_big;
cmd = CMD_WR_DATA_MEM;
} else {
print_npe(KERN_INFO, npe, "invalid firmware block #%i "
"type 0x%X\n", i, blk->type);
goto err;
}
if (blk->offset + sizeof(*cb) / 4 + cb->size > image->size) {
print_npe(KERN_INFO, npe, "firmware block #%i doesn't "
"fit in firmware image: type %c, start 0x%X,"
" length 0x%X\n", i,
blk->type == FW_BLOCK_TYPE_INSTR ? 'I' : 'D',
cb->npe_addr, cb->size);
goto err;
}
for (j = 0; j < cb->size; j++)
npe_cmd_write(npe, cb->npe_addr + j, cmd, cb->data[j]);
}
npe_start(npe);
if (!npe_running(npe))
print_npe(KERN_ERR, npe, "unable to start\n");
release_firmware(fw_entry);
return 0;
too_big:
print_npe(KERN_INFO, npe, "firmware block #%i doesn't fit in NPE "
"memory: type %c, start 0x%X, length 0x%X\n", i,
blk->type == FW_BLOCK_TYPE_INSTR ? 'I' : 'D',
cb->npe_addr, cb->size);
err:
release_firmware(fw_entry);
return err;
}
struct npe *npe_request(unsigned id)
{
if (id < NPE_COUNT)
if (npe_tab[id].valid)
if (try_module_get(THIS_MODULE))
return &npe_tab[id];
return NULL;
}
void npe_release(struct npe *npe)
{
module_put(THIS_MODULE);
}
static int __init npe_init_module(void)
{
int i, found = 0;
for (i = 0; i < NPE_COUNT; i++) {
struct npe *npe = &npe_tab[i];
if (!(ixp4xx_read_feature_bits() &
(IXP4XX_FEATURE_RESET_NPEA << i)))
continue; /* NPE already disabled or not present */
if (!(npe->mem_res = request_mem_region(npe->regs_phys,
REGS_SIZE,
npe_name(npe)))) {
print_npe(KERN_ERR, npe,
"failed to request memory region\n");
continue;
}
if (npe_reset(npe))
continue;
npe->valid = 1;
found++;
}
if (!found)
return -ENODEV;
return 0;
}
static void __exit npe_cleanup_module(void)
{
int i;
for (i = 0; i < NPE_COUNT; i++)
if (npe_tab[i].mem_res) {
npe_reset(&npe_tab[i]);
release_resource(npe_tab[i].mem_res);
}
}
module_init(npe_init_module);
module_exit(npe_cleanup_module);
MODULE_AUTHOR("Krzysztof Halasa");
MODULE_LICENSE("GPL v2");
MODULE_FIRMWARE(NPE_A_FIRMWARE);
MODULE_FIRMWARE(NPE_B_FIRMWARE);
MODULE_FIRMWARE(NPE_C_FIRMWARE);
EXPORT_SYMBOL(npe_names);
EXPORT_SYMBOL(npe_running);
EXPORT_SYMBOL(npe_request);
EXPORT_SYMBOL(npe_release);
EXPORT_SYMBOL(npe_load_firmware);
EXPORT_SYMBOL(npe_send_message);
EXPORT_SYMBOL(npe_recv_message);
EXPORT_SYMBOL(npe_send_recv_message);
| gpl-2.0 |
cile381/kernel_m7_4.4.3 | drivers/net/wireless/iwmc3200wifi/cfg80211.c | 5020 | 22230 | /*
* Intel Wireless Multicomm 3200 WiFi driver
*
* Copyright (C) 2009 Intel Corporation <ilw@linux.intel.com>
* Samuel Ortiz <samuel.ortiz@intel.com>
* Zhu Yi <yi.zhu@intel.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 Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/sched.h>
#include <linux/etherdevice.h>
#include <linux/wireless.h>
#include <linux/ieee80211.h>
#include <linux/slab.h>
#include <net/cfg80211.h>
#include "iwm.h"
#include "commands.h"
#include "cfg80211.h"
#include "debug.h"
#define RATETAB_ENT(_rate, _rateid, _flags) \
{ \
.bitrate = (_rate), \
.hw_value = (_rateid), \
.flags = (_flags), \
}
#define CHAN2G(_channel, _freq, _flags) { \
.band = IEEE80211_BAND_2GHZ, \
.center_freq = (_freq), \
.hw_value = (_channel), \
.flags = (_flags), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
#define CHAN5G(_channel, _flags) { \
.band = IEEE80211_BAND_5GHZ, \
.center_freq = 5000 + (5 * (_channel)), \
.hw_value = (_channel), \
.flags = (_flags), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
static struct ieee80211_rate iwm_rates[] = {
RATETAB_ENT(10, 0x1, 0),
RATETAB_ENT(20, 0x2, 0),
RATETAB_ENT(55, 0x4, 0),
RATETAB_ENT(110, 0x8, 0),
RATETAB_ENT(60, 0x10, 0),
RATETAB_ENT(90, 0x20, 0),
RATETAB_ENT(120, 0x40, 0),
RATETAB_ENT(180, 0x80, 0),
RATETAB_ENT(240, 0x100, 0),
RATETAB_ENT(360, 0x200, 0),
RATETAB_ENT(480, 0x400, 0),
RATETAB_ENT(540, 0x800, 0),
};
#define iwm_a_rates (iwm_rates + 4)
#define iwm_a_rates_size 8
#define iwm_g_rates (iwm_rates + 0)
#define iwm_g_rates_size 12
static struct ieee80211_channel iwm_2ghz_channels[] = {
CHAN2G(1, 2412, 0),
CHAN2G(2, 2417, 0),
CHAN2G(3, 2422, 0),
CHAN2G(4, 2427, 0),
CHAN2G(5, 2432, 0),
CHAN2G(6, 2437, 0),
CHAN2G(7, 2442, 0),
CHAN2G(8, 2447, 0),
CHAN2G(9, 2452, 0),
CHAN2G(10, 2457, 0),
CHAN2G(11, 2462, 0),
CHAN2G(12, 2467, 0),
CHAN2G(13, 2472, 0),
CHAN2G(14, 2484, 0),
};
static struct ieee80211_channel iwm_5ghz_a_channels[] = {
CHAN5G(34, 0), CHAN5G(36, 0),
CHAN5G(38, 0), CHAN5G(40, 0),
CHAN5G(42, 0), CHAN5G(44, 0),
CHAN5G(46, 0), CHAN5G(48, 0),
CHAN5G(52, 0), CHAN5G(56, 0),
CHAN5G(60, 0), CHAN5G(64, 0),
CHAN5G(100, 0), CHAN5G(104, 0),
CHAN5G(108, 0), CHAN5G(112, 0),
CHAN5G(116, 0), CHAN5G(120, 0),
CHAN5G(124, 0), CHAN5G(128, 0),
CHAN5G(132, 0), CHAN5G(136, 0),
CHAN5G(140, 0), CHAN5G(149, 0),
CHAN5G(153, 0), CHAN5G(157, 0),
CHAN5G(161, 0), CHAN5G(165, 0),
CHAN5G(184, 0), CHAN5G(188, 0),
CHAN5G(192, 0), CHAN5G(196, 0),
CHAN5G(200, 0), CHAN5G(204, 0),
CHAN5G(208, 0), CHAN5G(212, 0),
CHAN5G(216, 0),
};
static struct ieee80211_supported_band iwm_band_2ghz = {
.channels = iwm_2ghz_channels,
.n_channels = ARRAY_SIZE(iwm_2ghz_channels),
.bitrates = iwm_g_rates,
.n_bitrates = iwm_g_rates_size,
};
static struct ieee80211_supported_band iwm_band_5ghz = {
.channels = iwm_5ghz_a_channels,
.n_channels = ARRAY_SIZE(iwm_5ghz_a_channels),
.bitrates = iwm_a_rates,
.n_bitrates = iwm_a_rates_size,
};
static int iwm_key_init(struct iwm_key *key, u8 key_index,
const u8 *mac_addr, struct key_params *params)
{
key->hdr.key_idx = key_index;
if (!mac_addr || is_broadcast_ether_addr(mac_addr)) {
key->hdr.multicast = 1;
memset(key->hdr.mac, 0xff, ETH_ALEN);
} else {
key->hdr.multicast = 0;
memcpy(key->hdr.mac, mac_addr, ETH_ALEN);
}
if (params) {
if (params->key_len > WLAN_MAX_KEY_LEN ||
params->seq_len > IW_ENCODE_SEQ_MAX_SIZE)
return -EINVAL;
key->cipher = params->cipher;
key->key_len = params->key_len;
key->seq_len = params->seq_len;
memcpy(key->key, params->key, key->key_len);
memcpy(key->seq, params->seq, key->seq_len);
}
return 0;
}
static int iwm_cfg80211_add_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_index, bool pairwise, const u8 *mac_addr,
struct key_params *params)
{
struct iwm_priv *iwm = ndev_to_iwm(ndev);
struct iwm_key *key;
int ret;
IWM_DBG_WEXT(iwm, DBG, "Adding key for %pM\n", mac_addr);
if (key_index >= IWM_NUM_KEYS)
return -ENOENT;
key = &iwm->keys[key_index];
memset(key, 0, sizeof(struct iwm_key));
ret = iwm_key_init(key, key_index, mac_addr, params);
if (ret < 0) {
IWM_ERR(iwm, "Invalid key_params\n");
return ret;
}
return iwm_set_key(iwm, 0, key);
}
static int iwm_cfg80211_get_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_index, bool pairwise, const u8 *mac_addr,
void *cookie,
void (*callback)(void *cookie,
struct key_params*))
{
struct iwm_priv *iwm = ndev_to_iwm(ndev);
struct iwm_key *key;
struct key_params params;
IWM_DBG_WEXT(iwm, DBG, "Getting key %d\n", key_index);
if (key_index >= IWM_NUM_KEYS)
return -ENOENT;
memset(¶ms, 0, sizeof(params));
key = &iwm->keys[key_index];
params.cipher = key->cipher;
params.key_len = key->key_len;
params.seq_len = key->seq_len;
params.seq = key->seq;
params.key = key->key;
callback(cookie, ¶ms);
return key->key_len ? 0 : -ENOENT;
}
static int iwm_cfg80211_del_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_index, bool pairwise, const u8 *mac_addr)
{
struct iwm_priv *iwm = ndev_to_iwm(ndev);
struct iwm_key *key;
if (key_index >= IWM_NUM_KEYS)
return -ENOENT;
key = &iwm->keys[key_index];
if (!iwm->keys[key_index].key_len) {
IWM_DBG_WEXT(iwm, DBG, "Key %d not used\n", key_index);
return 0;
}
if (key_index == iwm->default_key)
iwm->default_key = -1;
return iwm_set_key(iwm, 1, key);
}
static int iwm_cfg80211_set_default_key(struct wiphy *wiphy,
struct net_device *ndev,
u8 key_index, bool unicast,
bool multicast)
{
struct iwm_priv *iwm = ndev_to_iwm(ndev);
IWM_DBG_WEXT(iwm, DBG, "Default key index is: %d\n", key_index);
if (key_index >= IWM_NUM_KEYS)
return -ENOENT;
if (!iwm->keys[key_index].key_len) {
IWM_ERR(iwm, "Key %d not used\n", key_index);
return -EINVAL;
}
iwm->default_key = key_index;
return iwm_set_tx_key(iwm, key_index);
}
static int iwm_cfg80211_get_station(struct wiphy *wiphy,
struct net_device *ndev,
u8 *mac, struct station_info *sinfo)
{
struct iwm_priv *iwm = ndev_to_iwm(ndev);
if (memcmp(mac, iwm->bssid, ETH_ALEN))
return -ENOENT;
sinfo->filled |= STATION_INFO_TX_BITRATE;
sinfo->txrate.legacy = iwm->rate * 10;
if (test_bit(IWM_STATUS_ASSOCIATED, &iwm->status)) {
sinfo->filled |= STATION_INFO_SIGNAL;
sinfo->signal = iwm->wstats.qual.level;
}
return 0;
}
int iwm_cfg80211_inform_bss(struct iwm_priv *iwm)
{
struct wiphy *wiphy = iwm_to_wiphy(iwm);
struct iwm_bss_info *bss;
struct iwm_umac_notif_bss_info *umac_bss;
struct ieee80211_mgmt *mgmt;
struct ieee80211_channel *channel;
struct ieee80211_supported_band *band;
s32 signal;
int freq;
list_for_each_entry(bss, &iwm->bss_list, node) {
umac_bss = bss->bss;
mgmt = (struct ieee80211_mgmt *)(umac_bss->frame_buf);
if (umac_bss->band == UMAC_BAND_2GHZ)
band = wiphy->bands[IEEE80211_BAND_2GHZ];
else if (umac_bss->band == UMAC_BAND_5GHZ)
band = wiphy->bands[IEEE80211_BAND_5GHZ];
else {
IWM_ERR(iwm, "Invalid band: %d\n", umac_bss->band);
return -EINVAL;
}
freq = ieee80211_channel_to_frequency(umac_bss->channel,
band->band);
channel = ieee80211_get_channel(wiphy, freq);
signal = umac_bss->rssi * 100;
if (!cfg80211_inform_bss_frame(wiphy, channel, mgmt,
le16_to_cpu(umac_bss->frame_len),
signal, GFP_KERNEL))
return -EINVAL;
}
return 0;
}
static int iwm_cfg80211_change_iface(struct wiphy *wiphy,
struct net_device *ndev,
enum nl80211_iftype type, u32 *flags,
struct vif_params *params)
{
struct wireless_dev *wdev;
struct iwm_priv *iwm;
u32 old_mode;
wdev = ndev->ieee80211_ptr;
iwm = ndev_to_iwm(ndev);
old_mode = iwm->conf.mode;
switch (type) {
case NL80211_IFTYPE_STATION:
iwm->conf.mode = UMAC_MODE_BSS;
break;
case NL80211_IFTYPE_ADHOC:
iwm->conf.mode = UMAC_MODE_IBSS;
break;
default:
return -EOPNOTSUPP;
}
wdev->iftype = type;
if ((old_mode == iwm->conf.mode) || !iwm->umac_profile)
return 0;
iwm->umac_profile->mode = cpu_to_le32(iwm->conf.mode);
if (iwm->umac_profile_active)
iwm_invalidate_mlme_profile(iwm);
return 0;
}
static int iwm_cfg80211_scan(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_scan_request *request)
{
struct iwm_priv *iwm = ndev_to_iwm(ndev);
int ret;
if (!test_bit(IWM_STATUS_READY, &iwm->status)) {
IWM_ERR(iwm, "Scan while device is not ready\n");
return -EIO;
}
if (test_bit(IWM_STATUS_SCANNING, &iwm->status)) {
IWM_ERR(iwm, "Scanning already\n");
return -EAGAIN;
}
if (test_bit(IWM_STATUS_SCAN_ABORTING, &iwm->status)) {
IWM_ERR(iwm, "Scanning being aborted\n");
return -EAGAIN;
}
set_bit(IWM_STATUS_SCANNING, &iwm->status);
ret = iwm_scan_ssids(iwm, request->ssids, request->n_ssids);
if (ret) {
clear_bit(IWM_STATUS_SCANNING, &iwm->status);
return ret;
}
iwm->scan_request = request;
return 0;
}
static int iwm_cfg80211_set_wiphy_params(struct wiphy *wiphy, u32 changed)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
if (changed & WIPHY_PARAM_RTS_THRESHOLD &&
(iwm->conf.rts_threshold != wiphy->rts_threshold)) {
int ret;
iwm->conf.rts_threshold = wiphy->rts_threshold;
ret = iwm_umac_set_config_fix(iwm, UMAC_PARAM_TBL_CFG_FIX,
CFG_RTS_THRESHOLD,
iwm->conf.rts_threshold);
if (ret < 0)
return ret;
}
if (changed & WIPHY_PARAM_FRAG_THRESHOLD &&
(iwm->conf.frag_threshold != wiphy->frag_threshold)) {
int ret;
iwm->conf.frag_threshold = wiphy->frag_threshold;
ret = iwm_umac_set_config_fix(iwm, UMAC_PARAM_TBL_FA_CFG_FIX,
CFG_FRAG_THRESHOLD,
iwm->conf.frag_threshold);
if (ret < 0)
return ret;
}
return 0;
}
static int iwm_cfg80211_join_ibss(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_ibss_params *params)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
struct ieee80211_channel *chan = params->channel;
if (!test_bit(IWM_STATUS_READY, &iwm->status))
return -EIO;
/* UMAC doesn't support creating or joining an IBSS network
* with specified bssid. */
if (params->bssid)
return -EOPNOTSUPP;
iwm->channel = ieee80211_frequency_to_channel(chan->center_freq);
iwm->umac_profile->ibss.band = chan->band;
iwm->umac_profile->ibss.channel = iwm->channel;
iwm->umac_profile->ssid.ssid_len = params->ssid_len;
memcpy(iwm->umac_profile->ssid.ssid, params->ssid, params->ssid_len);
return iwm_send_mlme_profile(iwm);
}
static int iwm_cfg80211_leave_ibss(struct wiphy *wiphy, struct net_device *dev)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
if (iwm->umac_profile_active)
return iwm_invalidate_mlme_profile(iwm);
return 0;
}
static int iwm_set_auth_type(struct iwm_priv *iwm,
enum nl80211_auth_type sme_auth_type)
{
u8 *auth_type = &iwm->umac_profile->sec.auth_type;
switch (sme_auth_type) {
case NL80211_AUTHTYPE_AUTOMATIC:
case NL80211_AUTHTYPE_OPEN_SYSTEM:
IWM_DBG_WEXT(iwm, DBG, "OPEN auth\n");
*auth_type = UMAC_AUTH_TYPE_OPEN;
break;
case NL80211_AUTHTYPE_SHARED_KEY:
if (iwm->umac_profile->sec.flags &
(UMAC_SEC_FLG_WPA_ON_MSK | UMAC_SEC_FLG_RSNA_ON_MSK)) {
IWM_DBG_WEXT(iwm, DBG, "WPA auth alg\n");
*auth_type = UMAC_AUTH_TYPE_RSNA_PSK;
} else {
IWM_DBG_WEXT(iwm, DBG, "WEP shared key auth alg\n");
*auth_type = UMAC_AUTH_TYPE_LEGACY_PSK;
}
break;
default:
IWM_ERR(iwm, "Unsupported auth alg: 0x%x\n", sme_auth_type);
return -ENOTSUPP;
}
return 0;
}
static int iwm_set_wpa_version(struct iwm_priv *iwm, u32 wpa_version)
{
IWM_DBG_WEXT(iwm, DBG, "wpa_version: %d\n", wpa_version);
if (!wpa_version) {
iwm->umac_profile->sec.flags = UMAC_SEC_FLG_LEGACY_PROFILE;
return 0;
}
if (wpa_version & NL80211_WPA_VERSION_1)
iwm->umac_profile->sec.flags = UMAC_SEC_FLG_WPA_ON_MSK;
if (wpa_version & NL80211_WPA_VERSION_2)
iwm->umac_profile->sec.flags = UMAC_SEC_FLG_RSNA_ON_MSK;
return 0;
}
static int iwm_set_cipher(struct iwm_priv *iwm, u32 cipher, bool ucast)
{
u8 *profile_cipher = ucast ? &iwm->umac_profile->sec.ucast_cipher :
&iwm->umac_profile->sec.mcast_cipher;
if (!cipher) {
*profile_cipher = UMAC_CIPHER_TYPE_NONE;
return 0;
}
IWM_DBG_WEXT(iwm, DBG, "%ccast cipher is 0x%x\n", ucast ? 'u' : 'm',
cipher);
switch (cipher) {
case IW_AUTH_CIPHER_NONE:
*profile_cipher = UMAC_CIPHER_TYPE_NONE;
break;
case WLAN_CIPHER_SUITE_WEP40:
*profile_cipher = UMAC_CIPHER_TYPE_WEP_40;
break;
case WLAN_CIPHER_SUITE_WEP104:
*profile_cipher = UMAC_CIPHER_TYPE_WEP_104;
break;
case WLAN_CIPHER_SUITE_TKIP:
*profile_cipher = UMAC_CIPHER_TYPE_TKIP;
break;
case WLAN_CIPHER_SUITE_CCMP:
*profile_cipher = UMAC_CIPHER_TYPE_CCMP;
break;
default:
IWM_ERR(iwm, "Unsupported cipher: 0x%x\n", cipher);
return -ENOTSUPP;
}
return 0;
}
static int iwm_set_key_mgt(struct iwm_priv *iwm, u32 key_mgt)
{
u8 *auth_type = &iwm->umac_profile->sec.auth_type;
IWM_DBG_WEXT(iwm, DBG, "key_mgt: 0x%x\n", key_mgt);
if (key_mgt == WLAN_AKM_SUITE_8021X)
*auth_type = UMAC_AUTH_TYPE_8021X;
else if (key_mgt == WLAN_AKM_SUITE_PSK) {
if (iwm->umac_profile->sec.flags &
(UMAC_SEC_FLG_WPA_ON_MSK | UMAC_SEC_FLG_RSNA_ON_MSK))
*auth_type = UMAC_AUTH_TYPE_RSNA_PSK;
else
*auth_type = UMAC_AUTH_TYPE_LEGACY_PSK;
} else {
IWM_ERR(iwm, "Invalid key mgt: 0x%x\n", key_mgt);
return -EINVAL;
}
return 0;
}
static int iwm_cfg80211_connect(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_connect_params *sme)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
struct ieee80211_channel *chan = sme->channel;
struct key_params key_param;
int ret;
if (!test_bit(IWM_STATUS_READY, &iwm->status))
return -EIO;
if (!sme->ssid)
return -EINVAL;
if (iwm->umac_profile_active) {
ret = iwm_invalidate_mlme_profile(iwm);
if (ret) {
IWM_ERR(iwm, "Couldn't invalidate profile\n");
return ret;
}
}
if (chan)
iwm->channel =
ieee80211_frequency_to_channel(chan->center_freq);
iwm->umac_profile->ssid.ssid_len = sme->ssid_len;
memcpy(iwm->umac_profile->ssid.ssid, sme->ssid, sme->ssid_len);
if (sme->bssid) {
IWM_DBG_WEXT(iwm, DBG, "BSSID: %pM\n", sme->bssid);
memcpy(&iwm->umac_profile->bssid[0], sme->bssid, ETH_ALEN);
iwm->umac_profile->bss_num = 1;
} else {
memset(&iwm->umac_profile->bssid[0], 0, ETH_ALEN);
iwm->umac_profile->bss_num = 0;
}
ret = iwm_set_wpa_version(iwm, sme->crypto.wpa_versions);
if (ret < 0)
return ret;
ret = iwm_set_auth_type(iwm, sme->auth_type);
if (ret < 0)
return ret;
if (sme->crypto.n_ciphers_pairwise) {
ret = iwm_set_cipher(iwm, sme->crypto.ciphers_pairwise[0],
true);
if (ret < 0)
return ret;
}
ret = iwm_set_cipher(iwm, sme->crypto.cipher_group, false);
if (ret < 0)
return ret;
if (sme->crypto.n_akm_suites) {
ret = iwm_set_key_mgt(iwm, sme->crypto.akm_suites[0]);
if (ret < 0)
return ret;
}
/*
* We save the WEP key in case we want to do shared authentication.
* We have to do it so because UMAC will assert whenever it gets a
* key before a profile.
*/
if (sme->key) {
key_param.key = kmemdup(sme->key, sme->key_len, GFP_KERNEL);
if (key_param.key == NULL)
return -ENOMEM;
key_param.key_len = sme->key_len;
key_param.seq_len = 0;
key_param.cipher = sme->crypto.ciphers_pairwise[0];
ret = iwm_key_init(&iwm->keys[sme->key_idx], sme->key_idx,
NULL, &key_param);
kfree(key_param.key);
if (ret < 0) {
IWM_ERR(iwm, "Invalid key_params\n");
return ret;
}
iwm->default_key = sme->key_idx;
}
/* WPA and open AUTH type from wpa_s means WPS (a.k.a. WSC) */
if ((iwm->umac_profile->sec.flags &
(UMAC_SEC_FLG_WPA_ON_MSK | UMAC_SEC_FLG_RSNA_ON_MSK)) &&
iwm->umac_profile->sec.auth_type == UMAC_AUTH_TYPE_OPEN) {
iwm->umac_profile->sec.flags = UMAC_SEC_FLG_WSC_ON_MSK;
}
ret = iwm_send_mlme_profile(iwm);
if (iwm->umac_profile->sec.auth_type != UMAC_AUTH_TYPE_LEGACY_PSK ||
sme->key == NULL)
return ret;
/*
* We want to do shared auth.
* We need to actually set the key we previously cached,
* and then tell the UMAC it's the default one.
* That will trigger the auth+assoc UMAC machinery, and again,
* this must be done after setting the profile.
*/
ret = iwm_set_key(iwm, 0, &iwm->keys[sme->key_idx]);
if (ret < 0)
return ret;
return iwm_set_tx_key(iwm, iwm->default_key);
}
static int iwm_cfg80211_disconnect(struct wiphy *wiphy, struct net_device *dev,
u16 reason_code)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
IWM_DBG_WEXT(iwm, DBG, "Active: %d\n", iwm->umac_profile_active);
if (iwm->umac_profile_active)
iwm_invalidate_mlme_profile(iwm);
return 0;
}
static int iwm_cfg80211_set_txpower(struct wiphy *wiphy,
enum nl80211_tx_power_setting type, int mbm)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
int ret;
switch (type) {
case NL80211_TX_POWER_AUTOMATIC:
return 0;
case NL80211_TX_POWER_FIXED:
if (mbm < 0 || (mbm % 100))
return -EOPNOTSUPP;
if (!test_bit(IWM_STATUS_READY, &iwm->status))
return 0;
ret = iwm_umac_set_config_fix(iwm, UMAC_PARAM_TBL_CFG_FIX,
CFG_TX_PWR_LIMIT_USR,
MBM_TO_DBM(mbm) * 2);
if (ret < 0)
return ret;
return iwm_tx_power_trigger(iwm);
default:
IWM_ERR(iwm, "Unsupported power type: %d\n", type);
return -EOPNOTSUPP;
}
return 0;
}
static int iwm_cfg80211_get_txpower(struct wiphy *wiphy, int *dbm)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
*dbm = iwm->txpower >> 1;
return 0;
}
static int iwm_cfg80211_set_power_mgmt(struct wiphy *wiphy,
struct net_device *dev,
bool enabled, int timeout)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
u32 power_index;
if (enabled)
power_index = IWM_POWER_INDEX_DEFAULT;
else
power_index = IWM_POWER_INDEX_MIN;
if (power_index == iwm->conf.power_index)
return 0;
iwm->conf.power_index = power_index;
return iwm_umac_set_config_fix(iwm, UMAC_PARAM_TBL_CFG_FIX,
CFG_POWER_INDEX, iwm->conf.power_index);
}
static int iwm_cfg80211_set_pmksa(struct wiphy *wiphy,
struct net_device *netdev,
struct cfg80211_pmksa *pmksa)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
return iwm_send_pmkid_update(iwm, pmksa, IWM_CMD_PMKID_ADD);
}
static int iwm_cfg80211_del_pmksa(struct wiphy *wiphy,
struct net_device *netdev,
struct cfg80211_pmksa *pmksa)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
return iwm_send_pmkid_update(iwm, pmksa, IWM_CMD_PMKID_DEL);
}
static int iwm_cfg80211_flush_pmksa(struct wiphy *wiphy,
struct net_device *netdev)
{
struct iwm_priv *iwm = wiphy_to_iwm(wiphy);
struct cfg80211_pmksa pmksa;
memset(&pmksa, 0, sizeof(struct cfg80211_pmksa));
return iwm_send_pmkid_update(iwm, &pmksa, IWM_CMD_PMKID_FLUSH);
}
static struct cfg80211_ops iwm_cfg80211_ops = {
.change_virtual_intf = iwm_cfg80211_change_iface,
.add_key = iwm_cfg80211_add_key,
.get_key = iwm_cfg80211_get_key,
.del_key = iwm_cfg80211_del_key,
.set_default_key = iwm_cfg80211_set_default_key,
.get_station = iwm_cfg80211_get_station,
.scan = iwm_cfg80211_scan,
.set_wiphy_params = iwm_cfg80211_set_wiphy_params,
.connect = iwm_cfg80211_connect,
.disconnect = iwm_cfg80211_disconnect,
.join_ibss = iwm_cfg80211_join_ibss,
.leave_ibss = iwm_cfg80211_leave_ibss,
.set_tx_power = iwm_cfg80211_set_txpower,
.get_tx_power = iwm_cfg80211_get_txpower,
.set_power_mgmt = iwm_cfg80211_set_power_mgmt,
.set_pmksa = iwm_cfg80211_set_pmksa,
.del_pmksa = iwm_cfg80211_del_pmksa,
.flush_pmksa = iwm_cfg80211_flush_pmksa,
};
static const u32 cipher_suites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
};
struct wireless_dev *iwm_wdev_alloc(int sizeof_bus, struct device *dev)
{
int ret = 0;
struct wireless_dev *wdev;
/*
* We're trying to have the following memory
* layout:
*
* +-------------------------+
* | struct wiphy |
* +-------------------------+
* | struct iwm_priv |
* +-------------------------+
* | bus private data |
* | (e.g. iwm_priv_sdio) |
* +-------------------------+
*
*/
wdev = kzalloc(sizeof(struct wireless_dev), GFP_KERNEL);
if (!wdev) {
dev_err(dev, "Couldn't allocate wireless device\n");
return ERR_PTR(-ENOMEM);
}
wdev->wiphy = wiphy_new(&iwm_cfg80211_ops,
sizeof(struct iwm_priv) + sizeof_bus);
if (!wdev->wiphy) {
dev_err(dev, "Couldn't allocate wiphy device\n");
ret = -ENOMEM;
goto out_err_new;
}
set_wiphy_dev(wdev->wiphy, dev);
wdev->wiphy->max_scan_ssids = UMAC_WIFI_IF_PROBE_OPTION_MAX;
wdev->wiphy->max_num_pmkids = UMAC_MAX_NUM_PMKIDS;
wdev->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC);
wdev->wiphy->bands[IEEE80211_BAND_2GHZ] = &iwm_band_2ghz;
wdev->wiphy->bands[IEEE80211_BAND_5GHZ] = &iwm_band_5ghz;
wdev->wiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM;
wdev->wiphy->cipher_suites = cipher_suites;
wdev->wiphy->n_cipher_suites = ARRAY_SIZE(cipher_suites);
ret = wiphy_register(wdev->wiphy);
if (ret < 0) {
dev_err(dev, "Couldn't register wiphy device\n");
goto out_err_register;
}
return wdev;
out_err_register:
wiphy_free(wdev->wiphy);
out_err_new:
kfree(wdev);
return ERR_PTR(ret);
}
void iwm_wdev_free(struct iwm_priv *iwm)
{
struct wireless_dev *wdev = iwm_to_wdev(iwm);
if (!wdev)
return;
wiphy_unregister(wdev->wiphy);
wiphy_free(wdev->wiphy);
kfree(wdev);
}
| gpl-2.0 |
NitroKK/kernel_lge_iproj | arch/m68k/emu/natfeat.c | 6300 | 1495 | /*
* natfeat.c - ARAnyM hardware support via Native Features (natfeats)
*
* Copyright (c) 2005 Petr Stehlik of ARAnyM dev team
*
* Reworked for Linux by Roman Zippel <zippel@linux-m68k.org>
*
* This software may be used and distributed according to the terms of
* the GNU General Public License (GPL), incorporated herein by reference.
*/
#include <linux/types.h>
#include <linux/console.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/io.h>
#include <asm/machdep.h>
#include <asm/natfeat.h>
asm("\n"
" .global nf_get_id,nf_call\n"
"nf_get_id:\n"
" .short 0x7300\n"
" rts\n"
"nf_call:\n"
" .short 0x7301\n"
" rts\n"
"1: moveq.l #0,%d0\n"
" rts\n"
" .section __ex_table,\"a\"\n"
" .long nf_get_id,1b\n"
" .long nf_call,1b\n"
" .previous");
EXPORT_SYMBOL_GPL(nf_get_id);
EXPORT_SYMBOL_GPL(nf_call);
void nfprint(const char *fmt, ...)
{
static char buf[256];
va_list ap;
int n;
va_start(ap, fmt);
n = vsnprintf(buf, 256, fmt, ap);
nf_call(nf_get_id("NF_STDERR"), buf);
va_end(ap);
}
static void nf_poweroff(void)
{
long id = nf_get_id("NF_SHUTDOWN");
if (id)
nf_call(id);
}
void nf_init(void)
{
unsigned long id, version;
char buf[256];
id = nf_get_id("NF_VERSION");
if (!id)
return;
version = nf_call(id);
id = nf_get_id("NF_NAME");
if (!id)
return;
nf_call(id, buf, 256);
buf[255] = 0;
pr_info("NatFeats found (%s, %lu.%lu)\n", buf, version >> 16,
version & 0xffff);
mach_power_off = nf_poweroff;
}
| gpl-2.0 |
insop/sched-deadline2 | arch/x86/um/syscalls_32.c | 8860 | 1828 | /*
* Copyright (C) 2000 - 2003 Jeff Dike (jdike@addtoit.com)
* Licensed under the GPL
*/
#include "linux/sched.h"
#include "linux/shm.h"
#include "linux/ipc.h"
#include "linux/syscalls.h"
#include "asm/mman.h"
#include "asm/uaccess.h"
#include "asm/unistd.h"
/*
* The prototype on i386 is:
*
* int clone(int flags, void * child_stack, int * parent_tidptr, struct user_desc * newtls, int * child_tidptr)
*
* and the "newtls" arg. on i386 is read by copy_thread directly from the
* register saved on the stack.
*/
long sys_clone(unsigned long clone_flags, unsigned long newsp,
int __user *parent_tid, void *newtls, int __user *child_tid)
{
long ret;
if (!newsp)
newsp = UPT_SP(¤t->thread.regs.regs);
current->thread.forking = 1;
ret = do_fork(clone_flags, newsp, ¤t->thread.regs, 0, parent_tid,
child_tid);
current->thread.forking = 0;
return ret;
}
long sys_sigaction(int sig, const struct old_sigaction __user *act,
struct old_sigaction __user *oact)
{
struct k_sigaction new_ka, old_ka;
int ret;
if (act) {
old_sigset_t mask;
if (!access_ok(VERIFY_READ, act, sizeof(*act)) ||
__get_user(new_ka.sa.sa_handler, &act->sa_handler) ||
__get_user(new_ka.sa.sa_restorer, &act->sa_restorer))
return -EFAULT;
__get_user(new_ka.sa.sa_flags, &act->sa_flags);
__get_user(mask, &act->sa_mask);
siginitset(&new_ka.sa.sa_mask, mask);
}
ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL);
if (!ret && oact) {
if (!access_ok(VERIFY_WRITE, oact, sizeof(*oact)) ||
__put_user(old_ka.sa.sa_handler, &oact->sa_handler) ||
__put_user(old_ka.sa.sa_restorer, &oact->sa_restorer))
return -EFAULT;
__put_user(old_ka.sa.sa_flags, &oact->sa_flags);
__put_user(old_ka.sa.sa_mask.sig[0], &oact->sa_mask);
}
return ret;
}
| gpl-2.0 |
wyldstallyns/roughneck-m8 | drivers/input/joystick/maplecontrol.c | 9884 | 4963 | /*
* SEGA Dreamcast controller driver
* Based on drivers/usb/iforce.c
*
* Copyright Yaegashi Takeshi, 2001
* Adrian McMenamin, 2008 - 2009
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/maple.h>
MODULE_AUTHOR("Adrian McMenamin <adrian@mcmen.demon.co.uk>");
MODULE_DESCRIPTION("SEGA Dreamcast controller driver");
MODULE_LICENSE("GPL");
struct dc_pad {
struct input_dev *dev;
struct maple_device *mdev;
};
static void dc_pad_callback(struct mapleq *mq)
{
unsigned short buttons;
struct maple_device *mapledev = mq->dev;
struct dc_pad *pad = maple_get_drvdata(mapledev);
struct input_dev *dev = pad->dev;
unsigned char *res = mq->recvbuf->buf;
buttons = ~le16_to_cpup((__le16 *)(res + 8));
input_report_abs(dev, ABS_HAT0Y,
(buttons & 0x0010 ? -1 : 0) + (buttons & 0x0020 ? 1 : 0));
input_report_abs(dev, ABS_HAT0X,
(buttons & 0x0040 ? -1 : 0) + (buttons & 0x0080 ? 1 : 0));
input_report_abs(dev, ABS_HAT1Y,
(buttons & 0x1000 ? -1 : 0) + (buttons & 0x2000 ? 1 : 0));
input_report_abs(dev, ABS_HAT1X,
(buttons & 0x4000 ? -1 : 0) + (buttons & 0x8000 ? 1 : 0));
input_report_key(dev, BTN_C, buttons & 0x0001);
input_report_key(dev, BTN_B, buttons & 0x0002);
input_report_key(dev, BTN_A, buttons & 0x0004);
input_report_key(dev, BTN_START, buttons & 0x0008);
input_report_key(dev, BTN_Z, buttons & 0x0100);
input_report_key(dev, BTN_Y, buttons & 0x0200);
input_report_key(dev, BTN_X, buttons & 0x0400);
input_report_key(dev, BTN_SELECT, buttons & 0x0800);
input_report_abs(dev, ABS_GAS, res[10]);
input_report_abs(dev, ABS_BRAKE, res[11]);
input_report_abs(dev, ABS_X, res[12]);
input_report_abs(dev, ABS_Y, res[13]);
input_report_abs(dev, ABS_RX, res[14]);
input_report_abs(dev, ABS_RY, res[15]);
}
static int dc_pad_open(struct input_dev *dev)
{
struct dc_pad *pad = dev->dev.platform_data;
maple_getcond_callback(pad->mdev, dc_pad_callback, HZ/20,
MAPLE_FUNC_CONTROLLER);
return 0;
}
static void dc_pad_close(struct input_dev *dev)
{
struct dc_pad *pad = dev->dev.platform_data;
maple_getcond_callback(pad->mdev, dc_pad_callback, 0,
MAPLE_FUNC_CONTROLLER);
}
/* allow the controller to be used */
static int __devinit probe_maple_controller(struct device *dev)
{
static const short btn_bit[32] = {
BTN_C, BTN_B, BTN_A, BTN_START, -1, -1, -1, -1,
BTN_Z, BTN_Y, BTN_X, BTN_SELECT, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
};
static const short abs_bit[32] = {
-1, -1, -1, -1, ABS_HAT0Y, ABS_HAT0Y, ABS_HAT0X, ABS_HAT0X,
-1, -1, -1, -1, ABS_HAT1Y, ABS_HAT1Y, ABS_HAT1X, ABS_HAT1X,
ABS_GAS, ABS_BRAKE, ABS_X, ABS_Y, ABS_RX, ABS_RY, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
};
struct maple_device *mdev = to_maple_dev(dev);
struct maple_driver *mdrv = to_maple_driver(dev->driver);
int i, error;
struct dc_pad *pad;
struct input_dev *idev;
unsigned long data = be32_to_cpu(mdev->devinfo.function_data[0]);
pad = kzalloc(sizeof(struct dc_pad), GFP_KERNEL);
idev = input_allocate_device();
if (!pad || !idev) {
error = -ENOMEM;
goto fail;
}
pad->dev = idev;
pad->mdev = mdev;
idev->open = dc_pad_open;
idev->close = dc_pad_close;
for (i = 0; i < 32; i++) {
if (data & (1 << i)) {
if (btn_bit[i] >= 0)
__set_bit(btn_bit[i], idev->keybit);
else if (abs_bit[i] >= 0)
__set_bit(abs_bit[i], idev->absbit);
}
}
if (idev->keybit[BIT_WORD(BTN_JOYSTICK)])
idev->evbit[0] |= BIT_MASK(EV_KEY);
if (idev->absbit[0])
idev->evbit[0] |= BIT_MASK(EV_ABS);
for (i = ABS_X; i <= ABS_BRAKE; i++)
input_set_abs_params(idev, i, 0, 255, 0, 0);
for (i = ABS_HAT0X; i <= ABS_HAT3Y; i++)
input_set_abs_params(idev, i, 1, -1, 0, 0);
idev->dev.platform_data = pad;
idev->dev.parent = &mdev->dev;
idev->name = mdev->product_name;
idev->id.bustype = BUS_HOST;
input_set_drvdata(idev, pad);
error = input_register_device(idev);
if (error)
goto fail;
mdev->driver = mdrv;
maple_set_drvdata(mdev, pad);
return 0;
fail:
input_free_device(idev);
kfree(pad);
maple_set_drvdata(mdev, NULL);
return error;
}
static int __devexit remove_maple_controller(struct device *dev)
{
struct maple_device *mdev = to_maple_dev(dev);
struct dc_pad *pad = maple_get_drvdata(mdev);
mdev->callback = NULL;
input_unregister_device(pad->dev);
maple_set_drvdata(mdev, NULL);
kfree(pad);
return 0;
}
static struct maple_driver dc_pad_driver = {
.function = MAPLE_FUNC_CONTROLLER,
.drv = {
.name = "Dreamcast_controller",
.probe = probe_maple_controller,
.remove = __devexit_p(remove_maple_controller),
},
};
static int __init dc_pad_init(void)
{
return maple_driver_register(&dc_pad_driver);
}
static void __exit dc_pad_exit(void)
{
maple_driver_unregister(&dc_pad_driver);
}
module_init(dc_pad_init);
module_exit(dc_pad_exit);
| gpl-2.0 |
omnirom/android_kernel_lge_x3 | fs/afs/security.c | 10140 | 9138 | /* AFS security handling
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/ctype.h>
#include <linux/sched.h>
#include <keys/rxrpc-type.h>
#include "internal.h"
/*
* get a key
*/
struct key *afs_request_key(struct afs_cell *cell)
{
struct key *key;
_enter("{%x}", key_serial(cell->anonymous_key));
_debug("key %s", cell->anonymous_key->description);
key = request_key(&key_type_rxrpc, cell->anonymous_key->description,
NULL);
if (IS_ERR(key)) {
if (PTR_ERR(key) != -ENOKEY) {
_leave(" = %ld", PTR_ERR(key));
return key;
}
/* act as anonymous user */
_leave(" = {%x} [anon]", key_serial(cell->anonymous_key));
return key_get(cell->anonymous_key);
} else {
/* act as authorised user */
_leave(" = {%x} [auth]", key_serial(key));
return key;
}
}
/*
* dispose of a permits list
*/
void afs_zap_permits(struct rcu_head *rcu)
{
struct afs_permits *permits =
container_of(rcu, struct afs_permits, rcu);
int loop;
_enter("{%d}", permits->count);
for (loop = permits->count - 1; loop >= 0; loop--)
key_put(permits->permits[loop].key);
kfree(permits);
}
/*
* dispose of a permits list in which all the key pointers have been copied
*/
static void afs_dispose_of_permits(struct rcu_head *rcu)
{
struct afs_permits *permits =
container_of(rcu, struct afs_permits, rcu);
_enter("{%d}", permits->count);
kfree(permits);
}
/*
* get the authorising vnode - this is the specified inode itself if it's a
* directory or it's the parent directory if the specified inode is a file or
* symlink
* - the caller must release the ref on the inode
*/
static struct afs_vnode *afs_get_auth_inode(struct afs_vnode *vnode,
struct key *key)
{
struct afs_vnode *auth_vnode;
struct inode *auth_inode;
_enter("");
if (S_ISDIR(vnode->vfs_inode.i_mode)) {
auth_inode = igrab(&vnode->vfs_inode);
ASSERT(auth_inode != NULL);
} else {
auth_inode = afs_iget(vnode->vfs_inode.i_sb, key,
&vnode->status.parent, NULL, NULL);
if (IS_ERR(auth_inode))
return ERR_CAST(auth_inode);
}
auth_vnode = AFS_FS_I(auth_inode);
_leave(" = {%x}", auth_vnode->fid.vnode);
return auth_vnode;
}
/*
* clear the permit cache on a directory vnode
*/
void afs_clear_permits(struct afs_vnode *vnode)
{
struct afs_permits *permits;
_enter("{%x:%u}", vnode->fid.vid, vnode->fid.vnode);
mutex_lock(&vnode->permits_lock);
permits = vnode->permits;
rcu_assign_pointer(vnode->permits, NULL);
mutex_unlock(&vnode->permits_lock);
if (permits)
call_rcu(&permits->rcu, afs_zap_permits);
_leave("");
}
/*
* add the result obtained for a vnode to its or its parent directory's cache
* for the key used to access it
*/
void afs_cache_permit(struct afs_vnode *vnode, struct key *key, long acl_order)
{
struct afs_permits *permits, *xpermits;
struct afs_permit *permit;
struct afs_vnode *auth_vnode;
int count, loop;
_enter("{%x:%u},%x,%lx",
vnode->fid.vid, vnode->fid.vnode, key_serial(key), acl_order);
auth_vnode = afs_get_auth_inode(vnode, key);
if (IS_ERR(auth_vnode)) {
_leave(" [get error %ld]", PTR_ERR(auth_vnode));
return;
}
mutex_lock(&auth_vnode->permits_lock);
/* guard against a rename being detected whilst we waited for the
* lock */
if (memcmp(&auth_vnode->fid, &vnode->status.parent,
sizeof(struct afs_fid)) != 0) {
_debug("renamed");
goto out_unlock;
}
/* have to be careful as the directory's callback may be broken between
* us receiving the status we're trying to cache and us getting the
* lock to update the cache for the status */
if (auth_vnode->acl_order - acl_order > 0) {
_debug("ACL changed?");
goto out_unlock;
}
/* always update the anonymous mask */
_debug("anon access %x", vnode->status.anon_access);
auth_vnode->status.anon_access = vnode->status.anon_access;
if (key == vnode->volume->cell->anonymous_key)
goto out_unlock;
xpermits = auth_vnode->permits;
count = 0;
if (xpermits) {
/* see if the permit is already in the list
* - if it is then we just amend the list
*/
count = xpermits->count;
permit = xpermits->permits;
for (loop = count; loop > 0; loop--) {
if (permit->key == key) {
permit->access_mask =
vnode->status.caller_access;
goto out_unlock;
}
permit++;
}
}
permits = kmalloc(sizeof(*permits) + sizeof(*permit) * (count + 1),
GFP_NOFS);
if (!permits)
goto out_unlock;
if (xpermits)
memcpy(permits->permits, xpermits->permits,
count * sizeof(struct afs_permit));
_debug("key %x access %x",
key_serial(key), vnode->status.caller_access);
permits->permits[count].access_mask = vnode->status.caller_access;
permits->permits[count].key = key_get(key);
permits->count = count + 1;
rcu_assign_pointer(auth_vnode->permits, permits);
if (xpermits)
call_rcu(&xpermits->rcu, afs_dispose_of_permits);
out_unlock:
mutex_unlock(&auth_vnode->permits_lock);
iput(&auth_vnode->vfs_inode);
_leave("");
}
/*
* check with the fileserver to see if the directory or parent directory is
* permitted to be accessed with this authorisation, and if so, what access it
* is granted
*/
static int afs_check_permit(struct afs_vnode *vnode, struct key *key,
afs_access_t *_access)
{
struct afs_permits *permits;
struct afs_permit *permit;
struct afs_vnode *auth_vnode;
bool valid;
int loop, ret;
_enter("{%x:%u},%x",
vnode->fid.vid, vnode->fid.vnode, key_serial(key));
auth_vnode = afs_get_auth_inode(vnode, key);
if (IS_ERR(auth_vnode)) {
*_access = 0;
_leave(" = %ld", PTR_ERR(auth_vnode));
return PTR_ERR(auth_vnode);
}
ASSERT(S_ISDIR(auth_vnode->vfs_inode.i_mode));
/* check the permits to see if we've got one yet */
if (key == auth_vnode->volume->cell->anonymous_key) {
_debug("anon");
*_access = auth_vnode->status.anon_access;
valid = true;
} else {
valid = false;
rcu_read_lock();
permits = rcu_dereference(auth_vnode->permits);
if (permits) {
permit = permits->permits;
for (loop = permits->count; loop > 0; loop--) {
if (permit->key == key) {
_debug("found in cache");
*_access = permit->access_mask;
valid = true;
break;
}
permit++;
}
}
rcu_read_unlock();
}
if (!valid) {
/* check the status on the file we're actually interested in
* (the post-processing will cache the result on auth_vnode) */
_debug("no valid permit");
set_bit(AFS_VNODE_CB_BROKEN, &vnode->flags);
ret = afs_vnode_fetch_status(vnode, auth_vnode, key);
if (ret < 0) {
iput(&auth_vnode->vfs_inode);
*_access = 0;
_leave(" = %d", ret);
return ret;
}
*_access = vnode->status.caller_access;
}
iput(&auth_vnode->vfs_inode);
_leave(" = 0 [access %x]", *_access);
return 0;
}
/*
* check the permissions on an AFS file
* - AFS ACLs are attached to directories only, and a file is controlled by its
* parent directory's ACL
*/
int afs_permission(struct inode *inode, int mask)
{
struct afs_vnode *vnode = AFS_FS_I(inode);
afs_access_t uninitialized_var(access);
struct key *key;
int ret;
if (mask & MAY_NOT_BLOCK)
return -ECHILD;
_enter("{{%x:%u},%lx},%x,",
vnode->fid.vid, vnode->fid.vnode, vnode->flags, mask);
key = afs_request_key(vnode->volume->cell);
if (IS_ERR(key)) {
_leave(" = %ld [key]", PTR_ERR(key));
return PTR_ERR(key);
}
/* if the promise has expired, we need to check the server again */
if (!vnode->cb_promised) {
_debug("not promised");
ret = afs_vnode_fetch_status(vnode, NULL, key);
if (ret < 0)
goto error;
_debug("new promise [fl=%lx]", vnode->flags);
}
/* check the permits to see if we've got one yet */
ret = afs_check_permit(vnode, key, &access);
if (ret < 0)
goto error;
/* interpret the access mask */
_debug("REQ %x ACC %x on %s",
mask, access, S_ISDIR(inode->i_mode) ? "dir" : "file");
if (S_ISDIR(inode->i_mode)) {
if (mask & MAY_EXEC) {
if (!(access & AFS_ACE_LOOKUP))
goto permission_denied;
} else if (mask & MAY_READ) {
if (!(access & AFS_ACE_READ))
goto permission_denied;
} else if (mask & MAY_WRITE) {
if (!(access & (AFS_ACE_DELETE | /* rmdir, unlink, rename from */
AFS_ACE_INSERT | /* create, mkdir, symlink, rename to */
AFS_ACE_WRITE))) /* chmod */
goto permission_denied;
} else {
BUG();
}
} else {
if (!(access & AFS_ACE_LOOKUP))
goto permission_denied;
if (mask & (MAY_EXEC | MAY_READ)) {
if (!(access & AFS_ACE_READ))
goto permission_denied;
} else if (mask & MAY_WRITE) {
if (!(access & AFS_ACE_WRITE))
goto permission_denied;
}
}
key_put(key);
ret = generic_permission(inode, mask);
_leave(" = %d", ret);
return ret;
permission_denied:
ret = -EACCES;
error:
key_put(key);
_leave(" = %d", ret);
return ret;
}
| gpl-2.0 |
TheMeddlingMonk/android_kernel_toshiba_tostab03 | drivers/media/dvb/dvb-core/dvb_math.c | 14748 | 5423 | /*
* dvb-math provides some complex fixed-point math
* operations shared between the dvb related stuff
*
* Copyright (C) 2006 Christoph Pfister (christophpfister@gmail.com)
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/bitops.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <asm/bug.h>
#include "dvb_math.h"
static const unsigned short logtable[256] = {
0x0000, 0x0171, 0x02e0, 0x044e, 0x05ba, 0x0725, 0x088e, 0x09f7,
0x0b5d, 0x0cc3, 0x0e27, 0x0f8a, 0x10eb, 0x124b, 0x13aa, 0x1508,
0x1664, 0x17bf, 0x1919, 0x1a71, 0x1bc8, 0x1d1e, 0x1e73, 0x1fc6,
0x2119, 0x226a, 0x23ba, 0x2508, 0x2656, 0x27a2, 0x28ed, 0x2a37,
0x2b80, 0x2cc8, 0x2e0f, 0x2f54, 0x3098, 0x31dc, 0x331e, 0x345f,
0x359f, 0x36de, 0x381b, 0x3958, 0x3a94, 0x3bce, 0x3d08, 0x3e41,
0x3f78, 0x40af, 0x41e4, 0x4319, 0x444c, 0x457f, 0x46b0, 0x47e1,
0x4910, 0x4a3f, 0x4b6c, 0x4c99, 0x4dc5, 0x4eef, 0x5019, 0x5142,
0x526a, 0x5391, 0x54b7, 0x55dc, 0x5700, 0x5824, 0x5946, 0x5a68,
0x5b89, 0x5ca8, 0x5dc7, 0x5ee5, 0x6003, 0x611f, 0x623a, 0x6355,
0x646f, 0x6588, 0x66a0, 0x67b7, 0x68ce, 0x69e4, 0x6af8, 0x6c0c,
0x6d20, 0x6e32, 0x6f44, 0x7055, 0x7165, 0x7274, 0x7383, 0x7490,
0x759d, 0x76aa, 0x77b5, 0x78c0, 0x79ca, 0x7ad3, 0x7bdb, 0x7ce3,
0x7dea, 0x7ef0, 0x7ff6, 0x80fb, 0x81ff, 0x8302, 0x8405, 0x8507,
0x8608, 0x8709, 0x8809, 0x8908, 0x8a06, 0x8b04, 0x8c01, 0x8cfe,
0x8dfa, 0x8ef5, 0x8fef, 0x90e9, 0x91e2, 0x92db, 0x93d2, 0x94ca,
0x95c0, 0x96b6, 0x97ab, 0x98a0, 0x9994, 0x9a87, 0x9b7a, 0x9c6c,
0x9d5e, 0x9e4f, 0x9f3f, 0xa02e, 0xa11e, 0xa20c, 0xa2fa, 0xa3e7,
0xa4d4, 0xa5c0, 0xa6ab, 0xa796, 0xa881, 0xa96a, 0xaa53, 0xab3c,
0xac24, 0xad0c, 0xadf2, 0xaed9, 0xafbe, 0xb0a4, 0xb188, 0xb26c,
0xb350, 0xb433, 0xb515, 0xb5f7, 0xb6d9, 0xb7ba, 0xb89a, 0xb97a,
0xba59, 0xbb38, 0xbc16, 0xbcf4, 0xbdd1, 0xbead, 0xbf8a, 0xc065,
0xc140, 0xc21b, 0xc2f5, 0xc3cf, 0xc4a8, 0xc580, 0xc658, 0xc730,
0xc807, 0xc8de, 0xc9b4, 0xca8a, 0xcb5f, 0xcc34, 0xcd08, 0xcddc,
0xceaf, 0xcf82, 0xd054, 0xd126, 0xd1f7, 0xd2c8, 0xd399, 0xd469,
0xd538, 0xd607, 0xd6d6, 0xd7a4, 0xd872, 0xd93f, 0xda0c, 0xdad9,
0xdba5, 0xdc70, 0xdd3b, 0xde06, 0xded0, 0xdf9a, 0xe063, 0xe12c,
0xe1f5, 0xe2bd, 0xe385, 0xe44c, 0xe513, 0xe5d9, 0xe69f, 0xe765,
0xe82a, 0xe8ef, 0xe9b3, 0xea77, 0xeb3b, 0xebfe, 0xecc1, 0xed83,
0xee45, 0xef06, 0xefc8, 0xf088, 0xf149, 0xf209, 0xf2c8, 0xf387,
0xf446, 0xf505, 0xf5c3, 0xf680, 0xf73e, 0xf7fb, 0xf8b7, 0xf973,
0xfa2f, 0xfaea, 0xfba5, 0xfc60, 0xfd1a, 0xfdd4, 0xfe8e, 0xff47
};
unsigned int intlog2(u32 value)
{
/**
* returns: log2(value) * 2^24
* wrong result if value = 0 (log2(0) is undefined)
*/
unsigned int msb;
unsigned int logentry;
unsigned int significand;
unsigned int interpolation;
if (unlikely(value == 0)) {
WARN_ON(1);
return 0;
}
/* first detect the msb (count begins at 0) */
msb = fls(value) - 1;
/**
* now we use a logtable after the following method:
*
* log2(2^x * y) * 2^24 = x * 2^24 + log2(y) * 2^24
* where x = msb and therefore 1 <= y < 2
* first y is determined by shifting the value left
* so that msb is bit 31
* 0x00231f56 -> 0x8C7D5800
* the result is y * 2^31 -> "significand"
* then the highest 9 bits are used for a table lookup
* the highest bit is discarded because it's always set
* the highest nine bits in our example are 100011000
* so we would use the entry 0x18
*/
significand = value << (31 - msb);
logentry = (significand >> 23) & 0xff;
/**
* last step we do is interpolation because of the
* limitations of the log table the error is that part of
* the significand which isn't used for lookup then we
* compute the ratio between the error and the next table entry
* and interpolate it between the log table entry used and the
* next one the biggest error possible is 0x7fffff
* (in our example it's 0x7D5800)
* needed value for next table entry is 0x800000
* so the interpolation is
* (error / 0x800000) * (logtable_next - logtable_current)
* in the implementation the division is moved to the end for
* better accuracy there is also an overflow correction if
* logtable_next is 256
*/
interpolation = ((significand & 0x7fffff) *
((logtable[(logentry + 1) & 0xff] -
logtable[logentry]) & 0xffff)) >> 15;
/* now we return the result */
return ((msb << 24) + (logtable[logentry] << 8) + interpolation);
}
EXPORT_SYMBOL(intlog2);
unsigned int intlog10(u32 value)
{
/**
* returns: log10(value) * 2^24
* wrong result if value = 0 (log10(0) is undefined)
*/
u64 log;
if (unlikely(value == 0)) {
WARN_ON(1);
return 0;
}
log = intlog2(value);
/**
* we use the following method:
* log10(x) = log2(x) * log10(2)
*/
return (log * 646456993) >> 31;
}
EXPORT_SYMBOL(intlog10);
| gpl-2.0 |
alexpotter1/QuantumKernel_msm8974_hammerhead | drivers/media/dvb/dvb-core/dvb_math.c | 14748 | 5423 | /*
* dvb-math provides some complex fixed-point math
* operations shared between the dvb related stuff
*
* Copyright (C) 2006 Christoph Pfister (christophpfister@gmail.com)
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/bitops.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <asm/bug.h>
#include "dvb_math.h"
static const unsigned short logtable[256] = {
0x0000, 0x0171, 0x02e0, 0x044e, 0x05ba, 0x0725, 0x088e, 0x09f7,
0x0b5d, 0x0cc3, 0x0e27, 0x0f8a, 0x10eb, 0x124b, 0x13aa, 0x1508,
0x1664, 0x17bf, 0x1919, 0x1a71, 0x1bc8, 0x1d1e, 0x1e73, 0x1fc6,
0x2119, 0x226a, 0x23ba, 0x2508, 0x2656, 0x27a2, 0x28ed, 0x2a37,
0x2b80, 0x2cc8, 0x2e0f, 0x2f54, 0x3098, 0x31dc, 0x331e, 0x345f,
0x359f, 0x36de, 0x381b, 0x3958, 0x3a94, 0x3bce, 0x3d08, 0x3e41,
0x3f78, 0x40af, 0x41e4, 0x4319, 0x444c, 0x457f, 0x46b0, 0x47e1,
0x4910, 0x4a3f, 0x4b6c, 0x4c99, 0x4dc5, 0x4eef, 0x5019, 0x5142,
0x526a, 0x5391, 0x54b7, 0x55dc, 0x5700, 0x5824, 0x5946, 0x5a68,
0x5b89, 0x5ca8, 0x5dc7, 0x5ee5, 0x6003, 0x611f, 0x623a, 0x6355,
0x646f, 0x6588, 0x66a0, 0x67b7, 0x68ce, 0x69e4, 0x6af8, 0x6c0c,
0x6d20, 0x6e32, 0x6f44, 0x7055, 0x7165, 0x7274, 0x7383, 0x7490,
0x759d, 0x76aa, 0x77b5, 0x78c0, 0x79ca, 0x7ad3, 0x7bdb, 0x7ce3,
0x7dea, 0x7ef0, 0x7ff6, 0x80fb, 0x81ff, 0x8302, 0x8405, 0x8507,
0x8608, 0x8709, 0x8809, 0x8908, 0x8a06, 0x8b04, 0x8c01, 0x8cfe,
0x8dfa, 0x8ef5, 0x8fef, 0x90e9, 0x91e2, 0x92db, 0x93d2, 0x94ca,
0x95c0, 0x96b6, 0x97ab, 0x98a0, 0x9994, 0x9a87, 0x9b7a, 0x9c6c,
0x9d5e, 0x9e4f, 0x9f3f, 0xa02e, 0xa11e, 0xa20c, 0xa2fa, 0xa3e7,
0xa4d4, 0xa5c0, 0xa6ab, 0xa796, 0xa881, 0xa96a, 0xaa53, 0xab3c,
0xac24, 0xad0c, 0xadf2, 0xaed9, 0xafbe, 0xb0a4, 0xb188, 0xb26c,
0xb350, 0xb433, 0xb515, 0xb5f7, 0xb6d9, 0xb7ba, 0xb89a, 0xb97a,
0xba59, 0xbb38, 0xbc16, 0xbcf4, 0xbdd1, 0xbead, 0xbf8a, 0xc065,
0xc140, 0xc21b, 0xc2f5, 0xc3cf, 0xc4a8, 0xc580, 0xc658, 0xc730,
0xc807, 0xc8de, 0xc9b4, 0xca8a, 0xcb5f, 0xcc34, 0xcd08, 0xcddc,
0xceaf, 0xcf82, 0xd054, 0xd126, 0xd1f7, 0xd2c8, 0xd399, 0xd469,
0xd538, 0xd607, 0xd6d6, 0xd7a4, 0xd872, 0xd93f, 0xda0c, 0xdad9,
0xdba5, 0xdc70, 0xdd3b, 0xde06, 0xded0, 0xdf9a, 0xe063, 0xe12c,
0xe1f5, 0xe2bd, 0xe385, 0xe44c, 0xe513, 0xe5d9, 0xe69f, 0xe765,
0xe82a, 0xe8ef, 0xe9b3, 0xea77, 0xeb3b, 0xebfe, 0xecc1, 0xed83,
0xee45, 0xef06, 0xefc8, 0xf088, 0xf149, 0xf209, 0xf2c8, 0xf387,
0xf446, 0xf505, 0xf5c3, 0xf680, 0xf73e, 0xf7fb, 0xf8b7, 0xf973,
0xfa2f, 0xfaea, 0xfba5, 0xfc60, 0xfd1a, 0xfdd4, 0xfe8e, 0xff47
};
unsigned int intlog2(u32 value)
{
/**
* returns: log2(value) * 2^24
* wrong result if value = 0 (log2(0) is undefined)
*/
unsigned int msb;
unsigned int logentry;
unsigned int significand;
unsigned int interpolation;
if (unlikely(value == 0)) {
WARN_ON(1);
return 0;
}
/* first detect the msb (count begins at 0) */
msb = fls(value) - 1;
/**
* now we use a logtable after the following method:
*
* log2(2^x * y) * 2^24 = x * 2^24 + log2(y) * 2^24
* where x = msb and therefore 1 <= y < 2
* first y is determined by shifting the value left
* so that msb is bit 31
* 0x00231f56 -> 0x8C7D5800
* the result is y * 2^31 -> "significand"
* then the highest 9 bits are used for a table lookup
* the highest bit is discarded because it's always set
* the highest nine bits in our example are 100011000
* so we would use the entry 0x18
*/
significand = value << (31 - msb);
logentry = (significand >> 23) & 0xff;
/**
* last step we do is interpolation because of the
* limitations of the log table the error is that part of
* the significand which isn't used for lookup then we
* compute the ratio between the error and the next table entry
* and interpolate it between the log table entry used and the
* next one the biggest error possible is 0x7fffff
* (in our example it's 0x7D5800)
* needed value for next table entry is 0x800000
* so the interpolation is
* (error / 0x800000) * (logtable_next - logtable_current)
* in the implementation the division is moved to the end for
* better accuracy there is also an overflow correction if
* logtable_next is 256
*/
interpolation = ((significand & 0x7fffff) *
((logtable[(logentry + 1) & 0xff] -
logtable[logentry]) & 0xffff)) >> 15;
/* now we return the result */
return ((msb << 24) + (logtable[logentry] << 8) + interpolation);
}
EXPORT_SYMBOL(intlog2);
unsigned int intlog10(u32 value)
{
/**
* returns: log10(value) * 2^24
* wrong result if value = 0 (log10(0) is undefined)
*/
u64 log;
if (unlikely(value == 0)) {
WARN_ON(1);
return 0;
}
log = intlog2(value);
/**
* we use the following method:
* log10(x) = log2(x) * log10(2)
*/
return (log * 646456993) >> 31;
}
EXPORT_SYMBOL(intlog10);
| gpl-2.0 |
lexi6725/linux-3.17.1 | drivers/i2c/busses/i2c-sirf.c | 413 | 12466 | /*
* I2C bus driver for CSR SiRFprimaII
*
* Copyright (c) 2011 Cambridge Silicon Radio Limited, a CSR plc group company.
*
* Licensed under GPLv2 or later.
*/
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#define SIRFSOC_I2C_CLK_CTRL 0x00
#define SIRFSOC_I2C_STATUS 0x0C
#define SIRFSOC_I2C_CTRL 0x10
#define SIRFSOC_I2C_IO_CTRL 0x14
#define SIRFSOC_I2C_SDA_DELAY 0x18
#define SIRFSOC_I2C_CMD_START 0x1C
#define SIRFSOC_I2C_CMD_BUF 0x30
#define SIRFSOC_I2C_DATA_BUF 0x80
#define SIRFSOC_I2C_CMD_BUF_MAX 16
#define SIRFSOC_I2C_DATA_BUF_MAX 16
#define SIRFSOC_I2C_CMD(x) (SIRFSOC_I2C_CMD_BUF + (x)*0x04)
#define SIRFSOC_I2C_DATA_MASK(x) (0xFF<<(((x)&3)*8))
#define SIRFSOC_I2C_DATA_SHIFT(x) (((x)&3)*8)
#define SIRFSOC_I2C_DIV_MASK (0xFFFF)
/* I2C status flags */
#define SIRFSOC_I2C_STAT_BUSY BIT(0)
#define SIRFSOC_I2C_STAT_TIP BIT(1)
#define SIRFSOC_I2C_STAT_NACK BIT(2)
#define SIRFSOC_I2C_STAT_TR_INT BIT(4)
#define SIRFSOC_I2C_STAT_STOP BIT(6)
#define SIRFSOC_I2C_STAT_CMD_DONE BIT(8)
#define SIRFSOC_I2C_STAT_ERR BIT(9)
#define SIRFSOC_I2C_CMD_INDEX (0x1F<<16)
/* I2C control flags */
#define SIRFSOC_I2C_RESET BIT(0)
#define SIRFSOC_I2C_CORE_EN BIT(1)
#define SIRFSOC_I2C_MASTER_MODE BIT(2)
#define SIRFSOC_I2C_CMD_DONE_EN BIT(11)
#define SIRFSOC_I2C_ERR_INT_EN BIT(12)
#define SIRFSOC_I2C_SDA_DELAY_MASK (0xFF)
#define SIRFSOC_I2C_SCLF_FILTER (3<<8)
#define SIRFSOC_I2C_START_CMD BIT(0)
#define SIRFSOC_I2C_CMD_RP(x) ((x)&0x7)
#define SIRFSOC_I2C_NACK BIT(3)
#define SIRFSOC_I2C_WRITE BIT(4)
#define SIRFSOC_I2C_READ BIT(5)
#define SIRFSOC_I2C_STOP BIT(6)
#define SIRFSOC_I2C_START BIT(7)
#define SIRFSOC_I2C_DEFAULT_SPEED 100000
#define SIRFSOC_I2C_ERR_NOACK 1
#define SIRFSOC_I2C_ERR_TIMEOUT 2
struct sirfsoc_i2c {
void __iomem *base;
struct clk *clk;
u32 cmd_ptr; /* Current position in CMD buffer */
u8 *buf; /* Buffer passed by user */
u32 msg_len; /* Message length */
u32 finished_len; /* number of bytes read/written */
u32 read_cmd_len; /* number of read cmd sent */
int msg_read; /* 1 indicates a read message */
int err_status; /* 1 indicates an error on bus */
u32 sda_delay; /* For suspend/resume */
u32 clk_div;
int last; /* Last message in transfer, STOP cmd can be sent */
struct completion done; /* indicates completion of message transfer */
struct i2c_adapter adapter;
};
static void i2c_sirfsoc_read_data(struct sirfsoc_i2c *siic)
{
u32 data = 0;
int i;
for (i = 0; i < siic->read_cmd_len; i++) {
if (!(i & 0x3))
data = readl(siic->base + SIRFSOC_I2C_DATA_BUF + i);
siic->buf[siic->finished_len++] =
(u8)((data & SIRFSOC_I2C_DATA_MASK(i)) >>
SIRFSOC_I2C_DATA_SHIFT(i));
}
}
static void i2c_sirfsoc_queue_cmd(struct sirfsoc_i2c *siic)
{
u32 regval;
int i = 0;
if (siic->msg_read) {
while (((siic->finished_len + i) < siic->msg_len)
&& (siic->cmd_ptr < SIRFSOC_I2C_CMD_BUF_MAX)) {
regval = SIRFSOC_I2C_READ | SIRFSOC_I2C_CMD_RP(0);
if (((siic->finished_len + i) ==
(siic->msg_len - 1)) && siic->last)
regval |= SIRFSOC_I2C_STOP | SIRFSOC_I2C_NACK;
writel(regval,
siic->base + SIRFSOC_I2C_CMD(siic->cmd_ptr++));
i++;
}
siic->read_cmd_len = i;
} else {
while ((siic->cmd_ptr < SIRFSOC_I2C_CMD_BUF_MAX - 1)
&& (siic->finished_len < siic->msg_len)) {
regval = SIRFSOC_I2C_WRITE | SIRFSOC_I2C_CMD_RP(0);
if ((siic->finished_len == (siic->msg_len - 1))
&& siic->last)
regval |= SIRFSOC_I2C_STOP;
writel(regval,
siic->base + SIRFSOC_I2C_CMD(siic->cmd_ptr++));
writel(siic->buf[siic->finished_len++],
siic->base + SIRFSOC_I2C_CMD(siic->cmd_ptr++));
}
}
siic->cmd_ptr = 0;
/* Trigger the transfer */
writel(SIRFSOC_I2C_START_CMD, siic->base + SIRFSOC_I2C_CMD_START);
}
static irqreturn_t i2c_sirfsoc_irq(int irq, void *dev_id)
{
struct sirfsoc_i2c *siic = (struct sirfsoc_i2c *)dev_id;
u32 i2c_stat = readl(siic->base + SIRFSOC_I2C_STATUS);
if (i2c_stat & SIRFSOC_I2C_STAT_ERR) {
/* Error conditions */
siic->err_status = SIRFSOC_I2C_ERR_NOACK;
writel(SIRFSOC_I2C_STAT_ERR, siic->base + SIRFSOC_I2C_STATUS);
if (i2c_stat & SIRFSOC_I2C_STAT_NACK)
dev_dbg(&siic->adapter.dev, "ACK not received\n");
else
dev_err(&siic->adapter.dev, "I2C error\n");
/*
* Due to hardware ANOMALY, we need to reset I2C earlier after
* we get NOACK while accessing non-existing clients, otherwise
* we will get errors even we access existing clients later
*/
writel(readl(siic->base + SIRFSOC_I2C_CTRL) | SIRFSOC_I2C_RESET,
siic->base + SIRFSOC_I2C_CTRL);
while (readl(siic->base + SIRFSOC_I2C_CTRL) & SIRFSOC_I2C_RESET)
cpu_relax();
complete(&siic->done);
} else if (i2c_stat & SIRFSOC_I2C_STAT_CMD_DONE) {
/* CMD buffer execution complete */
if (siic->msg_read)
i2c_sirfsoc_read_data(siic);
if (siic->finished_len == siic->msg_len)
complete(&siic->done);
else /* Fill a new CMD buffer for left data */
i2c_sirfsoc_queue_cmd(siic);
writel(SIRFSOC_I2C_STAT_CMD_DONE, siic->base + SIRFSOC_I2C_STATUS);
}
return IRQ_HANDLED;
}
static void i2c_sirfsoc_set_address(struct sirfsoc_i2c *siic,
struct i2c_msg *msg)
{
unsigned char addr;
u32 regval = SIRFSOC_I2C_START | SIRFSOC_I2C_CMD_RP(0) | SIRFSOC_I2C_WRITE;
/* no data and last message -> add STOP */
if (siic->last && (msg->len == 0))
regval |= SIRFSOC_I2C_STOP;
writel(regval, siic->base + SIRFSOC_I2C_CMD(siic->cmd_ptr++));
addr = msg->addr << 1; /* Generate address */
if (msg->flags & I2C_M_RD)
addr |= 1;
/* Reverse direction bit */
if (msg->flags & I2C_M_REV_DIR_ADDR)
addr ^= 1;
writel(addr, siic->base + SIRFSOC_I2C_CMD(siic->cmd_ptr++));
}
static int i2c_sirfsoc_xfer_msg(struct sirfsoc_i2c *siic, struct i2c_msg *msg)
{
u32 regval = readl(siic->base + SIRFSOC_I2C_CTRL);
/* timeout waiting for the xfer to finish or fail */
int timeout = msecs_to_jiffies((msg->len + 1) * 50);
i2c_sirfsoc_set_address(siic, msg);
writel(regval | SIRFSOC_I2C_CMD_DONE_EN | SIRFSOC_I2C_ERR_INT_EN,
siic->base + SIRFSOC_I2C_CTRL);
i2c_sirfsoc_queue_cmd(siic);
if (wait_for_completion_timeout(&siic->done, timeout) == 0) {
siic->err_status = SIRFSOC_I2C_ERR_TIMEOUT;
dev_err(&siic->adapter.dev, "Transfer timeout\n");
}
writel(regval & ~(SIRFSOC_I2C_CMD_DONE_EN | SIRFSOC_I2C_ERR_INT_EN),
siic->base + SIRFSOC_I2C_CTRL);
writel(0, siic->base + SIRFSOC_I2C_CMD_START);
/* i2c control doesn't response, reset it */
if (siic->err_status == SIRFSOC_I2C_ERR_TIMEOUT) {
writel(readl(siic->base + SIRFSOC_I2C_CTRL) | SIRFSOC_I2C_RESET,
siic->base + SIRFSOC_I2C_CTRL);
while (readl(siic->base + SIRFSOC_I2C_CTRL) & SIRFSOC_I2C_RESET)
cpu_relax();
}
return siic->err_status ? -EAGAIN : 0;
}
static u32 i2c_sirfsoc_func(struct i2c_adapter *adap)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
}
static int i2c_sirfsoc_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
int num)
{
struct sirfsoc_i2c *siic = adap->algo_data;
int i, ret;
clk_enable(siic->clk);
for (i = 0; i < num; i++) {
siic->buf = msgs[i].buf;
siic->msg_len = msgs[i].len;
siic->msg_read = !!(msgs[i].flags & I2C_M_RD);
siic->err_status = 0;
siic->cmd_ptr = 0;
siic->finished_len = 0;
siic->last = (i == (num - 1));
ret = i2c_sirfsoc_xfer_msg(siic, &msgs[i]);
if (ret) {
clk_disable(siic->clk);
return ret;
}
}
clk_disable(siic->clk);
return num;
}
/* I2C algorithms associated with this master controller driver */
static const struct i2c_algorithm i2c_sirfsoc_algo = {
.master_xfer = i2c_sirfsoc_xfer,
.functionality = i2c_sirfsoc_func,
};
static int i2c_sirfsoc_probe(struct platform_device *pdev)
{
struct sirfsoc_i2c *siic;
struct i2c_adapter *adap;
struct resource *mem_res;
struct clk *clk;
int bitrate;
int ctrl_speed;
int irq;
int err;
u32 regval;
clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(clk)) {
err = PTR_ERR(clk);
dev_err(&pdev->dev, "Clock get failed\n");
goto err_get_clk;
}
err = clk_prepare(clk);
if (err) {
dev_err(&pdev->dev, "Clock prepare failed\n");
goto err_clk_prep;
}
err = clk_enable(clk);
if (err) {
dev_err(&pdev->dev, "Clock enable failed\n");
goto err_clk_en;
}
ctrl_speed = clk_get_rate(clk);
siic = devm_kzalloc(&pdev->dev, sizeof(*siic), GFP_KERNEL);
if (!siic) {
err = -ENOMEM;
goto out;
}
adap = &siic->adapter;
adap->class = I2C_CLASS_DEPRECATED;
mem_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
siic->base = devm_ioremap_resource(&pdev->dev, mem_res);
if (IS_ERR(siic->base)) {
err = PTR_ERR(siic->base);
goto out;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
err = irq;
goto out;
}
err = devm_request_irq(&pdev->dev, irq, i2c_sirfsoc_irq, 0,
dev_name(&pdev->dev), siic);
if (err)
goto out;
adap->algo = &i2c_sirfsoc_algo;
adap->algo_data = siic;
adap->retries = 3;
adap->dev.of_node = pdev->dev.of_node;
adap->dev.parent = &pdev->dev;
adap->nr = pdev->id;
strlcpy(adap->name, "sirfsoc-i2c", sizeof(adap->name));
platform_set_drvdata(pdev, adap);
init_completion(&siic->done);
/* Controller Initalisation */
writel(SIRFSOC_I2C_RESET, siic->base + SIRFSOC_I2C_CTRL);
while (readl(siic->base + SIRFSOC_I2C_CTRL) & SIRFSOC_I2C_RESET)
cpu_relax();
writel(SIRFSOC_I2C_CORE_EN | SIRFSOC_I2C_MASTER_MODE,
siic->base + SIRFSOC_I2C_CTRL);
siic->clk = clk;
err = of_property_read_u32(pdev->dev.of_node,
"clock-frequency", &bitrate);
if (err < 0)
bitrate = SIRFSOC_I2C_DEFAULT_SPEED;
if (bitrate < 100000)
regval =
(2 * ctrl_speed) / (bitrate * 11);
else
regval = ctrl_speed / (bitrate * 5);
writel(regval, siic->base + SIRFSOC_I2C_CLK_CTRL);
if (regval > 0xFF)
writel(0xFF, siic->base + SIRFSOC_I2C_SDA_DELAY);
else
writel(regval, siic->base + SIRFSOC_I2C_SDA_DELAY);
err = i2c_add_numbered_adapter(adap);
if (err < 0) {
dev_err(&pdev->dev, "Can't add new i2c adapter\n");
goto out;
}
clk_disable(clk);
dev_info(&pdev->dev, " I2C adapter ready to operate\n");
return 0;
out:
clk_disable(clk);
err_clk_en:
clk_unprepare(clk);
err_clk_prep:
clk_put(clk);
err_get_clk:
return err;
}
static int i2c_sirfsoc_remove(struct platform_device *pdev)
{
struct i2c_adapter *adapter = platform_get_drvdata(pdev);
struct sirfsoc_i2c *siic = adapter->algo_data;
writel(SIRFSOC_I2C_RESET, siic->base + SIRFSOC_I2C_CTRL);
i2c_del_adapter(adapter);
clk_unprepare(siic->clk);
clk_put(siic->clk);
return 0;
}
#ifdef CONFIG_PM
static int i2c_sirfsoc_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct i2c_adapter *adapter = platform_get_drvdata(pdev);
struct sirfsoc_i2c *siic = adapter->algo_data;
clk_enable(siic->clk);
siic->sda_delay = readl(siic->base + SIRFSOC_I2C_SDA_DELAY);
siic->clk_div = readl(siic->base + SIRFSOC_I2C_CLK_CTRL);
clk_disable(siic->clk);
return 0;
}
static int i2c_sirfsoc_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct i2c_adapter *adapter = platform_get_drvdata(pdev);
struct sirfsoc_i2c *siic = adapter->algo_data;
clk_enable(siic->clk);
writel(SIRFSOC_I2C_RESET, siic->base + SIRFSOC_I2C_CTRL);
while (readl(siic->base + SIRFSOC_I2C_CTRL) & SIRFSOC_I2C_RESET)
cpu_relax();
writel(SIRFSOC_I2C_CORE_EN | SIRFSOC_I2C_MASTER_MODE,
siic->base + SIRFSOC_I2C_CTRL);
writel(siic->clk_div, siic->base + SIRFSOC_I2C_CLK_CTRL);
writel(siic->sda_delay, siic->base + SIRFSOC_I2C_SDA_DELAY);
clk_disable(siic->clk);
return 0;
}
static const struct dev_pm_ops i2c_sirfsoc_pm_ops = {
.suspend = i2c_sirfsoc_suspend,
.resume = i2c_sirfsoc_resume,
};
#endif
static const struct of_device_id sirfsoc_i2c_of_match[] = {
{ .compatible = "sirf,prima2-i2c", },
{},
};
MODULE_DEVICE_TABLE(of, sirfsoc_i2c_of_match);
static struct platform_driver i2c_sirfsoc_driver = {
.driver = {
.name = "sirfsoc_i2c",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &i2c_sirfsoc_pm_ops,
#endif
.of_match_table = sirfsoc_i2c_of_match,
},
.probe = i2c_sirfsoc_probe,
.remove = i2c_sirfsoc_remove,
};
module_platform_driver(i2c_sirfsoc_driver);
MODULE_DESCRIPTION("SiRF SoC I2C master controller driver");
MODULE_AUTHOR("Zhiwu Song <Zhiwu.Song@csr.com>, "
"Xiangzhen Ye <Xiangzhen.Ye@csr.com>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
tgnice/kvm | drivers/char/hw_random/picoxcell-rng.c | 413 | 4785 | /*
* Copyright (c) 2010-2011 Picochip Ltd., Jamie Iles
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* All enquiries to support@picochip.com
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/hw_random.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#define DATA_REG_OFFSET 0x0200
#define CSR_REG_OFFSET 0x0278
#define CSR_OUT_EMPTY_MASK (1 << 24)
#define CSR_FAULT_MASK (1 << 1)
#define TRNG_BLOCK_RESET_MASK (1 << 0)
#define TAI_REG_OFFSET 0x0380
/*
* The maximum amount of time in microseconds to spend waiting for data if the
* core wants us to wait. The TRNG should generate 32 bits every 320ns so a
* timeout of 20us seems reasonable. The TRNG does builtin tests of the data
* for randomness so we can't always assume there is data present.
*/
#define PICO_TRNG_TIMEOUT 20
static void __iomem *rng_base;
static struct clk *rng_clk;
static struct device *rng_dev;
static inline u32 picoxcell_trng_read_csr(void)
{
return __raw_readl(rng_base + CSR_REG_OFFSET);
}
static inline bool picoxcell_trng_is_empty(void)
{
return picoxcell_trng_read_csr() & CSR_OUT_EMPTY_MASK;
}
/*
* Take the random number generator out of reset and make sure the interrupts
* are masked. We shouldn't need to get large amounts of random bytes so just
* poll the status register. The hardware generates 32 bits every 320ns so we
* shouldn't have to wait long enough to warrant waiting for an IRQ.
*/
static void picoxcell_trng_start(void)
{
__raw_writel(0, rng_base + TAI_REG_OFFSET);
__raw_writel(0, rng_base + CSR_REG_OFFSET);
}
static void picoxcell_trng_reset(void)
{
__raw_writel(TRNG_BLOCK_RESET_MASK, rng_base + CSR_REG_OFFSET);
__raw_writel(TRNG_BLOCK_RESET_MASK, rng_base + TAI_REG_OFFSET);
picoxcell_trng_start();
}
/*
* Get some random data from the random number generator. The hw_random core
* layer provides us with locking.
*/
static int picoxcell_trng_read(struct hwrng *rng, void *buf, size_t max,
bool wait)
{
int i;
/* Wait for some data to become available. */
for (i = 0; i < PICO_TRNG_TIMEOUT && picoxcell_trng_is_empty(); ++i) {
if (!wait)
return 0;
udelay(1);
}
if (picoxcell_trng_read_csr() & CSR_FAULT_MASK) {
dev_err(rng_dev, "fault detected, resetting TRNG\n");
picoxcell_trng_reset();
return -EIO;
}
if (i == PICO_TRNG_TIMEOUT)
return 0;
*(u32 *)buf = __raw_readl(rng_base + DATA_REG_OFFSET);
return sizeof(u32);
}
static struct hwrng picoxcell_trng = {
.name = "picoxcell",
.read = picoxcell_trng_read,
};
static int picoxcell_trng_probe(struct platform_device *pdev)
{
int ret;
struct resource *mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_warn(&pdev->dev, "no memory resource\n");
return -ENOMEM;
}
if (!devm_request_mem_region(&pdev->dev, mem->start, resource_size(mem),
"picoxcell_trng")) {
dev_warn(&pdev->dev, "unable to request io mem\n");
return -EBUSY;
}
rng_base = devm_ioremap(&pdev->dev, mem->start, resource_size(mem));
if (!rng_base) {
dev_warn(&pdev->dev, "unable to remap io mem\n");
return -ENOMEM;
}
rng_clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(rng_clk)) {
dev_warn(&pdev->dev, "no clk\n");
return PTR_ERR(rng_clk);
}
ret = clk_enable(rng_clk);
if (ret) {
dev_warn(&pdev->dev, "unable to enable clk\n");
goto err_enable;
}
picoxcell_trng_start();
ret = hwrng_register(&picoxcell_trng);
if (ret)
goto err_register;
rng_dev = &pdev->dev;
dev_info(&pdev->dev, "pixoxcell random number generator active\n");
return 0;
err_register:
clk_disable(rng_clk);
err_enable:
clk_put(rng_clk);
return ret;
}
static int picoxcell_trng_remove(struct platform_device *pdev)
{
hwrng_unregister(&picoxcell_trng);
clk_disable(rng_clk);
clk_put(rng_clk);
return 0;
}
#ifdef CONFIG_PM
static int picoxcell_trng_suspend(struct device *dev)
{
clk_disable(rng_clk);
return 0;
}
static int picoxcell_trng_resume(struct device *dev)
{
return clk_enable(rng_clk);
}
static const struct dev_pm_ops picoxcell_trng_pm_ops = {
.suspend = picoxcell_trng_suspend,
.resume = picoxcell_trng_resume,
};
#endif /* CONFIG_PM */
static struct platform_driver picoxcell_trng_driver = {
.probe = picoxcell_trng_probe,
.remove = picoxcell_trng_remove,
.driver = {
.name = "picoxcell-trng",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &picoxcell_trng_pm_ops,
#endif /* CONFIG_PM */
},
};
module_platform_driver(picoxcell_trng_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jamie Iles");
MODULE_DESCRIPTION("Picochip picoXcell TRNG driver");
| gpl-2.0 |
CM-CHT/android_kernel_intel_cherrytrail | drivers/scsi/qla2xxx/qla_gs.c | 413 | 56526 | /*
* QLogic Fibre Channel HBA Driver
* Copyright (c) 2003-2013 QLogic Corporation
*
* See LICENSE.qla2xxx for copyright and licensing details.
*/
#include "qla_def.h"
#include "qla_target.h"
static int qla2x00_sns_ga_nxt(scsi_qla_host_t *, fc_port_t *);
static int qla2x00_sns_gid_pt(scsi_qla_host_t *, sw_info_t *);
static int qla2x00_sns_gpn_id(scsi_qla_host_t *, sw_info_t *);
static int qla2x00_sns_gnn_id(scsi_qla_host_t *, sw_info_t *);
static int qla2x00_sns_rft_id(scsi_qla_host_t *);
static int qla2x00_sns_rnn_id(scsi_qla_host_t *);
/**
* qla2x00_prep_ms_iocb() - Prepare common MS/CT IOCB fields for SNS CT query.
* @ha: HA context
* @req_size: request size in bytes
* @rsp_size: response size in bytes
*
* Returns a pointer to the @ha's ms_iocb.
*/
void *
qla2x00_prep_ms_iocb(scsi_qla_host_t *vha, uint32_t req_size, uint32_t rsp_size)
{
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
ms_pkt = ha->ms_iocb;
memset(ms_pkt, 0, sizeof(ms_iocb_entry_t));
ms_pkt->entry_type = MS_IOCB_TYPE;
ms_pkt->entry_count = 1;
SET_TARGET_ID(ha, ms_pkt->loop_id, SIMPLE_NAME_SERVER);
ms_pkt->control_flags = __constant_cpu_to_le16(CF_READ | CF_HEAD_TAG);
ms_pkt->timeout = cpu_to_le16(ha->r_a_tov / 10 * 2);
ms_pkt->cmd_dsd_count = __constant_cpu_to_le16(1);
ms_pkt->total_dsd_count = __constant_cpu_to_le16(2);
ms_pkt->rsp_bytecount = cpu_to_le32(rsp_size);
ms_pkt->req_bytecount = cpu_to_le32(req_size);
ms_pkt->dseg_req_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ms_pkt->dseg_req_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ms_pkt->dseg_req_length = ms_pkt->req_bytecount;
ms_pkt->dseg_rsp_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ms_pkt->dseg_rsp_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ms_pkt->dseg_rsp_length = ms_pkt->rsp_bytecount;
vha->qla_stats.control_requests++;
return (ms_pkt);
}
/**
* qla24xx_prep_ms_iocb() - Prepare common CT IOCB fields for SNS CT query.
* @ha: HA context
* @req_size: request size in bytes
* @rsp_size: response size in bytes
*
* Returns a pointer to the @ha's ms_iocb.
*/
void *
qla24xx_prep_ms_iocb(scsi_qla_host_t *vha, uint32_t req_size, uint32_t rsp_size)
{
struct qla_hw_data *ha = vha->hw;
struct ct_entry_24xx *ct_pkt;
ct_pkt = (struct ct_entry_24xx *)ha->ms_iocb;
memset(ct_pkt, 0, sizeof(struct ct_entry_24xx));
ct_pkt->entry_type = CT_IOCB_TYPE;
ct_pkt->entry_count = 1;
ct_pkt->nport_handle = __constant_cpu_to_le16(NPH_SNS);
ct_pkt->timeout = cpu_to_le16(ha->r_a_tov / 10 * 2);
ct_pkt->cmd_dsd_count = __constant_cpu_to_le16(1);
ct_pkt->rsp_dsd_count = __constant_cpu_to_le16(1);
ct_pkt->rsp_byte_count = cpu_to_le32(rsp_size);
ct_pkt->cmd_byte_count = cpu_to_le32(req_size);
ct_pkt->dseg_0_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ct_pkt->dseg_0_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ct_pkt->dseg_0_len = ct_pkt->cmd_byte_count;
ct_pkt->dseg_1_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ct_pkt->dseg_1_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ct_pkt->dseg_1_len = ct_pkt->rsp_byte_count;
ct_pkt->vp_index = vha->vp_idx;
vha->qla_stats.control_requests++;
return (ct_pkt);
}
/**
* qla2x00_prep_ct_req() - Prepare common CT request fields for SNS query.
* @ct_req: CT request buffer
* @cmd: GS command
* @rsp_size: response size in bytes
*
* Returns a pointer to the intitialized @ct_req.
*/
static inline struct ct_sns_req *
qla2x00_prep_ct_req(struct ct_sns_pkt *p, uint16_t cmd, uint16_t rsp_size)
{
memset(p, 0, sizeof(struct ct_sns_pkt));
p->p.req.header.revision = 0x01;
p->p.req.header.gs_type = 0xFC;
p->p.req.header.gs_subtype = 0x02;
p->p.req.command = cpu_to_be16(cmd);
p->p.req.max_rsp_size = cpu_to_be16((rsp_size - 16) / 4);
return &p->p.req;
}
static int
qla2x00_chk_ms_status(scsi_qla_host_t *vha, ms_iocb_entry_t *ms_pkt,
struct ct_sns_rsp *ct_rsp, const char *routine)
{
int rval;
uint16_t comp_status;
struct qla_hw_data *ha = vha->hw;
rval = QLA_FUNCTION_FAILED;
if (ms_pkt->entry_status != 0) {
ql_dbg(ql_dbg_disc, vha, 0x2031,
"%s failed, error status (%x) on port_id: %02x%02x%02x.\n",
routine, ms_pkt->entry_status, vha->d_id.b.domain,
vha->d_id.b.area, vha->d_id.b.al_pa);
} else {
if (IS_FWI2_CAPABLE(ha))
comp_status = le16_to_cpu(
((struct ct_entry_24xx *)ms_pkt)->comp_status);
else
comp_status = le16_to_cpu(ms_pkt->status);
switch (comp_status) {
case CS_COMPLETE:
case CS_DATA_UNDERRUN:
case CS_DATA_OVERRUN: /* Overrun? */
if (ct_rsp->header.response !=
__constant_cpu_to_be16(CT_ACCEPT_RESPONSE)) {
ql_dbg(ql_dbg_disc + ql_dbg_buffer, vha, 0x2077,
"%s failed rejected request on port_id: "
"%02x%02x%02x.\n", routine,
vha->d_id.b.domain, vha->d_id.b.area,
vha->d_id.b.al_pa);
ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha,
0x2078, (uint8_t *)&ct_rsp->header,
sizeof(struct ct_rsp_hdr));
rval = QLA_INVALID_COMMAND;
} else
rval = QLA_SUCCESS;
break;
default:
ql_dbg(ql_dbg_disc, vha, 0x2033,
"%s failed, completion status (%x) on port_id: "
"%02x%02x%02x.\n", routine, comp_status,
vha->d_id.b.domain, vha->d_id.b.area,
vha->d_id.b.al_pa);
break;
}
}
return rval;
}
/**
* qla2x00_ga_nxt() - SNS scan for fabric devices via GA_NXT command.
* @ha: HA context
* @fcport: fcport entry to updated
*
* Returns 0 on success.
*/
int
qla2x00_ga_nxt(scsi_qla_host_t *vha, fc_port_t *fcport)
{
int rval;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
struct qla_hw_data *ha = vha->hw;
if (IS_QLA2100(ha) || IS_QLA2200(ha))
return qla2x00_sns_ga_nxt(vha, fcport);
/* Issue GA_NXT */
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, GA_NXT_REQ_SIZE,
GA_NXT_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, GA_NXT_CMD,
GA_NXT_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id */
ct_req->req.port_id.port_id[0] = fcport->d_id.b.domain;
ct_req->req.port_id.port_id[1] = fcport->d_id.b.area;
ct_req->req.port_id.port_id[2] = fcport->d_id.b.al_pa;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2062,
"GA_NXT issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp, "GA_NXT") !=
QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
} else {
/* Populate fc_port_t entry. */
fcport->d_id.b.domain = ct_rsp->rsp.ga_nxt.port_id[0];
fcport->d_id.b.area = ct_rsp->rsp.ga_nxt.port_id[1];
fcport->d_id.b.al_pa = ct_rsp->rsp.ga_nxt.port_id[2];
memcpy(fcport->node_name, ct_rsp->rsp.ga_nxt.node_name,
WWN_SIZE);
memcpy(fcport->port_name, ct_rsp->rsp.ga_nxt.port_name,
WWN_SIZE);
fcport->fc4_type = (ct_rsp->rsp.ga_nxt.fc4_types[2] & BIT_0) ?
FC4_TYPE_FCP_SCSI : FC4_TYPE_OTHER;
if (ct_rsp->rsp.ga_nxt.port_type != NS_N_PORT_TYPE &&
ct_rsp->rsp.ga_nxt.port_type != NS_NL_PORT_TYPE)
fcport->d_id.b.domain = 0xf0;
ql_dbg(ql_dbg_disc, vha, 0x2063,
"GA_NXT entry - nn %8phN pn %8phN "
"port_id=%02x%02x%02x.\n",
fcport->node_name, fcport->port_name,
fcport->d_id.b.domain, fcport->d_id.b.area,
fcport->d_id.b.al_pa);
}
return (rval);
}
static inline int
qla2x00_gid_pt_rsp_size(scsi_qla_host_t *vha)
{
return vha->hw->max_fibre_devices * 4 + 16;
}
/**
* qla2x00_gid_pt() - SNS scan for fabric devices via GID_PT command.
* @ha: HA context
* @list: switch info entries to populate
*
* NOTE: Non-Nx_Ports are not requested.
*
* Returns 0 on success.
*/
int
qla2x00_gid_pt(scsi_qla_host_t *vha, sw_info_t *list)
{
int rval;
uint16_t i;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
struct ct_sns_gid_pt_data *gid_data;
struct qla_hw_data *ha = vha->hw;
uint16_t gid_pt_rsp_size;
if (IS_QLA2100(ha) || IS_QLA2200(ha))
return qla2x00_sns_gid_pt(vha, list);
gid_data = NULL;
gid_pt_rsp_size = qla2x00_gid_pt_rsp_size(vha);
/* Issue GID_PT */
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, GID_PT_REQ_SIZE,
gid_pt_rsp_size);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, GID_PT_CMD, gid_pt_rsp_size);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_type */
ct_req->req.gid_pt.port_type = NS_NX_PORT_TYPE;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2055,
"GID_PT issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp, "GID_PT") !=
QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
} else {
/* Set port IDs in switch info list. */
for (i = 0; i < ha->max_fibre_devices; i++) {
gid_data = &ct_rsp->rsp.gid_pt.entries[i];
list[i].d_id.b.domain = gid_data->port_id[0];
list[i].d_id.b.area = gid_data->port_id[1];
list[i].d_id.b.al_pa = gid_data->port_id[2];
memset(list[i].fabric_port_name, 0, WWN_SIZE);
list[i].fp_speed = PORT_SPEED_UNKNOWN;
/* Last one exit. */
if (gid_data->control_byte & BIT_7) {
list[i].d_id.b.rsvd_1 = gid_data->control_byte;
break;
}
}
/*
* If we've used all available slots, then the switch is
* reporting back more devices than we can handle with this
* single call. Return a failed status, and let GA_NXT handle
* the overload.
*/
if (i == ha->max_fibre_devices)
rval = QLA_FUNCTION_FAILED;
}
return (rval);
}
/**
* qla2x00_gpn_id() - SNS Get Port Name (GPN_ID) query.
* @ha: HA context
* @list: switch info entries to populate
*
* Returns 0 on success.
*/
int
qla2x00_gpn_id(scsi_qla_host_t *vha, sw_info_t *list)
{
int rval = QLA_SUCCESS;
uint16_t i;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
struct qla_hw_data *ha = vha->hw;
if (IS_QLA2100(ha) || IS_QLA2200(ha))
return qla2x00_sns_gpn_id(vha, list);
for (i = 0; i < ha->max_fibre_devices; i++) {
/* Issue GPN_ID */
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, GPN_ID_REQ_SIZE,
GPN_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, GPN_ID_CMD,
GPN_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id */
ct_req->req.port_id.port_id[0] = list[i].d_id.b.domain;
ct_req->req.port_id.port_id[1] = list[i].d_id.b.area;
ct_req->req.port_id.port_id[2] = list[i].d_id.b.al_pa;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2056,
"GPN_ID issue IOCB failed (%d).\n", rval);
break;
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp,
"GPN_ID") != QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
break;
} else {
/* Save portname */
memcpy(list[i].port_name,
ct_rsp->rsp.gpn_id.port_name, WWN_SIZE);
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
/**
* qla2x00_gnn_id() - SNS Get Node Name (GNN_ID) query.
* @ha: HA context
* @list: switch info entries to populate
*
* Returns 0 on success.
*/
int
qla2x00_gnn_id(scsi_qla_host_t *vha, sw_info_t *list)
{
int rval = QLA_SUCCESS;
uint16_t i;
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha))
return qla2x00_sns_gnn_id(vha, list);
for (i = 0; i < ha->max_fibre_devices; i++) {
/* Issue GNN_ID */
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, GNN_ID_REQ_SIZE,
GNN_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, GNN_ID_CMD,
GNN_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id */
ct_req->req.port_id.port_id[0] = list[i].d_id.b.domain;
ct_req->req.port_id.port_id[1] = list[i].d_id.b.area;
ct_req->req.port_id.port_id[2] = list[i].d_id.b.al_pa;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2057,
"GNN_ID issue IOCB failed (%d).\n", rval);
break;
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp,
"GNN_ID") != QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
break;
} else {
/* Save nodename */
memcpy(list[i].node_name,
ct_rsp->rsp.gnn_id.node_name, WWN_SIZE);
ql_dbg(ql_dbg_disc, vha, 0x2058,
"GID_PT entry - nn %8phN pn %8phN "
"portid=%02x%02x%02x.\n",
list[i].node_name, list[i].port_name,
list[i].d_id.b.domain, list[i].d_id.b.area,
list[i].d_id.b.al_pa);
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
/**
* qla2x00_rft_id() - SNS Register FC-4 TYPEs (RFT_ID) supported by the HBA.
* @ha: HA context
*
* Returns 0 on success.
*/
int
qla2x00_rft_id(scsi_qla_host_t *vha)
{
int rval;
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha))
return qla2x00_sns_rft_id(vha);
/* Issue RFT_ID */
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, RFT_ID_REQ_SIZE,
RFT_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, RFT_ID_CMD,
RFT_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id, FC-4 types */
ct_req->req.rft_id.port_id[0] = vha->d_id.b.domain;
ct_req->req.rft_id.port_id[1] = vha->d_id.b.area;
ct_req->req.rft_id.port_id[2] = vha->d_id.b.al_pa;
ct_req->req.rft_id.fc4_types[2] = 0x01; /* FCP-3 */
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2043,
"RFT_ID issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp, "RFT_ID") !=
QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
} else {
ql_dbg(ql_dbg_disc, vha, 0x2044,
"RFT_ID exiting normally.\n");
}
return (rval);
}
/**
* qla2x00_rff_id() - SNS Register FC-4 Features (RFF_ID) supported by the HBA.
* @ha: HA context
*
* Returns 0 on success.
*/
int
qla2x00_rff_id(scsi_qla_host_t *vha)
{
int rval;
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
ql_dbg(ql_dbg_disc, vha, 0x2046,
"RFF_ID call not supported on ISP2100/ISP2200.\n");
return (QLA_SUCCESS);
}
/* Issue RFF_ID */
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, RFF_ID_REQ_SIZE,
RFF_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, RFF_ID_CMD,
RFF_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id, FC-4 feature, FC-4 type */
ct_req->req.rff_id.port_id[0] = vha->d_id.b.domain;
ct_req->req.rff_id.port_id[1] = vha->d_id.b.area;
ct_req->req.rff_id.port_id[2] = vha->d_id.b.al_pa;
qlt_rff_id(vha, ct_req);
ct_req->req.rff_id.fc4_type = 0x08; /* SCSI - FCP */
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2047,
"RFF_ID issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp, "RFF_ID") !=
QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
} else {
ql_dbg(ql_dbg_disc, vha, 0x2048,
"RFF_ID exiting normally.\n");
}
return (rval);
}
/**
* qla2x00_rnn_id() - SNS Register Node Name (RNN_ID) of the HBA.
* @ha: HA context
*
* Returns 0 on success.
*/
int
qla2x00_rnn_id(scsi_qla_host_t *vha)
{
int rval;
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha))
return qla2x00_sns_rnn_id(vha);
/* Issue RNN_ID */
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, RNN_ID_REQ_SIZE,
RNN_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, RNN_ID_CMD, RNN_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id, node_name */
ct_req->req.rnn_id.port_id[0] = vha->d_id.b.domain;
ct_req->req.rnn_id.port_id[1] = vha->d_id.b.area;
ct_req->req.rnn_id.port_id[2] = vha->d_id.b.al_pa;
memcpy(ct_req->req.rnn_id.node_name, vha->node_name, WWN_SIZE);
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x204d,
"RNN_ID issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp, "RNN_ID") !=
QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
} else {
ql_dbg(ql_dbg_disc, vha, 0x204e,
"RNN_ID exiting normally.\n");
}
return (rval);
}
void
qla2x00_get_sym_node_name(scsi_qla_host_t *vha, uint8_t *snn)
{
struct qla_hw_data *ha = vha->hw;
if (IS_QLAFX00(ha))
sprintf(snn, "%s FW:v%s DVR:v%s", ha->model_number,
ha->mr.fw_version, qla2x00_version_str);
else
sprintf(snn, "%s FW:v%d.%02d.%02d DVR:v%s", ha->model_number,
ha->fw_major_version, ha->fw_minor_version,
ha->fw_subminor_version, qla2x00_version_str);
}
/**
* qla2x00_rsnn_nn() - SNS Register Symbolic Node Name (RSNN_NN) of the HBA.
* @ha: HA context
*
* Returns 0 on success.
*/
int
qla2x00_rsnn_nn(scsi_qla_host_t *vha)
{
int rval;
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (IS_QLA2100(ha) || IS_QLA2200(ha)) {
ql_dbg(ql_dbg_disc, vha, 0x2050,
"RSNN_ID call unsupported on ISP2100/ISP2200.\n");
return (QLA_SUCCESS);
}
/* Issue RSNN_NN */
/* Prepare common MS IOCB */
/* Request size adjusted after CT preparation */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, 0, RSNN_NN_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, RSNN_NN_CMD,
RSNN_NN_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- node_name, symbolic node_name, size */
memcpy(ct_req->req.rsnn_nn.node_name, vha->node_name, WWN_SIZE);
/* Prepare the Symbolic Node Name */
qla2x00_get_sym_node_name(vha, ct_req->req.rsnn_nn.sym_node_name);
/* Calculate SNN length */
ct_req->req.rsnn_nn.name_len =
(uint8_t)strlen(ct_req->req.rsnn_nn.sym_node_name);
/* Update MS IOCB request */
ms_pkt->req_bytecount =
cpu_to_le32(24 + 1 + ct_req->req.rsnn_nn.name_len);
ms_pkt->dseg_req_length = ms_pkt->req_bytecount;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2051,
"RSNN_NN issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp, "RSNN_NN") !=
QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
} else {
ql_dbg(ql_dbg_disc, vha, 0x2052,
"RSNN_NN exiting normally.\n");
}
return (rval);
}
/**
* qla2x00_prep_sns_cmd() - Prepare common SNS command request fields for query.
* @ha: HA context
* @cmd: GS command
* @scmd_len: Subcommand length
* @data_size: response size in bytes
*
* Returns a pointer to the @ha's sns_cmd.
*/
static inline struct sns_cmd_pkt *
qla2x00_prep_sns_cmd(scsi_qla_host_t *vha, uint16_t cmd, uint16_t scmd_len,
uint16_t data_size)
{
uint16_t wc;
struct sns_cmd_pkt *sns_cmd;
struct qla_hw_data *ha = vha->hw;
sns_cmd = ha->sns_cmd;
memset(sns_cmd, 0, sizeof(struct sns_cmd_pkt));
wc = data_size / 2; /* Size in 16bit words. */
sns_cmd->p.cmd.buffer_length = cpu_to_le16(wc);
sns_cmd->p.cmd.buffer_address[0] = cpu_to_le32(LSD(ha->sns_cmd_dma));
sns_cmd->p.cmd.buffer_address[1] = cpu_to_le32(MSD(ha->sns_cmd_dma));
sns_cmd->p.cmd.subcommand_length = cpu_to_le16(scmd_len);
sns_cmd->p.cmd.subcommand = cpu_to_le16(cmd);
wc = (data_size - 16) / 4; /* Size in 32bit words. */
sns_cmd->p.cmd.size = cpu_to_le16(wc);
vha->qla_stats.control_requests++;
return (sns_cmd);
}
/**
* qla2x00_sns_ga_nxt() - SNS scan for fabric devices via GA_NXT command.
* @ha: HA context
* @fcport: fcport entry to updated
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_ga_nxt(scsi_qla_host_t *vha, fc_port_t *fcport)
{
int rval = QLA_SUCCESS;
struct qla_hw_data *ha = vha->hw;
struct sns_cmd_pkt *sns_cmd;
/* Issue GA_NXT. */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(vha, GA_NXT_CMD, GA_NXT_SNS_SCMD_LEN,
GA_NXT_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id. */
sns_cmd->p.cmd.param[0] = fcport->d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = fcport->d_id.b.area;
sns_cmd->p.cmd.param[2] = fcport->d_id.b.domain;
/* Execute SNS command. */
rval = qla2x00_send_sns(vha, ha->sns_cmd_dma, GA_NXT_SNS_CMD_SIZE / 2,
sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x205f,
"GA_NXT Send SNS failed (%d).\n", rval);
} else if (sns_cmd->p.gan_data[8] != 0x80 ||
sns_cmd->p.gan_data[9] != 0x02) {
ql_dbg(ql_dbg_disc + ql_dbg_buffer, vha, 0x2084,
"GA_NXT failed, rejected request ga_nxt_rsp:\n");
ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x2074,
sns_cmd->p.gan_data, 16);
rval = QLA_FUNCTION_FAILED;
} else {
/* Populate fc_port_t entry. */
fcport->d_id.b.domain = sns_cmd->p.gan_data[17];
fcport->d_id.b.area = sns_cmd->p.gan_data[18];
fcport->d_id.b.al_pa = sns_cmd->p.gan_data[19];
memcpy(fcport->node_name, &sns_cmd->p.gan_data[284], WWN_SIZE);
memcpy(fcport->port_name, &sns_cmd->p.gan_data[20], WWN_SIZE);
if (sns_cmd->p.gan_data[16] != NS_N_PORT_TYPE &&
sns_cmd->p.gan_data[16] != NS_NL_PORT_TYPE)
fcport->d_id.b.domain = 0xf0;
ql_dbg(ql_dbg_disc, vha, 0x2061,
"GA_NXT entry - nn %8phN pn %8phN "
"port_id=%02x%02x%02x.\n",
fcport->node_name, fcport->port_name,
fcport->d_id.b.domain, fcport->d_id.b.area,
fcport->d_id.b.al_pa);
}
return (rval);
}
/**
* qla2x00_sns_gid_pt() - SNS scan for fabric devices via GID_PT command.
* @ha: HA context
* @list: switch info entries to populate
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* NOTE: Non-Nx_Ports are not requested.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_gid_pt(scsi_qla_host_t *vha, sw_info_t *list)
{
int rval;
struct qla_hw_data *ha = vha->hw;
uint16_t i;
uint8_t *entry;
struct sns_cmd_pkt *sns_cmd;
uint16_t gid_pt_sns_data_size;
gid_pt_sns_data_size = qla2x00_gid_pt_rsp_size(vha);
/* Issue GID_PT. */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(vha, GID_PT_CMD, GID_PT_SNS_SCMD_LEN,
gid_pt_sns_data_size);
/* Prepare SNS command arguments -- port_type. */
sns_cmd->p.cmd.param[0] = NS_NX_PORT_TYPE;
/* Execute SNS command. */
rval = qla2x00_send_sns(vha, ha->sns_cmd_dma, GID_PT_SNS_CMD_SIZE / 2,
sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x206d,
"GID_PT Send SNS failed (%d).\n", rval);
} else if (sns_cmd->p.gid_data[8] != 0x80 ||
sns_cmd->p.gid_data[9] != 0x02) {
ql_dbg(ql_dbg_disc, vha, 0x202f,
"GID_PT failed, rejected request, gid_rsp:\n");
ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x2081,
sns_cmd->p.gid_data, 16);
rval = QLA_FUNCTION_FAILED;
} else {
/* Set port IDs in switch info list. */
for (i = 0; i < ha->max_fibre_devices; i++) {
entry = &sns_cmd->p.gid_data[(i * 4) + 16];
list[i].d_id.b.domain = entry[1];
list[i].d_id.b.area = entry[2];
list[i].d_id.b.al_pa = entry[3];
/* Last one exit. */
if (entry[0] & BIT_7) {
list[i].d_id.b.rsvd_1 = entry[0];
break;
}
}
/*
* If we've used all available slots, then the switch is
* reporting back more devices that we can handle with this
* single call. Return a failed status, and let GA_NXT handle
* the overload.
*/
if (i == ha->max_fibre_devices)
rval = QLA_FUNCTION_FAILED;
}
return (rval);
}
/**
* qla2x00_sns_gpn_id() - SNS Get Port Name (GPN_ID) query.
* @ha: HA context
* @list: switch info entries to populate
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_gpn_id(scsi_qla_host_t *vha, sw_info_t *list)
{
int rval = QLA_SUCCESS;
struct qla_hw_data *ha = vha->hw;
uint16_t i;
struct sns_cmd_pkt *sns_cmd;
for (i = 0; i < ha->max_fibre_devices; i++) {
/* Issue GPN_ID */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(vha, GPN_ID_CMD,
GPN_ID_SNS_SCMD_LEN, GPN_ID_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id. */
sns_cmd->p.cmd.param[0] = list[i].d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = list[i].d_id.b.area;
sns_cmd->p.cmd.param[2] = list[i].d_id.b.domain;
/* Execute SNS command. */
rval = qla2x00_send_sns(vha, ha->sns_cmd_dma,
GPN_ID_SNS_CMD_SIZE / 2, sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2032,
"GPN_ID Send SNS failed (%d).\n", rval);
} else if (sns_cmd->p.gpn_data[8] != 0x80 ||
sns_cmd->p.gpn_data[9] != 0x02) {
ql_dbg(ql_dbg_disc + ql_dbg_buffer, vha, 0x207e,
"GPN_ID failed, rejected request, gpn_rsp:\n");
ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x207f,
sns_cmd->p.gpn_data, 16);
rval = QLA_FUNCTION_FAILED;
} else {
/* Save portname */
memcpy(list[i].port_name, &sns_cmd->p.gpn_data[16],
WWN_SIZE);
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
/**
* qla2x00_sns_gnn_id() - SNS Get Node Name (GNN_ID) query.
* @ha: HA context
* @list: switch info entries to populate
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_gnn_id(scsi_qla_host_t *vha, sw_info_t *list)
{
int rval = QLA_SUCCESS;
struct qla_hw_data *ha = vha->hw;
uint16_t i;
struct sns_cmd_pkt *sns_cmd;
for (i = 0; i < ha->max_fibre_devices; i++) {
/* Issue GNN_ID */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(vha, GNN_ID_CMD,
GNN_ID_SNS_SCMD_LEN, GNN_ID_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id. */
sns_cmd->p.cmd.param[0] = list[i].d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = list[i].d_id.b.area;
sns_cmd->p.cmd.param[2] = list[i].d_id.b.domain;
/* Execute SNS command. */
rval = qla2x00_send_sns(vha, ha->sns_cmd_dma,
GNN_ID_SNS_CMD_SIZE / 2, sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x203f,
"GNN_ID Send SNS failed (%d).\n", rval);
} else if (sns_cmd->p.gnn_data[8] != 0x80 ||
sns_cmd->p.gnn_data[9] != 0x02) {
ql_dbg(ql_dbg_disc + ql_dbg_buffer, vha, 0x2082,
"GNN_ID failed, rejected request, gnn_rsp:\n");
ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x207a,
sns_cmd->p.gnn_data, 16);
rval = QLA_FUNCTION_FAILED;
} else {
/* Save nodename */
memcpy(list[i].node_name, &sns_cmd->p.gnn_data[16],
WWN_SIZE);
ql_dbg(ql_dbg_disc, vha, 0x206e,
"GID_PT entry - nn %8phN pn %8phN "
"port_id=%02x%02x%02x.\n",
list[i].node_name, list[i].port_name,
list[i].d_id.b.domain, list[i].d_id.b.area,
list[i].d_id.b.al_pa);
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
/**
* qla2x00_snd_rft_id() - SNS Register FC-4 TYPEs (RFT_ID) supported by the HBA.
* @ha: HA context
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_rft_id(scsi_qla_host_t *vha)
{
int rval;
struct qla_hw_data *ha = vha->hw;
struct sns_cmd_pkt *sns_cmd;
/* Issue RFT_ID. */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(vha, RFT_ID_CMD, RFT_ID_SNS_SCMD_LEN,
RFT_ID_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id, FC-4 types */
sns_cmd->p.cmd.param[0] = vha->d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = vha->d_id.b.area;
sns_cmd->p.cmd.param[2] = vha->d_id.b.domain;
sns_cmd->p.cmd.param[5] = 0x01; /* FCP-3 */
/* Execute SNS command. */
rval = qla2x00_send_sns(vha, ha->sns_cmd_dma, RFT_ID_SNS_CMD_SIZE / 2,
sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2060,
"RFT_ID Send SNS failed (%d).\n", rval);
} else if (sns_cmd->p.rft_data[8] != 0x80 ||
sns_cmd->p.rft_data[9] != 0x02) {
ql_dbg(ql_dbg_disc + ql_dbg_buffer, vha, 0x2083,
"RFT_ID failed, rejected request rft_rsp:\n");
ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x2080,
sns_cmd->p.rft_data, 16);
rval = QLA_FUNCTION_FAILED;
} else {
ql_dbg(ql_dbg_disc, vha, 0x2073,
"RFT_ID exiting normally.\n");
}
return (rval);
}
/**
* qla2x00_sns_rnn_id() - SNS Register Node Name (RNN_ID) of the HBA.
* HBA.
* @ha: HA context
*
* This command uses the old Exectute SNS Command mailbox routine.
*
* Returns 0 on success.
*/
static int
qla2x00_sns_rnn_id(scsi_qla_host_t *vha)
{
int rval;
struct qla_hw_data *ha = vha->hw;
struct sns_cmd_pkt *sns_cmd;
/* Issue RNN_ID. */
/* Prepare SNS command request. */
sns_cmd = qla2x00_prep_sns_cmd(vha, RNN_ID_CMD, RNN_ID_SNS_SCMD_LEN,
RNN_ID_SNS_DATA_SIZE);
/* Prepare SNS command arguments -- port_id, nodename. */
sns_cmd->p.cmd.param[0] = vha->d_id.b.al_pa;
sns_cmd->p.cmd.param[1] = vha->d_id.b.area;
sns_cmd->p.cmd.param[2] = vha->d_id.b.domain;
sns_cmd->p.cmd.param[4] = vha->node_name[7];
sns_cmd->p.cmd.param[5] = vha->node_name[6];
sns_cmd->p.cmd.param[6] = vha->node_name[5];
sns_cmd->p.cmd.param[7] = vha->node_name[4];
sns_cmd->p.cmd.param[8] = vha->node_name[3];
sns_cmd->p.cmd.param[9] = vha->node_name[2];
sns_cmd->p.cmd.param[10] = vha->node_name[1];
sns_cmd->p.cmd.param[11] = vha->node_name[0];
/* Execute SNS command. */
rval = qla2x00_send_sns(vha, ha->sns_cmd_dma, RNN_ID_SNS_CMD_SIZE / 2,
sizeof(struct sns_cmd_pkt));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x204a,
"RNN_ID Send SNS failed (%d).\n", rval);
} else if (sns_cmd->p.rnn_data[8] != 0x80 ||
sns_cmd->p.rnn_data[9] != 0x02) {
ql_dbg(ql_dbg_disc + ql_dbg_buffer, vha, 0x207b,
"RNN_ID failed, rejected request, rnn_rsp:\n");
ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x207c,
sns_cmd->p.rnn_data, 16);
rval = QLA_FUNCTION_FAILED;
} else {
ql_dbg(ql_dbg_disc, vha, 0x204c,
"RNN_ID exiting normally.\n");
}
return (rval);
}
/**
* qla2x00_mgmt_svr_login() - Login to fabric Management Service.
* @ha: HA context
*
* Returns 0 on success.
*/
static int
qla2x00_mgmt_svr_login(scsi_qla_host_t *vha)
{
int ret, rval;
uint16_t mb[MAILBOX_REGISTER_COUNT];
struct qla_hw_data *ha = vha->hw;
ret = QLA_SUCCESS;
if (vha->flags.management_server_logged_in)
return ret;
rval = ha->isp_ops->fabric_login(vha, vha->mgmt_svr_loop_id, 0xff, 0xff,
0xfa, mb, BIT_1);
if (rval != QLA_SUCCESS || mb[0] != MBS_COMMAND_COMPLETE) {
if (rval == QLA_MEMORY_ALLOC_FAILED)
ql_dbg(ql_dbg_disc, vha, 0x2085,
"Failed management_server login: loopid=%x "
"rval=%d\n", vha->mgmt_svr_loop_id, rval);
else
ql_dbg(ql_dbg_disc, vha, 0x2024,
"Failed management_server login: loopid=%x "
"mb[0]=%x mb[1]=%x mb[2]=%x mb[6]=%x mb[7]=%x.\n",
vha->mgmt_svr_loop_id, mb[0], mb[1], mb[2], mb[6],
mb[7]);
ret = QLA_FUNCTION_FAILED;
} else
vha->flags.management_server_logged_in = 1;
return ret;
}
/**
* qla2x00_prep_ms_fdmi_iocb() - Prepare common MS IOCB fields for FDMI query.
* @ha: HA context
* @req_size: request size in bytes
* @rsp_size: response size in bytes
*
* Returns a pointer to the @ha's ms_iocb.
*/
void *
qla2x00_prep_ms_fdmi_iocb(scsi_qla_host_t *vha, uint32_t req_size,
uint32_t rsp_size)
{
ms_iocb_entry_t *ms_pkt;
struct qla_hw_data *ha = vha->hw;
ms_pkt = ha->ms_iocb;
memset(ms_pkt, 0, sizeof(ms_iocb_entry_t));
ms_pkt->entry_type = MS_IOCB_TYPE;
ms_pkt->entry_count = 1;
SET_TARGET_ID(ha, ms_pkt->loop_id, vha->mgmt_svr_loop_id);
ms_pkt->control_flags = __constant_cpu_to_le16(CF_READ | CF_HEAD_TAG);
ms_pkt->timeout = cpu_to_le16(ha->r_a_tov / 10 * 2);
ms_pkt->cmd_dsd_count = __constant_cpu_to_le16(1);
ms_pkt->total_dsd_count = __constant_cpu_to_le16(2);
ms_pkt->rsp_bytecount = cpu_to_le32(rsp_size);
ms_pkt->req_bytecount = cpu_to_le32(req_size);
ms_pkt->dseg_req_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ms_pkt->dseg_req_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ms_pkt->dseg_req_length = ms_pkt->req_bytecount;
ms_pkt->dseg_rsp_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ms_pkt->dseg_rsp_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ms_pkt->dseg_rsp_length = ms_pkt->rsp_bytecount;
return ms_pkt;
}
/**
* qla24xx_prep_ms_fdmi_iocb() - Prepare common MS IOCB fields for FDMI query.
* @ha: HA context
* @req_size: request size in bytes
* @rsp_size: response size in bytes
*
* Returns a pointer to the @ha's ms_iocb.
*/
void *
qla24xx_prep_ms_fdmi_iocb(scsi_qla_host_t *vha, uint32_t req_size,
uint32_t rsp_size)
{
struct ct_entry_24xx *ct_pkt;
struct qla_hw_data *ha = vha->hw;
ct_pkt = (struct ct_entry_24xx *)ha->ms_iocb;
memset(ct_pkt, 0, sizeof(struct ct_entry_24xx));
ct_pkt->entry_type = CT_IOCB_TYPE;
ct_pkt->entry_count = 1;
ct_pkt->nport_handle = cpu_to_le16(vha->mgmt_svr_loop_id);
ct_pkt->timeout = cpu_to_le16(ha->r_a_tov / 10 * 2);
ct_pkt->cmd_dsd_count = __constant_cpu_to_le16(1);
ct_pkt->rsp_dsd_count = __constant_cpu_to_le16(1);
ct_pkt->rsp_byte_count = cpu_to_le32(rsp_size);
ct_pkt->cmd_byte_count = cpu_to_le32(req_size);
ct_pkt->dseg_0_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ct_pkt->dseg_0_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ct_pkt->dseg_0_len = ct_pkt->cmd_byte_count;
ct_pkt->dseg_1_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ct_pkt->dseg_1_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ct_pkt->dseg_1_len = ct_pkt->rsp_byte_count;
ct_pkt->vp_index = vha->vp_idx;
return ct_pkt;
}
static inline ms_iocb_entry_t *
qla2x00_update_ms_fdmi_iocb(scsi_qla_host_t *vha, uint32_t req_size)
{
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt = ha->ms_iocb;
struct ct_entry_24xx *ct_pkt = (struct ct_entry_24xx *)ha->ms_iocb;
if (IS_FWI2_CAPABLE(ha)) {
ct_pkt->cmd_byte_count = cpu_to_le32(req_size);
ct_pkt->dseg_0_len = ct_pkt->cmd_byte_count;
} else {
ms_pkt->req_bytecount = cpu_to_le32(req_size);
ms_pkt->dseg_req_length = ms_pkt->req_bytecount;
}
return ms_pkt;
}
/**
* qla2x00_prep_ct_req() - Prepare common CT request fields for SNS query.
* @ct_req: CT request buffer
* @cmd: GS command
* @rsp_size: response size in bytes
*
* Returns a pointer to the intitialized @ct_req.
*/
static inline struct ct_sns_req *
qla2x00_prep_ct_fdmi_req(struct ct_sns_pkt *p, uint16_t cmd,
uint16_t rsp_size)
{
memset(p, 0, sizeof(struct ct_sns_pkt));
p->p.req.header.revision = 0x01;
p->p.req.header.gs_type = 0xFA;
p->p.req.header.gs_subtype = 0x10;
p->p.req.command = cpu_to_be16(cmd);
p->p.req.max_rsp_size = cpu_to_be16((rsp_size - 16) / 4);
return &p->p.req;
}
/**
* qla2x00_fdmi_rhba() -
* @ha: HA context
*
* Returns 0 on success.
*/
static int
qla2x00_fdmi_rhba(scsi_qla_host_t *vha)
{
int rval, alen;
uint32_t size, sn;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
uint8_t *entries;
struct ct_fdmi_hba_attr *eiter;
struct qla_hw_data *ha = vha->hw;
/* Issue RHBA */
/* Prepare common MS IOCB */
/* Request size adjusted after CT preparation */
ms_pkt = ha->isp_ops->prep_ms_fdmi_iocb(vha, 0, RHBA_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_fdmi_req(ha->ct_sns, RHBA_CMD, RHBA_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare FDMI command arguments -- attribute block, attributes. */
memcpy(ct_req->req.rhba.hba_identifier, vha->port_name, WWN_SIZE);
ct_req->req.rhba.entry_count = __constant_cpu_to_be32(1);
memcpy(ct_req->req.rhba.port_name, vha->port_name, WWN_SIZE);
size = 2 * WWN_SIZE + 4 + 4;
/* Attributes */
ct_req->req.rhba.attrs.count =
__constant_cpu_to_be32(FDMI_HBA_ATTR_COUNT);
entries = ct_req->req.rhba.hba_identifier;
/* Nodename. */
eiter = (struct ct_fdmi_hba_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_HBA_NODE_NAME);
eiter->len = __constant_cpu_to_be16(4 + WWN_SIZE);
memcpy(eiter->a.node_name, vha->node_name, WWN_SIZE);
size += 4 + WWN_SIZE;
ql_dbg(ql_dbg_disc, vha, 0x2025,
"NodeName = %8phN.\n", eiter->a.node_name);
/* Manufacturer. */
eiter = (struct ct_fdmi_hba_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_HBA_MANUFACTURER);
alen = strlen(QLA2XXX_MANUFACTURER);
strncpy(eiter->a.manufacturer, QLA2XXX_MANUFACTURER, alen + 1);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha, 0x2026,
"Manufacturer = %s.\n", eiter->a.manufacturer);
/* Serial number. */
eiter = (struct ct_fdmi_hba_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_HBA_SERIAL_NUMBER);
sn = ((ha->serial0 & 0x1f) << 16) | (ha->serial2 << 8) | ha->serial1;
sprintf(eiter->a.serial_num, "%c%05d", 'A' + sn / 100000, sn % 100000);
alen = strlen(eiter->a.serial_num);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha, 0x2027,
"Serial no. = %s.\n", eiter->a.serial_num);
/* Model name. */
eiter = (struct ct_fdmi_hba_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_HBA_MODEL);
strcpy(eiter->a.model, ha->model_number);
alen = strlen(eiter->a.model);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha, 0x2028,
"Model Name = %s.\n", eiter->a.model);
/* Model description. */
eiter = (struct ct_fdmi_hba_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_HBA_MODEL_DESCRIPTION);
strncpy(eiter->a.model_desc, ha->model_desc, 80);
alen = strlen(eiter->a.model_desc);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha, 0x2029,
"Model Desc = %s.\n", eiter->a.model_desc);
/* Hardware version. */
eiter = (struct ct_fdmi_hba_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_HBA_HARDWARE_VERSION);
strcpy(eiter->a.hw_version, ha->adapter_id);
alen = strlen(eiter->a.hw_version);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha, 0x202a,
"Hardware ver = %s.\n", eiter->a.hw_version);
/* Driver version. */
eiter = (struct ct_fdmi_hba_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_HBA_DRIVER_VERSION);
strcpy(eiter->a.driver_version, qla2x00_version_str);
alen = strlen(eiter->a.driver_version);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha, 0x202b,
"Driver ver = %s.\n", eiter->a.driver_version);
/* Option ROM version. */
eiter = (struct ct_fdmi_hba_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_HBA_OPTION_ROM_VERSION);
strcpy(eiter->a.orom_version, "0.00");
alen = strlen(eiter->a.orom_version);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha , 0x202c,
"Optrom vers = %s.\n", eiter->a.orom_version);
/* Firmware version */
eiter = (struct ct_fdmi_hba_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_HBA_FIRMWARE_VERSION);
ha->isp_ops->fw_version_str(vha, eiter->a.fw_version);
alen = strlen(eiter->a.fw_version);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha, 0x202d,
"Firmware vers = %s.\n", eiter->a.fw_version);
/* Update MS request size. */
qla2x00_update_ms_fdmi_iocb(vha, size + 16);
ql_dbg(ql_dbg_disc, vha, 0x202e,
"RHBA identifier = %8phN size=%d.\n",
ct_req->req.rhba.hba_identifier, size);
ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x2076,
entries, size);
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2030,
"RHBA issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp, "RHBA") !=
QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
if (ct_rsp->header.reason_code == CT_REASON_CANNOT_PERFORM &&
ct_rsp->header.explanation_code ==
CT_EXPL_ALREADY_REGISTERED) {
ql_dbg(ql_dbg_disc, vha, 0x2034,
"HBA already registered.\n");
rval = QLA_ALREADY_REGISTERED;
}
} else {
ql_dbg(ql_dbg_disc, vha, 0x2035,
"RHBA exiting normally.\n");
}
return rval;
}
/**
* qla2x00_fdmi_dhba() -
* @ha: HA context
*
* Returns 0 on success.
*/
static int
qla2x00_fdmi_dhba(scsi_qla_host_t *vha)
{
int rval;
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
/* Issue RPA */
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_fdmi_iocb(vha, DHBA_REQ_SIZE,
DHBA_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_fdmi_req(ha->ct_sns, DHBA_CMD, DHBA_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare FDMI command arguments -- portname. */
memcpy(ct_req->req.dhba.port_name, vha->port_name, WWN_SIZE);
ql_dbg(ql_dbg_disc, vha, 0x2036,
"DHBA portname = %8phN.\n", ct_req->req.dhba.port_name);
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2037,
"DHBA issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp, "DHBA") !=
QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
} else {
ql_dbg(ql_dbg_disc, vha, 0x2038,
"DHBA exiting normally.\n");
}
return rval;
}
/**
* qla2x00_fdmi_rpa() -
* @ha: HA context
*
* Returns 0 on success.
*/
static int
qla2x00_fdmi_rpa(scsi_qla_host_t *vha)
{
int rval, alen;
uint32_t size, max_frame_size;
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
uint8_t *entries;
struct ct_fdmi_port_attr *eiter;
struct init_cb_24xx *icb24 = (struct init_cb_24xx *)ha->init_cb;
/* Issue RPA */
/* Prepare common MS IOCB */
/* Request size adjusted after CT preparation */
ms_pkt = ha->isp_ops->prep_ms_fdmi_iocb(vha, 0, RPA_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_fdmi_req(ha->ct_sns, RPA_CMD, RPA_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare FDMI command arguments -- attribute block, attributes. */
memcpy(ct_req->req.rpa.port_name, vha->port_name, WWN_SIZE);
size = WWN_SIZE + 4;
/* Attributes */
ct_req->req.rpa.attrs.count =
__constant_cpu_to_be32(FDMI_PORT_ATTR_COUNT - 1);
entries = ct_req->req.rpa.port_name;
/* FC4 types. */
eiter = (struct ct_fdmi_port_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_PORT_FC4_TYPES);
eiter->len = __constant_cpu_to_be16(4 + 32);
eiter->a.fc4_types[2] = 0x01;
size += 4 + 32;
ql_dbg(ql_dbg_disc, vha, 0x2039,
"FC4_TYPES=%02x %02x.\n",
eiter->a.fc4_types[2],
eiter->a.fc4_types[1]);
/* Supported speed. */
eiter = (struct ct_fdmi_port_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_PORT_SUPPORT_SPEED);
eiter->len = __constant_cpu_to_be16(4 + 4);
if (IS_CNA_CAPABLE(ha))
eiter->a.sup_speed = __constant_cpu_to_be32(
FDMI_PORT_SPEED_10GB);
else if (IS_QLA25XX(ha))
eiter->a.sup_speed = __constant_cpu_to_be32(
FDMI_PORT_SPEED_1GB|FDMI_PORT_SPEED_2GB|
FDMI_PORT_SPEED_4GB|FDMI_PORT_SPEED_8GB);
else if (IS_QLA24XX_TYPE(ha))
eiter->a.sup_speed = __constant_cpu_to_be32(
FDMI_PORT_SPEED_1GB|FDMI_PORT_SPEED_2GB|
FDMI_PORT_SPEED_4GB);
else if (IS_QLA23XX(ha))
eiter->a.sup_speed =__constant_cpu_to_be32(
FDMI_PORT_SPEED_1GB|FDMI_PORT_SPEED_2GB);
else
eiter->a.sup_speed = __constant_cpu_to_be32(
FDMI_PORT_SPEED_1GB);
size += 4 + 4;
ql_dbg(ql_dbg_disc, vha, 0x203a,
"Supported_Speed=%x.\n", eiter->a.sup_speed);
/* Current speed. */
eiter = (struct ct_fdmi_port_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_PORT_CURRENT_SPEED);
eiter->len = __constant_cpu_to_be16(4 + 4);
switch (ha->link_data_rate) {
case PORT_SPEED_1GB:
eiter->a.cur_speed =
__constant_cpu_to_be32(FDMI_PORT_SPEED_1GB);
break;
case PORT_SPEED_2GB:
eiter->a.cur_speed =
__constant_cpu_to_be32(FDMI_PORT_SPEED_2GB);
break;
case PORT_SPEED_4GB:
eiter->a.cur_speed =
__constant_cpu_to_be32(FDMI_PORT_SPEED_4GB);
break;
case PORT_SPEED_8GB:
eiter->a.cur_speed =
__constant_cpu_to_be32(FDMI_PORT_SPEED_8GB);
break;
case PORT_SPEED_10GB:
eiter->a.cur_speed =
__constant_cpu_to_be32(FDMI_PORT_SPEED_10GB);
break;
case PORT_SPEED_16GB:
eiter->a.cur_speed =
__constant_cpu_to_be32(FDMI_PORT_SPEED_16GB);
break;
default:
eiter->a.cur_speed =
__constant_cpu_to_be32(FDMI_PORT_SPEED_UNKNOWN);
break;
}
size += 4 + 4;
ql_dbg(ql_dbg_disc, vha, 0x203b,
"Current_Speed=%x.\n", eiter->a.cur_speed);
/* Max frame size. */
eiter = (struct ct_fdmi_port_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_PORT_MAX_FRAME_SIZE);
eiter->len = __constant_cpu_to_be16(4 + 4);
max_frame_size = IS_FWI2_CAPABLE(ha) ?
le16_to_cpu(icb24->frame_payload_size):
le16_to_cpu(ha->init_cb->frame_payload_size);
eiter->a.max_frame_size = cpu_to_be32(max_frame_size);
size += 4 + 4;
ql_dbg(ql_dbg_disc, vha, 0x203c,
"Max_Frame_Size=%x.\n", eiter->a.max_frame_size);
/* OS device name. */
eiter = (struct ct_fdmi_port_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_PORT_OS_DEVICE_NAME);
alen = strlen(QLA2XXX_DRIVER_NAME);
strncpy(eiter->a.os_dev_name, QLA2XXX_DRIVER_NAME, alen + 1);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha, 0x204b,
"OS_Device_Name=%s.\n", eiter->a.os_dev_name);
/* Hostname. */
if (strlen(fc_host_system_hostname(vha->host))) {
ct_req->req.rpa.attrs.count =
__constant_cpu_to_be32(FDMI_PORT_ATTR_COUNT);
eiter = (struct ct_fdmi_port_attr *) (entries + size);
eiter->type = __constant_cpu_to_be16(FDMI_PORT_HOST_NAME);
snprintf(eiter->a.host_name, sizeof(eiter->a.host_name),
"%s", fc_host_system_hostname(vha->host));
alen = strlen(eiter->a.host_name);
alen += (alen & 3) ? (4 - (alen & 3)) : 4;
eiter->len = cpu_to_be16(4 + alen);
size += 4 + alen;
ql_dbg(ql_dbg_disc, vha, 0x203d,
"HostName=%s.\n", eiter->a.host_name);
}
/* Update MS request size. */
qla2x00_update_ms_fdmi_iocb(vha, size + 16);
ql_dbg(ql_dbg_disc, vha, 0x203e,
"RPA portname= %8phN size=%d.\n", ct_req->req.rpa.port_name, size);
ql_dump_buffer(ql_dbg_disc + ql_dbg_buffer, vha, 0x2079,
entries, size);
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2040,
"RPA issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp, "RPA") !=
QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
} else {
ql_dbg(ql_dbg_disc, vha, 0x2041,
"RPA exiting nornally.\n");
}
return rval;
}
/**
* qla2x00_fdmi_register() -
* @ha: HA context
*
* Returns 0 on success.
*/
int
qla2x00_fdmi_register(scsi_qla_host_t *vha)
{
int rval;
struct qla_hw_data *ha = vha->hw;
if (IS_QLA2100(ha) || IS_QLA2200(ha) ||
IS_QLAFX00(ha))
return QLA_FUNCTION_FAILED;
rval = qla2x00_mgmt_svr_login(vha);
if (rval)
return rval;
rval = qla2x00_fdmi_rhba(vha);
if (rval) {
if (rval != QLA_ALREADY_REGISTERED)
return rval;
rval = qla2x00_fdmi_dhba(vha);
if (rval)
return rval;
rval = qla2x00_fdmi_rhba(vha);
if (rval)
return rval;
}
rval = qla2x00_fdmi_rpa(vha);
return rval;
}
/**
* qla2x00_gfpn_id() - SNS Get Fabric Port Name (GFPN_ID) query.
* @ha: HA context
* @list: switch info entries to populate
*
* Returns 0 on success.
*/
int
qla2x00_gfpn_id(scsi_qla_host_t *vha, sw_info_t *list)
{
int rval = QLA_SUCCESS;
uint16_t i;
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (!IS_IIDMA_CAPABLE(ha))
return QLA_FUNCTION_FAILED;
for (i = 0; i < ha->max_fibre_devices; i++) {
/* Issue GFPN_ID */
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, GFPN_ID_REQ_SIZE,
GFPN_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, GFPN_ID_CMD,
GFPN_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id */
ct_req->req.port_id.port_id[0] = list[i].d_id.b.domain;
ct_req->req.port_id.port_id[1] = list[i].d_id.b.area;
ct_req->req.port_id.port_id[2] = list[i].d_id.b.al_pa;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2023,
"GFPN_ID issue IOCB failed (%d).\n", rval);
break;
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp,
"GFPN_ID") != QLA_SUCCESS) {
rval = QLA_FUNCTION_FAILED;
break;
} else {
/* Save fabric portname */
memcpy(list[i].fabric_port_name,
ct_rsp->rsp.gfpn_id.port_name, WWN_SIZE);
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
static inline void *
qla24xx_prep_ms_fm_iocb(scsi_qla_host_t *vha, uint32_t req_size,
uint32_t rsp_size)
{
struct ct_entry_24xx *ct_pkt;
struct qla_hw_data *ha = vha->hw;
ct_pkt = (struct ct_entry_24xx *)ha->ms_iocb;
memset(ct_pkt, 0, sizeof(struct ct_entry_24xx));
ct_pkt->entry_type = CT_IOCB_TYPE;
ct_pkt->entry_count = 1;
ct_pkt->nport_handle = cpu_to_le16(vha->mgmt_svr_loop_id);
ct_pkt->timeout = cpu_to_le16(ha->r_a_tov / 10 * 2);
ct_pkt->cmd_dsd_count = __constant_cpu_to_le16(1);
ct_pkt->rsp_dsd_count = __constant_cpu_to_le16(1);
ct_pkt->rsp_byte_count = cpu_to_le32(rsp_size);
ct_pkt->cmd_byte_count = cpu_to_le32(req_size);
ct_pkt->dseg_0_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ct_pkt->dseg_0_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ct_pkt->dseg_0_len = ct_pkt->cmd_byte_count;
ct_pkt->dseg_1_address[0] = cpu_to_le32(LSD(ha->ct_sns_dma));
ct_pkt->dseg_1_address[1] = cpu_to_le32(MSD(ha->ct_sns_dma));
ct_pkt->dseg_1_len = ct_pkt->rsp_byte_count;
ct_pkt->vp_index = vha->vp_idx;
return ct_pkt;
}
static inline struct ct_sns_req *
qla24xx_prep_ct_fm_req(struct ct_sns_pkt *p, uint16_t cmd,
uint16_t rsp_size)
{
memset(p, 0, sizeof(struct ct_sns_pkt));
p->p.req.header.revision = 0x01;
p->p.req.header.gs_type = 0xFA;
p->p.req.header.gs_subtype = 0x01;
p->p.req.command = cpu_to_be16(cmd);
p->p.req.max_rsp_size = cpu_to_be16((rsp_size - 16) / 4);
return &p->p.req;
}
/**
* qla2x00_gpsc() - FCS Get Port Speed Capabilities (GPSC) query.
* @ha: HA context
* @list: switch info entries to populate
*
* Returns 0 on success.
*/
int
qla2x00_gpsc(scsi_qla_host_t *vha, sw_info_t *list)
{
int rval;
uint16_t i;
struct qla_hw_data *ha = vha->hw;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
if (!IS_IIDMA_CAPABLE(ha))
return QLA_FUNCTION_FAILED;
if (!ha->flags.gpsc_supported)
return QLA_FUNCTION_FAILED;
rval = qla2x00_mgmt_svr_login(vha);
if (rval)
return rval;
for (i = 0; i < ha->max_fibre_devices; i++) {
/* Issue GFPN_ID */
/* Prepare common MS IOCB */
ms_pkt = qla24xx_prep_ms_fm_iocb(vha, GPSC_REQ_SIZE,
GPSC_RSP_SIZE);
/* Prepare CT request */
ct_req = qla24xx_prep_ct_fm_req(ha->ct_sns, GPSC_CMD,
GPSC_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_name */
memcpy(ct_req->req.gpsc.port_name, list[i].fabric_port_name,
WWN_SIZE);
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
/*EMPTY*/
ql_dbg(ql_dbg_disc, vha, 0x2059,
"GPSC issue IOCB failed (%d).\n", rval);
} else if ((rval = qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp,
"GPSC")) != QLA_SUCCESS) {
/* FM command unsupported? */
if (rval == QLA_INVALID_COMMAND &&
(ct_rsp->header.reason_code ==
CT_REASON_INVALID_COMMAND_CODE ||
ct_rsp->header.reason_code ==
CT_REASON_COMMAND_UNSUPPORTED)) {
ql_dbg(ql_dbg_disc, vha, 0x205a,
"GPSC command unsupported, disabling "
"query.\n");
ha->flags.gpsc_supported = 0;
rval = QLA_FUNCTION_FAILED;
break;
}
rval = QLA_FUNCTION_FAILED;
} else {
/* Save port-speed */
switch (be16_to_cpu(ct_rsp->rsp.gpsc.speed)) {
case BIT_15:
list[i].fp_speed = PORT_SPEED_1GB;
break;
case BIT_14:
list[i].fp_speed = PORT_SPEED_2GB;
break;
case BIT_13:
list[i].fp_speed = PORT_SPEED_4GB;
break;
case BIT_12:
list[i].fp_speed = PORT_SPEED_10GB;
break;
case BIT_11:
list[i].fp_speed = PORT_SPEED_8GB;
break;
case BIT_10:
list[i].fp_speed = PORT_SPEED_16GB;
break;
}
ql_dbg(ql_dbg_disc, vha, 0x205b,
"GPSC ext entry - fpn "
"%8phN speeds=%04x speed=%04x.\n",
list[i].fabric_port_name,
be16_to_cpu(ct_rsp->rsp.gpsc.speeds),
be16_to_cpu(ct_rsp->rsp.gpsc.speed));
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
return (rval);
}
/**
* qla2x00_gff_id() - SNS Get FC-4 Features (GFF_ID) query.
*
* @ha: HA context
* @list: switch info entries to populate
*
*/
void
qla2x00_gff_id(scsi_qla_host_t *vha, sw_info_t *list)
{
int rval;
uint16_t i;
ms_iocb_entry_t *ms_pkt;
struct ct_sns_req *ct_req;
struct ct_sns_rsp *ct_rsp;
struct qla_hw_data *ha = vha->hw;
uint8_t fcp_scsi_features = 0;
for (i = 0; i < ha->max_fibre_devices; i++) {
/* Set default FC4 Type as UNKNOWN so the default is to
* Process this port */
list[i].fc4_type = FC4_TYPE_UNKNOWN;
/* Do not attempt GFF_ID if we are not FWI_2 capable */
if (!IS_FWI2_CAPABLE(ha))
continue;
/* Prepare common MS IOCB */
ms_pkt = ha->isp_ops->prep_ms_iocb(vha, GFF_ID_REQ_SIZE,
GFF_ID_RSP_SIZE);
/* Prepare CT request */
ct_req = qla2x00_prep_ct_req(ha->ct_sns, GFF_ID_CMD,
GFF_ID_RSP_SIZE);
ct_rsp = &ha->ct_sns->p.rsp;
/* Prepare CT arguments -- port_id */
ct_req->req.port_id.port_id[0] = list[i].d_id.b.domain;
ct_req->req.port_id.port_id[1] = list[i].d_id.b.area;
ct_req->req.port_id.port_id[2] = list[i].d_id.b.al_pa;
/* Execute MS IOCB */
rval = qla2x00_issue_iocb(vha, ha->ms_iocb, ha->ms_iocb_dma,
sizeof(ms_iocb_entry_t));
if (rval != QLA_SUCCESS) {
ql_dbg(ql_dbg_disc, vha, 0x205c,
"GFF_ID issue IOCB failed (%d).\n", rval);
} else if (qla2x00_chk_ms_status(vha, ms_pkt, ct_rsp,
"GFF_ID") != QLA_SUCCESS) {
ql_dbg(ql_dbg_disc, vha, 0x205d,
"GFF_ID IOCB status had a failure status code.\n");
} else {
fcp_scsi_features =
ct_rsp->rsp.gff_id.fc4_features[GFF_FCP_SCSI_OFFSET];
fcp_scsi_features &= 0x0f;
if (fcp_scsi_features)
list[i].fc4_type = FC4_TYPE_FCP_SCSI;
else
list[i].fc4_type = FC4_TYPE_OTHER;
}
/* Last device exit. */
if (list[i].d_id.b.rsvd_1 != 0)
break;
}
}
| gpl-2.0 |
rfalize/endeavoru-suitcasekernel | drivers/ssb/driver_chipcommon_pmu.c | 413 | 19566 | /*
* Sonics Silicon Backplane
* Broadcom ChipCommon Power Management Unit driver
*
* Copyright 2009, Michael Buesch <m@bues.ch>
* Copyright 2007, Broadcom Corporation
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include <linux/ssb/ssb.h>
#include <linux/ssb/ssb_regs.h>
#include <linux/ssb/ssb_driver_chipcommon.h>
#include <linux/delay.h>
#include "ssb_private.h"
static u32 ssb_chipco_pll_read(struct ssb_chipcommon *cc, u32 offset)
{
chipco_write32(cc, SSB_CHIPCO_PLLCTL_ADDR, offset);
return chipco_read32(cc, SSB_CHIPCO_PLLCTL_DATA);
}
static void ssb_chipco_pll_write(struct ssb_chipcommon *cc,
u32 offset, u32 value)
{
chipco_write32(cc, SSB_CHIPCO_PLLCTL_ADDR, offset);
chipco_write32(cc, SSB_CHIPCO_PLLCTL_DATA, value);
}
static void ssb_chipco_regctl_maskset(struct ssb_chipcommon *cc,
u32 offset, u32 mask, u32 set)
{
u32 value;
chipco_read32(cc, SSB_CHIPCO_REGCTL_ADDR);
chipco_write32(cc, SSB_CHIPCO_REGCTL_ADDR, offset);
chipco_read32(cc, SSB_CHIPCO_REGCTL_ADDR);
value = chipco_read32(cc, SSB_CHIPCO_REGCTL_DATA);
value &= mask;
value |= set;
chipco_write32(cc, SSB_CHIPCO_REGCTL_DATA, value);
chipco_read32(cc, SSB_CHIPCO_REGCTL_DATA);
}
struct pmu0_plltab_entry {
u16 freq; /* Crystal frequency in kHz.*/
u8 xf; /* Crystal frequency value for PMU control */
u8 wb_int;
u32 wb_frac;
};
static const struct pmu0_plltab_entry pmu0_plltab[] = {
{ .freq = 12000, .xf = 1, .wb_int = 73, .wb_frac = 349525, },
{ .freq = 13000, .xf = 2, .wb_int = 67, .wb_frac = 725937, },
{ .freq = 14400, .xf = 3, .wb_int = 61, .wb_frac = 116508, },
{ .freq = 15360, .xf = 4, .wb_int = 57, .wb_frac = 305834, },
{ .freq = 16200, .xf = 5, .wb_int = 54, .wb_frac = 336579, },
{ .freq = 16800, .xf = 6, .wb_int = 52, .wb_frac = 399457, },
{ .freq = 19200, .xf = 7, .wb_int = 45, .wb_frac = 873813, },
{ .freq = 19800, .xf = 8, .wb_int = 44, .wb_frac = 466033, },
{ .freq = 20000, .xf = 9, .wb_int = 44, .wb_frac = 0, },
{ .freq = 25000, .xf = 10, .wb_int = 70, .wb_frac = 419430, },
{ .freq = 26000, .xf = 11, .wb_int = 67, .wb_frac = 725937, },
{ .freq = 30000, .xf = 12, .wb_int = 58, .wb_frac = 699050, },
{ .freq = 38400, .xf = 13, .wb_int = 45, .wb_frac = 873813, },
{ .freq = 40000, .xf = 14, .wb_int = 45, .wb_frac = 0, },
};
#define SSB_PMU0_DEFAULT_XTALFREQ 20000
static const struct pmu0_plltab_entry * pmu0_plltab_find_entry(u32 crystalfreq)
{
const struct pmu0_plltab_entry *e;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(pmu0_plltab); i++) {
e = &pmu0_plltab[i];
if (e->freq == crystalfreq)
return e;
}
return NULL;
}
/* Tune the PLL to the crystal speed. crystalfreq is in kHz. */
static void ssb_pmu0_pllinit_r0(struct ssb_chipcommon *cc,
u32 crystalfreq)
{
struct ssb_bus *bus = cc->dev->bus;
const struct pmu0_plltab_entry *e = NULL;
u32 pmuctl, tmp, pllctl;
unsigned int i;
if ((bus->chip_id == 0x5354) && !crystalfreq) {
/* The 5354 crystal freq is 25MHz */
crystalfreq = 25000;
}
if (crystalfreq)
e = pmu0_plltab_find_entry(crystalfreq);
if (!e)
e = pmu0_plltab_find_entry(SSB_PMU0_DEFAULT_XTALFREQ);
BUG_ON(!e);
crystalfreq = e->freq;
cc->pmu.crystalfreq = e->freq;
/* Check if the PLL already is programmed to this frequency. */
pmuctl = chipco_read32(cc, SSB_CHIPCO_PMU_CTL);
if (((pmuctl & SSB_CHIPCO_PMU_CTL_XTALFREQ) >> SSB_CHIPCO_PMU_CTL_XTALFREQ_SHIFT) == e->xf) {
/* We're already there... */
return;
}
ssb_printk(KERN_INFO PFX "Programming PLL to %u.%03u MHz\n",
(crystalfreq / 1000), (crystalfreq % 1000));
/* First turn the PLL off. */
switch (bus->chip_id) {
case 0x4328:
chipco_mask32(cc, SSB_CHIPCO_PMU_MINRES_MSK,
~(1 << SSB_PMURES_4328_BB_PLL_PU));
chipco_mask32(cc, SSB_CHIPCO_PMU_MAXRES_MSK,
~(1 << SSB_PMURES_4328_BB_PLL_PU));
break;
case 0x5354:
chipco_mask32(cc, SSB_CHIPCO_PMU_MINRES_MSK,
~(1 << SSB_PMURES_5354_BB_PLL_PU));
chipco_mask32(cc, SSB_CHIPCO_PMU_MAXRES_MSK,
~(1 << SSB_PMURES_5354_BB_PLL_PU));
break;
default:
SSB_WARN_ON(1);
}
for (i = 1500; i; i--) {
tmp = chipco_read32(cc, SSB_CHIPCO_CLKCTLST);
if (!(tmp & SSB_CHIPCO_CLKCTLST_HAVEHT))
break;
udelay(10);
}
tmp = chipco_read32(cc, SSB_CHIPCO_CLKCTLST);
if (tmp & SSB_CHIPCO_CLKCTLST_HAVEHT)
ssb_printk(KERN_EMERG PFX "Failed to turn the PLL off!\n");
/* Set PDIV in PLL control 0. */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU0_PLLCTL0);
if (crystalfreq >= SSB_PMU0_PLLCTL0_PDIV_FREQ)
pllctl |= SSB_PMU0_PLLCTL0_PDIV_MSK;
else
pllctl &= ~SSB_PMU0_PLLCTL0_PDIV_MSK;
ssb_chipco_pll_write(cc, SSB_PMU0_PLLCTL0, pllctl);
/* Set WILD in PLL control 1. */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU0_PLLCTL1);
pllctl &= ~SSB_PMU0_PLLCTL1_STOPMOD;
pllctl &= ~(SSB_PMU0_PLLCTL1_WILD_IMSK | SSB_PMU0_PLLCTL1_WILD_FMSK);
pllctl |= ((u32)e->wb_int << SSB_PMU0_PLLCTL1_WILD_IMSK_SHIFT) & SSB_PMU0_PLLCTL1_WILD_IMSK;
pllctl |= ((u32)e->wb_frac << SSB_PMU0_PLLCTL1_WILD_FMSK_SHIFT) & SSB_PMU0_PLLCTL1_WILD_FMSK;
if (e->wb_frac == 0)
pllctl |= SSB_PMU0_PLLCTL1_STOPMOD;
ssb_chipco_pll_write(cc, SSB_PMU0_PLLCTL1, pllctl);
/* Set WILD in PLL control 2. */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU0_PLLCTL2);
pllctl &= ~SSB_PMU0_PLLCTL2_WILD_IMSKHI;
pllctl |= (((u32)e->wb_int >> 4) << SSB_PMU0_PLLCTL2_WILD_IMSKHI_SHIFT) & SSB_PMU0_PLLCTL2_WILD_IMSKHI;
ssb_chipco_pll_write(cc, SSB_PMU0_PLLCTL2, pllctl);
/* Set the crystalfrequency and the divisor. */
pmuctl = chipco_read32(cc, SSB_CHIPCO_PMU_CTL);
pmuctl &= ~SSB_CHIPCO_PMU_CTL_ILP_DIV;
pmuctl |= (((crystalfreq + 127) / 128 - 1) << SSB_CHIPCO_PMU_CTL_ILP_DIV_SHIFT)
& SSB_CHIPCO_PMU_CTL_ILP_DIV;
pmuctl &= ~SSB_CHIPCO_PMU_CTL_XTALFREQ;
pmuctl |= ((u32)e->xf << SSB_CHIPCO_PMU_CTL_XTALFREQ_SHIFT) & SSB_CHIPCO_PMU_CTL_XTALFREQ;
chipco_write32(cc, SSB_CHIPCO_PMU_CTL, pmuctl);
}
struct pmu1_plltab_entry {
u16 freq; /* Crystal frequency in kHz.*/
u8 xf; /* Crystal frequency value for PMU control */
u8 ndiv_int;
u32 ndiv_frac;
u8 p1div;
u8 p2div;
};
static const struct pmu1_plltab_entry pmu1_plltab[] = {
{ .freq = 12000, .xf = 1, .p1div = 3, .p2div = 22, .ndiv_int = 0x9, .ndiv_frac = 0xFFFFEF, },
{ .freq = 13000, .xf = 2, .p1div = 1, .p2div = 6, .ndiv_int = 0xb, .ndiv_frac = 0x483483, },
{ .freq = 14400, .xf = 3, .p1div = 1, .p2div = 10, .ndiv_int = 0xa, .ndiv_frac = 0x1C71C7, },
{ .freq = 15360, .xf = 4, .p1div = 1, .p2div = 5, .ndiv_int = 0xb, .ndiv_frac = 0x755555, },
{ .freq = 16200, .xf = 5, .p1div = 1, .p2div = 10, .ndiv_int = 0x5, .ndiv_frac = 0x6E9E06, },
{ .freq = 16800, .xf = 6, .p1div = 1, .p2div = 10, .ndiv_int = 0x5, .ndiv_frac = 0x3CF3CF, },
{ .freq = 19200, .xf = 7, .p1div = 1, .p2div = 9, .ndiv_int = 0x5, .ndiv_frac = 0x17B425, },
{ .freq = 19800, .xf = 8, .p1div = 1, .p2div = 11, .ndiv_int = 0x4, .ndiv_frac = 0xA57EB, },
{ .freq = 20000, .xf = 9, .p1div = 1, .p2div = 11, .ndiv_int = 0x4, .ndiv_frac = 0, },
{ .freq = 24000, .xf = 10, .p1div = 3, .p2div = 11, .ndiv_int = 0xa, .ndiv_frac = 0, },
{ .freq = 25000, .xf = 11, .p1div = 5, .p2div = 16, .ndiv_int = 0xb, .ndiv_frac = 0, },
{ .freq = 26000, .xf = 12, .p1div = 1, .p2div = 2, .ndiv_int = 0x10, .ndiv_frac = 0xEC4EC4, },
{ .freq = 30000, .xf = 13, .p1div = 3, .p2div = 8, .ndiv_int = 0xb, .ndiv_frac = 0, },
{ .freq = 38400, .xf = 14, .p1div = 1, .p2div = 5, .ndiv_int = 0x4, .ndiv_frac = 0x955555, },
{ .freq = 40000, .xf = 15, .p1div = 1, .p2div = 2, .ndiv_int = 0xb, .ndiv_frac = 0, },
};
#define SSB_PMU1_DEFAULT_XTALFREQ 15360
static const struct pmu1_plltab_entry * pmu1_plltab_find_entry(u32 crystalfreq)
{
const struct pmu1_plltab_entry *e;
unsigned int i;
for (i = 0; i < ARRAY_SIZE(pmu1_plltab); i++) {
e = &pmu1_plltab[i];
if (e->freq == crystalfreq)
return e;
}
return NULL;
}
/* Tune the PLL to the crystal speed. crystalfreq is in kHz. */
static void ssb_pmu1_pllinit_r0(struct ssb_chipcommon *cc,
u32 crystalfreq)
{
struct ssb_bus *bus = cc->dev->bus;
const struct pmu1_plltab_entry *e = NULL;
u32 buffer_strength = 0;
u32 tmp, pllctl, pmuctl;
unsigned int i;
if (bus->chip_id == 0x4312) {
/* We do not touch the BCM4312 PLL and assume
* the default crystal settings work out-of-the-box. */
cc->pmu.crystalfreq = 20000;
return;
}
if (crystalfreq)
e = pmu1_plltab_find_entry(crystalfreq);
if (!e)
e = pmu1_plltab_find_entry(SSB_PMU1_DEFAULT_XTALFREQ);
BUG_ON(!e);
crystalfreq = e->freq;
cc->pmu.crystalfreq = e->freq;
/* Check if the PLL already is programmed to this frequency. */
pmuctl = chipco_read32(cc, SSB_CHIPCO_PMU_CTL);
if (((pmuctl & SSB_CHIPCO_PMU_CTL_XTALFREQ) >> SSB_CHIPCO_PMU_CTL_XTALFREQ_SHIFT) == e->xf) {
/* We're already there... */
return;
}
ssb_printk(KERN_INFO PFX "Programming PLL to %u.%03u MHz\n",
(crystalfreq / 1000), (crystalfreq % 1000));
/* First turn the PLL off. */
switch (bus->chip_id) {
case 0x4325:
chipco_mask32(cc, SSB_CHIPCO_PMU_MINRES_MSK,
~((1 << SSB_PMURES_4325_BBPLL_PWRSW_PU) |
(1 << SSB_PMURES_4325_HT_AVAIL)));
chipco_mask32(cc, SSB_CHIPCO_PMU_MAXRES_MSK,
~((1 << SSB_PMURES_4325_BBPLL_PWRSW_PU) |
(1 << SSB_PMURES_4325_HT_AVAIL)));
/* Adjust the BBPLL to 2 on all channels later. */
buffer_strength = 0x222222;
break;
default:
SSB_WARN_ON(1);
}
for (i = 1500; i; i--) {
tmp = chipco_read32(cc, SSB_CHIPCO_CLKCTLST);
if (!(tmp & SSB_CHIPCO_CLKCTLST_HAVEHT))
break;
udelay(10);
}
tmp = chipco_read32(cc, SSB_CHIPCO_CLKCTLST);
if (tmp & SSB_CHIPCO_CLKCTLST_HAVEHT)
ssb_printk(KERN_EMERG PFX "Failed to turn the PLL off!\n");
/* Set p1div and p2div. */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU1_PLLCTL0);
pllctl &= ~(SSB_PMU1_PLLCTL0_P1DIV | SSB_PMU1_PLLCTL0_P2DIV);
pllctl |= ((u32)e->p1div << SSB_PMU1_PLLCTL0_P1DIV_SHIFT) & SSB_PMU1_PLLCTL0_P1DIV;
pllctl |= ((u32)e->p2div << SSB_PMU1_PLLCTL0_P2DIV_SHIFT) & SSB_PMU1_PLLCTL0_P2DIV;
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL0, pllctl);
/* Set ndiv int and ndiv mode */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU1_PLLCTL2);
pllctl &= ~(SSB_PMU1_PLLCTL2_NDIVINT | SSB_PMU1_PLLCTL2_NDIVMODE);
pllctl |= ((u32)e->ndiv_int << SSB_PMU1_PLLCTL2_NDIVINT_SHIFT) & SSB_PMU1_PLLCTL2_NDIVINT;
pllctl |= (1 << SSB_PMU1_PLLCTL2_NDIVMODE_SHIFT) & SSB_PMU1_PLLCTL2_NDIVMODE;
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL2, pllctl);
/* Set ndiv frac */
pllctl = ssb_chipco_pll_read(cc, SSB_PMU1_PLLCTL3);
pllctl &= ~SSB_PMU1_PLLCTL3_NDIVFRAC;
pllctl |= ((u32)e->ndiv_frac << SSB_PMU1_PLLCTL3_NDIVFRAC_SHIFT) & SSB_PMU1_PLLCTL3_NDIVFRAC;
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL3, pllctl);
/* Change the drive strength, if required. */
if (buffer_strength) {
pllctl = ssb_chipco_pll_read(cc, SSB_PMU1_PLLCTL5);
pllctl &= ~SSB_PMU1_PLLCTL5_CLKDRV;
pllctl |= (buffer_strength << SSB_PMU1_PLLCTL5_CLKDRV_SHIFT) & SSB_PMU1_PLLCTL5_CLKDRV;
ssb_chipco_pll_write(cc, SSB_PMU1_PLLCTL5, pllctl);
}
/* Tune the crystalfreq and the divisor. */
pmuctl = chipco_read32(cc, SSB_CHIPCO_PMU_CTL);
pmuctl &= ~(SSB_CHIPCO_PMU_CTL_ILP_DIV | SSB_CHIPCO_PMU_CTL_XTALFREQ);
pmuctl |= ((((u32)e->freq + 127) / 128 - 1) << SSB_CHIPCO_PMU_CTL_ILP_DIV_SHIFT)
& SSB_CHIPCO_PMU_CTL_ILP_DIV;
pmuctl |= ((u32)e->xf << SSB_CHIPCO_PMU_CTL_XTALFREQ_SHIFT) & SSB_CHIPCO_PMU_CTL_XTALFREQ;
chipco_write32(cc, SSB_CHIPCO_PMU_CTL, pmuctl);
}
static void ssb_pmu_pll_init(struct ssb_chipcommon *cc)
{
struct ssb_bus *bus = cc->dev->bus;
u32 crystalfreq = 0; /* in kHz. 0 = keep default freq. */
if (bus->bustype == SSB_BUSTYPE_SSB) {
/* TODO: The user may override the crystal frequency. */
}
switch (bus->chip_id) {
case 0x4312:
case 0x4325:
ssb_pmu1_pllinit_r0(cc, crystalfreq);
break;
case 0x4328:
case 0x5354:
ssb_pmu0_pllinit_r0(cc, crystalfreq);
break;
case 0x4322:
if (cc->pmu.rev == 2) {
chipco_write32(cc, SSB_CHIPCO_PLLCTL_ADDR, 0x0000000A);
chipco_write32(cc, SSB_CHIPCO_PLLCTL_DATA, 0x380005C0);
}
break;
default:
ssb_printk(KERN_ERR PFX
"ERROR: PLL init unknown for device %04X\n",
bus->chip_id);
}
}
struct pmu_res_updown_tab_entry {
u8 resource; /* The resource number */
u16 updown; /* The updown value */
};
enum pmu_res_depend_tab_task {
PMU_RES_DEP_SET = 1,
PMU_RES_DEP_ADD,
PMU_RES_DEP_REMOVE,
};
struct pmu_res_depend_tab_entry {
u8 resource; /* The resource number */
u8 task; /* SET | ADD | REMOVE */
u32 depend; /* The depend mask */
};
static const struct pmu_res_updown_tab_entry pmu_res_updown_tab_4328a0[] = {
{ .resource = SSB_PMURES_4328_EXT_SWITCHER_PWM, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_BB_SWITCHER_PWM, .updown = 0x1F01, },
{ .resource = SSB_PMURES_4328_BB_SWITCHER_BURST, .updown = 0x010F, },
{ .resource = SSB_PMURES_4328_BB_EXT_SWITCHER_BURST, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_ILP_REQUEST, .updown = 0x0202, },
{ .resource = SSB_PMURES_4328_RADIO_SWITCHER_PWM, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_RADIO_SWITCHER_BURST, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_ROM_SWITCH, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_PA_REF_LDO, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_RADIO_LDO, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_AFE_LDO, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_PLL_LDO, .updown = 0x0F01, },
{ .resource = SSB_PMURES_4328_BG_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_TX_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_RX_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_XTAL_PU, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_XTAL_EN, .updown = 0xA001, },
{ .resource = SSB_PMURES_4328_BB_PLL_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_RF_PLL_FILTBYP, .updown = 0x0101, },
{ .resource = SSB_PMURES_4328_BB_PLL_PU, .updown = 0x0701, },
};
static const struct pmu_res_depend_tab_entry pmu_res_depend_tab_4328a0[] = {
{
/* Adjust ILP Request to avoid forcing EXT/BB into burst mode. */
.resource = SSB_PMURES_4328_ILP_REQUEST,
.task = PMU_RES_DEP_SET,
.depend = ((1 << SSB_PMURES_4328_EXT_SWITCHER_PWM) |
(1 << SSB_PMURES_4328_BB_SWITCHER_PWM)),
},
};
static const struct pmu_res_updown_tab_entry pmu_res_updown_tab_4325a0[] = {
{ .resource = SSB_PMURES_4325_XTAL_PU, .updown = 0x1501, },
};
static const struct pmu_res_depend_tab_entry pmu_res_depend_tab_4325a0[] = {
{
/* Adjust HT-Available dependencies. */
.resource = SSB_PMURES_4325_HT_AVAIL,
.task = PMU_RES_DEP_ADD,
.depend = ((1 << SSB_PMURES_4325_RX_PWRSW_PU) |
(1 << SSB_PMURES_4325_TX_PWRSW_PU) |
(1 << SSB_PMURES_4325_LOGEN_PWRSW_PU) |
(1 << SSB_PMURES_4325_AFE_PWRSW_PU)),
},
};
static void ssb_pmu_resources_init(struct ssb_chipcommon *cc)
{
struct ssb_bus *bus = cc->dev->bus;
u32 min_msk = 0, max_msk = 0;
unsigned int i;
const struct pmu_res_updown_tab_entry *updown_tab = NULL;
unsigned int updown_tab_size = 0;
const struct pmu_res_depend_tab_entry *depend_tab = NULL;
unsigned int depend_tab_size = 0;
switch (bus->chip_id) {
case 0x4312:
min_msk = 0xCBB;
break;
case 0x4322:
/* We keep the default settings:
* min_msk = 0xCBB
* max_msk = 0x7FFFF
*/
break;
case 0x4325:
/* Power OTP down later. */
min_msk = (1 << SSB_PMURES_4325_CBUCK_BURST) |
(1 << SSB_PMURES_4325_LNLDO2_PU);
if (chipco_read32(cc, SSB_CHIPCO_CHIPSTAT) &
SSB_CHIPCO_CHST_4325_PMUTOP_2B)
min_msk |= (1 << SSB_PMURES_4325_CLDO_CBUCK_BURST);
/* The PLL may turn on, if it decides so. */
max_msk = 0xFFFFF;
updown_tab = pmu_res_updown_tab_4325a0;
updown_tab_size = ARRAY_SIZE(pmu_res_updown_tab_4325a0);
depend_tab = pmu_res_depend_tab_4325a0;
depend_tab_size = ARRAY_SIZE(pmu_res_depend_tab_4325a0);
break;
case 0x4328:
min_msk = (1 << SSB_PMURES_4328_EXT_SWITCHER_PWM) |
(1 << SSB_PMURES_4328_BB_SWITCHER_PWM) |
(1 << SSB_PMURES_4328_XTAL_EN);
/* The PLL may turn on, if it decides so. */
max_msk = 0xFFFFF;
updown_tab = pmu_res_updown_tab_4328a0;
updown_tab_size = ARRAY_SIZE(pmu_res_updown_tab_4328a0);
depend_tab = pmu_res_depend_tab_4328a0;
depend_tab_size = ARRAY_SIZE(pmu_res_depend_tab_4328a0);
break;
case 0x5354:
/* The PLL may turn on, if it decides so. */
max_msk = 0xFFFFF;
break;
default:
ssb_printk(KERN_ERR PFX
"ERROR: PMU resource config unknown for device %04X\n",
bus->chip_id);
}
if (updown_tab) {
for (i = 0; i < updown_tab_size; i++) {
chipco_write32(cc, SSB_CHIPCO_PMU_RES_TABSEL,
updown_tab[i].resource);
chipco_write32(cc, SSB_CHIPCO_PMU_RES_UPDNTM,
updown_tab[i].updown);
}
}
if (depend_tab) {
for (i = 0; i < depend_tab_size; i++) {
chipco_write32(cc, SSB_CHIPCO_PMU_RES_TABSEL,
depend_tab[i].resource);
switch (depend_tab[i].task) {
case PMU_RES_DEP_SET:
chipco_write32(cc, SSB_CHIPCO_PMU_RES_DEPMSK,
depend_tab[i].depend);
break;
case PMU_RES_DEP_ADD:
chipco_set32(cc, SSB_CHIPCO_PMU_RES_DEPMSK,
depend_tab[i].depend);
break;
case PMU_RES_DEP_REMOVE:
chipco_mask32(cc, SSB_CHIPCO_PMU_RES_DEPMSK,
~(depend_tab[i].depend));
break;
default:
SSB_WARN_ON(1);
}
}
}
/* Set the resource masks. */
if (min_msk)
chipco_write32(cc, SSB_CHIPCO_PMU_MINRES_MSK, min_msk);
if (max_msk)
chipco_write32(cc, SSB_CHIPCO_PMU_MAXRES_MSK, max_msk);
}
/* http://bcm-v4.sipsolutions.net/802.11/SSB/PmuInit */
void ssb_pmu_init(struct ssb_chipcommon *cc)
{
u32 pmucap;
if (!(cc->capabilities & SSB_CHIPCO_CAP_PMU))
return;
pmucap = chipco_read32(cc, SSB_CHIPCO_PMU_CAP);
cc->pmu.rev = (pmucap & SSB_CHIPCO_PMU_CAP_REVISION);
ssb_dprintk(KERN_DEBUG PFX "Found rev %u PMU (capabilities 0x%08X)\n",
cc->pmu.rev, pmucap);
if (cc->pmu.rev == 1)
chipco_mask32(cc, SSB_CHIPCO_PMU_CTL,
~SSB_CHIPCO_PMU_CTL_NOILPONW);
else
chipco_set32(cc, SSB_CHIPCO_PMU_CTL,
SSB_CHIPCO_PMU_CTL_NOILPONW);
ssb_pmu_pll_init(cc);
ssb_pmu_resources_init(cc);
}
void ssb_pmu_set_ldo_voltage(struct ssb_chipcommon *cc,
enum ssb_pmu_ldo_volt_id id, u32 voltage)
{
struct ssb_bus *bus = cc->dev->bus;
u32 addr, shift, mask;
switch (bus->chip_id) {
case 0x4328:
case 0x5354:
switch (id) {
case LDO_VOLT1:
addr = 2;
shift = 25;
mask = 0xF;
break;
case LDO_VOLT2:
addr = 3;
shift = 1;
mask = 0xF;
break;
case LDO_VOLT3:
addr = 3;
shift = 9;
mask = 0xF;
break;
case LDO_PAREF:
addr = 3;
shift = 17;
mask = 0x3F;
break;
default:
SSB_WARN_ON(1);
return;
}
break;
case 0x4312:
if (SSB_WARN_ON(id != LDO_PAREF))
return;
addr = 0;
shift = 21;
mask = 0x3F;
break;
default:
return;
}
ssb_chipco_regctl_maskset(cc, addr, ~(mask << shift),
(voltage & mask) << shift);
}
void ssb_pmu_set_ldo_paref(struct ssb_chipcommon *cc, bool on)
{
struct ssb_bus *bus = cc->dev->bus;
int ldo;
switch (bus->chip_id) {
case 0x4312:
ldo = SSB_PMURES_4312_PA_REF_LDO;
break;
case 0x4328:
ldo = SSB_PMURES_4328_PA_REF_LDO;
break;
case 0x5354:
ldo = SSB_PMURES_5354_PA_REF_LDO;
break;
default:
return;
}
if (on)
chipco_set32(cc, SSB_CHIPCO_PMU_MINRES_MSK, 1 << ldo);
else
chipco_mask32(cc, SSB_CHIPCO_PMU_MINRES_MSK, ~(1 << ldo));
chipco_read32(cc, SSB_CHIPCO_PMU_MINRES_MSK); //SPEC FIXME found via mmiotrace - dummy read?
}
EXPORT_SYMBOL(ssb_pmu_set_ldo_voltage);
EXPORT_SYMBOL(ssb_pmu_set_ldo_paref);
| gpl-2.0 |
Skin1980/android_kernel_lge_dory | net/ipv4/inet_connection_sock.c | 925 | 26884 | /*
* 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.
*
* Support for INET connection oriented protocols.
*
* Authors: See the TCP sources
*
* 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/jhash.h>
#include <net/inet_connection_sock.h>
#include <net/inet_hashtables.h>
#include <net/inet_timewait_sock.h>
#include <net/ip.h>
#include <net/route.h>
#include <net/tcp_states.h>
#include <net/xfrm.h>
#ifdef INET_CSK_DEBUG
const char inet_csk_timer_bug_msg[] = "inet_csk BUG: unknown timer value\n";
EXPORT_SYMBOL(inet_csk_timer_bug_msg);
#endif
/*
* This struct holds the first and last local port number.
*/
struct local_ports sysctl_local_ports __read_mostly = {
.lock = __SEQLOCK_UNLOCKED(sysctl_local_ports.lock),
.range = { 32768, 61000 },
};
unsigned long *sysctl_local_reserved_ports;
EXPORT_SYMBOL(sysctl_local_reserved_ports);
void inet_get_local_port_range(int *low, int *high)
{
unsigned int seq;
do {
seq = read_seqbegin(&sysctl_local_ports.lock);
*low = sysctl_local_ports.range[0];
*high = sysctl_local_ports.range[1];
} while (read_seqretry(&sysctl_local_ports.lock, seq));
}
EXPORT_SYMBOL(inet_get_local_port_range);
int inet_csk_bind_conflict(const struct sock *sk,
const struct inet_bind_bucket *tb, bool relax)
{
struct sock *sk2;
int reuse = sk->sk_reuse;
int reuseport = sk->sk_reuseport;
kuid_t uid = sock_i_uid((struct sock *)sk);
/*
* Unlike other sk lookup places we do not check
* for sk_net here, since _all_ the socks listed
* in tb->owners list belong to the same net - the
* one this bucket belongs to.
*/
sk_for_each_bound(sk2, &tb->owners) {
if (sk != sk2 &&
!inet_v6_ipv6only(sk2) &&
(!sk->sk_bound_dev_if ||
!sk2->sk_bound_dev_if ||
sk->sk_bound_dev_if == sk2->sk_bound_dev_if)) {
if ((!reuse || !sk2->sk_reuse ||
sk2->sk_state == TCP_LISTEN) &&
(!reuseport || !sk2->sk_reuseport ||
(sk2->sk_state != TCP_TIME_WAIT &&
!uid_eq(uid, sock_i_uid(sk2))))) {
const __be32 sk2_rcv_saddr = sk_rcv_saddr(sk2);
if (!sk2_rcv_saddr || !sk_rcv_saddr(sk) ||
sk2_rcv_saddr == sk_rcv_saddr(sk))
break;
}
if (!relax && reuse && sk2->sk_reuse &&
sk2->sk_state != TCP_LISTEN) {
const __be32 sk2_rcv_saddr = sk_rcv_saddr(sk2);
if (!sk2_rcv_saddr || !sk_rcv_saddr(sk) ||
sk2_rcv_saddr == sk_rcv_saddr(sk))
break;
}
}
}
return sk2 != NULL;
}
EXPORT_SYMBOL_GPL(inet_csk_bind_conflict);
/* Obtain a reference to a local port for the given sock,
* if snum is zero it means select any available local port.
*/
int inet_csk_get_port(struct sock *sk, unsigned short snum)
{
struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
struct inet_bind_hashbucket *head;
struct inet_bind_bucket *tb;
int ret, attempts = 5;
struct net *net = sock_net(sk);
int smallest_size = -1, smallest_rover;
kuid_t uid = sock_i_uid(sk);
local_bh_disable();
if (!snum) {
int remaining, rover, low, high;
again:
inet_get_local_port_range(&low, &high);
remaining = (high - low) + 1;
smallest_rover = rover = net_random() % remaining + low;
smallest_size = -1;
do {
if (inet_is_reserved_local_port(rover))
goto next_nolock;
head = &hashinfo->bhash[inet_bhashfn(net, rover,
hashinfo->bhash_size)];
spin_lock(&head->lock);
inet_bind_bucket_for_each(tb, &head->chain)
if (net_eq(ib_net(tb), net) && tb->port == rover) {
if (((tb->fastreuse > 0 &&
sk->sk_reuse &&
sk->sk_state != TCP_LISTEN) ||
(tb->fastreuseport > 0 &&
sk->sk_reuseport &&
uid_eq(tb->fastuid, uid))) &&
(tb->num_owners < smallest_size || smallest_size == -1)) {
smallest_size = tb->num_owners;
smallest_rover = rover;
if (atomic_read(&hashinfo->bsockets) > (high - low) + 1 &&
!inet_csk(sk)->icsk_af_ops->bind_conflict(sk, tb, false)) {
snum = smallest_rover;
goto tb_found;
}
}
if (!inet_csk(sk)->icsk_af_ops->bind_conflict(sk, tb, false)) {
snum = rover;
goto tb_found;
}
goto next;
}
break;
next:
spin_unlock(&head->lock);
next_nolock:
if (++rover > high)
rover = low;
} while (--remaining > 0);
/* Exhausted local port range during search? It is not
* possible for us to be holding one of the bind hash
* locks if this test triggers, because if 'remaining'
* drops to zero, we broke out of the do/while loop at
* the top level, not from the 'break;' statement.
*/
ret = 1;
if (remaining <= 0) {
if (smallest_size != -1) {
snum = smallest_rover;
goto have_snum;
}
goto fail;
}
/* OK, here is the one we will use. HEAD is
* non-NULL and we hold it's mutex.
*/
snum = rover;
} else {
have_snum:
head = &hashinfo->bhash[inet_bhashfn(net, snum,
hashinfo->bhash_size)];
spin_lock(&head->lock);
inet_bind_bucket_for_each(tb, &head->chain)
if (net_eq(ib_net(tb), net) && tb->port == snum)
goto tb_found;
}
tb = NULL;
goto tb_not_found;
tb_found:
if (!hlist_empty(&tb->owners)) {
if (sk->sk_reuse == SK_FORCE_REUSE)
goto success;
if (((tb->fastreuse > 0 &&
sk->sk_reuse && sk->sk_state != TCP_LISTEN) ||
(tb->fastreuseport > 0 &&
sk->sk_reuseport && uid_eq(tb->fastuid, uid))) &&
smallest_size == -1) {
goto success;
} else {
ret = 1;
if (inet_csk(sk)->icsk_af_ops->bind_conflict(sk, tb, true)) {
if (((sk->sk_reuse && sk->sk_state != TCP_LISTEN) ||
(tb->fastreuseport > 0 &&
sk->sk_reuseport && uid_eq(tb->fastuid, uid))) &&
smallest_size != -1 && --attempts >= 0) {
spin_unlock(&head->lock);
goto again;
}
goto fail_unlock;
}
}
}
tb_not_found:
ret = 1;
if (!tb && (tb = inet_bind_bucket_create(hashinfo->bind_bucket_cachep,
net, head, snum)) == NULL)
goto fail_unlock;
if (hlist_empty(&tb->owners)) {
if (sk->sk_reuse && sk->sk_state != TCP_LISTEN)
tb->fastreuse = 1;
else
tb->fastreuse = 0;
if (sk->sk_reuseport) {
tb->fastreuseport = 1;
tb->fastuid = uid;
} else
tb->fastreuseport = 0;
} else {
if (tb->fastreuse &&
(!sk->sk_reuse || sk->sk_state == TCP_LISTEN))
tb->fastreuse = 0;
if (tb->fastreuseport &&
(!sk->sk_reuseport || !uid_eq(tb->fastuid, uid)))
tb->fastreuseport = 0;
}
success:
if (!inet_csk(sk)->icsk_bind_hash)
inet_bind_hash(sk, tb, snum);
WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
ret = 0;
fail_unlock:
spin_unlock(&head->lock);
fail:
local_bh_enable();
return ret;
}
EXPORT_SYMBOL_GPL(inet_csk_get_port);
/*
* Wait for an incoming connection, avoid race conditions. This must be called
* with the socket locked.
*/
static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
{
struct inet_connection_sock *icsk = inet_csk(sk);
DEFINE_WAIT(wait);
int err;
/*
* True wake-one mechanism for incoming connections: only
* one process gets woken up, not the 'whole herd'.
* Since we do not 'race & poll' for established sockets
* anymore, the common case will execute the loop only once.
*
* Subtle issue: "add_wait_queue_exclusive()" will be added
* after any current non-exclusive waiters, and we know that
* it will always _stay_ after any new non-exclusive waiters
* because all non-exclusive waiters are added at the
* beginning of the wait-queue. As such, it's ok to "drop"
* our exclusiveness temporarily when we get woken up without
* having to remove and re-insert us on the wait queue.
*/
for (;;) {
prepare_to_wait_exclusive(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
release_sock(sk);
if (reqsk_queue_empty(&icsk->icsk_accept_queue))
timeo = schedule_timeout(timeo);
lock_sock(sk);
err = 0;
if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
break;
err = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
break;
err = sock_intr_errno(timeo);
if (signal_pending(current))
break;
err = -EAGAIN;
if (!timeo)
break;
}
finish_wait(sk_sleep(sk), &wait);
return err;
}
/*
* This will accept the next outstanding connection.
*/
struct sock *inet_csk_accept(struct sock *sk, int flags, int *err)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct request_sock_queue *queue = &icsk->icsk_accept_queue;
struct sock *newsk;
struct request_sock *req;
int error;
lock_sock(sk);
/* We need to make sure that this socket is listening,
* and that it has something pending.
*/
error = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
goto out_err;
/* Find already established connection */
if (reqsk_queue_empty(queue)) {
long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
/* If this is a non blocking socket don't sleep */
error = -EAGAIN;
if (!timeo)
goto out_err;
error = inet_csk_wait_for_connect(sk, timeo);
if (error)
goto out_err;
}
req = reqsk_queue_remove(queue);
newsk = req->sk;
sk_acceptq_removed(sk);
if (sk->sk_protocol == IPPROTO_TCP && queue->fastopenq != NULL) {
spin_lock_bh(&queue->fastopenq->lock);
if (tcp_rsk(req)->listener) {
/* We are still waiting for the final ACK from 3WHS
* so can't free req now. Instead, we set req->sk to
* NULL to signify that the child socket is taken
* so reqsk_fastopen_remove() will free the req
* when 3WHS finishes (or is aborted).
*/
req->sk = NULL;
req = NULL;
}
spin_unlock_bh(&queue->fastopenq->lock);
}
out:
release_sock(sk);
if (req)
__reqsk_free(req);
return newsk;
out_err:
newsk = NULL;
req = NULL;
*err = error;
goto out;
}
EXPORT_SYMBOL(inet_csk_accept);
/*
* Using different timers for retransmit, delayed acks and probes
* We may wish use just one timer maintaining a list of expire jiffies
* to optimize.
*/
void inet_csk_init_xmit_timers(struct sock *sk,
void (*retransmit_handler)(unsigned long),
void (*delack_handler)(unsigned long),
void (*keepalive_handler)(unsigned long))
{
struct inet_connection_sock *icsk = inet_csk(sk);
setup_timer(&icsk->icsk_retransmit_timer, retransmit_handler,
(unsigned long)sk);
setup_timer(&icsk->icsk_delack_timer, delack_handler,
(unsigned long)sk);
setup_timer(&sk->sk_timer, keepalive_handler, (unsigned long)sk);
icsk->icsk_pending = icsk->icsk_ack.pending = 0;
}
EXPORT_SYMBOL(inet_csk_init_xmit_timers);
void inet_csk_clear_xmit_timers(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_pending = icsk->icsk_ack.pending = icsk->icsk_ack.blocked = 0;
sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
sk_stop_timer(sk, &icsk->icsk_delack_timer);
sk_stop_timer(sk, &sk->sk_timer);
}
EXPORT_SYMBOL(inet_csk_clear_xmit_timers);
void inet_csk_delete_keepalive_timer(struct sock *sk)
{
sk_stop_timer(sk, &sk->sk_timer);
}
EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);
void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
{
sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
}
EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);
struct dst_entry *inet_csk_route_req(struct sock *sk,
struct flowi4 *fl4,
const struct request_sock *req)
{
struct rtable *rt;
const struct inet_request_sock *ireq = inet_rsk(req);
struct ip_options_rcu *opt = inet_rsk(req)->opt;
struct net *net = sock_net(sk);
int flags = inet_sk_flowi_flags(sk);
flowi4_init_output(fl4, sk->sk_bound_dev_if, ireq->ir_mark,
RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
sk->sk_protocol,
flags,
(opt && opt->opt.srr) ? opt->opt.faddr : ireq->rmt_addr,
ireq->loc_addr, ireq->rmt_port, inet_sk(sk)->inet_sport,
sock_i_uid(sk));
security_req_classify_flow(req, flowi4_to_flowi(fl4));
rt = ip_route_output_flow(net, fl4, sk);
if (IS_ERR(rt))
goto no_route;
if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
goto route_err;
return &rt->dst;
route_err:
ip_rt_put(rt);
no_route:
IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
return NULL;
}
EXPORT_SYMBOL_GPL(inet_csk_route_req);
struct dst_entry *inet_csk_route_child_sock(struct sock *sk,
struct sock *newsk,
const struct request_sock *req)
{
const struct inet_request_sock *ireq = inet_rsk(req);
struct inet_sock *newinet = inet_sk(newsk);
struct ip_options_rcu *opt;
struct net *net = sock_net(sk);
struct flowi4 *fl4;
struct rtable *rt;
fl4 = &newinet->cork.fl.u.ip4;
rcu_read_lock();
opt = rcu_dereference(newinet->inet_opt);
flowi4_init_output(fl4, sk->sk_bound_dev_if, inet_rsk(req)->ir_mark,
RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
sk->sk_protocol, inet_sk_flowi_flags(sk),
(opt && opt->opt.srr) ? opt->opt.faddr : ireq->rmt_addr,
ireq->loc_addr, ireq->rmt_port, inet_sk(sk)->inet_sport,
sock_i_uid(sk));
security_req_classify_flow(req, flowi4_to_flowi(fl4));
rt = ip_route_output_flow(net, fl4, sk);
if (IS_ERR(rt))
goto no_route;
if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
goto route_err;
rcu_read_unlock();
return &rt->dst;
route_err:
ip_rt_put(rt);
no_route:
rcu_read_unlock();
IP_INC_STATS_BH(net, IPSTATS_MIB_OUTNOROUTES);
return NULL;
}
EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
static inline u32 inet_synq_hash(const __be32 raddr, const __be16 rport,
const u32 rnd, const u32 synq_hsize)
{
return jhash_2words((__force u32)raddr, (__force u32)rport, rnd) & (synq_hsize - 1);
}
#if IS_ENABLED(CONFIG_IPV6)
#define AF_INET_FAMILY(fam) ((fam) == AF_INET)
#else
#define AF_INET_FAMILY(fam) 1
#endif
struct request_sock *inet_csk_search_req(const struct sock *sk,
struct request_sock ***prevp,
const __be16 rport, const __be32 raddr,
const __be32 laddr)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
struct listen_sock *lopt = icsk->icsk_accept_queue.listen_opt;
struct request_sock *req, **prev;
for (prev = &lopt->syn_table[inet_synq_hash(raddr, rport, lopt->hash_rnd,
lopt->nr_table_entries)];
(req = *prev) != NULL;
prev = &req->dl_next) {
const struct inet_request_sock *ireq = inet_rsk(req);
if (ireq->rmt_port == rport &&
ireq->rmt_addr == raddr &&
ireq->loc_addr == laddr &&
AF_INET_FAMILY(req->rsk_ops->family)) {
WARN_ON(req->sk);
*prevp = prev;
break;
}
}
return req;
}
EXPORT_SYMBOL_GPL(inet_csk_search_req);
void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
unsigned long timeout)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct listen_sock *lopt = icsk->icsk_accept_queue.listen_opt;
const u32 h = inet_synq_hash(inet_rsk(req)->rmt_addr, inet_rsk(req)->rmt_port,
lopt->hash_rnd, lopt->nr_table_entries);
reqsk_queue_hash_req(&icsk->icsk_accept_queue, h, req, timeout);
inet_csk_reqsk_queue_added(sk, timeout);
}
EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
/* Only thing we need from tcp.h */
extern int sysctl_tcp_synack_retries;
/* Decide when to expire the request and when to resend SYN-ACK */
static inline void syn_ack_recalc(struct request_sock *req, const int thresh,
const int max_retries,
const u8 rskq_defer_accept,
int *expire, int *resend)
{
if (!rskq_defer_accept) {
*expire = req->num_timeout >= thresh;
*resend = 1;
return;
}
*expire = req->num_timeout >= thresh &&
(!inet_rsk(req)->acked || req->num_timeout >= max_retries);
/*
* Do not resend while waiting for data after ACK,
* start to resend on end of deferring period to give
* last chance for data or ACK to create established socket.
*/
*resend = !inet_rsk(req)->acked ||
req->num_timeout >= rskq_defer_accept - 1;
}
int inet_rtx_syn_ack(struct sock *parent, struct request_sock *req)
{
int err = req->rsk_ops->rtx_syn_ack(parent, req);
if (!err)
req->num_retrans++;
return err;
}
EXPORT_SYMBOL(inet_rtx_syn_ack);
void inet_csk_reqsk_queue_prune(struct sock *parent,
const unsigned long interval,
const unsigned long timeout,
const unsigned long max_rto)
{
struct inet_connection_sock *icsk = inet_csk(parent);
struct request_sock_queue *queue = &icsk->icsk_accept_queue;
struct listen_sock *lopt = queue->listen_opt;
int max_retries = icsk->icsk_syn_retries ? : sysctl_tcp_synack_retries;
int thresh = max_retries;
unsigned long now = jiffies;
struct request_sock **reqp, *req;
int i, budget;
if (lopt == NULL || lopt->qlen == 0)
return;
/* Normally all the openreqs are young and become mature
* (i.e. converted to established socket) for first timeout.
* If synack was not acknowledged for 1 second, it means
* one of the following things: synack was lost, ack was lost,
* rtt is high or nobody planned to ack (i.e. synflood).
* When server is a bit loaded, queue is populated with old
* open requests, reducing effective size of queue.
* When server is well loaded, queue size reduces to zero
* after several minutes of work. It is not synflood,
* it is normal operation. The solution is pruning
* too old entries overriding normal timeout, when
* situation becomes dangerous.
*
* Essentially, we reserve half of room for young
* embrions; and abort old ones without pity, if old
* ones are about to clog our table.
*/
if (lopt->qlen>>(lopt->max_qlen_log-1)) {
int young = (lopt->qlen_young<<1);
while (thresh > 2) {
if (lopt->qlen < young)
break;
thresh--;
young <<= 1;
}
}
if (queue->rskq_defer_accept)
max_retries = queue->rskq_defer_accept;
budget = 2 * (lopt->nr_table_entries / (timeout / interval));
i = lopt->clock_hand;
do {
reqp=&lopt->syn_table[i];
while ((req = *reqp) != NULL) {
if (time_after_eq(now, req->expires)) {
int expire = 0, resend = 0;
syn_ack_recalc(req, thresh, max_retries,
queue->rskq_defer_accept,
&expire, &resend);
req->rsk_ops->syn_ack_timeout(parent, req);
if (!expire &&
(!resend ||
!inet_rtx_syn_ack(parent, req) ||
inet_rsk(req)->acked)) {
unsigned long timeo;
if (req->num_timeout++ == 0)
lopt->qlen_young--;
timeo = min(timeout << req->num_timeout,
max_rto);
req->expires = now + timeo;
reqp = &req->dl_next;
continue;
}
/* Drop this request */
inet_csk_reqsk_queue_unlink(parent, req, reqp);
reqsk_queue_removed(queue, req);
reqsk_free(req);
continue;
}
reqp = &req->dl_next;
}
i = (i + 1) & (lopt->nr_table_entries - 1);
} while (--budget > 0);
lopt->clock_hand = i;
if (lopt->qlen)
inet_csk_reset_keepalive_timer(parent, interval);
}
EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_prune);
/**
* inet_csk_clone_lock - clone an inet socket, and lock its clone
* @sk: the socket to clone
* @req: request_sock
* @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
*
* Caller must unlock socket even in error path (bh_unlock_sock(newsk))
*/
struct sock *inet_csk_clone_lock(const struct sock *sk,
const struct request_sock *req,
const gfp_t priority)
{
struct sock *newsk = sk_clone_lock(sk, priority);
if (newsk != NULL) {
struct inet_connection_sock *newicsk = inet_csk(newsk);
newsk->sk_state = TCP_SYN_RECV;
newicsk->icsk_bind_hash = NULL;
inet_sk(newsk)->inet_dport = inet_rsk(req)->rmt_port;
inet_sk(newsk)->inet_num = ntohs(inet_rsk(req)->loc_port);
inet_sk(newsk)->inet_sport = inet_rsk(req)->loc_port;
newsk->sk_write_space = sk_stream_write_space;
newsk->sk_mark = inet_rsk(req)->ir_mark;
newicsk->icsk_retransmits = 0;
newicsk->icsk_backoff = 0;
newicsk->icsk_probes_out = 0;
/* Deinitialize accept_queue to trap illegal accesses. */
memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
security_inet_csk_clone(newsk, req);
}
return newsk;
}
EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
/*
* At this point, there should be no process reference to this
* socket, and thus no user references at all. Therefore we
* can assume the socket waitqueue is inactive and nobody will
* try to jump onto it.
*/
void inet_csk_destroy_sock(struct sock *sk)
{
WARN_ON(sk->sk_state != TCP_CLOSE);
WARN_ON(!sock_flag(sk, SOCK_DEAD));
/* It cannot be in hash table! */
WARN_ON(!sk_unhashed(sk));
/* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
sk->sk_prot->destroy(sk);
sk_stream_kill_queues(sk);
xfrm_sk_free_policy(sk);
sk_refcnt_debug_release(sk);
percpu_counter_dec(sk->sk_prot->orphan_count);
sock_put(sk);
}
EXPORT_SYMBOL(inet_csk_destroy_sock);
/* This function allows to force a closure of a socket after the call to
* tcp/dccp_create_openreq_child().
*/
void inet_csk_prepare_forced_close(struct sock *sk)
__releases(&sk->sk_lock.slock)
{
/* sk_clone_lock locked the socket and set refcnt to 2 */
bh_unlock_sock(sk);
sock_put(sk);
/* The below has to be done to allow calling inet_csk_destroy_sock */
sock_set_flag(sk, SOCK_DEAD);
percpu_counter_inc(sk->sk_prot->orphan_count);
inet_sk(sk)->inet_num = 0;
}
EXPORT_SYMBOL(inet_csk_prepare_forced_close);
int inet_csk_listen_start(struct sock *sk, const int nr_table_entries)
{
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
int rc = reqsk_queue_alloc(&icsk->icsk_accept_queue, nr_table_entries);
if (rc != 0)
return rc;
sk->sk_max_ack_backlog = 0;
sk->sk_ack_backlog = 0;
inet_csk_delack_init(sk);
/* There is race window here: we announce ourselves listening,
* but this transition is still not validated by get_port().
* It is OK, because this socket enters to hash table only
* after validation is complete.
*/
sk->sk_state = TCP_LISTEN;
if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
inet->inet_sport = htons(inet->inet_num);
sk_dst_reset(sk);
sk->sk_prot->hash(sk);
return 0;
}
sk->sk_state = TCP_CLOSE;
__reqsk_queue_destroy(&icsk->icsk_accept_queue);
return -EADDRINUSE;
}
EXPORT_SYMBOL_GPL(inet_csk_listen_start);
/*
* This routine closes sockets which have been at least partially
* opened, but not yet accepted.
*/
void inet_csk_listen_stop(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct request_sock_queue *queue = &icsk->icsk_accept_queue;
struct request_sock *acc_req;
struct request_sock *req;
inet_csk_delete_keepalive_timer(sk);
/* make all the listen_opt local to us */
acc_req = reqsk_queue_yank_acceptq(queue);
/* Following specs, it would be better either to send FIN
* (and enter FIN-WAIT-1, it is normal close)
* or to send active reset (abort).
* Certainly, it is pretty dangerous while synflood, but it is
* bad justification for our negligence 8)
* To be honest, we are not able to make either
* of the variants now. --ANK
*/
reqsk_queue_destroy(queue);
while ((req = acc_req) != NULL) {
struct sock *child = req->sk;
acc_req = req->dl_next;
local_bh_disable();
bh_lock_sock(child);
WARN_ON(sock_owned_by_user(child));
sock_hold(child);
sk->sk_prot->disconnect(child, O_NONBLOCK);
sock_orphan(child);
percpu_counter_inc(sk->sk_prot->orphan_count);
if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->listener) {
BUG_ON(tcp_sk(child)->fastopen_rsk != req);
BUG_ON(sk != tcp_rsk(req)->listener);
/* Paranoid, to prevent race condition if
* an inbound pkt destined for child is
* blocked by sock lock in tcp_v4_rcv().
* Also to satisfy an assertion in
* tcp_v4_destroy_sock().
*/
tcp_sk(child)->fastopen_rsk = NULL;
sock_put(sk);
}
inet_csk_destroy_sock(child);
bh_unlock_sock(child);
local_bh_enable();
sock_put(child);
sk_acceptq_removed(sk);
__reqsk_free(req);
}
if (queue->fastopenq != NULL) {
/* Free all the reqs queued in rskq_rst_head. */
spin_lock_bh(&queue->fastopenq->lock);
acc_req = queue->fastopenq->rskq_rst_head;
queue->fastopenq->rskq_rst_head = NULL;
spin_unlock_bh(&queue->fastopenq->lock);
while ((req = acc_req) != NULL) {
acc_req = req->dl_next;
__reqsk_free(req);
}
}
WARN_ON(sk->sk_ack_backlog);
}
EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
{
struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
const struct inet_sock *inet = inet_sk(sk);
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = inet->inet_daddr;
sin->sin_port = inet->inet_dport;
}
EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
#ifdef CONFIG_COMPAT
int inet_csk_compat_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
if (icsk->icsk_af_ops->compat_getsockopt != NULL)
return icsk->icsk_af_ops->compat_getsockopt(sk, level, optname,
optval, optlen);
return icsk->icsk_af_ops->getsockopt(sk, level, optname,
optval, optlen);
}
EXPORT_SYMBOL_GPL(inet_csk_compat_getsockopt);
int inet_csk_compat_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
if (icsk->icsk_af_ops->compat_setsockopt != NULL)
return icsk->icsk_af_ops->compat_setsockopt(sk, level, optname,
optval, optlen);
return icsk->icsk_af_ops->setsockopt(sk, level, optname,
optval, optlen);
}
EXPORT_SYMBOL_GPL(inet_csk_compat_setsockopt);
#endif
static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
{
const struct inet_sock *inet = inet_sk(sk);
const struct ip_options_rcu *inet_opt;
__be32 daddr = inet->inet_daddr;
struct flowi4 *fl4;
struct rtable *rt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
fl4 = &fl->u.ip4;
rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
inet->inet_saddr, inet->inet_dport,
inet->inet_sport, sk->sk_protocol,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
if (IS_ERR(rt))
rt = NULL;
if (rt)
sk_setup_caps(sk, &rt->dst);
rcu_read_unlock();
return &rt->dst;
}
struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
{
struct dst_entry *dst = __sk_dst_check(sk, 0);
struct inet_sock *inet = inet_sk(sk);
if (!dst) {
dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
if (!dst)
goto out;
}
dst->ops->update_pmtu(dst, sk, NULL, mtu);
dst = __sk_dst_check(sk, 0);
if (!dst)
dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
out:
return dst;
}
EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);
| gpl-2.0 |
ResurrectionRemix-Devices/android_kernel_samsung_smdk4412 | drivers/mmc/host/bfin_sdh.c | 3229 | 16273 | /*
* bfin_sdh.c - Analog Devices Blackfin SDH Controller
*
* Copyright (C) 2007-2009 Analog Device Inc.
*
* Licensed under the GPL-2 or later.
*/
#define DRIVER_NAME "bfin-sdh"
#include <linux/module.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/mmc/host.h>
#include <linux/proc_fs.h>
#include <linux/gfp.h>
#include <asm/cacheflush.h>
#include <asm/dma.h>
#include <asm/portmux.h>
#include <asm/bfin_sdh.h>
#if defined(CONFIG_BF51x)
#define bfin_read_SDH_PWR_CTL bfin_read_RSI_PWR_CTL
#define bfin_write_SDH_PWR_CTL bfin_write_RSI_PWR_CTL
#define bfin_read_SDH_CLK_CTL bfin_read_RSI_CLK_CTL
#define bfin_write_SDH_CLK_CTL bfin_write_RSI_CLK_CTL
#define bfin_write_SDH_ARGUMENT bfin_write_RSI_ARGUMENT
#define bfin_write_SDH_COMMAND bfin_write_RSI_COMMAND
#define bfin_write_SDH_DATA_TIMER bfin_write_RSI_DATA_TIMER
#define bfin_read_SDH_RESPONSE0 bfin_read_RSI_RESPONSE0
#define bfin_read_SDH_RESPONSE1 bfin_read_RSI_RESPONSE1
#define bfin_read_SDH_RESPONSE2 bfin_read_RSI_RESPONSE2
#define bfin_read_SDH_RESPONSE3 bfin_read_RSI_RESPONSE3
#define bfin_write_SDH_DATA_LGTH bfin_write_RSI_DATA_LGTH
#define bfin_read_SDH_DATA_CTL bfin_read_RSI_DATA_CTL
#define bfin_write_SDH_DATA_CTL bfin_write_RSI_DATA_CTL
#define bfin_read_SDH_DATA_CNT bfin_read_RSI_DATA_CNT
#define bfin_write_SDH_STATUS_CLR bfin_write_RSI_STATUS_CLR
#define bfin_read_SDH_E_STATUS bfin_read_RSI_E_STATUS
#define bfin_write_SDH_E_STATUS bfin_write_RSI_E_STATUS
#define bfin_read_SDH_STATUS bfin_read_RSI_STATUS
#define bfin_write_SDH_MASK0 bfin_write_RSI_MASK0
#define bfin_read_SDH_CFG bfin_read_RSI_CFG
#define bfin_write_SDH_CFG bfin_write_RSI_CFG
#endif
struct dma_desc_array {
unsigned long start_addr;
unsigned short cfg;
unsigned short x_count;
short x_modify;
} __packed;
struct sdh_host {
struct mmc_host *mmc;
spinlock_t lock;
struct resource *res;
void __iomem *base;
int irq;
int stat_irq;
int dma_ch;
int dma_dir;
struct dma_desc_array *sg_cpu;
dma_addr_t sg_dma;
int dma_len;
unsigned int imask;
unsigned int power_mode;
unsigned int clk_div;
struct mmc_request *mrq;
struct mmc_command *cmd;
struct mmc_data *data;
};
static struct bfin_sd_host *get_sdh_data(struct platform_device *pdev)
{
return pdev->dev.platform_data;
}
static void sdh_stop_clock(struct sdh_host *host)
{
bfin_write_SDH_CLK_CTL(bfin_read_SDH_CLK_CTL() & ~CLK_E);
SSYNC();
}
static void sdh_enable_stat_irq(struct sdh_host *host, unsigned int mask)
{
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
host->imask |= mask;
bfin_write_SDH_MASK0(mask);
SSYNC();
spin_unlock_irqrestore(&host->lock, flags);
}
static void sdh_disable_stat_irq(struct sdh_host *host, unsigned int mask)
{
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
host->imask &= ~mask;
bfin_write_SDH_MASK0(host->imask);
SSYNC();
spin_unlock_irqrestore(&host->lock, flags);
}
static int sdh_setup_data(struct sdh_host *host, struct mmc_data *data)
{
unsigned int length;
unsigned int data_ctl;
unsigned int dma_cfg;
unsigned int cycle_ns, timeout;
dev_dbg(mmc_dev(host->mmc), "%s enter flags: 0x%x\n", __func__, data->flags);
host->data = data;
data_ctl = 0;
dma_cfg = 0;
length = data->blksz * data->blocks;
bfin_write_SDH_DATA_LGTH(length);
if (data->flags & MMC_DATA_STREAM)
data_ctl |= DTX_MODE;
if (data->flags & MMC_DATA_READ)
data_ctl |= DTX_DIR;
/* Only supports power-of-2 block size */
if (data->blksz & (data->blksz - 1))
return -EINVAL;
data_ctl |= ((ffs(data->blksz) - 1) << 4);
bfin_write_SDH_DATA_CTL(data_ctl);
/* the time of a host clock period in ns */
cycle_ns = 1000000000 / (get_sclk() / (2 * (host->clk_div + 1)));
timeout = data->timeout_ns / cycle_ns;
timeout += data->timeout_clks;
bfin_write_SDH_DATA_TIMER(timeout);
SSYNC();
if (data->flags & MMC_DATA_READ) {
host->dma_dir = DMA_FROM_DEVICE;
dma_cfg |= WNR;
} else
host->dma_dir = DMA_TO_DEVICE;
sdh_enable_stat_irq(host, (DAT_CRC_FAIL | DAT_TIME_OUT | DAT_END));
host->dma_len = dma_map_sg(mmc_dev(host->mmc), data->sg, data->sg_len, host->dma_dir);
#if defined(CONFIG_BF54x)
dma_cfg |= DMAFLOW_ARRAY | NDSIZE_5 | RESTART | WDSIZE_32 | DMAEN;
{
struct scatterlist *sg;
int i;
for_each_sg(data->sg, sg, host->dma_len, i) {
host->sg_cpu[i].start_addr = sg_dma_address(sg);
host->sg_cpu[i].cfg = dma_cfg;
host->sg_cpu[i].x_count = sg_dma_len(sg) / 4;
host->sg_cpu[i].x_modify = 4;
dev_dbg(mmc_dev(host->mmc), "%d: start_addr:0x%lx, "
"cfg:0x%x, x_count:0x%x, x_modify:0x%x\n",
i, host->sg_cpu[i].start_addr,
host->sg_cpu[i].cfg, host->sg_cpu[i].x_count,
host->sg_cpu[i].x_modify);
}
}
flush_dcache_range((unsigned int)host->sg_cpu,
(unsigned int)host->sg_cpu +
host->dma_len * sizeof(struct dma_desc_array));
/* Set the last descriptor to stop mode */
host->sg_cpu[host->dma_len - 1].cfg &= ~(DMAFLOW | NDSIZE);
host->sg_cpu[host->dma_len - 1].cfg |= DI_EN;
set_dma_curr_desc_addr(host->dma_ch, (unsigned long *)host->sg_dma);
set_dma_x_count(host->dma_ch, 0);
set_dma_x_modify(host->dma_ch, 0);
set_dma_config(host->dma_ch, dma_cfg);
#elif defined(CONFIG_BF51x)
/* RSI DMA doesn't work in array mode */
dma_cfg |= WDSIZE_32 | DMAEN;
set_dma_start_addr(host->dma_ch, sg_dma_address(&data->sg[0]));
set_dma_x_count(host->dma_ch, length / 4);
set_dma_x_modify(host->dma_ch, 4);
set_dma_config(host->dma_ch, dma_cfg);
#endif
bfin_write_SDH_DATA_CTL(bfin_read_SDH_DATA_CTL() | DTX_DMA_E | DTX_E);
SSYNC();
dev_dbg(mmc_dev(host->mmc), "%s exit\n", __func__);
return 0;
}
static void sdh_start_cmd(struct sdh_host *host, struct mmc_command *cmd)
{
unsigned int sdh_cmd;
unsigned int stat_mask;
dev_dbg(mmc_dev(host->mmc), "%s enter cmd: 0x%p\n", __func__, cmd);
WARN_ON(host->cmd != NULL);
host->cmd = cmd;
sdh_cmd = 0;
stat_mask = 0;
sdh_cmd |= cmd->opcode;
if (cmd->flags & MMC_RSP_PRESENT) {
sdh_cmd |= CMD_RSP;
stat_mask |= CMD_RESP_END;
} else {
stat_mask |= CMD_SENT;
}
if (cmd->flags & MMC_RSP_136)
sdh_cmd |= CMD_L_RSP;
stat_mask |= CMD_CRC_FAIL | CMD_TIME_OUT;
sdh_enable_stat_irq(host, stat_mask);
bfin_write_SDH_ARGUMENT(cmd->arg);
bfin_write_SDH_COMMAND(sdh_cmd | CMD_E);
bfin_write_SDH_CLK_CTL(bfin_read_SDH_CLK_CTL() | CLK_E);
SSYNC();
}
static void sdh_finish_request(struct sdh_host *host, struct mmc_request *mrq)
{
dev_dbg(mmc_dev(host->mmc), "%s enter\n", __func__);
host->mrq = NULL;
host->cmd = NULL;
host->data = NULL;
mmc_request_done(host->mmc, mrq);
}
static int sdh_cmd_done(struct sdh_host *host, unsigned int stat)
{
struct mmc_command *cmd = host->cmd;
int ret = 0;
dev_dbg(mmc_dev(host->mmc), "%s enter cmd: %p\n", __func__, cmd);
if (!cmd)
return 0;
host->cmd = NULL;
if (cmd->flags & MMC_RSP_PRESENT) {
cmd->resp[0] = bfin_read_SDH_RESPONSE0();
if (cmd->flags & MMC_RSP_136) {
cmd->resp[1] = bfin_read_SDH_RESPONSE1();
cmd->resp[2] = bfin_read_SDH_RESPONSE2();
cmd->resp[3] = bfin_read_SDH_RESPONSE3();
}
}
if (stat & CMD_TIME_OUT)
cmd->error = -ETIMEDOUT;
else if (stat & CMD_CRC_FAIL && cmd->flags & MMC_RSP_CRC)
cmd->error = -EILSEQ;
sdh_disable_stat_irq(host, (CMD_SENT | CMD_RESP_END | CMD_TIME_OUT | CMD_CRC_FAIL));
if (host->data && !cmd->error) {
if (host->data->flags & MMC_DATA_WRITE) {
ret = sdh_setup_data(host, host->data);
if (ret)
return 0;
}
sdh_enable_stat_irq(host, DAT_END | RX_OVERRUN | TX_UNDERRUN | DAT_TIME_OUT);
} else
sdh_finish_request(host, host->mrq);
return 1;
}
static int sdh_data_done(struct sdh_host *host, unsigned int stat)
{
struct mmc_data *data = host->data;
dev_dbg(mmc_dev(host->mmc), "%s enter stat: 0x%x\n", __func__, stat);
if (!data)
return 0;
disable_dma(host->dma_ch);
dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
host->dma_dir);
if (stat & DAT_TIME_OUT)
data->error = -ETIMEDOUT;
else if (stat & DAT_CRC_FAIL)
data->error = -EILSEQ;
else if (stat & (RX_OVERRUN | TX_UNDERRUN))
data->error = -EIO;
if (!data->error)
data->bytes_xfered = data->blocks * data->blksz;
else
data->bytes_xfered = 0;
sdh_disable_stat_irq(host, DAT_END | DAT_TIME_OUT | DAT_CRC_FAIL | RX_OVERRUN | TX_UNDERRUN);
bfin_write_SDH_STATUS_CLR(DAT_END_STAT | DAT_TIMEOUT_STAT | \
DAT_CRC_FAIL_STAT | DAT_BLK_END_STAT | RX_OVERRUN | TX_UNDERRUN);
bfin_write_SDH_DATA_CTL(0);
SSYNC();
host->data = NULL;
if (host->mrq->stop) {
sdh_stop_clock(host);
sdh_start_cmd(host, host->mrq->stop);
} else {
sdh_finish_request(host, host->mrq);
}
return 1;
}
static void sdh_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct sdh_host *host = mmc_priv(mmc);
int ret = 0;
dev_dbg(mmc_dev(host->mmc), "%s enter, mrp:%p, cmd:%p\n", __func__, mrq, mrq->cmd);
WARN_ON(host->mrq != NULL);
host->mrq = mrq;
host->data = mrq->data;
if (mrq->data && mrq->data->flags & MMC_DATA_READ) {
ret = sdh_setup_data(host, mrq->data);
if (ret)
return;
}
sdh_start_cmd(host, mrq->cmd);
}
static void sdh_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct sdh_host *host;
unsigned long flags;
u16 clk_ctl = 0;
u16 pwr_ctl = 0;
u16 cfg;
host = mmc_priv(mmc);
spin_lock_irqsave(&host->lock, flags);
if (ios->clock) {
unsigned long sys_clk, ios_clk;
unsigned char clk_div;
ios_clk = 2 * ios->clock;
sys_clk = get_sclk();
clk_div = sys_clk / ios_clk;
if (sys_clk % ios_clk == 0)
clk_div -= 1;
clk_div = min_t(unsigned char, clk_div, 0xFF);
clk_ctl |= clk_div;
clk_ctl |= CLK_E;
host->clk_div = clk_div;
} else
sdh_stop_clock(host);
if (ios->bus_mode == MMC_BUSMODE_OPENDRAIN)
#ifdef CONFIG_SDH_BFIN_MISSING_CMD_PULLUP_WORKAROUND
pwr_ctl |= ROD_CTL;
#else
pwr_ctl |= SD_CMD_OD | ROD_CTL;
#endif
if (ios->bus_width == MMC_BUS_WIDTH_4) {
cfg = bfin_read_SDH_CFG();
cfg &= ~PD_SDDAT3;
cfg |= PUP_SDDAT3;
/* Enable 4 bit SDIO */
cfg |= (SD4E | MWE);
bfin_write_SDH_CFG(cfg);
clk_ctl |= WIDE_BUS;
} else {
cfg = bfin_read_SDH_CFG();
cfg |= MWE;
bfin_write_SDH_CFG(cfg);
}
bfin_write_SDH_CLK_CTL(clk_ctl);
host->power_mode = ios->power_mode;
if (ios->power_mode == MMC_POWER_ON)
pwr_ctl |= PWR_ON;
bfin_write_SDH_PWR_CTL(pwr_ctl);
SSYNC();
spin_unlock_irqrestore(&host->lock, flags);
dev_dbg(mmc_dev(host->mmc), "SDH: clk_div = 0x%x actual clock:%ld expected clock:%d\n",
host->clk_div,
host->clk_div ? get_sclk() / (2 * (host->clk_div + 1)) : 0,
ios->clock);
}
static const struct mmc_host_ops sdh_ops = {
.request = sdh_request,
.set_ios = sdh_set_ios,
};
static irqreturn_t sdh_dma_irq(int irq, void *devid)
{
struct sdh_host *host = devid;
dev_dbg(mmc_dev(host->mmc), "%s enter, irq_stat: 0x%04x\n", __func__,
get_dma_curr_irqstat(host->dma_ch));
clear_dma_irqstat(host->dma_ch);
SSYNC();
return IRQ_HANDLED;
}
static irqreturn_t sdh_stat_irq(int irq, void *devid)
{
struct sdh_host *host = devid;
unsigned int status;
int handled = 0;
dev_dbg(mmc_dev(host->mmc), "%s enter\n", __func__);
status = bfin_read_SDH_E_STATUS();
if (status & SD_CARD_DET) {
mmc_detect_change(host->mmc, 0);
bfin_write_SDH_E_STATUS(SD_CARD_DET);
}
status = bfin_read_SDH_STATUS();
if (status & (CMD_SENT | CMD_RESP_END | CMD_TIME_OUT | CMD_CRC_FAIL)) {
handled |= sdh_cmd_done(host, status);
bfin_write_SDH_STATUS_CLR(CMD_SENT_STAT | CMD_RESP_END_STAT | \
CMD_TIMEOUT_STAT | CMD_CRC_FAIL_STAT);
SSYNC();
}
status = bfin_read_SDH_STATUS();
if (status & (DAT_END | DAT_TIME_OUT | DAT_CRC_FAIL | RX_OVERRUN | TX_UNDERRUN))
handled |= sdh_data_done(host, status);
dev_dbg(mmc_dev(host->mmc), "%s exit\n\n", __func__);
return IRQ_RETVAL(handled);
}
static int __devinit sdh_probe(struct platform_device *pdev)
{
struct mmc_host *mmc;
struct sdh_host *host;
struct bfin_sd_host *drv_data = get_sdh_data(pdev);
int ret;
if (!drv_data) {
dev_err(&pdev->dev, "missing platform driver data\n");
ret = -EINVAL;
goto out;
}
mmc = mmc_alloc_host(sizeof(struct sdh_host), &pdev->dev);
if (!mmc) {
ret = -ENOMEM;
goto out;
}
mmc->ops = &sdh_ops;
mmc->max_segs = 32;
mmc->max_seg_size = 1 << 16;
mmc->max_blk_size = 1 << 11;
mmc->max_blk_count = 1 << 11;
mmc->max_req_size = PAGE_SIZE;
mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;
mmc->f_max = get_sclk();
mmc->f_min = mmc->f_max >> 9;
mmc->caps = MMC_CAP_4_BIT_DATA | MMC_CAP_NEEDS_POLL;
host = mmc_priv(mmc);
host->mmc = mmc;
spin_lock_init(&host->lock);
host->irq = drv_data->irq_int0;
host->dma_ch = drv_data->dma_chan;
ret = request_dma(host->dma_ch, DRIVER_NAME "DMA");
if (ret) {
dev_err(&pdev->dev, "unable to request DMA channel\n");
goto out1;
}
ret = set_dma_callback(host->dma_ch, sdh_dma_irq, host);
if (ret) {
dev_err(&pdev->dev, "unable to request DMA irq\n");
goto out2;
}
host->sg_cpu = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &host->sg_dma, GFP_KERNEL);
if (host->sg_cpu == NULL) {
ret = -ENOMEM;
goto out2;
}
platform_set_drvdata(pdev, mmc);
mmc_add_host(mmc);
ret = request_irq(host->irq, sdh_stat_irq, 0, "SDH Status IRQ", host);
if (ret) {
dev_err(&pdev->dev, "unable to request status irq\n");
goto out3;
}
ret = peripheral_request_list(drv_data->pin_req, DRIVER_NAME);
if (ret) {
dev_err(&pdev->dev, "unable to request peripheral pins\n");
goto out4;
}
#if defined(CONFIG_BF54x)
/* Secure Digital Host shares DMA with Nand controller */
bfin_write_DMAC1_PERIMUX(bfin_read_DMAC1_PERIMUX() | 0x1);
#endif
bfin_write_SDH_CFG(bfin_read_SDH_CFG() | CLKS_EN);
SSYNC();
/* Disable card inserting detection pin. set MMC_CAP_NEES_POLL, and
* mmc stack will do the detection.
*/
bfin_write_SDH_CFG((bfin_read_SDH_CFG() & 0x1F) | (PUP_SDDAT | PUP_SDDAT3));
SSYNC();
return 0;
out4:
free_irq(host->irq, host);
out3:
mmc_remove_host(mmc);
dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma);
out2:
free_dma(host->dma_ch);
out1:
mmc_free_host(mmc);
out:
return ret;
}
static int __devexit sdh_remove(struct platform_device *pdev)
{
struct mmc_host *mmc = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
if (mmc) {
struct sdh_host *host = mmc_priv(mmc);
mmc_remove_host(mmc);
sdh_stop_clock(host);
free_irq(host->irq, host);
free_dma(host->dma_ch);
dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma);
mmc_free_host(mmc);
}
return 0;
}
#ifdef CONFIG_PM
static int sdh_suspend(struct platform_device *dev, pm_message_t state)
{
struct mmc_host *mmc = platform_get_drvdata(dev);
struct bfin_sd_host *drv_data = get_sdh_data(dev);
int ret = 0;
if (mmc)
ret = mmc_suspend_host(mmc);
bfin_write_SDH_PWR_CTL(bfin_read_SDH_PWR_CTL() & ~PWR_ON);
peripheral_free_list(drv_data->pin_req);
return ret;
}
static int sdh_resume(struct platform_device *dev)
{
struct mmc_host *mmc = platform_get_drvdata(dev);
struct bfin_sd_host *drv_data = get_sdh_data(dev);
int ret = 0;
ret = peripheral_request_list(drv_data->pin_req, DRIVER_NAME);
if (ret) {
dev_err(&dev->dev, "unable to request peripheral pins\n");
return ret;
}
bfin_write_SDH_PWR_CTL(bfin_read_SDH_PWR_CTL() | PWR_ON);
#if defined(CONFIG_BF54x)
/* Secure Digital Host shares DMA with Nand controller */
bfin_write_DMAC1_PERIMUX(bfin_read_DMAC1_PERIMUX() | 0x1);
#endif
bfin_write_SDH_CFG(bfin_read_SDH_CFG() | CLKS_EN);
SSYNC();
bfin_write_SDH_CFG((bfin_read_SDH_CFG() & 0x1F) | (PUP_SDDAT | PUP_SDDAT3));
SSYNC();
if (mmc)
ret = mmc_resume_host(mmc);
return ret;
}
#else
# define sdh_suspend NULL
# define sdh_resume NULL
#endif
static struct platform_driver sdh_driver = {
.probe = sdh_probe,
.remove = __devexit_p(sdh_remove),
.suspend = sdh_suspend,
.resume = sdh_resume,
.driver = {
.name = DRIVER_NAME,
},
};
static int __init sdh_init(void)
{
return platform_driver_register(&sdh_driver);
}
module_init(sdh_init);
static void __exit sdh_exit(void)
{
platform_driver_unregister(&sdh_driver);
}
module_exit(sdh_exit);
MODULE_DESCRIPTION("Blackfin Secure Digital Host Driver");
MODULE_AUTHOR("Cliff Cai, Roy Huang");
MODULE_LICENSE("GPL");
| gpl-2.0 |
daedae1112/kernel | drivers/isdn/hisax/s0box.c | 5021 | 7062 | /* $Id: s0box.c,v 2.6.2.4 2004/01/13 23:48:39 keil Exp $
*
* low level stuff for Creatix S0BOX
*
* Author Enrik Berkhan
* Copyright by Enrik Berkhan <enrik@starfleet.inka.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/init.h>
#include "hisax.h"
#include "isac.h"
#include "hscx.h"
#include "isdnl1.h"
static const char *s0box_revision = "$Revision: 2.6.2.4 $";
static inline void
writereg(unsigned int padr, signed int addr, u_char off, u_char val) {
outb_p(0x1c,padr+2);
outb_p(0x14,padr+2);
outb_p((addr+off)&0x7f,padr);
outb_p(0x16,padr+2);
outb_p(val,padr);
outb_p(0x17,padr+2);
outb_p(0x14,padr+2);
outb_p(0x1c,padr+2);
}
static u_char nibtab[] = { 1, 9, 5, 0xd, 3, 0xb, 7, 0xf,
0, 0, 0, 0, 0, 0, 0, 0,
0, 8, 4, 0xc, 2, 0xa, 6, 0xe } ;
static inline u_char
readreg(unsigned int padr, signed int addr, u_char off) {
register u_char n1, n2;
outb_p(0x1c,padr+2);
outb_p(0x14,padr+2);
outb_p((addr+off)|0x80,padr);
outb_p(0x16,padr+2);
outb_p(0x17,padr+2);
n1 = (inb_p(padr+1) >> 3) & 0x17;
outb_p(0x16,padr+2);
n2 = (inb_p(padr+1) >> 3) & 0x17;
outb_p(0x14,padr+2);
outb_p(0x1c,padr+2);
return nibtab[n1] | (nibtab[n2] << 4);
}
static inline void
read_fifo(unsigned int padr, signed int adr, u_char * data, int size)
{
int i;
register u_char n1, n2;
outb_p(0x1c, padr+2);
outb_p(0x14, padr+2);
outb_p(adr|0x80, padr);
outb_p(0x16, padr+2);
for (i=0; i<size; i++) {
outb_p(0x17, padr+2);
n1 = (inb_p(padr+1) >> 3) & 0x17;
outb_p(0x16,padr+2);
n2 = (inb_p(padr+1) >> 3) & 0x17;
*(data++)=nibtab[n1] | (nibtab[n2] << 4);
}
outb_p(0x14,padr+2);
outb_p(0x1c,padr+2);
return;
}
static inline void
write_fifo(unsigned int padr, signed int adr, u_char * data, int size)
{
int i;
outb_p(0x1c, padr+2);
outb_p(0x14, padr+2);
outb_p(adr&0x7f, padr);
for (i=0; i<size; i++) {
outb_p(0x16, padr+2);
outb_p(*(data++), padr);
outb_p(0x17, padr+2);
}
outb_p(0x14,padr+2);
outb_p(0x1c,padr+2);
return;
}
/* Interface functions */
static u_char
ReadISAC(struct IsdnCardState *cs, u_char offset)
{
return (readreg(cs->hw.teles3.cfg_reg, cs->hw.teles3.isac, offset));
}
static void
WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value)
{
writereg(cs->hw.teles3.cfg_reg, cs->hw.teles3.isac, offset, value);
}
static void
ReadISACfifo(struct IsdnCardState *cs, u_char * data, int size)
{
read_fifo(cs->hw.teles3.cfg_reg, cs->hw.teles3.isacfifo, data, size);
}
static void
WriteISACfifo(struct IsdnCardState *cs, u_char * data, int size)
{
write_fifo(cs->hw.teles3.cfg_reg, cs->hw.teles3.isacfifo, data, size);
}
static u_char
ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset)
{
return (readreg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[hscx], offset));
}
static void
WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value)
{
writereg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[hscx], offset, value);
}
/*
* fast interrupt HSCX stuff goes here
*/
#define READHSCX(cs, nr, reg) readreg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[nr], reg)
#define WRITEHSCX(cs, nr, reg, data) writereg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[nr], reg, data)
#define READHSCXFIFO(cs, nr, ptr, cnt) read_fifo(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscxfifo[nr], ptr, cnt)
#define WRITEHSCXFIFO(cs, nr, ptr, cnt) write_fifo(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscxfifo[nr], ptr, cnt)
#include "hscx_irq.c"
static irqreturn_t
s0box_interrupt(int intno, void *dev_id)
{
#define MAXCOUNT 5
struct IsdnCardState *cs = dev_id;
u_char val;
u_long flags;
int count = 0;
spin_lock_irqsave(&cs->lock, flags);
val = readreg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[1], HSCX_ISTA);
Start_HSCX:
if (val)
hscx_int_main(cs, val);
val = readreg(cs->hw.teles3.cfg_reg, cs->hw.teles3.isac, ISAC_ISTA);
Start_ISAC:
if (val)
isac_interrupt(cs, val);
count++;
val = readreg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[1], HSCX_ISTA);
if (val && count < MAXCOUNT) {
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "HSCX IntStat after IntRoutine");
goto Start_HSCX;
}
val = readreg(cs->hw.teles3.cfg_reg, cs->hw.teles3.isac, ISAC_ISTA);
if (val && count < MAXCOUNT) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "ISAC IntStat after IntRoutine");
goto Start_ISAC;
}
if (count >= MAXCOUNT)
printk(KERN_WARNING "S0Box: more than %d loops in s0box_interrupt\n", count);
writereg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[0], HSCX_MASK, 0xFF);
writereg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[1], HSCX_MASK, 0xFF);
writereg(cs->hw.teles3.cfg_reg, cs->hw.teles3.isac, ISAC_MASK, 0xFF);
writereg(cs->hw.teles3.cfg_reg, cs->hw.teles3.isac, ISAC_MASK, 0x0);
writereg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[0], HSCX_MASK, 0x0);
writereg(cs->hw.teles3.cfg_reg, cs->hw.teles3.hscx[1], HSCX_MASK, 0x0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static void
release_io_s0box(struct IsdnCardState *cs)
{
release_region(cs->hw.teles3.cfg_reg, 8);
}
static int
S0Box_card_msg(struct IsdnCardState *cs, int mt, void *arg)
{
u_long flags;
switch (mt) {
case CARD_RESET:
break;
case CARD_RELEASE:
release_io_s0box(cs);
break;
case CARD_INIT:
spin_lock_irqsave(&cs->lock, flags);
inithscxisac(cs, 3);
spin_unlock_irqrestore(&cs->lock, flags);
break;
case CARD_TEST:
break;
}
return(0);
}
int __devinit
setup_s0box(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
char tmp[64];
strcpy(tmp, s0box_revision);
printk(KERN_INFO "HiSax: S0Box IO driver Rev. %s\n", HiSax_getrev(tmp));
if (cs->typ != ISDN_CTYPE_S0BOX)
return (0);
cs->hw.teles3.cfg_reg = card->para[1];
cs->hw.teles3.hscx[0] = -0x20;
cs->hw.teles3.hscx[1] = 0x0;
cs->hw.teles3.isac = 0x20;
cs->hw.teles3.isacfifo = cs->hw.teles3.isac + 0x3e;
cs->hw.teles3.hscxfifo[0] = cs->hw.teles3.hscx[0] + 0x3e;
cs->hw.teles3.hscxfifo[1] = cs->hw.teles3.hscx[1] + 0x3e;
cs->irq = card->para[0];
if (!request_region(cs->hw.teles3.cfg_reg,8, "S0Box parallel I/O")) {
printk(KERN_WARNING "HiSax: S0Box ports %x-%x already in use\n",
cs->hw.teles3.cfg_reg,
cs->hw.teles3.cfg_reg + 7);
return 0;
}
printk(KERN_INFO "HiSax: S0Box config irq:%d isac:0x%x cfg:0x%x\n",
cs->irq,
cs->hw.teles3.isac, cs->hw.teles3.cfg_reg);
printk(KERN_INFO "HiSax: hscx A:0x%x hscx B:0x%x\n",
cs->hw.teles3.hscx[0], cs->hw.teles3.hscx[1]);
setup_isac(cs);
cs->readisac = &ReadISAC;
cs->writeisac = &WriteISAC;
cs->readisacfifo = &ReadISACfifo;
cs->writeisacfifo = &WriteISACfifo;
cs->BC_Read_Reg = &ReadHSCX;
cs->BC_Write_Reg = &WriteHSCX;
cs->BC_Send_Data = &hscx_fill_fifo;
cs->cardmsg = &S0Box_card_msg;
cs->irq_func = &s0box_interrupt;
ISACVersion(cs, "S0Box:");
if (HscxVersion(cs, "S0Box:")) {
printk(KERN_WARNING
"S0Box: wrong HSCX versions check IO address\n");
release_io_s0box(cs);
return (0);
}
return (1);
}
| gpl-2.0 |
SlimRoms/kernel_samsung_exynos5410 | sound/core/pcm_timer.c | 11677 | 3755 | /*
* 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/time.h>
#include <linux/gcd.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/timer.h>
/*
* Timer functions
*/
void snd_pcm_timer_resolution_change(struct snd_pcm_substream *substream)
{
unsigned long rate, mult, fsize, l, post;
struct snd_pcm_runtime *runtime = substream->runtime;
mult = 1000000000;
rate = runtime->rate;
if (snd_BUG_ON(!rate))
return;
l = gcd(mult, rate);
mult /= l;
rate /= l;
fsize = runtime->period_size;
if (snd_BUG_ON(!fsize))
return;
l = gcd(rate, fsize);
rate /= l;
fsize /= l;
post = 1;
while ((mult * fsize) / fsize != mult) {
mult /= 2;
post *= 2;
}
if (rate == 0) {
snd_printk(KERN_ERR "pcm timer resolution out of range (rate = %u, period_size = %lu)\n", runtime->rate, runtime->period_size);
runtime->timer_resolution = -1;
return;
}
runtime->timer_resolution = (mult * fsize / rate) * post;
}
static unsigned long snd_pcm_timer_resolution(struct snd_timer * timer)
{
struct snd_pcm_substream *substream;
substream = timer->private_data;
return substream->runtime ? substream->runtime->timer_resolution : 0;
}
static int snd_pcm_timer_start(struct snd_timer * timer)
{
struct snd_pcm_substream *substream;
substream = snd_timer_chip(timer);
substream->timer_running = 1;
return 0;
}
static int snd_pcm_timer_stop(struct snd_timer * timer)
{
struct snd_pcm_substream *substream;
substream = snd_timer_chip(timer);
substream->timer_running = 0;
return 0;
}
static struct snd_timer_hardware snd_pcm_timer =
{
.flags = SNDRV_TIMER_HW_AUTO | SNDRV_TIMER_HW_SLAVE,
.resolution = 0,
.ticks = 1,
.c_resolution = snd_pcm_timer_resolution,
.start = snd_pcm_timer_start,
.stop = snd_pcm_timer_stop,
};
/*
* Init functions
*/
static void snd_pcm_timer_free(struct snd_timer *timer)
{
struct snd_pcm_substream *substream = timer->private_data;
substream->timer = NULL;
}
void snd_pcm_timer_init(struct snd_pcm_substream *substream)
{
struct snd_timer_id tid;
struct snd_timer *timer;
tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
tid.dev_class = SNDRV_TIMER_CLASS_PCM;
tid.card = substream->pcm->card->number;
tid.device = substream->pcm->device;
tid.subdevice = (substream->number << 1) | (substream->stream & 1);
if (snd_timer_new(substream->pcm->card, "PCM", &tid, &timer) < 0)
return;
sprintf(timer->name, "PCM %s %i-%i-%i",
substream->stream == SNDRV_PCM_STREAM_CAPTURE ?
"capture" : "playback",
tid.card, tid.device, tid.subdevice);
timer->hw = snd_pcm_timer;
if (snd_device_register(timer->card, timer) < 0) {
snd_device_free(timer->card, timer);
return;
}
timer->private_data = substream;
timer->private_free = snd_pcm_timer_free;
substream->timer = timer;
}
void snd_pcm_timer_done(struct snd_pcm_substream *substream)
{
if (substream->timer) {
snd_device_free(substream->pcm->card, substream->timer);
substream->timer = NULL;
}
}
| gpl-2.0 |
95A31/android_kernel_msm | arch/x86/boot/memory.c | 12445 | 3367 | /* -*- linux-c -*- ------------------------------------------------------- *
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright 2007 rPath, Inc. - All Rights Reserved
* Copyright 2009 Intel Corporation; author H. Peter Anvin
*
* This file is part of the Linux kernel, and is made available under
* the terms of the GNU General Public License version 2.
*
* ----------------------------------------------------------------------- */
/*
* Memory detection code
*/
#include "boot.h"
#define SMAP 0x534d4150 /* ASCII "SMAP" */
static int detect_memory_e820(void)
{
int count = 0;
struct biosregs ireg, oreg;
struct e820entry *desc = boot_params.e820_map;
static struct e820entry buf; /* static so it is zeroed */
initregs(&ireg);
ireg.ax = 0xe820;
ireg.cx = sizeof buf;
ireg.edx = SMAP;
ireg.di = (size_t)&buf;
/*
* Note: at least one BIOS is known which assumes that the
* buffer pointed to by one e820 call is the same one as
* the previous call, and only changes modified fields. Therefore,
* we use a temporary buffer and copy the results entry by entry.
*
* This routine deliberately does not try to account for
* ACPI 3+ extended attributes. This is because there are
* BIOSes in the field which report zero for the valid bit for
* all ranges, and we don't currently make any use of the
* other attribute bits. Revisit this if we see the extended
* attribute bits deployed in a meaningful way in the future.
*/
do {
intcall(0x15, &ireg, &oreg);
ireg.ebx = oreg.ebx; /* for next iteration... */
/* BIOSes which terminate the chain with CF = 1 as opposed
to %ebx = 0 don't always report the SMAP signature on
the final, failing, probe. */
if (oreg.eflags & X86_EFLAGS_CF)
break;
/* Some BIOSes stop returning SMAP in the middle of
the search loop. We don't know exactly how the BIOS
screwed up the map at that point, we might have a
partial map, the full map, or complete garbage, so
just return failure. */
if (oreg.eax != SMAP) {
count = 0;
break;
}
*desc++ = buf;
count++;
} while (ireg.ebx && count < ARRAY_SIZE(boot_params.e820_map));
return boot_params.e820_entries = count;
}
static int detect_memory_e801(void)
{
struct biosregs ireg, oreg;
initregs(&ireg);
ireg.ax = 0xe801;
intcall(0x15, &ireg, &oreg);
if (oreg.eflags & X86_EFLAGS_CF)
return -1;
/* Do we really need to do this? */
if (oreg.cx || oreg.dx) {
oreg.ax = oreg.cx;
oreg.bx = oreg.dx;
}
if (oreg.ax > 15*1024) {
return -1; /* Bogus! */
} else if (oreg.ax == 15*1024) {
boot_params.alt_mem_k = (oreg.bx << 6) + oreg.ax;
} else {
/*
* This ignores memory above 16MB if we have a memory
* hole there. If someone actually finds a machine
* with a memory hole at 16MB and no support for
* 0E820h they should probably generate a fake e820
* map.
*/
boot_params.alt_mem_k = oreg.ax;
}
return 0;
}
static int detect_memory_88(void)
{
struct biosregs ireg, oreg;
initregs(&ireg);
ireg.ah = 0x88;
intcall(0x15, &ireg, &oreg);
boot_params.screen_info.ext_mem_k = oreg.ax;
return -(oreg.eflags & X86_EFLAGS_CF); /* 0 or -1 */
}
int detect_memory(void)
{
int err = -1;
if (detect_memory_e820() > 0)
err = 0;
if (!detect_memory_e801())
err = 0;
if (!detect_memory_88())
err = 0;
return err;
}
| gpl-2.0 |
zeroprobe/ZeroMHL-Overclocked-V3 | arch/x86/boot/memory.c | 12445 | 3367 | /* -*- linux-c -*- ------------------------------------------------------- *
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright 2007 rPath, Inc. - All Rights Reserved
* Copyright 2009 Intel Corporation; author H. Peter Anvin
*
* This file is part of the Linux kernel, and is made available under
* the terms of the GNU General Public License version 2.
*
* ----------------------------------------------------------------------- */
/*
* Memory detection code
*/
#include "boot.h"
#define SMAP 0x534d4150 /* ASCII "SMAP" */
static int detect_memory_e820(void)
{
int count = 0;
struct biosregs ireg, oreg;
struct e820entry *desc = boot_params.e820_map;
static struct e820entry buf; /* static so it is zeroed */
initregs(&ireg);
ireg.ax = 0xe820;
ireg.cx = sizeof buf;
ireg.edx = SMAP;
ireg.di = (size_t)&buf;
/*
* Note: at least one BIOS is known which assumes that the
* buffer pointed to by one e820 call is the same one as
* the previous call, and only changes modified fields. Therefore,
* we use a temporary buffer and copy the results entry by entry.
*
* This routine deliberately does not try to account for
* ACPI 3+ extended attributes. This is because there are
* BIOSes in the field which report zero for the valid bit for
* all ranges, and we don't currently make any use of the
* other attribute bits. Revisit this if we see the extended
* attribute bits deployed in a meaningful way in the future.
*/
do {
intcall(0x15, &ireg, &oreg);
ireg.ebx = oreg.ebx; /* for next iteration... */
/* BIOSes which terminate the chain with CF = 1 as opposed
to %ebx = 0 don't always report the SMAP signature on
the final, failing, probe. */
if (oreg.eflags & X86_EFLAGS_CF)
break;
/* Some BIOSes stop returning SMAP in the middle of
the search loop. We don't know exactly how the BIOS
screwed up the map at that point, we might have a
partial map, the full map, or complete garbage, so
just return failure. */
if (oreg.eax != SMAP) {
count = 0;
break;
}
*desc++ = buf;
count++;
} while (ireg.ebx && count < ARRAY_SIZE(boot_params.e820_map));
return boot_params.e820_entries = count;
}
static int detect_memory_e801(void)
{
struct biosregs ireg, oreg;
initregs(&ireg);
ireg.ax = 0xe801;
intcall(0x15, &ireg, &oreg);
if (oreg.eflags & X86_EFLAGS_CF)
return -1;
/* Do we really need to do this? */
if (oreg.cx || oreg.dx) {
oreg.ax = oreg.cx;
oreg.bx = oreg.dx;
}
if (oreg.ax > 15*1024) {
return -1; /* Bogus! */
} else if (oreg.ax == 15*1024) {
boot_params.alt_mem_k = (oreg.bx << 6) + oreg.ax;
} else {
/*
* This ignores memory above 16MB if we have a memory
* hole there. If someone actually finds a machine
* with a memory hole at 16MB and no support for
* 0E820h they should probably generate a fake e820
* map.
*/
boot_params.alt_mem_k = oreg.ax;
}
return 0;
}
static int detect_memory_88(void)
{
struct biosregs ireg, oreg;
initregs(&ireg);
ireg.ah = 0x88;
intcall(0x15, &ireg, &oreg);
boot_params.screen_info.ext_mem_k = oreg.ax;
return -(oreg.eflags & X86_EFLAGS_CF); /* 0 or -1 */
}
int detect_memory(void)
{
int err = -1;
if (detect_memory_e820() > 0)
err = 0;
if (!detect_memory_e801())
err = 0;
if (!detect_memory_88())
err = 0;
return err;
}
| gpl-2.0 |
volk3/CS736 | arch/mips/dec/tc.c | 14237 | 2056 | /*
* TURBOchannel architecture calls.
*
* Copyright (c) Harald Koerfgen, 1998
* Copyright (c) 2001, 2003, 2005, 2006 Maciej W. Rozycki
* Copyright (c) 2005 James Simmons
*
* 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/compiler.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/tc.h>
#include <linux/types.h>
#include <asm/addrspace.h>
#include <asm/bootinfo.h>
#include <asm/paccess.h>
#include <asm/dec/interrupts.h>
#include <asm/dec/prom.h>
#include <asm/dec/system.h>
/*
* Protected read byte from TURBOchannel slot space.
*/
int tc_preadb(u8 *valp, void __iomem *addr)
{
return get_dbe(*valp, (u8 *)addr);
}
/*
* Get TURBOchannel bus information as specified by the spec, plus
* the slot space base address and the number of slots.
*/
int __init tc_bus_get_info(struct tc_bus *tbus)
{
if (!dec_tc_bus)
return -ENXIO;
memcpy(&tbus->info, rex_gettcinfo(), sizeof(tbus->info));
tbus->slot_base = CPHYSADDR((long)rex_slot_address(0));
switch (mips_machtype) {
case MACH_DS5000_200:
tbus->num_tcslots = 7;
break;
case MACH_DS5000_2X0:
case MACH_DS5900:
tbus->ext_slot_base = 0x20000000;
tbus->ext_slot_size = 0x20000000;
/* fall through */
case MACH_DS5000_1XX:
tbus->num_tcslots = 3;
break;
case MACH_DS5000_XX:
tbus->num_tcslots = 2;
default:
break;
}
return 0;
}
/*
* Get the IRQ for the specified slot.
*/
void __init tc_device_get_irq(struct tc_dev *tdev)
{
switch (tdev->slot) {
case 0:
tdev->interrupt = dec_interrupt[DEC_IRQ_TC0];
break;
case 1:
tdev->interrupt = dec_interrupt[DEC_IRQ_TC1];
break;
case 2:
tdev->interrupt = dec_interrupt[DEC_IRQ_TC2];
break;
/*
* Yuck! DS5000/200 onboard devices
*/
case 5:
tdev->interrupt = dec_interrupt[DEC_IRQ_TC5];
break;
case 6:
tdev->interrupt = dec_interrupt[DEC_IRQ_TC6];
break;
default:
tdev->interrupt = -1;
break;
}
}
| gpl-2.0 |
keiranFTW/android_kernel_sony_u8500 | fs/jfs/namei.c | 926 | 38047 | /*
* Copyright (C) International Business Machines Corp., 2000-2004
* Portions Copyright (C) Christoph Hellwig, 2001-2002
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/fs.h>
#include <linux/ctype.h>
#include <linux/quotaops.h>
#include <linux/exportfs.h>
#include "jfs_incore.h"
#include "jfs_superblock.h"
#include "jfs_inode.h"
#include "jfs_dinode.h"
#include "jfs_dmap.h"
#include "jfs_unicode.h"
#include "jfs_metapage.h"
#include "jfs_xattr.h"
#include "jfs_acl.h"
#include "jfs_debug.h"
/*
* forward references
*/
const struct dentry_operations jfs_ci_dentry_operations;
static s64 commitZeroLink(tid_t, struct inode *);
/*
* NAME: free_ea_wmap(inode)
*
* FUNCTION: free uncommitted extended attributes from working map
*
*/
static inline void free_ea_wmap(struct inode *inode)
{
dxd_t *ea = &JFS_IP(inode)->ea;
if (ea->flag & DXD_EXTENT) {
/* free EA pages from cache */
invalidate_dxd_metapages(inode, *ea);
dbFree(inode, addressDXD(ea), lengthDXD(ea));
}
ea->flag = 0;
}
/*
* NAME: jfs_create(dip, dentry, mode)
*
* FUNCTION: create a regular file in the parent directory <dip>
* with name = <from dentry> and mode = <mode>
*
* PARAMETER: dip - parent directory vnode
* dentry - dentry of new file
* mode - create mode (rwxrwxrwx).
* nd- nd struct
*
* RETURN: Errors from subroutines
*
*/
static int jfs_create(struct inode *dip, struct dentry *dentry, int mode,
struct nameidata *nd)
{
int rc = 0;
tid_t tid; /* transaction id */
struct inode *ip = NULL; /* child directory inode */
ino_t ino;
struct component_name dname; /* child directory name */
struct btstack btstack;
struct inode *iplist[2];
struct tblock *tblk;
jfs_info("jfs_create: dip:0x%p name:%s", dip, dentry->d_name.name);
dquot_initialize(dip);
/*
* search parent directory for entry/freespace
* (dtSearch() returns parent directory page pinned)
*/
if ((rc = get_UCSname(&dname, dentry)))
goto out1;
/*
* Either iAlloc() or txBegin() may block. Deadlock can occur if we
* block there while holding dtree page, so we allocate the inode &
* begin the transaction before we search the directory.
*/
ip = ialloc(dip, mode);
if (IS_ERR(ip)) {
rc = PTR_ERR(ip);
goto out2;
}
tid = txBegin(dip->i_sb, 0);
mutex_lock_nested(&JFS_IP(dip)->commit_mutex, COMMIT_MUTEX_PARENT);
mutex_lock_nested(&JFS_IP(ip)->commit_mutex, COMMIT_MUTEX_CHILD);
rc = jfs_init_acl(tid, ip, dip);
if (rc)
goto out3;
rc = jfs_init_security(tid, ip, dip);
if (rc) {
txAbort(tid, 0);
goto out3;
}
if ((rc = dtSearch(dip, &dname, &ino, &btstack, JFS_CREATE))) {
jfs_err("jfs_create: dtSearch returned %d", rc);
txAbort(tid, 0);
goto out3;
}
tblk = tid_to_tblock(tid);
tblk->xflag |= COMMIT_CREATE;
tblk->ino = ip->i_ino;
tblk->u.ixpxd = JFS_IP(ip)->ixpxd;
iplist[0] = dip;
iplist[1] = ip;
/*
* initialize the child XAD tree root in-line in inode
*/
xtInitRoot(tid, ip);
/*
* create entry in parent directory for child directory
* (dtInsert() releases parent directory page)
*/
ino = ip->i_ino;
if ((rc = dtInsert(tid, dip, &dname, &ino, &btstack))) {
if (rc == -EIO) {
jfs_err("jfs_create: dtInsert returned -EIO");
txAbort(tid, 1); /* Marks Filesystem dirty */
} else
txAbort(tid, 0); /* Filesystem full */
goto out3;
}
ip->i_op = &jfs_file_inode_operations;
ip->i_fop = &jfs_file_operations;
ip->i_mapping->a_ops = &jfs_aops;
mark_inode_dirty(ip);
dip->i_ctime = dip->i_mtime = CURRENT_TIME;
mark_inode_dirty(dip);
rc = txCommit(tid, 2, &iplist[0], 0);
out3:
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dip)->commit_mutex);
if (rc) {
free_ea_wmap(ip);
ip->i_nlink = 0;
unlock_new_inode(ip);
iput(ip);
} else {
d_instantiate(dentry, ip);
unlock_new_inode(ip);
}
out2:
free_UCSname(&dname);
out1:
jfs_info("jfs_create: rc:%d", rc);
return rc;
}
/*
* NAME: jfs_mkdir(dip, dentry, mode)
*
* FUNCTION: create a child directory in the parent directory <dip>
* with name = <from dentry> and mode = <mode>
*
* PARAMETER: dip - parent directory vnode
* dentry - dentry of child directory
* mode - create mode (rwxrwxrwx).
*
* RETURN: Errors from subroutines
*
* note:
* EACCESS: user needs search+write permission on the parent directory
*/
static int jfs_mkdir(struct inode *dip, struct dentry *dentry, int mode)
{
int rc = 0;
tid_t tid; /* transaction id */
struct inode *ip = NULL; /* child directory inode */
ino_t ino;
struct component_name dname; /* child directory name */
struct btstack btstack;
struct inode *iplist[2];
struct tblock *tblk;
jfs_info("jfs_mkdir: dip:0x%p name:%s", dip, dentry->d_name.name);
dquot_initialize(dip);
/* link count overflow on parent directory ? */
if (dip->i_nlink == JFS_LINK_MAX) {
rc = -EMLINK;
goto out1;
}
/*
* search parent directory for entry/freespace
* (dtSearch() returns parent directory page pinned)
*/
if ((rc = get_UCSname(&dname, dentry)))
goto out1;
/*
* Either iAlloc() or txBegin() may block. Deadlock can occur if we
* block there while holding dtree page, so we allocate the inode &
* begin the transaction before we search the directory.
*/
ip = ialloc(dip, S_IFDIR | mode);
if (IS_ERR(ip)) {
rc = PTR_ERR(ip);
goto out2;
}
tid = txBegin(dip->i_sb, 0);
mutex_lock_nested(&JFS_IP(dip)->commit_mutex, COMMIT_MUTEX_PARENT);
mutex_lock_nested(&JFS_IP(ip)->commit_mutex, COMMIT_MUTEX_CHILD);
rc = jfs_init_acl(tid, ip, dip);
if (rc)
goto out3;
rc = jfs_init_security(tid, ip, dip);
if (rc) {
txAbort(tid, 0);
goto out3;
}
if ((rc = dtSearch(dip, &dname, &ino, &btstack, JFS_CREATE))) {
jfs_err("jfs_mkdir: dtSearch returned %d", rc);
txAbort(tid, 0);
goto out3;
}
tblk = tid_to_tblock(tid);
tblk->xflag |= COMMIT_CREATE;
tblk->ino = ip->i_ino;
tblk->u.ixpxd = JFS_IP(ip)->ixpxd;
iplist[0] = dip;
iplist[1] = ip;
/*
* initialize the child directory in-line in inode
*/
dtInitRoot(tid, ip, dip->i_ino);
/*
* create entry in parent directory for child directory
* (dtInsert() releases parent directory page)
*/
ino = ip->i_ino;
if ((rc = dtInsert(tid, dip, &dname, &ino, &btstack))) {
if (rc == -EIO) {
jfs_err("jfs_mkdir: dtInsert returned -EIO");
txAbort(tid, 1); /* Marks Filesystem dirty */
} else
txAbort(tid, 0); /* Filesystem full */
goto out3;
}
ip->i_nlink = 2; /* for '.' */
ip->i_op = &jfs_dir_inode_operations;
ip->i_fop = &jfs_dir_operations;
mark_inode_dirty(ip);
/* update parent directory inode */
inc_nlink(dip); /* for '..' from child directory */
dip->i_ctime = dip->i_mtime = CURRENT_TIME;
mark_inode_dirty(dip);
rc = txCommit(tid, 2, &iplist[0], 0);
out3:
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dip)->commit_mutex);
if (rc) {
free_ea_wmap(ip);
ip->i_nlink = 0;
unlock_new_inode(ip);
iput(ip);
} else {
d_instantiate(dentry, ip);
unlock_new_inode(ip);
}
out2:
free_UCSname(&dname);
out1:
jfs_info("jfs_mkdir: rc:%d", rc);
return rc;
}
/*
* NAME: jfs_rmdir(dip, dentry)
*
* FUNCTION: remove a link to child directory
*
* PARAMETER: dip - parent inode
* dentry - child directory dentry
*
* RETURN: -EINVAL - if name is . or ..
* -EINVAL - if . or .. exist but are invalid.
* errors from subroutines
*
* note:
* if other threads have the directory open when the last link
* is removed, the "." and ".." entries, if present, are removed before
* rmdir() returns and no new entries may be created in the directory,
* but the directory is not removed until the last reference to
* the directory is released (cf.unlink() of regular file).
*/
static int jfs_rmdir(struct inode *dip, struct dentry *dentry)
{
int rc;
tid_t tid; /* transaction id */
struct inode *ip = dentry->d_inode;
ino_t ino;
struct component_name dname;
struct inode *iplist[2];
struct tblock *tblk;
jfs_info("jfs_rmdir: dip:0x%p name:%s", dip, dentry->d_name.name);
/* Init inode for quota operations. */
dquot_initialize(dip);
dquot_initialize(ip);
/* directory must be empty to be removed */
if (!dtEmpty(ip)) {
rc = -ENOTEMPTY;
goto out;
}
if ((rc = get_UCSname(&dname, dentry))) {
goto out;
}
tid = txBegin(dip->i_sb, 0);
mutex_lock_nested(&JFS_IP(dip)->commit_mutex, COMMIT_MUTEX_PARENT);
mutex_lock_nested(&JFS_IP(ip)->commit_mutex, COMMIT_MUTEX_CHILD);
iplist[0] = dip;
iplist[1] = ip;
tblk = tid_to_tblock(tid);
tblk->xflag |= COMMIT_DELETE;
tblk->u.ip = ip;
/*
* delete the entry of target directory from parent directory
*/
ino = ip->i_ino;
if ((rc = dtDelete(tid, dip, &dname, &ino, JFS_REMOVE))) {
jfs_err("jfs_rmdir: dtDelete returned %d", rc);
if (rc == -EIO)
txAbort(tid, 1);
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dip)->commit_mutex);
goto out2;
}
/* update parent directory's link count corresponding
* to ".." entry of the target directory deleted
*/
dip->i_ctime = dip->i_mtime = CURRENT_TIME;
inode_dec_link_count(dip);
/*
* OS/2 could have created EA and/or ACL
*/
/* free EA from both persistent and working map */
if (JFS_IP(ip)->ea.flag & DXD_EXTENT) {
/* free EA pages */
txEA(tid, ip, &JFS_IP(ip)->ea, NULL);
}
JFS_IP(ip)->ea.flag = 0;
/* free ACL from both persistent and working map */
if (JFS_IP(ip)->acl.flag & DXD_EXTENT) {
/* free ACL pages */
txEA(tid, ip, &JFS_IP(ip)->acl, NULL);
}
JFS_IP(ip)->acl.flag = 0;
/* mark the target directory as deleted */
clear_nlink(ip);
mark_inode_dirty(ip);
rc = txCommit(tid, 2, &iplist[0], 0);
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dip)->commit_mutex);
/*
* Truncating the directory index table is not guaranteed. It
* may need to be done iteratively
*/
if (test_cflag(COMMIT_Stale, dip)) {
if (dip->i_size > 1)
jfs_truncate_nolock(dip, 0);
clear_cflag(COMMIT_Stale, dip);
}
out2:
free_UCSname(&dname);
out:
jfs_info("jfs_rmdir: rc:%d", rc);
return rc;
}
/*
* NAME: jfs_unlink(dip, dentry)
*
* FUNCTION: remove a link to object <vp> named by <name>
* from parent directory <dvp>
*
* PARAMETER: dip - inode of parent directory
* dentry - dentry of object to be removed
*
* RETURN: errors from subroutines
*
* note:
* temporary file: if one or more processes have the file open
* when the last link is removed, the link will be removed before
* unlink() returns, but the removal of the file contents will be
* postponed until all references to the files are closed.
*
* JFS does NOT support unlink() on directories.
*
*/
static int jfs_unlink(struct inode *dip, struct dentry *dentry)
{
int rc;
tid_t tid; /* transaction id */
struct inode *ip = dentry->d_inode;
ino_t ino;
struct component_name dname; /* object name */
struct inode *iplist[2];
struct tblock *tblk;
s64 new_size = 0;
int commit_flag;
jfs_info("jfs_unlink: dip:0x%p name:%s", dip, dentry->d_name.name);
/* Init inode for quota operations. */
dquot_initialize(dip);
dquot_initialize(ip);
if ((rc = get_UCSname(&dname, dentry)))
goto out;
IWRITE_LOCK(ip, RDWRLOCK_NORMAL);
tid = txBegin(dip->i_sb, 0);
mutex_lock_nested(&JFS_IP(dip)->commit_mutex, COMMIT_MUTEX_PARENT);
mutex_lock_nested(&JFS_IP(ip)->commit_mutex, COMMIT_MUTEX_CHILD);
iplist[0] = dip;
iplist[1] = ip;
/*
* delete the entry of target file from parent directory
*/
ino = ip->i_ino;
if ((rc = dtDelete(tid, dip, &dname, &ino, JFS_REMOVE))) {
jfs_err("jfs_unlink: dtDelete returned %d", rc);
if (rc == -EIO)
txAbort(tid, 1); /* Marks FS Dirty */
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dip)->commit_mutex);
IWRITE_UNLOCK(ip);
goto out1;
}
ASSERT(ip->i_nlink);
ip->i_ctime = dip->i_ctime = dip->i_mtime = CURRENT_TIME;
mark_inode_dirty(dip);
/* update target's inode */
inode_dec_link_count(ip);
/*
* commit zero link count object
*/
if (ip->i_nlink == 0) {
assert(!test_cflag(COMMIT_Nolink, ip));
/* free block resources */
if ((new_size = commitZeroLink(tid, ip)) < 0) {
txAbort(tid, 1); /* Marks FS Dirty */
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dip)->commit_mutex);
IWRITE_UNLOCK(ip);
rc = new_size;
goto out1;
}
tblk = tid_to_tblock(tid);
tblk->xflag |= COMMIT_DELETE;
tblk->u.ip = ip;
}
/*
* Incomplete truncate of file data can
* result in timing problems unless we synchronously commit the
* transaction.
*/
if (new_size)
commit_flag = COMMIT_SYNC;
else
commit_flag = 0;
/*
* If xtTruncate was incomplete, commit synchronously to avoid
* timing complications
*/
rc = txCommit(tid, 2, &iplist[0], commit_flag);
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dip)->commit_mutex);
while (new_size && (rc == 0)) {
tid = txBegin(dip->i_sb, 0);
mutex_lock(&JFS_IP(ip)->commit_mutex);
new_size = xtTruncate_pmap(tid, ip, new_size);
if (new_size < 0) {
txAbort(tid, 1); /* Marks FS Dirty */
rc = new_size;
} else
rc = txCommit(tid, 2, &iplist[0], COMMIT_SYNC);
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
}
if (ip->i_nlink == 0)
set_cflag(COMMIT_Nolink, ip);
IWRITE_UNLOCK(ip);
/*
* Truncating the directory index table is not guaranteed. It
* may need to be done iteratively
*/
if (test_cflag(COMMIT_Stale, dip)) {
if (dip->i_size > 1)
jfs_truncate_nolock(dip, 0);
clear_cflag(COMMIT_Stale, dip);
}
out1:
free_UCSname(&dname);
out:
jfs_info("jfs_unlink: rc:%d", rc);
return rc;
}
/*
* NAME: commitZeroLink()
*
* FUNCTION: for non-directory, called by jfs_remove(),
* truncate a regular file, directory or symbolic
* link to zero length. return 0 if type is not
* one of these.
*
* if the file is currently associated with a VM segment
* only permanent disk and inode map resources are freed,
* and neither the inode nor indirect blocks are modified
* so that the resources can be later freed in the work
* map by ctrunc1.
* if there is no VM segment on entry, the resources are
* freed in both work and permanent map.
* (? for temporary file - memory object is cached even
* after no reference:
* reference count > 0 - )
*
* PARAMETERS: cd - pointer to commit data structure.
* current inode is the one to truncate.
*
* RETURN: Errors from subroutines
*/
static s64 commitZeroLink(tid_t tid, struct inode *ip)
{
int filetype;
struct tblock *tblk;
jfs_info("commitZeroLink: tid = %d, ip = 0x%p", tid, ip);
filetype = ip->i_mode & S_IFMT;
switch (filetype) {
case S_IFREG:
break;
case S_IFLNK:
/* fast symbolic link */
if (ip->i_size < IDATASIZE) {
ip->i_size = 0;
return 0;
}
break;
default:
assert(filetype != S_IFDIR);
return 0;
}
set_cflag(COMMIT_Freewmap, ip);
/* mark transaction of block map update type */
tblk = tid_to_tblock(tid);
tblk->xflag |= COMMIT_PMAP;
/*
* free EA
*/
if (JFS_IP(ip)->ea.flag & DXD_EXTENT)
/* acquire maplock on EA to be freed from block map */
txEA(tid, ip, &JFS_IP(ip)->ea, NULL);
/*
* free ACL
*/
if (JFS_IP(ip)->acl.flag & DXD_EXTENT)
/* acquire maplock on EA to be freed from block map */
txEA(tid, ip, &JFS_IP(ip)->acl, NULL);
/*
* free xtree/data (truncate to zero length):
* free xtree/data pages from cache if COMMIT_PWMAP,
* free xtree/data blocks from persistent block map, and
* free xtree/data blocks from working block map if COMMIT_PWMAP;
*/
if (ip->i_size)
return xtTruncate_pmap(tid, ip, 0);
return 0;
}
/*
* NAME: jfs_free_zero_link()
*
* FUNCTION: for non-directory, called by iClose(),
* free resources of a file from cache and WORKING map
* for a file previously committed with zero link count
* while associated with a pager object,
*
* PARAMETER: ip - pointer to inode of file.
*/
void jfs_free_zero_link(struct inode *ip)
{
int type;
jfs_info("jfs_free_zero_link: ip = 0x%p", ip);
/* return if not reg or symbolic link or if size is
* already ok.
*/
type = ip->i_mode & S_IFMT;
switch (type) {
case S_IFREG:
break;
case S_IFLNK:
/* if its contained in inode nothing to do */
if (ip->i_size < IDATASIZE)
return;
break;
default:
return;
}
/*
* free EA
*/
if (JFS_IP(ip)->ea.flag & DXD_EXTENT) {
s64 xaddr = addressDXD(&JFS_IP(ip)->ea);
int xlen = lengthDXD(&JFS_IP(ip)->ea);
struct maplock maplock; /* maplock for COMMIT_WMAP */
struct pxd_lock *pxdlock; /* maplock for COMMIT_WMAP */
/* free EA pages from cache */
invalidate_dxd_metapages(ip, JFS_IP(ip)->ea);
/* free EA extent from working block map */
maplock.index = 1;
pxdlock = (struct pxd_lock *) & maplock;
pxdlock->flag = mlckFREEPXD;
PXDaddress(&pxdlock->pxd, xaddr);
PXDlength(&pxdlock->pxd, xlen);
txFreeMap(ip, pxdlock, NULL, COMMIT_WMAP);
}
/*
* free ACL
*/
if (JFS_IP(ip)->acl.flag & DXD_EXTENT) {
s64 xaddr = addressDXD(&JFS_IP(ip)->acl);
int xlen = lengthDXD(&JFS_IP(ip)->acl);
struct maplock maplock; /* maplock for COMMIT_WMAP */
struct pxd_lock *pxdlock; /* maplock for COMMIT_WMAP */
invalidate_dxd_metapages(ip, JFS_IP(ip)->acl);
/* free ACL extent from working block map */
maplock.index = 1;
pxdlock = (struct pxd_lock *) & maplock;
pxdlock->flag = mlckFREEPXD;
PXDaddress(&pxdlock->pxd, xaddr);
PXDlength(&pxdlock->pxd, xlen);
txFreeMap(ip, pxdlock, NULL, COMMIT_WMAP);
}
/*
* free xtree/data (truncate to zero length):
* free xtree/data pages from cache, and
* free xtree/data blocks from working block map;
*/
if (ip->i_size)
xtTruncate(0, ip, 0, COMMIT_WMAP);
}
/*
* NAME: jfs_link(vp, dvp, name, crp)
*
* FUNCTION: create a link to <vp> by the name = <name>
* in the parent directory <dvp>
*
* PARAMETER: vp - target object
* dvp - parent directory of new link
* name - name of new link to target object
* crp - credential
*
* RETURN: Errors from subroutines
*
* note:
* JFS does NOT support link() on directories (to prevent circular
* path in the directory hierarchy);
* EPERM: the target object is a directory, and either the caller
* does not have appropriate privileges or the implementation prohibits
* using link() on directories [XPG4.2].
*
* JFS does NOT support links between file systems:
* EXDEV: target object and new link are on different file systems and
* implementation does not support links between file systems [XPG4.2].
*/
static int jfs_link(struct dentry *old_dentry,
struct inode *dir, struct dentry *dentry)
{
int rc;
tid_t tid;
struct inode *ip = old_dentry->d_inode;
ino_t ino;
struct component_name dname;
struct btstack btstack;
struct inode *iplist[2];
jfs_info("jfs_link: %s %s", old_dentry->d_name.name,
dentry->d_name.name);
if (ip->i_nlink == JFS_LINK_MAX)
return -EMLINK;
if (ip->i_nlink == 0)
return -ENOENT;
dquot_initialize(dir);
tid = txBegin(ip->i_sb, 0);
mutex_lock_nested(&JFS_IP(dir)->commit_mutex, COMMIT_MUTEX_PARENT);
mutex_lock_nested(&JFS_IP(ip)->commit_mutex, COMMIT_MUTEX_CHILD);
/*
* scan parent directory for entry/freespace
*/
if ((rc = get_UCSname(&dname, dentry)))
goto out;
if ((rc = dtSearch(dir, &dname, &ino, &btstack, JFS_CREATE)))
goto free_dname;
/*
* create entry for new link in parent directory
*/
ino = ip->i_ino;
if ((rc = dtInsert(tid, dir, &dname, &ino, &btstack)))
goto free_dname;
/* update object inode */
inc_nlink(ip); /* for new link */
ip->i_ctime = CURRENT_TIME;
dir->i_ctime = dir->i_mtime = CURRENT_TIME;
mark_inode_dirty(dir);
atomic_inc(&ip->i_count);
iplist[0] = ip;
iplist[1] = dir;
rc = txCommit(tid, 2, &iplist[0], 0);
if (rc) {
ip->i_nlink--; /* never instantiated */
iput(ip);
} else
d_instantiate(dentry, ip);
free_dname:
free_UCSname(&dname);
out:
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dir)->commit_mutex);
jfs_info("jfs_link: rc:%d", rc);
return rc;
}
/*
* NAME: jfs_symlink(dip, dentry, name)
*
* FUNCTION: creates a symbolic link to <symlink> by name <name>
* in directory <dip>
*
* PARAMETER: dip - parent directory vnode
* dentry - dentry of symbolic link
* name - the path name of the existing object
* that will be the source of the link
*
* RETURN: errors from subroutines
*
* note:
* ENAMETOOLONG: pathname resolution of a symbolic link produced
* an intermediate result whose length exceeds PATH_MAX [XPG4.2]
*/
static int jfs_symlink(struct inode *dip, struct dentry *dentry,
const char *name)
{
int rc;
tid_t tid;
ino_t ino = 0;
struct component_name dname;
int ssize; /* source pathname size */
struct btstack btstack;
struct inode *ip = dentry->d_inode;
unchar *i_fastsymlink;
s64 xlen = 0;
int bmask = 0, xsize;
s64 extent = 0, xaddr;
struct metapage *mp;
struct super_block *sb;
struct tblock *tblk;
struct inode *iplist[2];
jfs_info("jfs_symlink: dip:0x%p name:%s", dip, name);
dquot_initialize(dip);
ssize = strlen(name) + 1;
/*
* search parent directory for entry/freespace
* (dtSearch() returns parent directory page pinned)
*/
if ((rc = get_UCSname(&dname, dentry)))
goto out1;
/*
* allocate on-disk/in-memory inode for symbolic link:
* (iAlloc() returns new, locked inode)
*/
ip = ialloc(dip, S_IFLNK | 0777);
if (IS_ERR(ip)) {
rc = PTR_ERR(ip);
goto out2;
}
tid = txBegin(dip->i_sb, 0);
mutex_lock_nested(&JFS_IP(dip)->commit_mutex, COMMIT_MUTEX_PARENT);
mutex_lock_nested(&JFS_IP(ip)->commit_mutex, COMMIT_MUTEX_CHILD);
rc = jfs_init_security(tid, ip, dip);
if (rc)
goto out3;
tblk = tid_to_tblock(tid);
tblk->xflag |= COMMIT_CREATE;
tblk->ino = ip->i_ino;
tblk->u.ixpxd = JFS_IP(ip)->ixpxd;
/* fix symlink access permission
* (dir_create() ANDs in the u.u_cmask,
* but symlinks really need to be 777 access)
*/
ip->i_mode |= 0777;
/*
* write symbolic link target path name
*/
xtInitRoot(tid, ip);
/*
* write source path name inline in on-disk inode (fast symbolic link)
*/
if (ssize <= IDATASIZE) {
ip->i_op = &jfs_fast_symlink_inode_operations;
i_fastsymlink = JFS_IP(ip)->i_inline;
memcpy(i_fastsymlink, name, ssize);
ip->i_size = ssize - 1;
/*
* if symlink is > 128 bytes, we don't have the space to
* store inline extended attributes
*/
if (ssize > sizeof (JFS_IP(ip)->i_inline))
JFS_IP(ip)->mode2 &= ~INLINEEA;
jfs_info("jfs_symlink: fast symlink added ssize:%d name:%s ",
ssize, name);
}
/*
* write source path name in a single extent
*/
else {
jfs_info("jfs_symlink: allocate extent ip:0x%p", ip);
ip->i_op = &jfs_symlink_inode_operations;
ip->i_mapping->a_ops = &jfs_aops;
/*
* even though the data of symlink object (source
* path name) is treated as non-journaled user data,
* it is read/written thru buffer cache for performance.
*/
sb = ip->i_sb;
bmask = JFS_SBI(sb)->bsize - 1;
xsize = (ssize + bmask) & ~bmask;
xaddr = 0;
xlen = xsize >> JFS_SBI(sb)->l2bsize;
if ((rc = xtInsert(tid, ip, 0, 0, xlen, &xaddr, 0))) {
txAbort(tid, 0);
goto out3;
}
extent = xaddr;
ip->i_size = ssize - 1;
while (ssize) {
/* This is kind of silly since PATH_MAX == 4K */
int copy_size = min(ssize, PSIZE);
mp = get_metapage(ip, xaddr, PSIZE, 1);
if (mp == NULL) {
xtTruncate(tid, ip, 0, COMMIT_PWMAP);
rc = -EIO;
txAbort(tid, 0);
goto out3;
}
memcpy(mp->data, name, copy_size);
flush_metapage(mp);
ssize -= copy_size;
name += copy_size;
xaddr += JFS_SBI(sb)->nbperpage;
}
}
/*
* create entry for symbolic link in parent directory
*/
rc = dtSearch(dip, &dname, &ino, &btstack, JFS_CREATE);
if (rc == 0) {
ino = ip->i_ino;
rc = dtInsert(tid, dip, &dname, &ino, &btstack);
}
if (rc) {
if (xlen)
xtTruncate(tid, ip, 0, COMMIT_PWMAP);
txAbort(tid, 0);
/* discard new inode */
goto out3;
}
mark_inode_dirty(ip);
dip->i_ctime = dip->i_mtime = CURRENT_TIME;
mark_inode_dirty(dip);
/*
* commit update of parent directory and link object
*/
iplist[0] = dip;
iplist[1] = ip;
rc = txCommit(tid, 2, &iplist[0], 0);
out3:
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dip)->commit_mutex);
if (rc) {
free_ea_wmap(ip);
ip->i_nlink = 0;
unlock_new_inode(ip);
iput(ip);
} else {
d_instantiate(dentry, ip);
unlock_new_inode(ip);
}
out2:
free_UCSname(&dname);
out1:
jfs_info("jfs_symlink: rc:%d", rc);
return rc;
}
/*
* NAME: jfs_rename
*
* FUNCTION: rename a file or directory
*/
static int jfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct btstack btstack;
ino_t ino;
struct component_name new_dname;
struct inode *new_ip;
struct component_name old_dname;
struct inode *old_ip;
int rc;
tid_t tid;
struct tlock *tlck;
struct dt_lock *dtlck;
struct lv *lv;
int ipcount;
struct inode *iplist[4];
struct tblock *tblk;
s64 new_size = 0;
int commit_flag;
jfs_info("jfs_rename: %s %s", old_dentry->d_name.name,
new_dentry->d_name.name);
dquot_initialize(old_dir);
dquot_initialize(new_dir);
old_ip = old_dentry->d_inode;
new_ip = new_dentry->d_inode;
if ((rc = get_UCSname(&old_dname, old_dentry)))
goto out1;
if ((rc = get_UCSname(&new_dname, new_dentry)))
goto out2;
/*
* Make sure source inode number is what we think it is
*/
rc = dtSearch(old_dir, &old_dname, &ino, &btstack, JFS_LOOKUP);
if (rc || (ino != old_ip->i_ino)) {
rc = -ENOENT;
goto out3;
}
/*
* Make sure dest inode number (if any) is what we think it is
*/
rc = dtSearch(new_dir, &new_dname, &ino, &btstack, JFS_LOOKUP);
if (!rc) {
if ((!new_ip) || (ino != new_ip->i_ino)) {
rc = -ESTALE;
goto out3;
}
} else if (rc != -ENOENT)
goto out3;
else if (new_ip) {
/* no entry exists, but one was expected */
rc = -ESTALE;
goto out3;
}
if (S_ISDIR(old_ip->i_mode)) {
if (new_ip) {
if (!dtEmpty(new_ip)) {
rc = -ENOTEMPTY;
goto out3;
}
} else if ((new_dir != old_dir) &&
(new_dir->i_nlink == JFS_LINK_MAX)) {
rc = -EMLINK;
goto out3;
}
} else if (new_ip) {
IWRITE_LOCK(new_ip, RDWRLOCK_NORMAL);
/* Init inode for quota operations. */
dquot_initialize(new_ip);
}
/*
* The real work starts here
*/
tid = txBegin(new_dir->i_sb, 0);
/*
* How do we know the locking is safe from deadlocks?
* The vfs does the hard part for us. Any time we are taking nested
* commit_mutexes, the vfs already has i_mutex held on the parent.
* Here, the vfs has already taken i_mutex on both old_dir and new_dir.
*/
mutex_lock_nested(&JFS_IP(new_dir)->commit_mutex, COMMIT_MUTEX_PARENT);
mutex_lock_nested(&JFS_IP(old_ip)->commit_mutex, COMMIT_MUTEX_CHILD);
if (old_dir != new_dir)
mutex_lock_nested(&JFS_IP(old_dir)->commit_mutex,
COMMIT_MUTEX_SECOND_PARENT);
if (new_ip) {
mutex_lock_nested(&JFS_IP(new_ip)->commit_mutex,
COMMIT_MUTEX_VICTIM);
/*
* Change existing directory entry to new inode number
*/
ino = new_ip->i_ino;
rc = dtModify(tid, new_dir, &new_dname, &ino,
old_ip->i_ino, JFS_RENAME);
if (rc)
goto out4;
drop_nlink(new_ip);
if (S_ISDIR(new_ip->i_mode)) {
drop_nlink(new_ip);
if (new_ip->i_nlink) {
mutex_unlock(&JFS_IP(new_ip)->commit_mutex);
if (old_dir != new_dir)
mutex_unlock(&JFS_IP(old_dir)->commit_mutex);
mutex_unlock(&JFS_IP(old_ip)->commit_mutex);
mutex_unlock(&JFS_IP(new_dir)->commit_mutex);
if (!S_ISDIR(old_ip->i_mode) && new_ip)
IWRITE_UNLOCK(new_ip);
jfs_error(new_ip->i_sb,
"jfs_rename: new_ip->i_nlink != 0");
return -EIO;
}
tblk = tid_to_tblock(tid);
tblk->xflag |= COMMIT_DELETE;
tblk->u.ip = new_ip;
} else if (new_ip->i_nlink == 0) {
assert(!test_cflag(COMMIT_Nolink, new_ip));
/* free block resources */
if ((new_size = commitZeroLink(tid, new_ip)) < 0) {
txAbort(tid, 1); /* Marks FS Dirty */
rc = new_size;
goto out4;
}
tblk = tid_to_tblock(tid);
tblk->xflag |= COMMIT_DELETE;
tblk->u.ip = new_ip;
} else {
new_ip->i_ctime = CURRENT_TIME;
mark_inode_dirty(new_ip);
}
} else {
/*
* Add new directory entry
*/
rc = dtSearch(new_dir, &new_dname, &ino, &btstack,
JFS_CREATE);
if (rc) {
jfs_err("jfs_rename didn't expect dtSearch to fail "
"w/rc = %d", rc);
goto out4;
}
ino = old_ip->i_ino;
rc = dtInsert(tid, new_dir, &new_dname, &ino, &btstack);
if (rc) {
if (rc == -EIO)
jfs_err("jfs_rename: dtInsert returned -EIO");
goto out4;
}
if (S_ISDIR(old_ip->i_mode))
inc_nlink(new_dir);
}
/*
* Remove old directory entry
*/
ino = old_ip->i_ino;
rc = dtDelete(tid, old_dir, &old_dname, &ino, JFS_REMOVE);
if (rc) {
jfs_err("jfs_rename did not expect dtDelete to return rc = %d",
rc);
txAbort(tid, 1); /* Marks Filesystem dirty */
goto out4;
}
if (S_ISDIR(old_ip->i_mode)) {
drop_nlink(old_dir);
if (old_dir != new_dir) {
/*
* Change inode number of parent for moved directory
*/
JFS_IP(old_ip)->i_dtroot.header.idotdot =
cpu_to_le32(new_dir->i_ino);
/* Linelock header of dtree */
tlck = txLock(tid, old_ip,
(struct metapage *) &JFS_IP(old_ip)->bxflag,
tlckDTREE | tlckBTROOT | tlckRELINK);
dtlck = (struct dt_lock *) & tlck->lock;
ASSERT(dtlck->index == 0);
lv = & dtlck->lv[0];
lv->offset = 0;
lv->length = 1;
dtlck->index++;
}
}
/*
* Update ctime on changed/moved inodes & mark dirty
*/
old_ip->i_ctime = CURRENT_TIME;
mark_inode_dirty(old_ip);
new_dir->i_ctime = new_dir->i_mtime = current_fs_time(new_dir->i_sb);
mark_inode_dirty(new_dir);
/* Build list of inodes modified by this transaction */
ipcount = 0;
iplist[ipcount++] = old_ip;
if (new_ip)
iplist[ipcount++] = new_ip;
iplist[ipcount++] = old_dir;
if (old_dir != new_dir) {
iplist[ipcount++] = new_dir;
old_dir->i_ctime = old_dir->i_mtime = CURRENT_TIME;
mark_inode_dirty(old_dir);
}
/*
* Incomplete truncate of file data can
* result in timing problems unless we synchronously commit the
* transaction.
*/
if (new_size)
commit_flag = COMMIT_SYNC;
else
commit_flag = 0;
rc = txCommit(tid, ipcount, iplist, commit_flag);
out4:
txEnd(tid);
if (new_ip)
mutex_unlock(&JFS_IP(new_ip)->commit_mutex);
if (old_dir != new_dir)
mutex_unlock(&JFS_IP(old_dir)->commit_mutex);
mutex_unlock(&JFS_IP(old_ip)->commit_mutex);
mutex_unlock(&JFS_IP(new_dir)->commit_mutex);
while (new_size && (rc == 0)) {
tid = txBegin(new_ip->i_sb, 0);
mutex_lock(&JFS_IP(new_ip)->commit_mutex);
new_size = xtTruncate_pmap(tid, new_ip, new_size);
if (new_size < 0) {
txAbort(tid, 1);
rc = new_size;
} else
rc = txCommit(tid, 1, &new_ip, COMMIT_SYNC);
txEnd(tid);
mutex_unlock(&JFS_IP(new_ip)->commit_mutex);
}
if (new_ip && (new_ip->i_nlink == 0))
set_cflag(COMMIT_Nolink, new_ip);
out3:
free_UCSname(&new_dname);
out2:
free_UCSname(&old_dname);
out1:
if (new_ip && !S_ISDIR(new_ip->i_mode))
IWRITE_UNLOCK(new_ip);
/*
* Truncating the directory index table is not guaranteed. It
* may need to be done iteratively
*/
if (test_cflag(COMMIT_Stale, old_dir)) {
if (old_dir->i_size > 1)
jfs_truncate_nolock(old_dir, 0);
clear_cflag(COMMIT_Stale, old_dir);
}
jfs_info("jfs_rename: returning %d", rc);
return rc;
}
/*
* NAME: jfs_mknod
*
* FUNCTION: Create a special file (device)
*/
static int jfs_mknod(struct inode *dir, struct dentry *dentry,
int mode, dev_t rdev)
{
struct jfs_inode_info *jfs_ip;
struct btstack btstack;
struct component_name dname;
ino_t ino;
struct inode *ip;
struct inode *iplist[2];
int rc;
tid_t tid;
struct tblock *tblk;
if (!new_valid_dev(rdev))
return -EINVAL;
jfs_info("jfs_mknod: %s", dentry->d_name.name);
dquot_initialize(dir);
if ((rc = get_UCSname(&dname, dentry)))
goto out;
ip = ialloc(dir, mode);
if (IS_ERR(ip)) {
rc = PTR_ERR(ip);
goto out1;
}
jfs_ip = JFS_IP(ip);
tid = txBegin(dir->i_sb, 0);
mutex_lock_nested(&JFS_IP(dir)->commit_mutex, COMMIT_MUTEX_PARENT);
mutex_lock_nested(&JFS_IP(ip)->commit_mutex, COMMIT_MUTEX_CHILD);
rc = jfs_init_acl(tid, ip, dir);
if (rc)
goto out3;
rc = jfs_init_security(tid, ip, dir);
if (rc) {
txAbort(tid, 0);
goto out3;
}
if ((rc = dtSearch(dir, &dname, &ino, &btstack, JFS_CREATE))) {
txAbort(tid, 0);
goto out3;
}
tblk = tid_to_tblock(tid);
tblk->xflag |= COMMIT_CREATE;
tblk->ino = ip->i_ino;
tblk->u.ixpxd = JFS_IP(ip)->ixpxd;
ino = ip->i_ino;
if ((rc = dtInsert(tid, dir, &dname, &ino, &btstack))) {
txAbort(tid, 0);
goto out3;
}
ip->i_op = &jfs_file_inode_operations;
jfs_ip->dev = new_encode_dev(rdev);
init_special_inode(ip, ip->i_mode, rdev);
mark_inode_dirty(ip);
dir->i_ctime = dir->i_mtime = CURRENT_TIME;
mark_inode_dirty(dir);
iplist[0] = dir;
iplist[1] = ip;
rc = txCommit(tid, 2, iplist, 0);
out3:
txEnd(tid);
mutex_unlock(&JFS_IP(ip)->commit_mutex);
mutex_unlock(&JFS_IP(dir)->commit_mutex);
if (rc) {
free_ea_wmap(ip);
ip->i_nlink = 0;
unlock_new_inode(ip);
iput(ip);
} else {
d_instantiate(dentry, ip);
unlock_new_inode(ip);
}
out1:
free_UCSname(&dname);
out:
jfs_info("jfs_mknod: returning %d", rc);
return rc;
}
static struct dentry *jfs_lookup(struct inode *dip, struct dentry *dentry, struct nameidata *nd)
{
struct btstack btstack;
ino_t inum;
struct inode *ip;
struct component_name key;
const char *name = dentry->d_name.name;
int len = dentry->d_name.len;
int rc;
jfs_info("jfs_lookup: name = %s", name);
if (JFS_SBI(dip->i_sb)->mntflag & JFS_OS2)
dentry->d_op = &jfs_ci_dentry_operations;
if ((name[0] == '.') && (len == 1))
inum = dip->i_ino;
else if (strcmp(name, "..") == 0)
inum = PARENT(dip);
else {
if ((rc = get_UCSname(&key, dentry)))
return ERR_PTR(rc);
rc = dtSearch(dip, &key, &inum, &btstack, JFS_LOOKUP);
free_UCSname(&key);
if (rc == -ENOENT) {
d_add(dentry, NULL);
return NULL;
} else if (rc) {
jfs_err("jfs_lookup: dtSearch returned %d", rc);
return ERR_PTR(rc);
}
}
ip = jfs_iget(dip->i_sb, inum);
if (IS_ERR(ip)) {
jfs_err("jfs_lookup: iget failed on inum %d", (uint) inum);
return ERR_CAST(ip);
}
dentry = d_splice_alias(ip, dentry);
if (dentry && (JFS_SBI(dip->i_sb)->mntflag & JFS_OS2))
dentry->d_op = &jfs_ci_dentry_operations;
return dentry;
}
static struct inode *jfs_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct inode *inode;
if (ino == 0)
return ERR_PTR(-ESTALE);
inode = jfs_iget(sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
struct dentry *jfs_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
jfs_nfs_get_inode);
}
struct dentry *jfs_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
jfs_nfs_get_inode);
}
struct dentry *jfs_get_parent(struct dentry *dentry)
{
unsigned long parent_ino;
parent_ino =
le32_to_cpu(JFS_IP(dentry->d_inode)->i_dtroot.header.idotdot);
return d_obtain_alias(jfs_iget(dentry->d_inode->i_sb, parent_ino));
}
const struct inode_operations jfs_dir_inode_operations = {
.create = jfs_create,
.lookup = jfs_lookup,
.link = jfs_link,
.unlink = jfs_unlink,
.symlink = jfs_symlink,
.mkdir = jfs_mkdir,
.rmdir = jfs_rmdir,
.mknod = jfs_mknod,
.rename = jfs_rename,
.setxattr = jfs_setxattr,
.getxattr = jfs_getxattr,
.listxattr = jfs_listxattr,
.removexattr = jfs_removexattr,
.setattr = jfs_setattr,
#ifdef CONFIG_JFS_POSIX_ACL
.check_acl = jfs_check_acl,
#endif
};
const struct file_operations jfs_dir_operations = {
.read = generic_read_dir,
.readdir = jfs_readdir,
.fsync = jfs_fsync,
.unlocked_ioctl = jfs_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = jfs_compat_ioctl,
#endif
.llseek = generic_file_llseek,
};
static int jfs_ci_hash(struct dentry *dir, struct qstr *this)
{
unsigned long hash;
int i;
hash = init_name_hash();
for (i=0; i < this->len; i++)
hash = partial_name_hash(tolower(this->name[i]), hash);
this->hash = end_name_hash(hash);
return 0;
}
static int jfs_ci_compare(struct dentry *dir, struct qstr *a, struct qstr *b)
{
int i, result = 1;
if (a->len != b->len)
goto out;
for (i=0; i < a->len; i++) {
if (tolower(a->name[i]) != tolower(b->name[i]))
goto out;
}
result = 0;
/*
* We want creates to preserve case. A negative dentry, a, that
* has a different case than b may cause a new entry to be created
* with the wrong case. Since we can't tell if a comes from a negative
* dentry, we blindly replace it with b. This should be harmless if
* a is not a negative dentry.
*/
memcpy((unsigned char *)a->name, b->name, a->len);
out:
return result;
}
const struct dentry_operations jfs_ci_dentry_operations =
{
.d_hash = jfs_ci_hash,
.d_compare = jfs_ci_compare,
};
| gpl-2.0 |
javilonas/Enki-GT-I9300 | arch/ia64/mm/contig.c | 2718 | 9676 | /*
* 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) 1998-2003 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
* Stephane Eranian <eranian@hpl.hp.com>
* Copyright (C) 2000, Rohit Seth <rohit.seth@intel.com>
* Copyright (C) 1999 VA Linux Systems
* Copyright (C) 1999 Walt Drummond <drummond@valinux.com>
* Copyright (C) 2003 Silicon Graphics, Inc. All rights reserved.
*
* Routines used by ia64 machines with contiguous (or virtually contiguous)
* memory.
*/
#include <linux/bootmem.h>
#include <linux/efi.h>
#include <linux/mm.h>
#include <linux/nmi.h>
#include <linux/swap.h>
#include <asm/meminit.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/sections.h>
#include <asm/mca.h>
#ifdef CONFIG_VIRTUAL_MEM_MAP
static unsigned long max_gap;
#endif
/**
* show_mem - give short summary of memory stats
*
* Shows a simple page count of reserved and used pages in the system.
* For discontig machines, it does this on a per-pgdat basis.
*/
void show_mem(unsigned int filter)
{
int i, total_reserved = 0;
int total_shared = 0, total_cached = 0;
unsigned long total_present = 0;
pg_data_t *pgdat;
printk(KERN_INFO "Mem-info:\n");
show_free_areas(filter);
printk(KERN_INFO "Node memory in pages:\n");
for_each_online_pgdat(pgdat) {
unsigned long present;
unsigned long flags;
int shared = 0, cached = 0, reserved = 0;
int nid = pgdat->node_id;
if (skip_free_areas_node(filter, nid))
continue;
pgdat_resize_lock(pgdat, &flags);
present = pgdat->node_present_pages;
for(i = 0; i < pgdat->node_spanned_pages; i++) {
struct page *page;
if (unlikely(i % MAX_ORDER_NR_PAGES == 0))
touch_nmi_watchdog();
if (pfn_valid(pgdat->node_start_pfn + i))
page = pfn_to_page(pgdat->node_start_pfn + i);
else {
#ifdef CONFIG_VIRTUAL_MEM_MAP
if (max_gap < LARGE_GAP)
continue;
#endif
i = vmemmap_find_next_valid_pfn(nid, i) - 1;
continue;
}
if (PageReserved(page))
reserved++;
else if (PageSwapCache(page))
cached++;
else if (page_count(page))
shared += page_count(page)-1;
}
pgdat_resize_unlock(pgdat, &flags);
total_present += present;
total_reserved += reserved;
total_cached += cached;
total_shared += shared;
printk(KERN_INFO "Node %4d: RAM: %11ld, rsvd: %8d, "
"shrd: %10d, swpd: %10d\n", nid,
present, reserved, shared, cached);
}
printk(KERN_INFO "%ld pages of RAM\n", total_present);
printk(KERN_INFO "%d reserved pages\n", total_reserved);
printk(KERN_INFO "%d pages shared\n", total_shared);
printk(KERN_INFO "%d pages swap cached\n", total_cached);
printk(KERN_INFO "Total of %ld pages in page table cache\n",
quicklist_total_size());
printk(KERN_INFO "%d free buffer pages\n", nr_free_buffer_pages());
}
/* physical address where the bootmem map is located */
unsigned long bootmap_start;
/**
* find_bootmap_location - callback to find a memory area for the bootmap
* @start: start of region
* @end: end of region
* @arg: unused callback data
*
* Find a place to put the bootmap and return its starting address in
* bootmap_start. This address must be page-aligned.
*/
static int __init
find_bootmap_location (u64 start, u64 end, void *arg)
{
u64 needed = *(unsigned long *)arg;
u64 range_start, range_end, free_start;
int i;
#if IGNORE_PFN0
if (start == PAGE_OFFSET) {
start += PAGE_SIZE;
if (start >= end)
return 0;
}
#endif
free_start = PAGE_OFFSET;
for (i = 0; i < num_rsvd_regions; i++) {
range_start = max(start, free_start);
range_end = min(end, rsvd_region[i].start & PAGE_MASK);
free_start = PAGE_ALIGN(rsvd_region[i].end);
if (range_end <= range_start)
continue; /* skip over empty range */
if (range_end - range_start >= needed) {
bootmap_start = __pa(range_start);
return -1; /* done */
}
/* nothing more available in this segment */
if (range_end == end)
return 0;
}
return 0;
}
#ifdef CONFIG_SMP
static void *cpu_data;
/**
* per_cpu_init - setup per-cpu variables
*
* Allocate and setup per-cpu data areas.
*/
void * __cpuinit
per_cpu_init (void)
{
static bool first_time = true;
void *cpu0_data = __cpu0_per_cpu;
unsigned int cpu;
if (!first_time)
goto skip;
first_time = false;
/*
* get_free_pages() cannot be used before cpu_init() done.
* BSP allocates PERCPU_PAGE_SIZE bytes for all possible CPUs
* to avoid that AP calls get_zeroed_page().
*/
for_each_possible_cpu(cpu) {
void *src = cpu == 0 ? cpu0_data : __phys_per_cpu_start;
memcpy(cpu_data, src, __per_cpu_end - __per_cpu_start);
__per_cpu_offset[cpu] = (char *)cpu_data - __per_cpu_start;
per_cpu(local_per_cpu_offset, cpu) = __per_cpu_offset[cpu];
/*
* percpu area for cpu0 is moved from the __init area
* which is setup by head.S and used till this point.
* Update ar.k3. This move is ensures that percpu
* area for cpu0 is on the correct node and its
* virtual address isn't insanely far from other
* percpu areas which is important for congruent
* percpu allocator.
*/
if (cpu == 0)
ia64_set_kr(IA64_KR_PER_CPU_DATA, __pa(cpu_data) -
(unsigned long)__per_cpu_start);
cpu_data += PERCPU_PAGE_SIZE;
}
skip:
return __per_cpu_start + __per_cpu_offset[smp_processor_id()];
}
static inline void
alloc_per_cpu_data(void)
{
cpu_data = __alloc_bootmem(PERCPU_PAGE_SIZE * num_possible_cpus(),
PERCPU_PAGE_SIZE, __pa(MAX_DMA_ADDRESS));
}
/**
* setup_per_cpu_areas - setup percpu areas
*
* Arch code has already allocated and initialized percpu areas. All
* this function has to do is to teach the determined layout to the
* dynamic percpu allocator, which happens to be more complex than
* creating whole new ones using helpers.
*/
void __init
setup_per_cpu_areas(void)
{
struct pcpu_alloc_info *ai;
struct pcpu_group_info *gi;
unsigned int cpu;
ssize_t static_size, reserved_size, dyn_size;
int rc;
ai = pcpu_alloc_alloc_info(1, num_possible_cpus());
if (!ai)
panic("failed to allocate pcpu_alloc_info");
gi = &ai->groups[0];
/* units are assigned consecutively to possible cpus */
for_each_possible_cpu(cpu)
gi->cpu_map[gi->nr_units++] = cpu;
/* set parameters */
static_size = __per_cpu_end - __per_cpu_start;
reserved_size = PERCPU_MODULE_RESERVE;
dyn_size = PERCPU_PAGE_SIZE - static_size - reserved_size;
if (dyn_size < 0)
panic("percpu area overflow static=%zd reserved=%zd\n",
static_size, reserved_size);
ai->static_size = static_size;
ai->reserved_size = reserved_size;
ai->dyn_size = dyn_size;
ai->unit_size = PERCPU_PAGE_SIZE;
ai->atom_size = PAGE_SIZE;
ai->alloc_size = PERCPU_PAGE_SIZE;
rc = pcpu_setup_first_chunk(ai, __per_cpu_start + __per_cpu_offset[0]);
if (rc)
panic("failed to setup percpu area (err=%d)", rc);
pcpu_free_alloc_info(ai);
}
#else
#define alloc_per_cpu_data() do { } while (0)
#endif /* CONFIG_SMP */
/**
* find_memory - setup memory map
*
* Walk the EFI memory map and find usable memory for the system, taking
* into account reserved areas.
*/
void __init
find_memory (void)
{
unsigned long bootmap_size;
reserve_memory();
/* first find highest page frame number */
min_low_pfn = ~0UL;
max_low_pfn = 0;
efi_memmap_walk(find_max_min_low_pfn, NULL);
max_pfn = max_low_pfn;
/* how many bytes to cover all the pages */
bootmap_size = bootmem_bootmap_pages(max_pfn) << PAGE_SHIFT;
/* look for a location to hold the bootmap */
bootmap_start = ~0UL;
efi_memmap_walk(find_bootmap_location, &bootmap_size);
if (bootmap_start == ~0UL)
panic("Cannot find %ld bytes for bootmap\n", bootmap_size);
bootmap_size = init_bootmem_node(NODE_DATA(0),
(bootmap_start >> PAGE_SHIFT), 0, max_pfn);
/* Free all available memory, then mark bootmem-map as being in use. */
efi_memmap_walk(filter_rsvd_memory, free_bootmem);
reserve_bootmem(bootmap_start, bootmap_size, BOOTMEM_DEFAULT);
find_initrd();
alloc_per_cpu_data();
}
static int count_pages(u64 start, u64 end, void *arg)
{
unsigned long *count = arg;
*count += (end - start) >> PAGE_SHIFT;
return 0;
}
/*
* Set up the page tables.
*/
void __init
paging_init (void)
{
unsigned long max_dma;
unsigned long max_zone_pfns[MAX_NR_ZONES];
num_physpages = 0;
efi_memmap_walk(count_pages, &num_physpages);
memset(max_zone_pfns, 0, sizeof(max_zone_pfns));
#ifdef CONFIG_ZONE_DMA
max_dma = virt_to_phys((void *) MAX_DMA_ADDRESS) >> PAGE_SHIFT;
max_zone_pfns[ZONE_DMA] = max_dma;
#endif
max_zone_pfns[ZONE_NORMAL] = max_low_pfn;
#ifdef CONFIG_VIRTUAL_MEM_MAP
efi_memmap_walk(filter_memory, register_active_ranges);
efi_memmap_walk(find_largest_hole, (u64 *)&max_gap);
if (max_gap < LARGE_GAP) {
vmem_map = (struct page *) 0;
free_area_init_nodes(max_zone_pfns);
} else {
unsigned long map_size;
/* allocate virtual_mem_map */
map_size = PAGE_ALIGN(ALIGN(max_low_pfn, MAX_ORDER_NR_PAGES) *
sizeof(struct page));
VMALLOC_END -= map_size;
vmem_map = (struct page *) VMALLOC_END;
efi_memmap_walk(create_mem_map_page_table, NULL);
/*
* alloc_node_mem_map makes an adjustment for mem_map
* which isn't compatible with vmem_map.
*/
NODE_DATA(0)->node_mem_map = vmem_map +
find_min_pfn_with_active_regions();
free_area_init_nodes(max_zone_pfns);
printk("Virtual mem_map starts at 0x%p\n", mem_map);
}
#else /* !CONFIG_VIRTUAL_MEM_MAP */
add_active_range(0, 0, max_low_pfn);
free_area_init_nodes(max_zone_pfns);
#endif /* !CONFIG_VIRTUAL_MEM_MAP */
zero_page_memmap_ptr = virt_to_page(ia64_imva(empty_zero_page));
}
| gpl-2.0 |
CaptainThrowback/kernel_android-tegra-flounder-3.10 | sound/drivers/portman2x4.c | 2718 | 25836 | /*
* Driver for Midiman Portman2x4 parallel port midi interface
*
* Copyright (c) by Levent Guendogdu <levon@feature-it.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* ChangeLog
* Jan 24 2007 Matthias Koenig <mkoenig@suse.de>
* - cleanup and rewrite
* Sep 30 2004 Tobias Gehrig <tobias@gehrig.tk>
* - source code cleanup
* Sep 03 2004 Tobias Gehrig <tobias@gehrig.tk>
* - fixed compilation problem with alsa 1.0.6a (removed MODULE_CLASSES,
* MODULE_PARM_SYNTAX and changed MODULE_DEVICES to
* MODULE_SUPPORTED_DEVICE)
* Mar 24 2004 Tobias Gehrig <tobias@gehrig.tk>
* - added 2.6 kernel support
* Mar 18 2004 Tobias Gehrig <tobias@gehrig.tk>
* - added parport_unregister_driver to the startup routine if the driver fails to detect a portman
* - added support for all 4 output ports in portman_putmidi
* Mar 17 2004 Tobias Gehrig <tobias@gehrig.tk>
* - added checks for opened input device in interrupt handler
* Feb 20 2004 Tobias Gehrig <tobias@gehrig.tk>
* - ported from alsa 0.5 to 1.0
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/parport.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/rawmidi.h>
#include <sound/control.h>
#define CARD_NAME "Portman 2x4"
#define DRIVER_NAME "portman"
#define PLATFORM_DRIVER "snd_portman2x4"
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
static struct platform_device *platform_devices[SNDRV_CARDS];
static int device_count;
module_param_array(index, int, NULL, S_IRUGO);
MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
module_param_array(id, charp, NULL, S_IRUGO);
MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
module_param_array(enable, bool, NULL, S_IRUGO);
MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
MODULE_AUTHOR("Levent Guendogdu, Tobias Gehrig, Matthias Koenig");
MODULE_DESCRIPTION("Midiman Portman2x4");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Midiman,Portman2x4}}");
/*********************************************************************
* Chip specific
*********************************************************************/
#define PORTMAN_NUM_INPUT_PORTS 2
#define PORTMAN_NUM_OUTPUT_PORTS 4
struct portman {
spinlock_t reg_lock;
struct snd_card *card;
struct snd_rawmidi *rmidi;
struct pardevice *pardev;
int pardev_claimed;
int open_count;
int mode[PORTMAN_NUM_INPUT_PORTS];
struct snd_rawmidi_substream *midi_input[PORTMAN_NUM_INPUT_PORTS];
};
static int portman_free(struct portman *pm)
{
kfree(pm);
return 0;
}
static int portman_create(struct snd_card *card,
struct pardevice *pardev,
struct portman **rchip)
{
struct portman *pm;
*rchip = NULL;
pm = kzalloc(sizeof(struct portman), GFP_KERNEL);
if (pm == NULL)
return -ENOMEM;
/* Init chip specific data */
spin_lock_init(&pm->reg_lock);
pm->card = card;
pm->pardev = pardev;
*rchip = pm;
return 0;
}
/*********************************************************************
* HW related constants
*********************************************************************/
/* Standard PC parallel port status register equates. */
#define PP_STAT_BSY 0x80 /* Busy status. Inverted. */
#define PP_STAT_ACK 0x40 /* Acknowledge. Non-Inverted. */
#define PP_STAT_POUT 0x20 /* Paper Out. Non-Inverted. */
#define PP_STAT_SEL 0x10 /* Select. Non-Inverted. */
#define PP_STAT_ERR 0x08 /* Error. Non-Inverted. */
/* Standard PC parallel port command register equates. */
#define PP_CMD_IEN 0x10 /* IRQ Enable. Non-Inverted. */
#define PP_CMD_SELI 0x08 /* Select Input. Inverted. */
#define PP_CMD_INIT 0x04 /* Init Printer. Non-Inverted. */
#define PP_CMD_FEED 0x02 /* Auto Feed. Inverted. */
#define PP_CMD_STB 0x01 /* Strobe. Inverted. */
/* Parallel Port Command Register as implemented by PCP2x4. */
#define INT_EN PP_CMD_IEN /* Interrupt enable. */
#define STROBE PP_CMD_STB /* Command strobe. */
/* The parallel port command register field (b1..b3) selects the
* various "registers" within the PC/P 2x4. These are the internal
* address of these "registers" that must be written to the parallel
* port command register.
*/
#define RXDATA0 (0 << 1) /* PCP RxData channel 0. */
#define RXDATA1 (1 << 1) /* PCP RxData channel 1. */
#define GEN_CTL (2 << 1) /* PCP General Control Register. */
#define SYNC_CTL (3 << 1) /* PCP Sync Control Register. */
#define TXDATA0 (4 << 1) /* PCP TxData channel 0. */
#define TXDATA1 (5 << 1) /* PCP TxData channel 1. */
#define TXDATA2 (6 << 1) /* PCP TxData channel 2. */
#define TXDATA3 (7 << 1) /* PCP TxData channel 3. */
/* Parallel Port Status Register as implemented by PCP2x4. */
#define ESTB PP_STAT_POUT /* Echoed strobe. */
#define INT_REQ PP_STAT_ACK /* Input data int request. */
#define BUSY PP_STAT_ERR /* Interface Busy. */
/* Parallel Port Status Register BUSY and SELECT lines are multiplexed
* between several functions. Depending on which 2x4 "register" is
* currently selected (b1..b3), the BUSY and SELECT lines are
* assigned as follows:
*
* SELECT LINE: A3 A2 A1
* --------
*/
#define RXAVAIL PP_STAT_SEL /* Rx Available, channel 0. 0 0 0 */
// RXAVAIL1 PP_STAT_SEL /* Rx Available, channel 1. 0 0 1 */
#define SYNC_STAT PP_STAT_SEL /* Reserved - Sync Status. 0 1 0 */
// /* Reserved. 0 1 1 */
#define TXEMPTY PP_STAT_SEL /* Tx Empty, channel 0. 1 0 0 */
// TXEMPTY1 PP_STAT_SEL /* Tx Empty, channel 1. 1 0 1 */
// TXEMPTY2 PP_STAT_SEL /* Tx Empty, channel 2. 1 1 0 */
// TXEMPTY3 PP_STAT_SEL /* Tx Empty, channel 3. 1 1 1 */
/* BUSY LINE: A3 A2 A1
* --------
*/
#define RXDATA PP_STAT_BSY /* Rx Input Data, channel 0. 0 0 0 */
// RXDATA1 PP_STAT_BSY /* Rx Input Data, channel 1. 0 0 1 */
#define SYNC_DATA PP_STAT_BSY /* Reserved - Sync Data. 0 1 0 */
/* Reserved. 0 1 1 */
#define DATA_ECHO PP_STAT_BSY /* Parallel Port Data Echo. 1 0 0 */
#define A0_ECHO PP_STAT_BSY /* Address 0 Echo. 1 0 1 */
#define A1_ECHO PP_STAT_BSY /* Address 1 Echo. 1 1 0 */
#define A2_ECHO PP_STAT_BSY /* Address 2 Echo. 1 1 1 */
#define PORTMAN2X4_MODE_INPUT_TRIGGERED 0x01
/*********************************************************************
* Hardware specific functions
*********************************************************************/
static inline void portman_write_command(struct portman *pm, u8 value)
{
parport_write_control(pm->pardev->port, value);
}
static inline u8 portman_read_command(struct portman *pm)
{
return parport_read_control(pm->pardev->port);
}
static inline u8 portman_read_status(struct portman *pm)
{
return parport_read_status(pm->pardev->port);
}
static inline u8 portman_read_data(struct portman *pm)
{
return parport_read_data(pm->pardev->port);
}
static inline void portman_write_data(struct portman *pm, u8 value)
{
parport_write_data(pm->pardev->port, value);
}
static void portman_write_midi(struct portman *pm,
int port, u8 mididata)
{
int command = ((port + 4) << 1);
/* Get entering data byte and port number in BL and BH respectively.
* Set up Tx Channel address field for use with PP Cmd Register.
* Store address field in BH register.
* Inputs: AH = Output port number (0..3).
* AL = Data byte.
* command = TXDATA0 | INT_EN;
* Align port num with address field (b1...b3),
* set address for TXDatax, Strobe=0
*/
command |= INT_EN;
/* Disable interrupts so that the process is not interrupted, then
* write the address associated with the current Tx channel to the
* PP Command Reg. Do not set the Strobe signal yet.
*/
do {
portman_write_command(pm, command);
/* While the address lines settle, write parallel output data to
* PP Data Reg. This has no effect until Strobe signal is asserted.
*/
portman_write_data(pm, mididata);
/* If PCP channel's TxEmpty is set (TxEmpty is read through the PP
* Status Register), then go write data. Else go back and wait.
*/
} while ((portman_read_status(pm) & TXEMPTY) != TXEMPTY);
/* TxEmpty is set. Maintain PC/P destination address and assert
* Strobe through the PP Command Reg. This will Strobe data into
* the PC/P transmitter and set the PC/P BUSY signal.
*/
portman_write_command(pm, command | STROBE);
/* Wait for strobe line to settle and echo back through hardware.
* Once it has echoed back, assume that the address and data lines
* have settled!
*/
while ((portman_read_status(pm) & ESTB) == 0)
cpu_relax();
/* Release strobe and immediately re-allow interrupts. */
portman_write_command(pm, command);
while ((portman_read_status(pm) & ESTB) == ESTB)
cpu_relax();
/* PC/P BUSY is now set. We must wait until BUSY resets itself.
* We'll reenable ints while we're waiting.
*/
while ((portman_read_status(pm) & BUSY) == BUSY)
cpu_relax();
/* Data sent. */
}
/*
* Read MIDI byte from port
* Attempt to read input byte from specified hardware input port (0..).
* Return -1 if no data
*/
static int portman_read_midi(struct portman *pm, int port)
{
unsigned char midi_data = 0;
unsigned char cmdout; /* Saved address+IE bit. */
/* Make sure clocking edge is down before starting... */
portman_write_data(pm, 0); /* Make sure edge is down. */
/* Set destination address to PCP. */
cmdout = (port << 1) | INT_EN; /* Address + IE + No Strobe. */
portman_write_command(pm, cmdout);
while ((portman_read_status(pm) & ESTB) == ESTB)
cpu_relax(); /* Wait for strobe echo. */
/* After the address lines settle, check multiplexed RxAvail signal.
* If data is available, read it.
*/
if ((portman_read_status(pm) & RXAVAIL) == 0)
return -1; /* No data. */
/* Set the Strobe signal to enable the Rx clocking circuitry. */
portman_write_command(pm, cmdout | STROBE); /* Write address+IE+Strobe. */
while ((portman_read_status(pm) & ESTB) == 0)
cpu_relax(); /* Wait for strobe echo. */
/* The first data bit (msb) is already sitting on the input line. */
midi_data = (portman_read_status(pm) & 128);
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 6. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 1) & 64;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 5. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 2) & 32;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 4. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 3) & 16;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 3. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 4) & 8;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 2. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 5) & 4;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 1. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 6) & 2;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
/* Data bit 0. */
portman_write_data(pm, 0); /* Cause falling edge while data settles. */
midi_data |= (portman_read_status(pm) >> 7) & 1;
portman_write_data(pm, 1); /* Cause rising edge, which shifts data. */
portman_write_data(pm, 0); /* Return data clock low. */
/* De-assert Strobe and return data. */
portman_write_command(pm, cmdout); /* Output saved address+IE. */
/* Wait for strobe echo. */
while ((portman_read_status(pm) & ESTB) == ESTB)
cpu_relax();
return (midi_data & 255); /* Shift back and return value. */
}
/*
* Checks if any input data on the given channel is available
* Checks RxAvail
*/
static int portman_data_avail(struct portman *pm, int channel)
{
int command = INT_EN;
switch (channel) {
case 0:
command |= RXDATA0;
break;
case 1:
command |= RXDATA1;
break;
}
/* Write hardware (assumme STROBE=0) */
portman_write_command(pm, command);
/* Check multiplexed RxAvail signal */
if ((portman_read_status(pm) & RXAVAIL) == RXAVAIL)
return 1; /* Data available */
/* No Data available */
return 0;
}
/*
* Flushes any input
*/
static void portman_flush_input(struct portman *pm, unsigned char port)
{
/* Local variable for counting things */
unsigned int i = 0;
unsigned char command = 0;
switch (port) {
case 0:
command = RXDATA0;
break;
case 1:
command = RXDATA1;
break;
default:
snd_printk(KERN_WARNING
"portman_flush_input() Won't flush port %i\n",
port);
return;
}
/* Set address for specified channel in port and allow to settle. */
portman_write_command(pm, command);
/* Assert the Strobe and wait for echo back. */
portman_write_command(pm, command | STROBE);
/* Wait for ESTB */
while ((portman_read_status(pm) & ESTB) == 0)
cpu_relax();
/* Output clock cycles to the Rx circuitry. */
portman_write_data(pm, 0);
/* Flush 250 bits... */
for (i = 0; i < 250; i++) {
portman_write_data(pm, 1);
portman_write_data(pm, 0);
}
/* Deassert the Strobe signal of the port and wait for it to settle. */
portman_write_command(pm, command | INT_EN);
/* Wait for settling */
while ((portman_read_status(pm) & ESTB) == ESTB)
cpu_relax();
}
static int portman_probe(struct parport *p)
{
/* Initialize the parallel port data register. Will set Rx clocks
* low in case we happen to be addressing the Rx ports at this time.
*/
/* 1 */
parport_write_data(p, 0);
/* Initialize the parallel port command register, thus initializing
* hardware handshake lines to midi box:
*
* Strobe = 0
* Interrupt Enable = 0
*/
/* 2 */
parport_write_control(p, 0);
/* Check if Portman PC/P 2x4 is out there. */
/* 3 */
parport_write_control(p, RXDATA0); /* Write Strobe=0 to command reg. */
/* Check for ESTB to be clear */
/* 4 */
if ((parport_read_status(p) & ESTB) == ESTB)
return 1; /* CODE 1 - Strobe Failure. */
/* Set for RXDATA0 where no damage will be done. */
/* 5 */
parport_write_control(p, RXDATA0 + STROBE); /* Write Strobe=1 to command reg. */
/* 6 */
if ((parport_read_status(p) & ESTB) != ESTB)
return 1; /* CODE 1 - Strobe Failure. */
/* 7 */
parport_write_control(p, 0); /* Reset Strobe=0. */
/* Check if Tx circuitry is functioning properly. If initialized
* unit TxEmpty is false, send out char and see if if goes true.
*/
/* 8 */
parport_write_control(p, TXDATA0); /* Tx channel 0, strobe off. */
/* If PCP channel's TxEmpty is set (TxEmpty is read through the PP
* Status Register), then go write data. Else go back and wait.
*/
/* 9 */
if ((parport_read_status(p) & TXEMPTY) == 0)
return 2;
/* Return OK status. */
return 0;
}
static int portman_device_init(struct portman *pm)
{
portman_flush_input(pm, 0);
portman_flush_input(pm, 1);
return 0;
}
/*********************************************************************
* Rawmidi
*********************************************************************/
static int snd_portman_midi_open(struct snd_rawmidi_substream *substream)
{
return 0;
}
static int snd_portman_midi_close(struct snd_rawmidi_substream *substream)
{
return 0;
}
static void snd_portman_midi_input_trigger(struct snd_rawmidi_substream *substream,
int up)
{
struct portman *pm = substream->rmidi->private_data;
unsigned long flags;
spin_lock_irqsave(&pm->reg_lock, flags);
if (up)
pm->mode[substream->number] |= PORTMAN2X4_MODE_INPUT_TRIGGERED;
else
pm->mode[substream->number] &= ~PORTMAN2X4_MODE_INPUT_TRIGGERED;
spin_unlock_irqrestore(&pm->reg_lock, flags);
}
static void snd_portman_midi_output_trigger(struct snd_rawmidi_substream *substream,
int up)
{
struct portman *pm = substream->rmidi->private_data;
unsigned long flags;
unsigned char byte;
spin_lock_irqsave(&pm->reg_lock, flags);
if (up) {
while ((snd_rawmidi_transmit(substream, &byte, 1) == 1))
portman_write_midi(pm, substream->number, byte);
}
spin_unlock_irqrestore(&pm->reg_lock, flags);
}
static struct snd_rawmidi_ops snd_portman_midi_output = {
.open = snd_portman_midi_open,
.close = snd_portman_midi_close,
.trigger = snd_portman_midi_output_trigger,
};
static struct snd_rawmidi_ops snd_portman_midi_input = {
.open = snd_portman_midi_open,
.close = snd_portman_midi_close,
.trigger = snd_portman_midi_input_trigger,
};
/* Create and initialize the rawmidi component */
static int snd_portman_rawmidi_create(struct snd_card *card)
{
struct portman *pm = card->private_data;
struct snd_rawmidi *rmidi;
struct snd_rawmidi_substream *substream;
int err;
err = snd_rawmidi_new(card, CARD_NAME, 0,
PORTMAN_NUM_OUTPUT_PORTS,
PORTMAN_NUM_INPUT_PORTS,
&rmidi);
if (err < 0)
return err;
rmidi->private_data = pm;
strcpy(rmidi->name, CARD_NAME);
rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
SNDRV_RAWMIDI_INFO_INPUT |
SNDRV_RAWMIDI_INFO_DUPLEX;
pm->rmidi = rmidi;
/* register rawmidi ops */
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT,
&snd_portman_midi_output);
snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT,
&snd_portman_midi_input);
/* name substreams */
/* output */
list_for_each_entry(substream,
&rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT].substreams,
list) {
sprintf(substream->name,
"Portman2x4 %d", substream->number+1);
}
/* input */
list_for_each_entry(substream,
&rmidi->streams[SNDRV_RAWMIDI_STREAM_INPUT].substreams,
list) {
pm->midi_input[substream->number] = substream;
sprintf(substream->name,
"Portman2x4 %d", substream->number+1);
}
return err;
}
/*********************************************************************
* parport stuff
*********************************************************************/
static void snd_portman_interrupt(void *userdata)
{
unsigned char midivalue = 0;
struct portman *pm = ((struct snd_card*)userdata)->private_data;
spin_lock(&pm->reg_lock);
/* While any input data is waiting */
while ((portman_read_status(pm) & INT_REQ) == INT_REQ) {
/* If data available on channel 0,
read it and stuff it into the queue. */
if (portman_data_avail(pm, 0)) {
/* Read Midi */
midivalue = portman_read_midi(pm, 0);
/* put midi into queue... */
if (pm->mode[0] & PORTMAN2X4_MODE_INPUT_TRIGGERED)
snd_rawmidi_receive(pm->midi_input[0],
&midivalue, 1);
}
/* If data available on channel 1,
read it and stuff it into the queue. */
if (portman_data_avail(pm, 1)) {
/* Read Midi */
midivalue = portman_read_midi(pm, 1);
/* put midi into queue... */
if (pm->mode[1] & PORTMAN2X4_MODE_INPUT_TRIGGERED)
snd_rawmidi_receive(pm->midi_input[1],
&midivalue, 1);
}
}
spin_unlock(&pm->reg_lock);
}
static int snd_portman_probe_port(struct parport *p)
{
struct pardevice *pardev;
int res;
pardev = parport_register_device(p, DRIVER_NAME,
NULL, NULL, NULL,
0, NULL);
if (!pardev)
return -EIO;
if (parport_claim(pardev)) {
parport_unregister_device(pardev);
return -EIO;
}
res = portman_probe(p);
parport_release(pardev);
parport_unregister_device(pardev);
return res ? -EIO : 0;
}
static void snd_portman_attach(struct parport *p)
{
struct platform_device *device;
device = platform_device_alloc(PLATFORM_DRIVER, device_count);
if (!device)
return;
/* Temporary assignment to forward the parport */
platform_set_drvdata(device, p);
if (platform_device_add(device) < 0) {
platform_device_put(device);
return;
}
/* Since we dont get the return value of probe
* We need to check if device probing succeeded or not */
if (!platform_get_drvdata(device)) {
platform_device_unregister(device);
return;
}
/* register device in global table */
platform_devices[device_count] = device;
device_count++;
}
static void snd_portman_detach(struct parport *p)
{
/* nothing to do here */
}
static struct parport_driver portman_parport_driver = {
.name = "portman2x4",
.attach = snd_portman_attach,
.detach = snd_portman_detach
};
/*********************************************************************
* platform stuff
*********************************************************************/
static void snd_portman_card_private_free(struct snd_card *card)
{
struct portman *pm = card->private_data;
struct pardevice *pardev = pm->pardev;
if (pardev) {
if (pm->pardev_claimed)
parport_release(pardev);
parport_unregister_device(pardev);
}
portman_free(pm);
}
static int snd_portman_probe(struct platform_device *pdev)
{
struct pardevice *pardev;
struct parport *p;
int dev = pdev->id;
struct snd_card *card = NULL;
struct portman *pm = NULL;
int err;
p = platform_get_drvdata(pdev);
platform_set_drvdata(pdev, NULL);
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev])
return -ENOENT;
if ((err = snd_portman_probe_port(p)) < 0)
return err;
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0) {
snd_printd("Cannot create card\n");
return err;
}
strcpy(card->driver, DRIVER_NAME);
strcpy(card->shortname, CARD_NAME);
sprintf(card->longname, "%s at 0x%lx, irq %i",
card->shortname, p->base, p->irq);
pardev = parport_register_device(p, /* port */
DRIVER_NAME, /* name */
NULL, /* preempt */
NULL, /* wakeup */
snd_portman_interrupt, /* ISR */
PARPORT_DEV_EXCL, /* flags */
(void *)card); /* private */
if (pardev == NULL) {
snd_printd("Cannot register pardevice\n");
err = -EIO;
goto __err;
}
if ((err = portman_create(card, pardev, &pm)) < 0) {
snd_printd("Cannot create main component\n");
parport_unregister_device(pardev);
goto __err;
}
card->private_data = pm;
card->private_free = snd_portman_card_private_free;
if ((err = snd_portman_rawmidi_create(card)) < 0) {
snd_printd("Creating Rawmidi component failed\n");
goto __err;
}
/* claim parport */
if (parport_claim(pardev)) {
snd_printd("Cannot claim parport 0x%lx\n", pardev->port->base);
err = -EIO;
goto __err;
}
pm->pardev_claimed = 1;
/* init device */
if ((err = portman_device_init(pm)) < 0)
goto __err;
platform_set_drvdata(pdev, card);
snd_card_set_dev(card, &pdev->dev);
/* At this point card will be usable */
if ((err = snd_card_register(card)) < 0) {
snd_printd("Cannot register card\n");
goto __err;
}
snd_printk(KERN_INFO "Portman 2x4 on 0x%lx\n", p->base);
return 0;
__err:
snd_card_free(card);
return err;
}
static int snd_portman_remove(struct platform_device *pdev)
{
struct snd_card *card = platform_get_drvdata(pdev);
if (card)
snd_card_free(card);
return 0;
}
static struct platform_driver snd_portman_driver = {
.probe = snd_portman_probe,
.remove = snd_portman_remove,
.driver = {
.name = PLATFORM_DRIVER,
.owner = THIS_MODULE,
}
};
/*********************************************************************
* module init stuff
*********************************************************************/
static void snd_portman_unregister_all(void)
{
int i;
for (i = 0; i < SNDRV_CARDS; ++i) {
if (platform_devices[i]) {
platform_device_unregister(platform_devices[i]);
platform_devices[i] = NULL;
}
}
platform_driver_unregister(&snd_portman_driver);
parport_unregister_driver(&portman_parport_driver);
}
static int __init snd_portman_module_init(void)
{
int err;
if ((err = platform_driver_register(&snd_portman_driver)) < 0)
return err;
if (parport_register_driver(&portman_parport_driver) != 0) {
platform_driver_unregister(&snd_portman_driver);
return -EIO;
}
if (device_count == 0) {
snd_portman_unregister_all();
return -ENODEV;
}
return 0;
}
static void __exit snd_portman_module_exit(void)
{
snd_portman_unregister_all();
}
module_init(snd_portman_module_init);
module_exit(snd_portman_module_exit);
| gpl-2.0 |
Alucard24/SGS4-SAMMY-Kernel | arch/arm/mach-s3c64xx/clock.c | 4766 | 23619 | /* linux/arch/arm/plat-s3c64xx/clock.c
*
* Copyright 2008 Openmoko, Inc.
* Copyright 2008 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
* http://armlinux.simtec.co.uk/
*
* S3C64XX Base clock 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/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <mach/map.h>
#include <mach/regs-sys.h>
#include <mach/regs-clock.h>
#include <plat/cpu.h>
#include <plat/devs.h>
#include <plat/cpu-freq.h>
#include <plat/clock.h>
#include <plat/clock-clksrc.h>
#include <plat/pll.h>
/* fin_apll, fin_mpll and fin_epll are all the same clock, which we call
* ext_xtal_mux for want of an actual name from the manual.
*/
static struct clk clk_ext_xtal_mux = {
.name = "ext_xtal",
};
#define clk_fin_apll clk_ext_xtal_mux
#define clk_fin_mpll clk_ext_xtal_mux
#define clk_fin_epll clk_ext_xtal_mux
#define clk_fout_mpll clk_mpll
#define clk_fout_epll clk_epll
struct clk clk_h2 = {
.name = "hclk2",
.rate = 0,
};
struct clk clk_27m = {
.name = "clk_27m",
.rate = 27000000,
};
static int clk_48m_ctrl(struct clk *clk, int enable)
{
unsigned long flags;
u32 val;
/* can't rely on clock lock, this register has other usages */
local_irq_save(flags);
val = __raw_readl(S3C64XX_OTHERS);
if (enable)
val |= S3C64XX_OTHERS_USBMASK;
else
val &= ~S3C64XX_OTHERS_USBMASK;
__raw_writel(val, S3C64XX_OTHERS);
local_irq_restore(flags);
return 0;
}
struct clk clk_48m = {
.name = "clk_48m",
.rate = 48000000,
.enable = clk_48m_ctrl,
};
struct clk clk_xusbxti = {
.name = "xusbxti",
.rate = 48000000,
};
static int inline s3c64xx_gate(void __iomem *reg,
struct clk *clk,
int enable)
{
unsigned int ctrlbit = clk->ctrlbit;
u32 con;
con = __raw_readl(reg);
if (enable)
con |= ctrlbit;
else
con &= ~ctrlbit;
__raw_writel(con, reg);
return 0;
}
static int s3c64xx_pclk_ctrl(struct clk *clk, int enable)
{
return s3c64xx_gate(S3C_PCLK_GATE, clk, enable);
}
static int s3c64xx_hclk_ctrl(struct clk *clk, int enable)
{
return s3c64xx_gate(S3C_HCLK_GATE, clk, enable);
}
int s3c64xx_sclk_ctrl(struct clk *clk, int enable)
{
return s3c64xx_gate(S3C_SCLK_GATE, clk, enable);
}
static struct clk init_clocks_off[] = {
{
.name = "nand",
.parent = &clk_h,
}, {
.name = "rtc",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_RTC,
}, {
.name = "adc",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_TSADC,
}, {
.name = "i2c",
#ifdef CONFIG_S3C_DEV_I2C1
.devname = "s3c2440-i2c.0",
#else
.devname = "s3c2440-i2c",
#endif
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_IIC,
}, {
.name = "i2c",
.devname = "s3c2440-i2c.1",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C6410_CLKCON_PCLK_I2C1,
}, {
.name = "iis",
.devname = "samsung-i2s.0",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_IIS0,
}, {
.name = "iis",
.devname = "samsung-i2s.1",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_IIS1,
}, {
#ifdef CONFIG_CPU_S3C6410
.name = "iis",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C6410_CLKCON_PCLK_IIS2,
}, {
#endif
.name = "keypad",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_KEYPAD,
}, {
.name = "spi",
.devname = "s3c64xx-spi.0",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_SPI0,
}, {
.name = "spi",
.devname = "s3c64xx-spi.1",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_SPI1,
}, {
.name = "48m",
.devname = "s3c-sdhci.0",
.parent = &clk_48m,
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_MMC0_48,
}, {
.name = "48m",
.devname = "s3c-sdhci.1",
.parent = &clk_48m,
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_MMC1_48,
}, {
.name = "48m",
.devname = "s3c-sdhci.2",
.parent = &clk_48m,
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_MMC2_48,
}, {
.name = "ac97",
.parent = &clk_p,
.ctrlbit = S3C_CLKCON_PCLK_AC97,
}, {
.name = "cfcon",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_IHOST,
}, {
.name = "dma0",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_DMA0,
}, {
.name = "dma1",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_DMA1,
}, {
.name = "3dse",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_3DSE,
}, {
.name = "hclk_secur",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_SECUR,
}, {
.name = "sdma1",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_SDMA1,
}, {
.name = "sdma0",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_SDMA0,
}, {
.name = "hclk_jpeg",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_JPEG,
}, {
.name = "camif",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_CAMIF,
}, {
.name = "hclk_scaler",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_SCALER,
}, {
.name = "2d",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_2D,
}, {
.name = "tv",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_TV,
}, {
.name = "post0",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_POST0,
}, {
.name = "rot",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_ROT,
}, {
.name = "hclk_mfc",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_MFC,
}, {
.name = "pclk_mfc",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_MFC,
}, {
.name = "dac27",
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_DAC27,
}, {
.name = "tv27",
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_TV27,
}, {
.name = "scaler27",
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_SCALER27,
}, {
.name = "sclk_scaler",
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_SCALER,
}, {
.name = "post0_27",
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_POST0_27,
}, {
.name = "secur",
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_SECUR,
}, {
.name = "sclk_mfc",
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_MFC,
}, {
.name = "cam",
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_CAM,
}, {
.name = "sclk_jpeg",
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_JPEG,
},
};
static struct clk clk_48m_spi0 = {
.name = "spi_48m",
.devname = "s3c64xx-spi.0",
.parent = &clk_48m,
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_SPI0_48,
};
static struct clk clk_48m_spi1 = {
.name = "spi_48m",
.devname = "s3c64xx-spi.1",
.parent = &clk_48m,
.enable = s3c64xx_sclk_ctrl,
.ctrlbit = S3C_CLKCON_SCLK_SPI1_48,
};
static struct clk init_clocks[] = {
{
.name = "lcd",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_LCD,
}, {
.name = "gpio",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_GPIO,
}, {
.name = "usb-host",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_UHOST,
}, {
.name = "otg",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_USB,
}, {
.name = "timers",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_PWM,
}, {
.name = "uart",
.devname = "s3c6400-uart.0",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_UART0,
}, {
.name = "uart",
.devname = "s3c6400-uart.1",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_UART1,
}, {
.name = "uart",
.devname = "s3c6400-uart.2",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_UART2,
}, {
.name = "uart",
.devname = "s3c6400-uart.3",
.parent = &clk_p,
.enable = s3c64xx_pclk_ctrl,
.ctrlbit = S3C_CLKCON_PCLK_UART3,
}, {
.name = "watchdog",
.parent = &clk_p,
.ctrlbit = S3C_CLKCON_PCLK_WDT,
},
};
static struct clk clk_hsmmc0 = {
.name = "hsmmc",
.devname = "s3c-sdhci.0",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_HSMMC0,
};
static struct clk clk_hsmmc1 = {
.name = "hsmmc",
.devname = "s3c-sdhci.1",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_HSMMC1,
};
static struct clk clk_hsmmc2 = {
.name = "hsmmc",
.devname = "s3c-sdhci.2",
.parent = &clk_h,
.enable = s3c64xx_hclk_ctrl,
.ctrlbit = S3C_CLKCON_HCLK_HSMMC2,
};
static struct clk clk_fout_apll = {
.name = "fout_apll",
};
static struct clk *clk_src_apll_list[] = {
[0] = &clk_fin_apll,
[1] = &clk_fout_apll,
};
static struct clksrc_sources clk_src_apll = {
.sources = clk_src_apll_list,
.nr_sources = ARRAY_SIZE(clk_src_apll_list),
};
static struct clksrc_clk clk_mout_apll = {
.clk = {
.name = "mout_apll",
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 0, .size = 1 },
.sources = &clk_src_apll,
};
static struct clk *clk_src_epll_list[] = {
[0] = &clk_fin_epll,
[1] = &clk_fout_epll,
};
static struct clksrc_sources clk_src_epll = {
.sources = clk_src_epll_list,
.nr_sources = ARRAY_SIZE(clk_src_epll_list),
};
static struct clksrc_clk clk_mout_epll = {
.clk = {
.name = "mout_epll",
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 2, .size = 1 },
.sources = &clk_src_epll,
};
static struct clk *clk_src_mpll_list[] = {
[0] = &clk_fin_mpll,
[1] = &clk_fout_mpll,
};
static struct clksrc_sources clk_src_mpll = {
.sources = clk_src_mpll_list,
.nr_sources = ARRAY_SIZE(clk_src_mpll_list),
};
static struct clksrc_clk clk_mout_mpll = {
.clk = {
.name = "mout_mpll",
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 1, .size = 1 },
.sources = &clk_src_mpll,
};
static unsigned int armclk_mask;
static unsigned long s3c64xx_clk_arm_get_rate(struct clk *clk)
{
unsigned long rate = clk_get_rate(clk->parent);
u32 clkdiv;
/* divisor mask starts at bit0, so no need to shift */
clkdiv = __raw_readl(S3C_CLK_DIV0) & armclk_mask;
return rate / (clkdiv + 1);
}
static unsigned long s3c64xx_clk_arm_round_rate(struct clk *clk,
unsigned long rate)
{
unsigned long parent = clk_get_rate(clk->parent);
u32 div;
if (parent < rate)
return parent;
div = (parent / rate) - 1;
if (div > armclk_mask)
div = armclk_mask;
return parent / (div + 1);
}
static int s3c64xx_clk_arm_set_rate(struct clk *clk, unsigned long rate)
{
unsigned long parent = clk_get_rate(clk->parent);
u32 div;
u32 val;
if (rate < parent / (armclk_mask + 1))
return -EINVAL;
rate = clk_round_rate(clk, rate);
div = clk_get_rate(clk->parent) / rate;
val = __raw_readl(S3C_CLK_DIV0);
val &= ~armclk_mask;
val |= (div - 1);
__raw_writel(val, S3C_CLK_DIV0);
return 0;
}
static struct clk clk_arm = {
.name = "armclk",
.parent = &clk_mout_apll.clk,
.ops = &(struct clk_ops) {
.get_rate = s3c64xx_clk_arm_get_rate,
.set_rate = s3c64xx_clk_arm_set_rate,
.round_rate = s3c64xx_clk_arm_round_rate,
},
};
static unsigned long s3c64xx_clk_doutmpll_get_rate(struct clk *clk)
{
unsigned long rate = clk_get_rate(clk->parent);
printk(KERN_DEBUG "%s: parent is %ld\n", __func__, rate);
if (__raw_readl(S3C_CLK_DIV0) & S3C6400_CLKDIV0_MPLL_MASK)
rate /= 2;
return rate;
}
static struct clk_ops clk_dout_ops = {
.get_rate = s3c64xx_clk_doutmpll_get_rate,
};
static struct clk clk_dout_mpll = {
.name = "dout_mpll",
.parent = &clk_mout_mpll.clk,
.ops = &clk_dout_ops,
};
static struct clk *clkset_spi_mmc_list[] = {
&clk_mout_epll.clk,
&clk_dout_mpll,
&clk_fin_epll,
&clk_27m,
};
static struct clksrc_sources clkset_spi_mmc = {
.sources = clkset_spi_mmc_list,
.nr_sources = ARRAY_SIZE(clkset_spi_mmc_list),
};
static struct clk *clkset_irda_list[] = {
&clk_mout_epll.clk,
&clk_dout_mpll,
NULL,
&clk_27m,
};
static struct clksrc_sources clkset_irda = {
.sources = clkset_irda_list,
.nr_sources = ARRAY_SIZE(clkset_irda_list),
};
static struct clk *clkset_uart_list[] = {
&clk_mout_epll.clk,
&clk_dout_mpll,
NULL,
NULL
};
static struct clksrc_sources clkset_uart = {
.sources = clkset_uart_list,
.nr_sources = ARRAY_SIZE(clkset_uart_list),
};
static struct clk *clkset_uhost_list[] = {
&clk_48m,
&clk_mout_epll.clk,
&clk_dout_mpll,
&clk_fin_epll,
};
static struct clksrc_sources clkset_uhost = {
.sources = clkset_uhost_list,
.nr_sources = ARRAY_SIZE(clkset_uhost_list),
};
/* The peripheral clocks are all controlled via clocksource followed
* by an optional divider and gate stage. We currently roll this into
* one clock which hides the intermediate clock from the mux.
*
* Note, the JPEG clock can only be an even divider...
*
* The scaler and LCD clocks depend on the S3C64XX version, and also
* have a common parent divisor so are not included here.
*/
/* clocks that feed other parts of the clock source tree */
static struct clk clk_iis_cd0 = {
.name = "iis_cdclk0",
};
static struct clk clk_iis_cd1 = {
.name = "iis_cdclk1",
};
static struct clk clk_iisv4_cd = {
.name = "iis_cdclk_v4",
};
static struct clk clk_pcm_cd = {
.name = "pcm_cdclk",
};
static struct clk *clkset_audio0_list[] = {
[0] = &clk_mout_epll.clk,
[1] = &clk_dout_mpll,
[2] = &clk_fin_epll,
[3] = &clk_iis_cd0,
[4] = &clk_pcm_cd,
};
static struct clksrc_sources clkset_audio0 = {
.sources = clkset_audio0_list,
.nr_sources = ARRAY_SIZE(clkset_audio0_list),
};
static struct clk *clkset_audio1_list[] = {
[0] = &clk_mout_epll.clk,
[1] = &clk_dout_mpll,
[2] = &clk_fin_epll,
[3] = &clk_iis_cd1,
[4] = &clk_pcm_cd,
};
static struct clksrc_sources clkset_audio1 = {
.sources = clkset_audio1_list,
.nr_sources = ARRAY_SIZE(clkset_audio1_list),
};
static struct clk *clkset_audio2_list[] = {
[0] = &clk_mout_epll.clk,
[1] = &clk_dout_mpll,
[2] = &clk_fin_epll,
[3] = &clk_iisv4_cd,
[4] = &clk_pcm_cd,
};
static struct clksrc_sources clkset_audio2 = {
.sources = clkset_audio2_list,
.nr_sources = ARRAY_SIZE(clkset_audio2_list),
};
static struct clk *clkset_camif_list[] = {
&clk_h2,
};
static struct clksrc_sources clkset_camif = {
.sources = clkset_camif_list,
.nr_sources = ARRAY_SIZE(clkset_camif_list),
};
static struct clksrc_clk clksrcs[] = {
{
.clk = {
.name = "usb-bus-host",
.ctrlbit = S3C_CLKCON_SCLK_UHOST,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 5, .size = 2 },
.reg_div = { .reg = S3C_CLK_DIV1, .shift = 20, .size = 4 },
.sources = &clkset_uhost,
}, {
.clk = {
.name = "audio-bus",
.devname = "samsung-i2s.0",
.ctrlbit = S3C_CLKCON_SCLK_AUDIO0,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 7, .size = 3 },
.reg_div = { .reg = S3C_CLK_DIV2, .shift = 8, .size = 4 },
.sources = &clkset_audio0,
}, {
.clk = {
.name = "audio-bus",
.devname = "samsung-i2s.1",
.ctrlbit = S3C_CLKCON_SCLK_AUDIO1,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 10, .size = 3 },
.reg_div = { .reg = S3C_CLK_DIV2, .shift = 12, .size = 4 },
.sources = &clkset_audio1,
}, {
.clk = {
.name = "audio-bus",
.devname = "samsung-i2s.2",
.ctrlbit = S3C6410_CLKCON_SCLK_AUDIO2,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C6410_CLK_SRC2, .shift = 0, .size = 3 },
.reg_div = { .reg = S3C_CLK_DIV2, .shift = 24, .size = 4 },
.sources = &clkset_audio2,
}, {
.clk = {
.name = "irda-bus",
.ctrlbit = S3C_CLKCON_SCLK_IRDA,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 24, .size = 2 },
.reg_div = { .reg = S3C_CLK_DIV2, .shift = 20, .size = 4 },
.sources = &clkset_irda,
}, {
.clk = {
.name = "camera",
.ctrlbit = S3C_CLKCON_SCLK_CAM,
.enable = s3c64xx_sclk_ctrl,
},
.reg_div = { .reg = S3C_CLK_DIV0, .shift = 20, .size = 4 },
.reg_src = { .reg = NULL, .shift = 0, .size = 0 },
.sources = &clkset_camif,
},
};
/* Where does UCLK0 come from? */
static struct clksrc_clk clk_sclk_uclk = {
.clk = {
.name = "uclk1",
.ctrlbit = S3C_CLKCON_SCLK_UART,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 13, .size = 1 },
.reg_div = { .reg = S3C_CLK_DIV2, .shift = 16, .size = 4 },
.sources = &clkset_uart,
};
static struct clksrc_clk clk_sclk_mmc0 = {
.clk = {
.name = "mmc_bus",
.devname = "s3c-sdhci.0",
.ctrlbit = S3C_CLKCON_SCLK_MMC0,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 18, .size = 2 },
.reg_div = { .reg = S3C_CLK_DIV1, .shift = 0, .size = 4 },
.sources = &clkset_spi_mmc,
};
static struct clksrc_clk clk_sclk_mmc1 = {
.clk = {
.name = "mmc_bus",
.devname = "s3c-sdhci.1",
.ctrlbit = S3C_CLKCON_SCLK_MMC1,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 20, .size = 2 },
.reg_div = { .reg = S3C_CLK_DIV1, .shift = 4, .size = 4 },
.sources = &clkset_spi_mmc,
};
static struct clksrc_clk clk_sclk_mmc2 = {
.clk = {
.name = "mmc_bus",
.devname = "s3c-sdhci.2",
.ctrlbit = S3C_CLKCON_SCLK_MMC2,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 22, .size = 2 },
.reg_div = { .reg = S3C_CLK_DIV1, .shift = 8, .size = 4 },
.sources = &clkset_spi_mmc,
};
static struct clksrc_clk clk_sclk_spi0 = {
.clk = {
.name = "spi-bus",
.devname = "s3c64xx-spi.0",
.ctrlbit = S3C_CLKCON_SCLK_SPI0,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 14, .size = 2 },
.reg_div = { .reg = S3C_CLK_DIV2, .shift = 0, .size = 4 },
.sources = &clkset_spi_mmc,
};
static struct clksrc_clk clk_sclk_spi1 = {
.clk = {
.name = "spi-bus",
.devname = "s3c64xx-spi.1",
.ctrlbit = S3C_CLKCON_SCLK_SPI1,
.enable = s3c64xx_sclk_ctrl,
},
.reg_src = { .reg = S3C_CLK_SRC, .shift = 16, .size = 2 },
.reg_div = { .reg = S3C_CLK_DIV2, .shift = 4, .size = 4 },
.sources = &clkset_spi_mmc,
};
/* Clock initialisation code */
static struct clksrc_clk *init_parents[] = {
&clk_mout_apll,
&clk_mout_epll,
&clk_mout_mpll,
};
static struct clksrc_clk *clksrc_cdev[] = {
&clk_sclk_uclk,
&clk_sclk_mmc0,
&clk_sclk_mmc1,
&clk_sclk_mmc2,
&clk_sclk_spi0,
&clk_sclk_spi1,
};
static struct clk *clk_cdev[] = {
&clk_hsmmc0,
&clk_hsmmc1,
&clk_hsmmc2,
&clk_48m_spi0,
&clk_48m_spi1,
};
static struct clk_lookup s3c64xx_clk_lookup[] = {
CLKDEV_INIT(NULL, "clk_uart_baud2", &clk_p),
CLKDEV_INIT(NULL, "clk_uart_baud3", &clk_sclk_uclk.clk),
CLKDEV_INIT("s3c-sdhci.0", "mmc_busclk.0", &clk_hsmmc0),
CLKDEV_INIT("s3c-sdhci.1", "mmc_busclk.0", &clk_hsmmc1),
CLKDEV_INIT("s3c-sdhci.2", "mmc_busclk.0", &clk_hsmmc2),
CLKDEV_INIT("s3c-sdhci.0", "mmc_busclk.2", &clk_sclk_mmc0.clk),
CLKDEV_INIT("s3c-sdhci.1", "mmc_busclk.2", &clk_sclk_mmc1.clk),
CLKDEV_INIT("s3c-sdhci.2", "mmc_busclk.2", &clk_sclk_mmc2.clk),
CLKDEV_INIT(NULL, "spi_busclk0", &clk_p),
CLKDEV_INIT("s3c64xx-spi.0", "spi_busclk1", &clk_sclk_spi0.clk),
CLKDEV_INIT("s3c64xx-spi.0", "spi_busclk2", &clk_48m_spi0),
CLKDEV_INIT("s3c64xx-spi.1", "spi_busclk1", &clk_sclk_spi1.clk),
CLKDEV_INIT("s3c64xx-spi.1", "spi_busclk2", &clk_48m_spi1),
};
#define GET_DIV(clk, field) ((((clk) & field##_MASK) >> field##_SHIFT) + 1)
void __init_or_cpufreq s3c64xx_setup_clocks(void)
{
struct clk *xtal_clk;
unsigned long xtal;
unsigned long fclk;
unsigned long hclk;
unsigned long hclk2;
unsigned long pclk;
unsigned long epll;
unsigned long apll;
unsigned long mpll;
unsigned int ptr;
u32 clkdiv0;
printk(KERN_DEBUG "%s: registering clocks\n", __func__);
clkdiv0 = __raw_readl(S3C_CLK_DIV0);
printk(KERN_DEBUG "%s: clkdiv0 = %08x\n", __func__, clkdiv0);
xtal_clk = clk_get(NULL, "xtal");
BUG_ON(IS_ERR(xtal_clk));
xtal = clk_get_rate(xtal_clk);
clk_put(xtal_clk);
printk(KERN_DEBUG "%s: xtal is %ld\n", __func__, xtal);
/* For now assume the mux always selects the crystal */
clk_ext_xtal_mux.parent = xtal_clk;
epll = s3c_get_pll6553x(xtal, __raw_readl(S3C_EPLL_CON0),
__raw_readl(S3C_EPLL_CON1));
mpll = s3c6400_get_pll(xtal, __raw_readl(S3C_MPLL_CON));
apll = s3c6400_get_pll(xtal, __raw_readl(S3C_APLL_CON));
fclk = mpll;
printk(KERN_INFO "S3C64XX: PLL settings, A=%ld, M=%ld, E=%ld\n",
apll, mpll, epll);
if(__raw_readl(S3C64XX_OTHERS) & S3C64XX_OTHERS_SYNCMUXSEL)
/* Synchronous mode */
hclk2 = apll / GET_DIV(clkdiv0, S3C6400_CLKDIV0_HCLK2);
else
/* Asynchronous mode */
hclk2 = mpll / GET_DIV(clkdiv0, S3C6400_CLKDIV0_HCLK2);
hclk = hclk2 / GET_DIV(clkdiv0, S3C6400_CLKDIV0_HCLK);
pclk = hclk2 / GET_DIV(clkdiv0, S3C6400_CLKDIV0_PCLK);
printk(KERN_INFO "S3C64XX: HCLK2=%ld, HCLK=%ld, PCLK=%ld\n",
hclk2, hclk, pclk);
clk_fout_mpll.rate = mpll;
clk_fout_epll.rate = epll;
clk_fout_apll.rate = apll;
clk_h2.rate = hclk2;
clk_h.rate = hclk;
clk_p.rate = pclk;
clk_f.rate = fclk;
for (ptr = 0; ptr < ARRAY_SIZE(init_parents); ptr++)
s3c_set_clksrc(init_parents[ptr], true);
for (ptr = 0; ptr < ARRAY_SIZE(clksrcs); ptr++)
s3c_set_clksrc(&clksrcs[ptr], true);
}
static struct clk *clks1[] __initdata = {
&clk_ext_xtal_mux,
&clk_iis_cd0,
&clk_iis_cd1,
&clk_iisv4_cd,
&clk_pcm_cd,
&clk_mout_epll.clk,
&clk_mout_mpll.clk,
&clk_dout_mpll,
&clk_arm,
};
static struct clk *clks[] __initdata = {
&clk_ext,
&clk_epll,
&clk_27m,
&clk_48m,
&clk_h2,
&clk_xusbxti,
};
/**
* s3c64xx_register_clocks - register clocks for s3c6400 and s3c6410
* @xtal: The rate for the clock crystal feeding the PLLs.
* @armclk_divlimit: Divisor mask for ARMCLK.
*
* Register the clocks for the S3C6400 and S3C6410 SoC range, such
* as ARMCLK as well as the necessary parent clocks.
*
* This call does not setup the clocks, which is left to the
* s3c64xx_setup_clocks() call which may be needed by the cpufreq
* or resume code to re-set the clocks if the bootloader has changed
* them.
*/
void __init s3c64xx_register_clocks(unsigned long xtal,
unsigned armclk_divlimit)
{
unsigned int cnt;
armclk_mask = armclk_divlimit;
s3c24xx_register_baseclocks(xtal);
s3c24xx_register_clocks(clks, ARRAY_SIZE(clks));
s3c_register_clocks(init_clocks, ARRAY_SIZE(init_clocks));
s3c_register_clocks(init_clocks_off, ARRAY_SIZE(init_clocks_off));
s3c_disable_clocks(init_clocks_off, ARRAY_SIZE(init_clocks_off));
s3c24xx_register_clocks(clk_cdev, ARRAY_SIZE(clk_cdev));
for (cnt = 0; cnt < ARRAY_SIZE(clk_cdev); cnt++)
s3c_disable_clocks(clk_cdev[cnt], 1);
s3c24xx_register_clocks(clks1, ARRAY_SIZE(clks1));
s3c_register_clksrc(clksrcs, ARRAY_SIZE(clksrcs));
for (cnt = 0; cnt < ARRAY_SIZE(clksrc_cdev); cnt++)
s3c_register_clksrc(clksrc_cdev[cnt], 1);
clkdev_add_table(s3c64xx_clk_lookup, ARRAY_SIZE(s3c64xx_clk_lookup));
s3c_pwmclk_init();
}
| gpl-2.0 |
moddingg33k/android_kernel_synopsis_backup | lib/locking-selftest.c | 5022 | 29290 | /*
* lib/locking-selftest.c
*
* Testsuite for various locking APIs: spinlocks, rwlocks,
* mutexes and rw-semaphores.
*
* It is checking both false positives and false negatives.
*
* Started by Ingo Molnar:
*
* Copyright (C) 2006 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
*/
#include <linux/rwsem.h>
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/lockdep.h>
#include <linux/spinlock.h>
#include <linux/kallsyms.h>
#include <linux/interrupt.h>
#include <linux/debug_locks.h>
#include <linux/irqflags.h>
/*
* Change this to 1 if you want to see the failure printouts:
*/
static unsigned int debug_locks_verbose;
static int __init setup_debug_locks_verbose(char *str)
{
get_option(&str, &debug_locks_verbose);
return 1;
}
__setup("debug_locks_verbose=", setup_debug_locks_verbose);
#define FAILURE 0
#define SUCCESS 1
#define LOCKTYPE_SPIN 0x1
#define LOCKTYPE_RWLOCK 0x2
#define LOCKTYPE_MUTEX 0x4
#define LOCKTYPE_RWSEM 0x8
/*
* Normal standalone locks, for the circular and irq-context
* dependency tests:
*/
static DEFINE_SPINLOCK(lock_A);
static DEFINE_SPINLOCK(lock_B);
static DEFINE_SPINLOCK(lock_C);
static DEFINE_SPINLOCK(lock_D);
static DEFINE_RWLOCK(rwlock_A);
static DEFINE_RWLOCK(rwlock_B);
static DEFINE_RWLOCK(rwlock_C);
static DEFINE_RWLOCK(rwlock_D);
static DEFINE_MUTEX(mutex_A);
static DEFINE_MUTEX(mutex_B);
static DEFINE_MUTEX(mutex_C);
static DEFINE_MUTEX(mutex_D);
static DECLARE_RWSEM(rwsem_A);
static DECLARE_RWSEM(rwsem_B);
static DECLARE_RWSEM(rwsem_C);
static DECLARE_RWSEM(rwsem_D);
/*
* Locks that we initialize dynamically as well so that
* e.g. X1 and X2 becomes two instances of the same class,
* but X* and Y* are different classes. We do this so that
* we do not trigger a real lockup:
*/
static DEFINE_SPINLOCK(lock_X1);
static DEFINE_SPINLOCK(lock_X2);
static DEFINE_SPINLOCK(lock_Y1);
static DEFINE_SPINLOCK(lock_Y2);
static DEFINE_SPINLOCK(lock_Z1);
static DEFINE_SPINLOCK(lock_Z2);
static DEFINE_RWLOCK(rwlock_X1);
static DEFINE_RWLOCK(rwlock_X2);
static DEFINE_RWLOCK(rwlock_Y1);
static DEFINE_RWLOCK(rwlock_Y2);
static DEFINE_RWLOCK(rwlock_Z1);
static DEFINE_RWLOCK(rwlock_Z2);
static DEFINE_MUTEX(mutex_X1);
static DEFINE_MUTEX(mutex_X2);
static DEFINE_MUTEX(mutex_Y1);
static DEFINE_MUTEX(mutex_Y2);
static DEFINE_MUTEX(mutex_Z1);
static DEFINE_MUTEX(mutex_Z2);
static DECLARE_RWSEM(rwsem_X1);
static DECLARE_RWSEM(rwsem_X2);
static DECLARE_RWSEM(rwsem_Y1);
static DECLARE_RWSEM(rwsem_Y2);
static DECLARE_RWSEM(rwsem_Z1);
static DECLARE_RWSEM(rwsem_Z2);
/*
* non-inlined runtime initializers, to let separate locks share
* the same lock-class:
*/
#define INIT_CLASS_FUNC(class) \
static noinline void \
init_class_##class(spinlock_t *lock, rwlock_t *rwlock, struct mutex *mutex, \
struct rw_semaphore *rwsem) \
{ \
spin_lock_init(lock); \
rwlock_init(rwlock); \
mutex_init(mutex); \
init_rwsem(rwsem); \
}
INIT_CLASS_FUNC(X)
INIT_CLASS_FUNC(Y)
INIT_CLASS_FUNC(Z)
static void init_shared_classes(void)
{
init_class_X(&lock_X1, &rwlock_X1, &mutex_X1, &rwsem_X1);
init_class_X(&lock_X2, &rwlock_X2, &mutex_X2, &rwsem_X2);
init_class_Y(&lock_Y1, &rwlock_Y1, &mutex_Y1, &rwsem_Y1);
init_class_Y(&lock_Y2, &rwlock_Y2, &mutex_Y2, &rwsem_Y2);
init_class_Z(&lock_Z1, &rwlock_Z1, &mutex_Z1, &rwsem_Z1);
init_class_Z(&lock_Z2, &rwlock_Z2, &mutex_Z2, &rwsem_Z2);
}
/*
* For spinlocks and rwlocks we also do hardirq-safe / softirq-safe tests.
* The following functions use a lock from a simulated hardirq/softirq
* context, causing the locks to be marked as hardirq-safe/softirq-safe:
*/
#define HARDIRQ_DISABLE local_irq_disable
#define HARDIRQ_ENABLE local_irq_enable
#define HARDIRQ_ENTER() \
local_irq_disable(); \
__irq_enter(); \
WARN_ON(!in_irq());
#define HARDIRQ_EXIT() \
__irq_exit(); \
local_irq_enable();
#define SOFTIRQ_DISABLE local_bh_disable
#define SOFTIRQ_ENABLE local_bh_enable
#define SOFTIRQ_ENTER() \
local_bh_disable(); \
local_irq_disable(); \
lockdep_softirq_enter(); \
WARN_ON(!in_softirq());
#define SOFTIRQ_EXIT() \
lockdep_softirq_exit(); \
local_irq_enable(); \
local_bh_enable();
/*
* Shortcuts for lock/unlock API variants, to keep
* the testcases compact:
*/
#define L(x) spin_lock(&lock_##x)
#define U(x) spin_unlock(&lock_##x)
#define LU(x) L(x); U(x)
#define SI(x) spin_lock_init(&lock_##x)
#define WL(x) write_lock(&rwlock_##x)
#define WU(x) write_unlock(&rwlock_##x)
#define WLU(x) WL(x); WU(x)
#define RL(x) read_lock(&rwlock_##x)
#define RU(x) read_unlock(&rwlock_##x)
#define RLU(x) RL(x); RU(x)
#define RWI(x) rwlock_init(&rwlock_##x)
#define ML(x) mutex_lock(&mutex_##x)
#define MU(x) mutex_unlock(&mutex_##x)
#define MI(x) mutex_init(&mutex_##x)
#define WSL(x) down_write(&rwsem_##x)
#define WSU(x) up_write(&rwsem_##x)
#define RSL(x) down_read(&rwsem_##x)
#define RSU(x) up_read(&rwsem_##x)
#define RWSI(x) init_rwsem(&rwsem_##x)
#define LOCK_UNLOCK_2(x,y) LOCK(x); LOCK(y); UNLOCK(y); UNLOCK(x)
/*
* Generate different permutations of the same testcase, using
* the same basic lock-dependency/state events:
*/
#define GENERATE_TESTCASE(name) \
\
static void name(void) { E(); }
#define GENERATE_PERMUTATIONS_2_EVENTS(name) \
\
static void name##_12(void) { E1(); E2(); } \
static void name##_21(void) { E2(); E1(); }
#define GENERATE_PERMUTATIONS_3_EVENTS(name) \
\
static void name##_123(void) { E1(); E2(); E3(); } \
static void name##_132(void) { E1(); E3(); E2(); } \
static void name##_213(void) { E2(); E1(); E3(); } \
static void name##_231(void) { E2(); E3(); E1(); } \
static void name##_312(void) { E3(); E1(); E2(); } \
static void name##_321(void) { E3(); E2(); E1(); }
/*
* AA deadlock:
*/
#define E() \
\
LOCK(X1); \
LOCK(X2); /* this one should fail */
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(AA_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(AA_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(AA_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(AA_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(AA_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(AA_rsem)
#undef E
/*
* Special-case for read-locking, they are
* allowed to recurse on the same lock class:
*/
static void rlock_AA1(void)
{
RL(X1);
RL(X1); // this one should NOT fail
}
static void rlock_AA1B(void)
{
RL(X1);
RL(X2); // this one should NOT fail
}
static void rsem_AA1(void)
{
RSL(X1);
RSL(X1); // this one should fail
}
static void rsem_AA1B(void)
{
RSL(X1);
RSL(X2); // this one should fail
}
/*
* The mixing of read and write locks is not allowed:
*/
static void rlock_AA2(void)
{
RL(X1);
WL(X2); // this one should fail
}
static void rsem_AA2(void)
{
RSL(X1);
WSL(X2); // this one should fail
}
static void rlock_AA3(void)
{
WL(X1);
RL(X2); // this one should fail
}
static void rsem_AA3(void)
{
WSL(X1);
RSL(X2); // this one should fail
}
/*
* ABBA deadlock:
*/
#define E() \
\
LOCK_UNLOCK_2(A, B); \
LOCK_UNLOCK_2(B, A); /* fail */
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(ABBA_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(ABBA_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(ABBA_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(ABBA_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(ABBA_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(ABBA_rsem)
#undef E
/*
* AB BC CA deadlock:
*/
#define E() \
\
LOCK_UNLOCK_2(A, B); \
LOCK_UNLOCK_2(B, C); \
LOCK_UNLOCK_2(C, A); /* fail */
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(ABBCCA_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(ABBCCA_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(ABBCCA_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(ABBCCA_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(ABBCCA_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(ABBCCA_rsem)
#undef E
/*
* AB CA BC deadlock:
*/
#define E() \
\
LOCK_UNLOCK_2(A, B); \
LOCK_UNLOCK_2(C, A); \
LOCK_UNLOCK_2(B, C); /* fail */
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(ABCABC_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(ABCABC_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(ABCABC_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(ABCABC_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(ABCABC_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(ABCABC_rsem)
#undef E
/*
* AB BC CD DA deadlock:
*/
#define E() \
\
LOCK_UNLOCK_2(A, B); \
LOCK_UNLOCK_2(B, C); \
LOCK_UNLOCK_2(C, D); \
LOCK_UNLOCK_2(D, A); /* fail */
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(ABBCCDDA_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(ABBCCDDA_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(ABBCCDDA_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(ABBCCDDA_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(ABBCCDDA_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(ABBCCDDA_rsem)
#undef E
/*
* AB CD BD DA deadlock:
*/
#define E() \
\
LOCK_UNLOCK_2(A, B); \
LOCK_UNLOCK_2(C, D); \
LOCK_UNLOCK_2(B, D); \
LOCK_UNLOCK_2(D, A); /* fail */
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(ABCDBDDA_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(ABCDBDDA_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(ABCDBDDA_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(ABCDBDDA_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(ABCDBDDA_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(ABCDBDDA_rsem)
#undef E
/*
* AB CD BC DA deadlock:
*/
#define E() \
\
LOCK_UNLOCK_2(A, B); \
LOCK_UNLOCK_2(C, D); \
LOCK_UNLOCK_2(B, C); \
LOCK_UNLOCK_2(D, A); /* fail */
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(ABCDBCDA_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(ABCDBCDA_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(ABCDBCDA_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(ABCDBCDA_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(ABCDBCDA_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(ABCDBCDA_rsem)
#undef E
/*
* Double unlock:
*/
#define E() \
\
LOCK(A); \
UNLOCK(A); \
UNLOCK(A); /* fail */
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(double_unlock_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(double_unlock_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(double_unlock_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(double_unlock_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(double_unlock_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(double_unlock_rsem)
#undef E
/*
* Bad unlock ordering:
*/
#define E() \
\
LOCK(A); \
LOCK(B); \
UNLOCK(A); /* fail */ \
UNLOCK(B);
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(bad_unlock_order_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(bad_unlock_order_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(bad_unlock_order_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(bad_unlock_order_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(bad_unlock_order_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(bad_unlock_order_rsem)
#undef E
/*
* initializing a held lock:
*/
#define E() \
\
LOCK(A); \
INIT(A); /* fail */
/*
* 6 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_TESTCASE(init_held_spin)
#include "locking-selftest-wlock.h"
GENERATE_TESTCASE(init_held_wlock)
#include "locking-selftest-rlock.h"
GENERATE_TESTCASE(init_held_rlock)
#include "locking-selftest-mutex.h"
GENERATE_TESTCASE(init_held_mutex)
#include "locking-selftest-wsem.h"
GENERATE_TESTCASE(init_held_wsem)
#include "locking-selftest-rsem.h"
GENERATE_TESTCASE(init_held_rsem)
#undef E
/*
* locking an irq-safe lock with irqs enabled:
*/
#define E1() \
\
IRQ_ENTER(); \
LOCK(A); \
UNLOCK(A); \
IRQ_EXIT();
#define E2() \
\
LOCK(A); \
UNLOCK(A);
/*
* Generate 24 testcases:
*/
#include "locking-selftest-spin-hardirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_hard_spin)
#include "locking-selftest-rlock-hardirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_hard_rlock)
#include "locking-selftest-wlock-hardirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_hard_wlock)
#include "locking-selftest-spin-softirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_soft_spin)
#include "locking-selftest-rlock-softirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_soft_rlock)
#include "locking-selftest-wlock-softirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe1_soft_wlock)
#undef E1
#undef E2
/*
* Enabling hardirqs with a softirq-safe lock held:
*/
#define E1() \
\
SOFTIRQ_ENTER(); \
LOCK(A); \
UNLOCK(A); \
SOFTIRQ_EXIT();
#define E2() \
\
HARDIRQ_DISABLE(); \
LOCK(A); \
HARDIRQ_ENABLE(); \
UNLOCK(A);
/*
* Generate 12 testcases:
*/
#include "locking-selftest-spin.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2A_spin)
#include "locking-selftest-wlock.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2A_wlock)
#include "locking-selftest-rlock.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2A_rlock)
#undef E1
#undef E2
/*
* Enabling irqs with an irq-safe lock held:
*/
#define E1() \
\
IRQ_ENTER(); \
LOCK(A); \
UNLOCK(A); \
IRQ_EXIT();
#define E2() \
\
IRQ_DISABLE(); \
LOCK(A); \
IRQ_ENABLE(); \
UNLOCK(A);
/*
* Generate 24 testcases:
*/
#include "locking-selftest-spin-hardirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_hard_spin)
#include "locking-selftest-rlock-hardirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_hard_rlock)
#include "locking-selftest-wlock-hardirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_hard_wlock)
#include "locking-selftest-spin-softirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_soft_spin)
#include "locking-selftest-rlock-softirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_soft_rlock)
#include "locking-selftest-wlock-softirq.h"
GENERATE_PERMUTATIONS_2_EVENTS(irqsafe2B_soft_wlock)
#undef E1
#undef E2
/*
* Acquiring a irq-unsafe lock while holding an irq-safe-lock:
*/
#define E1() \
\
LOCK(A); \
LOCK(B); \
UNLOCK(B); \
UNLOCK(A); \
#define E2() \
\
LOCK(B); \
UNLOCK(B);
#define E3() \
\
IRQ_ENTER(); \
LOCK(A); \
UNLOCK(A); \
IRQ_EXIT();
/*
* Generate 36 testcases:
*/
#include "locking-selftest-spin-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_hard_spin)
#include "locking-selftest-rlock-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_hard_rlock)
#include "locking-selftest-wlock-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_hard_wlock)
#include "locking-selftest-spin-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_soft_spin)
#include "locking-selftest-rlock-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_soft_rlock)
#include "locking-selftest-wlock-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe3_soft_wlock)
#undef E1
#undef E2
#undef E3
/*
* If a lock turns into softirq-safe, but earlier it took
* a softirq-unsafe lock:
*/
#define E1() \
IRQ_DISABLE(); \
LOCK(A); \
LOCK(B); \
UNLOCK(B); \
UNLOCK(A); \
IRQ_ENABLE();
#define E2() \
LOCK(B); \
UNLOCK(B);
#define E3() \
IRQ_ENTER(); \
LOCK(A); \
UNLOCK(A); \
IRQ_EXIT();
/*
* Generate 36 testcases:
*/
#include "locking-selftest-spin-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_hard_spin)
#include "locking-selftest-rlock-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_hard_rlock)
#include "locking-selftest-wlock-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_hard_wlock)
#include "locking-selftest-spin-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_soft_spin)
#include "locking-selftest-rlock-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_soft_rlock)
#include "locking-selftest-wlock-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irqsafe4_soft_wlock)
#undef E1
#undef E2
#undef E3
/*
* read-lock / write-lock irq inversion.
*
* Deadlock scenario:
*
* CPU#1 is at #1, i.e. it has write-locked A, but has not
* taken B yet.
*
* CPU#2 is at #2, i.e. it has locked B.
*
* Hardirq hits CPU#2 at point #2 and is trying to read-lock A.
*
* The deadlock occurs because CPU#1 will spin on B, and CPU#2
* will spin on A.
*/
#define E1() \
\
IRQ_DISABLE(); \
WL(A); \
LOCK(B); \
UNLOCK(B); \
WU(A); \
IRQ_ENABLE();
#define E2() \
\
LOCK(B); \
UNLOCK(B);
#define E3() \
\
IRQ_ENTER(); \
RL(A); \
RU(A); \
IRQ_EXIT();
/*
* Generate 36 testcases:
*/
#include "locking-selftest-spin-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_hard_spin)
#include "locking-selftest-rlock-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_hard_rlock)
#include "locking-selftest-wlock-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_hard_wlock)
#include "locking-selftest-spin-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_soft_spin)
#include "locking-selftest-rlock-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_soft_rlock)
#include "locking-selftest-wlock-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irq_inversion_soft_wlock)
#undef E1
#undef E2
#undef E3
/*
* read-lock / write-lock recursion that is actually safe.
*/
#define E1() \
\
IRQ_DISABLE(); \
WL(A); \
WU(A); \
IRQ_ENABLE();
#define E2() \
\
RL(A); \
RU(A); \
#define E3() \
\
IRQ_ENTER(); \
RL(A); \
L(B); \
U(B); \
RU(A); \
IRQ_EXIT();
/*
* Generate 12 testcases:
*/
#include "locking-selftest-hardirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion_hard)
#include "locking-selftest-softirq.h"
GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion_soft)
#undef E1
#undef E2
#undef E3
/*
* read-lock / write-lock recursion that is unsafe.
*/
#define E1() \
\
IRQ_DISABLE(); \
L(B); \
WL(A); \
WU(A); \
U(B); \
IRQ_ENABLE();
#define E2() \
\
RL(A); \
RU(A); \
#define E3() \
\
IRQ_ENTER(); \
L(B); \
U(B); \
IRQ_EXIT();
/*
* Generate 12 testcases:
*/
#include "locking-selftest-hardirq.h"
// GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion2_hard)
#include "locking-selftest-softirq.h"
// GENERATE_PERMUTATIONS_3_EVENTS(irq_read_recursion2_soft)
#ifdef CONFIG_DEBUG_LOCK_ALLOC
# define I_SPINLOCK(x) lockdep_reset_lock(&lock_##x.dep_map)
# define I_RWLOCK(x) lockdep_reset_lock(&rwlock_##x.dep_map)
# define I_MUTEX(x) lockdep_reset_lock(&mutex_##x.dep_map)
# define I_RWSEM(x) lockdep_reset_lock(&rwsem_##x.dep_map)
#else
# define I_SPINLOCK(x)
# define I_RWLOCK(x)
# define I_MUTEX(x)
# define I_RWSEM(x)
#endif
#define I1(x) \
do { \
I_SPINLOCK(x); \
I_RWLOCK(x); \
I_MUTEX(x); \
I_RWSEM(x); \
} while (0)
#define I2(x) \
do { \
spin_lock_init(&lock_##x); \
rwlock_init(&rwlock_##x); \
mutex_init(&mutex_##x); \
init_rwsem(&rwsem_##x); \
} while (0)
static void reset_locks(void)
{
local_irq_disable();
I1(A); I1(B); I1(C); I1(D);
I1(X1); I1(X2); I1(Y1); I1(Y2); I1(Z1); I1(Z2);
lockdep_reset();
I2(A); I2(B); I2(C); I2(D);
init_shared_classes();
local_irq_enable();
}
#undef I
static int testcase_total;
static int testcase_successes;
static int expected_testcase_failures;
static int unexpected_testcase_failures;
static void dotest(void (*testcase_fn)(void), int expected, int lockclass_mask)
{
unsigned long saved_preempt_count = preempt_count();
int expected_failure = 0;
WARN_ON(irqs_disabled());
testcase_fn();
/*
* Filter out expected failures:
*/
#ifndef CONFIG_PROVE_LOCKING
if ((lockclass_mask & LOCKTYPE_SPIN) && debug_locks != expected)
expected_failure = 1;
if ((lockclass_mask & LOCKTYPE_RWLOCK) && debug_locks != expected)
expected_failure = 1;
if ((lockclass_mask & LOCKTYPE_MUTEX) && debug_locks != expected)
expected_failure = 1;
if ((lockclass_mask & LOCKTYPE_RWSEM) && debug_locks != expected)
expected_failure = 1;
#endif
if (debug_locks != expected) {
if (expected_failure) {
expected_testcase_failures++;
printk("failed|");
} else {
unexpected_testcase_failures++;
printk("FAILED|");
dump_stack();
}
} else {
testcase_successes++;
printk(" ok |");
}
testcase_total++;
if (debug_locks_verbose)
printk(" lockclass mask: %x, debug_locks: %d, expected: %d\n",
lockclass_mask, debug_locks, expected);
/*
* Some tests (e.g. double-unlock) might corrupt the preemption
* count, so restore it:
*/
preempt_count() = saved_preempt_count;
#ifdef CONFIG_TRACE_IRQFLAGS
if (softirq_count())
current->softirqs_enabled = 0;
else
current->softirqs_enabled = 1;
#endif
reset_locks();
}
static inline void print_testname(const char *testname)
{
printk("%33s:", testname);
}
#define DO_TESTCASE_1(desc, name, nr) \
print_testname(desc"/"#nr); \
dotest(name##_##nr, SUCCESS, LOCKTYPE_RWLOCK); \
printk("\n");
#define DO_TESTCASE_1B(desc, name, nr) \
print_testname(desc"/"#nr); \
dotest(name##_##nr, FAILURE, LOCKTYPE_RWLOCK); \
printk("\n");
#define DO_TESTCASE_3(desc, name, nr) \
print_testname(desc"/"#nr); \
dotest(name##_spin_##nr, FAILURE, LOCKTYPE_SPIN); \
dotest(name##_wlock_##nr, FAILURE, LOCKTYPE_RWLOCK); \
dotest(name##_rlock_##nr, SUCCESS, LOCKTYPE_RWLOCK); \
printk("\n");
#define DO_TESTCASE_3RW(desc, name, nr) \
print_testname(desc"/"#nr); \
dotest(name##_spin_##nr, FAILURE, LOCKTYPE_SPIN|LOCKTYPE_RWLOCK);\
dotest(name##_wlock_##nr, FAILURE, LOCKTYPE_RWLOCK); \
dotest(name##_rlock_##nr, SUCCESS, LOCKTYPE_RWLOCK); \
printk("\n");
#define DO_TESTCASE_6(desc, name) \
print_testname(desc); \
dotest(name##_spin, FAILURE, LOCKTYPE_SPIN); \
dotest(name##_wlock, FAILURE, LOCKTYPE_RWLOCK); \
dotest(name##_rlock, FAILURE, LOCKTYPE_RWLOCK); \
dotest(name##_mutex, FAILURE, LOCKTYPE_MUTEX); \
dotest(name##_wsem, FAILURE, LOCKTYPE_RWSEM); \
dotest(name##_rsem, FAILURE, LOCKTYPE_RWSEM); \
printk("\n");
#define DO_TESTCASE_6_SUCCESS(desc, name) \
print_testname(desc); \
dotest(name##_spin, SUCCESS, LOCKTYPE_SPIN); \
dotest(name##_wlock, SUCCESS, LOCKTYPE_RWLOCK); \
dotest(name##_rlock, SUCCESS, LOCKTYPE_RWLOCK); \
dotest(name##_mutex, SUCCESS, LOCKTYPE_MUTEX); \
dotest(name##_wsem, SUCCESS, LOCKTYPE_RWSEM); \
dotest(name##_rsem, SUCCESS, LOCKTYPE_RWSEM); \
printk("\n");
/*
* 'read' variant: rlocks must not trigger.
*/
#define DO_TESTCASE_6R(desc, name) \
print_testname(desc); \
dotest(name##_spin, FAILURE, LOCKTYPE_SPIN); \
dotest(name##_wlock, FAILURE, LOCKTYPE_RWLOCK); \
dotest(name##_rlock, SUCCESS, LOCKTYPE_RWLOCK); \
dotest(name##_mutex, FAILURE, LOCKTYPE_MUTEX); \
dotest(name##_wsem, FAILURE, LOCKTYPE_RWSEM); \
dotest(name##_rsem, FAILURE, LOCKTYPE_RWSEM); \
printk("\n");
#define DO_TESTCASE_2I(desc, name, nr) \
DO_TESTCASE_1("hard-"desc, name##_hard, nr); \
DO_TESTCASE_1("soft-"desc, name##_soft, nr);
#define DO_TESTCASE_2IB(desc, name, nr) \
DO_TESTCASE_1B("hard-"desc, name##_hard, nr); \
DO_TESTCASE_1B("soft-"desc, name##_soft, nr);
#define DO_TESTCASE_6I(desc, name, nr) \
DO_TESTCASE_3("hard-"desc, name##_hard, nr); \
DO_TESTCASE_3("soft-"desc, name##_soft, nr);
#define DO_TESTCASE_6IRW(desc, name, nr) \
DO_TESTCASE_3RW("hard-"desc, name##_hard, nr); \
DO_TESTCASE_3RW("soft-"desc, name##_soft, nr);
#define DO_TESTCASE_2x3(desc, name) \
DO_TESTCASE_3(desc, name, 12); \
DO_TESTCASE_3(desc, name, 21);
#define DO_TESTCASE_2x6(desc, name) \
DO_TESTCASE_6I(desc, name, 12); \
DO_TESTCASE_6I(desc, name, 21);
#define DO_TESTCASE_6x2(desc, name) \
DO_TESTCASE_2I(desc, name, 123); \
DO_TESTCASE_2I(desc, name, 132); \
DO_TESTCASE_2I(desc, name, 213); \
DO_TESTCASE_2I(desc, name, 231); \
DO_TESTCASE_2I(desc, name, 312); \
DO_TESTCASE_2I(desc, name, 321);
#define DO_TESTCASE_6x2B(desc, name) \
DO_TESTCASE_2IB(desc, name, 123); \
DO_TESTCASE_2IB(desc, name, 132); \
DO_TESTCASE_2IB(desc, name, 213); \
DO_TESTCASE_2IB(desc, name, 231); \
DO_TESTCASE_2IB(desc, name, 312); \
DO_TESTCASE_2IB(desc, name, 321);
#define DO_TESTCASE_6x6(desc, name) \
DO_TESTCASE_6I(desc, name, 123); \
DO_TESTCASE_6I(desc, name, 132); \
DO_TESTCASE_6I(desc, name, 213); \
DO_TESTCASE_6I(desc, name, 231); \
DO_TESTCASE_6I(desc, name, 312); \
DO_TESTCASE_6I(desc, name, 321);
#define DO_TESTCASE_6x6RW(desc, name) \
DO_TESTCASE_6IRW(desc, name, 123); \
DO_TESTCASE_6IRW(desc, name, 132); \
DO_TESTCASE_6IRW(desc, name, 213); \
DO_TESTCASE_6IRW(desc, name, 231); \
DO_TESTCASE_6IRW(desc, name, 312); \
DO_TESTCASE_6IRW(desc, name, 321);
void locking_selftest(void)
{
/*
* Got a locking failure before the selftest ran?
*/
if (!debug_locks) {
printk("----------------------------------\n");
printk("| Locking API testsuite disabled |\n");
printk("----------------------------------\n");
return;
}
/*
* Run the testsuite:
*/
printk("------------------------\n");
printk("| Locking API testsuite:\n");
printk("----------------------------------------------------------------------------\n");
printk(" | spin |wlock |rlock |mutex | wsem | rsem |\n");
printk(" --------------------------------------------------------------------------\n");
init_shared_classes();
debug_locks_silent = !debug_locks_verbose;
DO_TESTCASE_6R("A-A deadlock", AA);
DO_TESTCASE_6R("A-B-B-A deadlock", ABBA);
DO_TESTCASE_6R("A-B-B-C-C-A deadlock", ABBCCA);
DO_TESTCASE_6R("A-B-C-A-B-C deadlock", ABCABC);
DO_TESTCASE_6R("A-B-B-C-C-D-D-A deadlock", ABBCCDDA);
DO_TESTCASE_6R("A-B-C-D-B-D-D-A deadlock", ABCDBDDA);
DO_TESTCASE_6R("A-B-C-D-B-C-D-A deadlock", ABCDBCDA);
DO_TESTCASE_6("double unlock", double_unlock);
DO_TESTCASE_6("initialize held", init_held);
DO_TESTCASE_6_SUCCESS("bad unlock order", bad_unlock_order);
printk(" --------------------------------------------------------------------------\n");
print_testname("recursive read-lock");
printk(" |");
dotest(rlock_AA1, SUCCESS, LOCKTYPE_RWLOCK);
printk(" |");
dotest(rsem_AA1, FAILURE, LOCKTYPE_RWSEM);
printk("\n");
print_testname("recursive read-lock #2");
printk(" |");
dotest(rlock_AA1B, SUCCESS, LOCKTYPE_RWLOCK);
printk(" |");
dotest(rsem_AA1B, FAILURE, LOCKTYPE_RWSEM);
printk("\n");
print_testname("mixed read-write-lock");
printk(" |");
dotest(rlock_AA2, FAILURE, LOCKTYPE_RWLOCK);
printk(" |");
dotest(rsem_AA2, FAILURE, LOCKTYPE_RWSEM);
printk("\n");
print_testname("mixed write-read-lock");
printk(" |");
dotest(rlock_AA3, FAILURE, LOCKTYPE_RWLOCK);
printk(" |");
dotest(rsem_AA3, FAILURE, LOCKTYPE_RWSEM);
printk("\n");
printk(" --------------------------------------------------------------------------\n");
/*
* irq-context testcases:
*/
DO_TESTCASE_2x6("irqs-on + irq-safe-A", irqsafe1);
DO_TESTCASE_2x3("sirq-safe-A => hirqs-on", irqsafe2A);
DO_TESTCASE_2x6("safe-A + irqs-on", irqsafe2B);
DO_TESTCASE_6x6("safe-A + unsafe-B #1", irqsafe3);
DO_TESTCASE_6x6("safe-A + unsafe-B #2", irqsafe4);
DO_TESTCASE_6x6RW("irq lock-inversion", irq_inversion);
DO_TESTCASE_6x2("irq read-recursion", irq_read_recursion);
// DO_TESTCASE_6x2B("irq read-recursion #2", irq_read_recursion2);
if (unexpected_testcase_failures) {
printk("-----------------------------------------------------------------\n");
debug_locks = 0;
printk("BUG: %3d unexpected failures (out of %3d) - debugging disabled! |\n",
unexpected_testcase_failures, testcase_total);
printk("-----------------------------------------------------------------\n");
} else if (expected_testcase_failures && testcase_successes) {
printk("--------------------------------------------------------\n");
printk("%3d out of %3d testcases failed, as expected. |\n",
expected_testcase_failures, testcase_total);
printk("----------------------------------------------------\n");
debug_locks = 1;
} else if (expected_testcase_failures && !testcase_successes) {
printk("--------------------------------------------------------\n");
printk("All %3d testcases failed, as expected. |\n",
expected_testcase_failures);
printk("----------------------------------------\n");
debug_locks = 1;
} else {
printk("-------------------------------------------------------\n");
printk("Good, all %3d testcases passed! |\n",
testcase_successes);
printk("---------------------------------\n");
debug_locks = 1;
}
debug_locks_silent = 0;
}
| gpl-2.0 |
holyangel/M8-GPE_M | scripts/dtc/libfdt/fdt_wip.c | 6046 | 3669 | /*
* libfdt - Flat Device Tree manipulation
* Copyright (C) 2006 David Gibson, IBM Corporation.
*
* libfdt is dual licensed: you can use it either under the terms of
* the GPL, or the BSD license, at your option.
*
* a) This library 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 library 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 library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301 USA
*
* Alternatively,
*
* b) Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 "libfdt_env.h"
#include <fdt.h>
#include <libfdt.h>
#include "libfdt_internal.h"
int fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,
const void *val, int len)
{
void *propval;
int proplen;
propval = fdt_getprop_w(fdt, nodeoffset, name, &proplen);
if (! propval)
return proplen;
if (proplen != len)
return -FDT_ERR_NOSPACE;
memcpy(propval, val, len);
return 0;
}
static void _fdt_nop_region(void *start, int len)
{
uint32_t *p;
for (p = start; (char *)p < ((char *)start + len); p++)
*p = cpu_to_fdt32(FDT_NOP);
}
int fdt_nop_property(void *fdt, int nodeoffset, const char *name)
{
struct fdt_property *prop;
int len;
prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
if (! prop)
return len;
_fdt_nop_region(prop, len + sizeof(*prop));
return 0;
}
int _fdt_node_end_offset(void *fdt, int offset)
{
int depth = 0;
while ((offset >= 0) && (depth >= 0))
offset = fdt_next_node(fdt, offset, &depth);
return offset;
}
int fdt_nop_node(void *fdt, int nodeoffset)
{
int endoffset;
endoffset = _fdt_node_end_offset(fdt, nodeoffset);
if (endoffset < 0)
return endoffset;
_fdt_nop_region(fdt_offset_ptr_w(fdt, nodeoffset, 0),
endoffset - nodeoffset);
return 0;
}
| gpl-2.0 |
AmperificSuperKANG/kernel_hammerhead | arch/alpha/kernel/sys_jensen.c | 6814 | 5671 | /*
* linux/arch/alpha/kernel/sys_jensen.c
*
* Copyright (C) 1995 Linus Torvalds
* Copyright (C) 1998, 1999 Richard Henderson
*
* Code supporting the Jensen.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <asm/ptrace.h>
#define __EXTERN_INLINE inline
#include <asm/io.h>
#include <asm/jensen.h>
#undef __EXTERN_INLINE
#include <asm/dma.h>
#include <asm/irq.h>
#include <asm/mmu_context.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
#include "proto.h"
#include "irq_impl.h"
#include "pci_impl.h"
#include "machvec_impl.h"
/*
* Jensen is special: the vector is 0x8X0 for EISA interrupt X, and
* 0x9X0 for the local motherboard interrupts.
*
* Note especially that those local interrupts CANNOT be masked,
* which causes much of the pain below...
*
* 0x660 - NMI
*
* 0x800 - IRQ0 interval timer (not used, as we use the RTC timer)
* 0x810 - IRQ1 line printer (duh..)
* 0x860 - IRQ6 floppy disk
*
* 0x900 - COM1
* 0x920 - COM2
* 0x980 - keyboard
* 0x990 - mouse
*
* PCI-based systems are more sane: they don't have the local
* interrupts at all, and have only normal PCI interrupts from
* devices. Happily it's easy enough to do a sane mapping from the
* Jensen.
*
* Note that this means that we may have to do a hardware
* "local_op" to a different interrupt than we report to the rest of the
* world.
*/
static void
jensen_local_enable(struct irq_data *d)
{
/* the parport is really hw IRQ 1, silly Jensen. */
if (d->irq == 7)
i8259a_enable_irq(d);
}
static void
jensen_local_disable(struct irq_data *d)
{
/* the parport is really hw IRQ 1, silly Jensen. */
if (d->irq == 7)
i8259a_disable_irq(d);
}
static void
jensen_local_mask_ack(struct irq_data *d)
{
/* the parport is really hw IRQ 1, silly Jensen. */
if (d->irq == 7)
i8259a_mask_and_ack_irq(d);
}
static struct irq_chip jensen_local_irq_type = {
.name = "LOCAL",
.irq_unmask = jensen_local_enable,
.irq_mask = jensen_local_disable,
.irq_mask_ack = jensen_local_mask_ack,
};
static void
jensen_device_interrupt(unsigned long vector)
{
int irq;
switch (vector) {
case 0x660:
printk("Whee.. NMI received. Probable hardware error\n");
printk("61=%02x, 461=%02x\n", inb(0x61), inb(0x461));
return;
/* local device interrupts: */
case 0x900: irq = 4; break; /* com1 -> irq 4 */
case 0x920: irq = 3; break; /* com2 -> irq 3 */
case 0x980: irq = 1; break; /* kbd -> irq 1 */
case 0x990: irq = 9; break; /* mouse -> irq 9 */
default:
if (vector > 0x900) {
printk("Unknown local interrupt %lx\n", vector);
return;
}
irq = (vector - 0x800) >> 4;
if (irq == 1)
irq = 7;
break;
}
/* If there is no handler yet... */
if (!irq_has_action(irq)) {
/* If it is a local interrupt that cannot be masked... */
if (vector >= 0x900)
{
/* Clear keyboard/mouse state */
inb(0x64);
inb(0x60);
/* Reset serial ports */
inb(0x3fa);
inb(0x2fa);
outb(0x0c, 0x3fc);
outb(0x0c, 0x2fc);
/* Clear NMI */
outb(0,0x61);
outb(0,0x461);
}
}
#if 0
/* A useful bit of code to find out if an interrupt is going wild. */
{
static unsigned int last_msg = 0, last_cc = 0;
static int last_irq = -1, count = 0;
unsigned int cc;
__asm __volatile("rpcc %0" : "=r"(cc));
++count;
#define JENSEN_CYCLES_PER_SEC (150000000)
if (cc - last_msg > ((JENSEN_CYCLES_PER_SEC) * 3) ||
irq != last_irq) {
printk(KERN_CRIT " irq %d count %d cc %u @ %lx\n",
irq, count, cc-last_cc, get_irq_regs()->pc);
count = 0;
last_msg = cc;
last_irq = irq;
}
last_cc = cc;
}
#endif
handle_irq(irq);
}
static void __init
jensen_init_irq(void)
{
init_i8259a_irqs();
irq_set_chip_and_handler(1, &jensen_local_irq_type, handle_level_irq);
irq_set_chip_and_handler(4, &jensen_local_irq_type, handle_level_irq);
irq_set_chip_and_handler(3, &jensen_local_irq_type, handle_level_irq);
irq_set_chip_and_handler(7, &jensen_local_irq_type, handle_level_irq);
irq_set_chip_and_handler(9, &jensen_local_irq_type, handle_level_irq);
common_init_isa_dma();
}
static void __init
jensen_init_arch(void)
{
struct pci_controller *hose;
#ifdef CONFIG_PCI
static struct pci_dev fake_isa_bridge = { .dma_mask = 0xffffffffUL, };
isa_bridge = &fake_isa_bridge;
#endif
/* Create a hose so that we can report i/o base addresses to
userland. */
pci_isa_hose = hose = alloc_pci_controller();
hose->io_space = &ioport_resource;
hose->mem_space = &iomem_resource;
hose->index = 0;
hose->sparse_mem_base = EISA_MEM - IDENT_ADDR;
hose->dense_mem_base = 0;
hose->sparse_io_base = EISA_IO - IDENT_ADDR;
hose->dense_io_base = 0;
hose->sg_isa = hose->sg_pci = NULL;
__direct_map_base = 0;
__direct_map_size = 0xffffffff;
}
static void
jensen_machine_check(unsigned long vector, unsigned long la)
{
printk(KERN_CRIT "Machine check\n");
}
/*
* The System Vector
*/
struct alpha_machine_vector jensen_mv __initmv = {
.vector_name = "Jensen",
DO_EV4_MMU,
IO_LITE(JENSEN,jensen),
.machine_check = jensen_machine_check,
.max_isa_dma_address = ALPHA_MAX_ISA_DMA_ADDRESS,
.rtc_port = 0x170,
.rtc_get_time = common_get_rtc_time,
.rtc_set_time = common_set_rtc_time,
.nr_irqs = 16,
.device_interrupt = jensen_device_interrupt,
.init_arch = jensen_init_arch,
.init_irq = jensen_init_irq,
.init_rtc = common_init_rtc,
.init_pci = NULL,
.kill_arch = NULL,
};
ALIAS_MV(jensen)
| gpl-2.0 |
R-M-S/RMS_EXPERIMENTAL_Kernel | drivers/staging/speakup/speakup_ltlk.c | 7582 | 6036 | /*
* originally written by: Kirk Reiser <kirk@braille.uwo.ca>
* this version considerably modified by David Borowski, david575@rogers.com
*
* Copyright (C) 1998-99 Kirk Reiser.
* Copyright (C) 2003 David Borowski.
*
* 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
*
* specificly written as a driver for the speakup screenreview
* s not a general device driver.
*/
#include "speakup.h"
#include "spk_priv.h"
#include "serialio.h"
#include "speakup_dtlk.h" /* local header file for LiteTalk values */
#define DRV_VERSION "2.11"
#define PROCSPEECH 0x0d
static int synth_probe(struct spk_synth *synth);
static struct var_t vars[] = {
{ CAPS_START, .u.s = {"\x01+35p" } },
{ CAPS_STOP, .u.s = {"\x01-35p" } },
{ RATE, .u.n = {"\x01%ds", 8, 0, 9, 0, 0, NULL } },
{ PITCH, .u.n = {"\x01%dp", 50, 0, 99, 0, 0, NULL } },
{ VOL, .u.n = {"\x01%dv", 5, 0, 9, 0, 0, NULL } },
{ TONE, .u.n = {"\x01%dx", 1, 0, 2, 0, 0, NULL } },
{ PUNCT, .u.n = {"\x01%db", 7, 0, 15, 0, 0, NULL } },
{ VOICE, .u.n = {"\x01%do", 0, 0, 7, 0, 0, NULL } },
{ FREQUENCY, .u.n = {"\x01%df", 5, 0, 9, 0, 0, NULL } },
{ DIRECT, .u.n = {NULL, 0, 0, 1, 0, 0, NULL } },
V_LAST_VAR
};
/*
* These attributes will appear in /sys/accessibility/speakup/ltlk.
*/
static struct kobj_attribute caps_start_attribute =
__ATTR(caps_start, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute caps_stop_attribute =
__ATTR(caps_stop, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute freq_attribute =
__ATTR(freq, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute pitch_attribute =
__ATTR(pitch, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute punct_attribute =
__ATTR(punct, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute rate_attribute =
__ATTR(rate, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute tone_attribute =
__ATTR(tone, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute voice_attribute =
__ATTR(voice, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute vol_attribute =
__ATTR(vol, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute delay_time_attribute =
__ATTR(delay_time, ROOT_W, spk_var_show, spk_var_store);
static struct kobj_attribute direct_attribute =
__ATTR(direct, USER_RW, spk_var_show, spk_var_store);
static struct kobj_attribute full_time_attribute =
__ATTR(full_time, ROOT_W, spk_var_show, spk_var_store);
static struct kobj_attribute jiffy_delta_attribute =
__ATTR(jiffy_delta, ROOT_W, spk_var_show, spk_var_store);
static struct kobj_attribute trigger_time_attribute =
__ATTR(trigger_time, ROOT_W, spk_var_show, spk_var_store);
/*
* Create a group of attributes so that we can create and destroy them all
* at once.
*/
static struct attribute *synth_attrs[] = {
&caps_start_attribute.attr,
&caps_stop_attribute.attr,
&freq_attribute.attr,
&pitch_attribute.attr,
&punct_attribute.attr,
&rate_attribute.attr,
&tone_attribute.attr,
&voice_attribute.attr,
&vol_attribute.attr,
&delay_time_attribute.attr,
&direct_attribute.attr,
&full_time_attribute.attr,
&jiffy_delta_attribute.attr,
&trigger_time_attribute.attr,
NULL, /* need to NULL terminate the list of attributes */
};
static struct spk_synth synth_ltlk = {
.name = "ltlk",
.version = DRV_VERSION,
.long_name = "LiteTalk",
.init = "\01@\x01\x31y\n\0",
.procspeech = PROCSPEECH,
.clear = SYNTH_CLEAR,
.delay = 500,
.trigger = 50,
.jiffies = 50,
.full = 40000,
.startup = SYNTH_START,
.checkval = SYNTH_CHECK,
.vars = vars,
.probe = synth_probe,
.release = spk_serial_release,
.synth_immediate = spk_synth_immediate,
.catch_up = spk_do_catch_up,
.flush = spk_synth_flush,
.is_alive = spk_synth_is_alive_restart,
.synth_adjust = NULL,
.read_buff_add = NULL,
.get_index = spk_serial_in_nowait,
.indexing = {
.command = "\x01%di",
.lowindex = 1,
.highindex = 5,
.currindex = 1,
},
.attributes = {
.attrs = synth_attrs,
.name = "ltlk",
},
};
/* interrogate the LiteTalk and print its settings */
static void synth_interrogate(struct spk_synth *synth)
{
unsigned char *t, i;
unsigned char buf[50], rom_v[20];
spk_synth_immediate(synth, "\x18\x01?");
for (i = 0; i < 50; i++) {
buf[i] = spk_serial_in();
if (i > 2 && buf[i] == 0x7f)
break;
}
t = buf+2;
for (i = 0; *t != '\r'; t++) {
rom_v[i] = *t;
if (++i >= 19)
break;
}
rom_v[i] = 0;
pr_info("%s: ROM version: %s\n", synth->long_name, rom_v);
}
static int synth_probe(struct spk_synth *synth)
{
int failed = 0;
failed = serial_synth_probe(synth);
if (failed == 0)
synth_interrogate(synth);
synth->alive = !failed;
return failed;
}
module_param_named(ser, synth_ltlk.ser, int, S_IRUGO);
module_param_named(start, synth_ltlk.startup, short, S_IRUGO);
MODULE_PARM_DESC(ser, "Set the serial port for the synthesizer (0-based).");
MODULE_PARM_DESC(start, "Start the synthesizer once it is loaded.");
static int __init ltlk_init(void)
{
return synth_add(&synth_ltlk);
}
static void __exit ltlk_exit(void)
{
synth_remove(&synth_ltlk);
}
module_init(ltlk_init);
module_exit(ltlk_exit);
MODULE_AUTHOR("Kirk Reiser <kirk@braille.uwo.ca>");
MODULE_AUTHOR("David Borowski");
MODULE_DESCRIPTION("Speakup support for DoubleTalk LT/LiteTalk synthesizers");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
xiaognol/android_kernel_chm_cl00 | drivers/media/pci/saa7164/saa7164-dvb.c | 8094 | 15853 | /*
* 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 "saa7164.h"
#include "tda10048.h"
#include "tda18271.h"
#include "s5h1411.h"
#define DRIVER_NAME "saa7164"
DVB_DEFINE_MOD_OPT_ADAPTER_NR(adapter_nr);
/* addr is in the card struct, get it from there */
static struct tda10048_config hauppauge_hvr2200_1_config = {
.demod_address = 0x10 >> 1,
.output_mode = TDA10048_SERIAL_OUTPUT,
.fwbulkwritelen = TDA10048_BULKWRITE_200,
.inversion = TDA10048_INVERSION_ON,
.dtv6_if_freq_khz = TDA10048_IF_3300,
.dtv7_if_freq_khz = TDA10048_IF_3500,
.dtv8_if_freq_khz = TDA10048_IF_4000,
.clk_freq_khz = TDA10048_CLK_16000,
};
static struct tda10048_config hauppauge_hvr2200_2_config = {
.demod_address = 0x12 >> 1,
.output_mode = TDA10048_SERIAL_OUTPUT,
.fwbulkwritelen = TDA10048_BULKWRITE_200,
.inversion = TDA10048_INVERSION_ON,
.dtv6_if_freq_khz = TDA10048_IF_3300,
.dtv7_if_freq_khz = TDA10048_IF_3500,
.dtv8_if_freq_khz = TDA10048_IF_4000,
.clk_freq_khz = TDA10048_CLK_16000,
};
static struct tda18271_std_map hauppauge_tda18271_std_map = {
.atsc_6 = { .if_freq = 3250, .agc_mode = 3, .std = 3,
.if_lvl = 6, .rfagc_top = 0x37 },
.qam_6 = { .if_freq = 4000, .agc_mode = 3, .std = 0,
.if_lvl = 6, .rfagc_top = 0x37 },
};
static struct tda18271_config hauppauge_hvr22x0_tuner_config = {
.std_map = &hauppauge_tda18271_std_map,
.gate = TDA18271_GATE_ANALOG,
.role = TDA18271_MASTER,
};
static struct tda18271_config hauppauge_hvr22x0s_tuner_config = {
.std_map = &hauppauge_tda18271_std_map,
.gate = TDA18271_GATE_ANALOG,
.role = TDA18271_SLAVE,
.output_opt = TDA18271_OUTPUT_LT_OFF,
.rf_cal_on_startup = 1
};
static struct s5h1411_config hauppauge_s5h1411_config = {
.output_mode = S5H1411_SERIAL_OUTPUT,
.gpio = S5H1411_GPIO_ON,
.qam_if = S5H1411_IF_4000,
.vsb_if = S5H1411_IF_3250,
.inversion = S5H1411_INVERSION_ON,
.status_mode = S5H1411_DEMODLOCKING,
.mpeg_timing = S5H1411_MPEGTIMING_CONTINOUS_NONINVERTING_CLOCK,
};
static int saa7164_dvb_stop_port(struct saa7164_port *port)
{
struct saa7164_dev *dev = port->dev;
int ret;
ret = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
if ((ret != SAA_OK) && (ret != SAA_ERR_ALREADY_STOPPED)) {
printk(KERN_ERR "%s() stop transition failed, ret = 0x%x\n",
__func__, ret);
ret = -EIO;
} else {
dprintk(DBGLVL_DVB, "%s() Stopped\n", __func__);
ret = 0;
}
return ret;
}
static int saa7164_dvb_acquire_port(struct saa7164_port *port)
{
struct saa7164_dev *dev = port->dev;
int ret;
ret = saa7164_api_transition_port(port, SAA_DMASTATE_ACQUIRE);
if ((ret != SAA_OK) && (ret != SAA_ERR_ALREADY_STOPPED)) {
printk(KERN_ERR "%s() acquire transition failed, ret = 0x%x\n",
__func__, ret);
ret = -EIO;
} else {
dprintk(DBGLVL_DVB, "%s() Acquired\n", __func__);
ret = 0;
}
return ret;
}
static int saa7164_dvb_pause_port(struct saa7164_port *port)
{
struct saa7164_dev *dev = port->dev;
int ret;
ret = saa7164_api_transition_port(port, SAA_DMASTATE_PAUSE);
if ((ret != SAA_OK) && (ret != SAA_ERR_ALREADY_STOPPED)) {
printk(KERN_ERR "%s() pause transition failed, ret = 0x%x\n",
__func__, ret);
ret = -EIO;
} else {
dprintk(DBGLVL_DVB, "%s() Paused\n", __func__);
ret = 0;
}
return ret;
}
/* Firmware is very windows centric, meaning you have to transition
* the part through AVStream / KS Windows stages, forwards or backwards.
* States are: stopped, acquired (h/w), paused, started.
*/
static int saa7164_dvb_stop_streaming(struct saa7164_port *port)
{
struct saa7164_dev *dev = port->dev;
struct saa7164_buffer *buf;
struct list_head *p, *q;
int ret;
dprintk(DBGLVL_DVB, "%s(port=%d)\n", __func__, port->nr);
ret = saa7164_dvb_pause_port(port);
ret = saa7164_dvb_acquire_port(port);
ret = saa7164_dvb_stop_port(port);
/* Mark the hardware buffers as free */
mutex_lock(&port->dmaqueue_lock);
list_for_each_safe(p, q, &port->dmaqueue.list) {
buf = list_entry(p, struct saa7164_buffer, list);
buf->flags = SAA7164_BUFFER_FREE;
}
mutex_unlock(&port->dmaqueue_lock);
return ret;
}
static int saa7164_dvb_start_port(struct saa7164_port *port)
{
struct saa7164_dev *dev = port->dev;
int ret = 0, result;
dprintk(DBGLVL_DVB, "%s(port=%d)\n", __func__, port->nr);
saa7164_buffer_cfg_port(port);
/* Acquire the hardware */
result = saa7164_api_transition_port(port, SAA_DMASTATE_ACQUIRE);
if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
printk(KERN_ERR "%s() acquire transition failed, res = 0x%x\n",
__func__, result);
/* Stop the hardware, regardless */
result = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
printk(KERN_ERR "%s() acquire/forced stop transition "
"failed, res = 0x%x\n", __func__, result);
}
ret = -EIO;
goto out;
} else
dprintk(DBGLVL_DVB, "%s() Acquired\n", __func__);
/* Pause the hardware */
result = saa7164_api_transition_port(port, SAA_DMASTATE_PAUSE);
if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
printk(KERN_ERR "%s() pause transition failed, res = 0x%x\n",
__func__, result);
/* Stop the hardware, regardless */
result = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
printk(KERN_ERR "%s() pause/forced stop transition "
"failed, res = 0x%x\n", __func__, result);
}
ret = -EIO;
goto out;
} else
dprintk(DBGLVL_DVB, "%s() Paused\n", __func__);
/* Start the hardware */
result = saa7164_api_transition_port(port, SAA_DMASTATE_RUN);
if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
printk(KERN_ERR "%s() run transition failed, result = 0x%x\n",
__func__, result);
/* Stop the hardware, regardless */
result = saa7164_api_transition_port(port, SAA_DMASTATE_STOP);
if ((result != SAA_OK) && (result != SAA_ERR_ALREADY_STOPPED)) {
printk(KERN_ERR "%s() run/forced stop transition "
"failed, res = 0x%x\n", __func__, result);
}
ret = -EIO;
} else
dprintk(DBGLVL_DVB, "%s() Running\n", __func__);
out:
return ret;
}
static int saa7164_dvb_start_feed(struct dvb_demux_feed *feed)
{
struct dvb_demux *demux = feed->demux;
struct saa7164_port *port = (struct saa7164_port *) demux->priv;
struct saa7164_dvb *dvb = &port->dvb;
struct saa7164_dev *dev = port->dev;
int ret = 0;
dprintk(DBGLVL_DVB, "%s(port=%d)\n", __func__, port->nr);
if (!demux->dmx.frontend)
return -EINVAL;
if (dvb) {
mutex_lock(&dvb->lock);
if (dvb->feeding++ == 0) {
/* Start transport */
ret = saa7164_dvb_start_port(port);
}
mutex_unlock(&dvb->lock);
dprintk(DBGLVL_DVB, "%s(port=%d) now feeding = %d\n",
__func__, port->nr, dvb->feeding);
}
return ret;
}
static int saa7164_dvb_stop_feed(struct dvb_demux_feed *feed)
{
struct dvb_demux *demux = feed->demux;
struct saa7164_port *port = (struct saa7164_port *) demux->priv;
struct saa7164_dvb *dvb = &port->dvb;
struct saa7164_dev *dev = port->dev;
int ret = 0;
dprintk(DBGLVL_DVB, "%s(port=%d)\n", __func__, port->nr);
if (dvb) {
mutex_lock(&dvb->lock);
if (--dvb->feeding == 0) {
/* Stop transport */
ret = saa7164_dvb_stop_streaming(port);
}
mutex_unlock(&dvb->lock);
dprintk(DBGLVL_DVB, "%s(port=%d) now feeding = %d\n",
__func__, port->nr, dvb->feeding);
}
return ret;
}
static int dvb_register(struct saa7164_port *port)
{
struct saa7164_dvb *dvb = &port->dvb;
struct saa7164_dev *dev = port->dev;
struct saa7164_buffer *buf;
int result, i;
dprintk(DBGLVL_DVB, "%s(port=%d)\n", __func__, port->nr);
if (port->type != SAA7164_MPEG_DVB)
BUG();
/* Sanity check that the PCI configuration space is active */
if (port->hwcfg.BARLocation == 0) {
result = -ENOMEM;
printk(KERN_ERR "%s: dvb_register_adapter failed "
"(errno = %d), NO PCI configuration\n",
DRIVER_NAME, result);
goto fail_adapter;
}
/* Init and establish defaults */
port->hw_streamingparams.bitspersample = 8;
port->hw_streamingparams.samplesperline = 188;
port->hw_streamingparams.numberoflines =
(SAA7164_TS_NUMBER_OF_LINES * 188) / 188;
port->hw_streamingparams.pitch = 188;
port->hw_streamingparams.linethreshold = 0;
port->hw_streamingparams.pagetablelistvirt = NULL;
port->hw_streamingparams.pagetablelistphys = NULL;
port->hw_streamingparams.numpagetables = 2 +
((SAA7164_TS_NUMBER_OF_LINES * 188) / PAGE_SIZE);
port->hw_streamingparams.numpagetableentries = port->hwcfg.buffercount;
/* Allocate the PCI resources */
for (i = 0; i < port->hwcfg.buffercount; i++) {
buf = saa7164_buffer_alloc(port,
port->hw_streamingparams.numberoflines *
port->hw_streamingparams.pitch);
if (!buf) {
result = -ENOMEM;
printk(KERN_ERR "%s: dvb_register_adapter failed "
"(errno = %d), unable to allocate buffers\n",
DRIVER_NAME, result);
goto fail_adapter;
}
mutex_lock(&port->dmaqueue_lock);
list_add_tail(&buf->list, &port->dmaqueue.list);
mutex_unlock(&port->dmaqueue_lock);
}
/* register adapter */
result = dvb_register_adapter(&dvb->adapter, DRIVER_NAME, THIS_MODULE,
&dev->pci->dev, adapter_nr);
if (result < 0) {
printk(KERN_ERR "%s: dvb_register_adapter failed "
"(errno = %d)\n", DRIVER_NAME, result);
goto fail_adapter;
}
dvb->adapter.priv = port;
/* register frontend */
result = dvb_register_frontend(&dvb->adapter, dvb->frontend);
if (result < 0) {
printk(KERN_ERR "%s: dvb_register_frontend failed "
"(errno = %d)\n", DRIVER_NAME, result);
goto fail_frontend;
}
/* register demux stuff */
dvb->demux.dmx.capabilities =
DMX_TS_FILTERING | DMX_SECTION_FILTERING |
DMX_MEMORY_BASED_FILTERING;
dvb->demux.priv = port;
dvb->demux.filternum = 256;
dvb->demux.feednum = 256;
dvb->demux.start_feed = saa7164_dvb_start_feed;
dvb->demux.stop_feed = saa7164_dvb_stop_feed;
result = dvb_dmx_init(&dvb->demux);
if (result < 0) {
printk(KERN_ERR "%s: dvb_dmx_init failed (errno = %d)\n",
DRIVER_NAME, result);
goto fail_dmx;
}
dvb->dmxdev.filternum = 256;
dvb->dmxdev.demux = &dvb->demux.dmx;
dvb->dmxdev.capabilities = 0;
result = dvb_dmxdev_init(&dvb->dmxdev, &dvb->adapter);
if (result < 0) {
printk(KERN_ERR "%s: dvb_dmxdev_init failed (errno = %d)\n",
DRIVER_NAME, result);
goto fail_dmxdev;
}
dvb->fe_hw.source = DMX_FRONTEND_0;
result = dvb->demux.dmx.add_frontend(&dvb->demux.dmx, &dvb->fe_hw);
if (result < 0) {
printk(KERN_ERR "%s: add_frontend failed "
"(DMX_FRONTEND_0, errno = %d)\n", DRIVER_NAME, result);
goto fail_fe_hw;
}
dvb->fe_mem.source = DMX_MEMORY_FE;
result = dvb->demux.dmx.add_frontend(&dvb->demux.dmx, &dvb->fe_mem);
if (result < 0) {
printk(KERN_ERR "%s: add_frontend failed "
"(DMX_MEMORY_FE, errno = %d)\n", DRIVER_NAME, result);
goto fail_fe_mem;
}
result = dvb->demux.dmx.connect_frontend(&dvb->demux.dmx, &dvb->fe_hw);
if (result < 0) {
printk(KERN_ERR "%s: connect_frontend failed (errno = %d)\n",
DRIVER_NAME, result);
goto fail_fe_conn;
}
/* register network adapter */
dvb_net_init(&dvb->adapter, &dvb->net, &dvb->demux.dmx);
return 0;
fail_fe_conn:
dvb->demux.dmx.remove_frontend(&dvb->demux.dmx, &dvb->fe_mem);
fail_fe_mem:
dvb->demux.dmx.remove_frontend(&dvb->demux.dmx, &dvb->fe_hw);
fail_fe_hw:
dvb_dmxdev_release(&dvb->dmxdev);
fail_dmxdev:
dvb_dmx_release(&dvb->demux);
fail_dmx:
dvb_unregister_frontend(dvb->frontend);
fail_frontend:
dvb_frontend_detach(dvb->frontend);
dvb_unregister_adapter(&dvb->adapter);
fail_adapter:
return result;
}
int saa7164_dvb_unregister(struct saa7164_port *port)
{
struct saa7164_dvb *dvb = &port->dvb;
struct saa7164_dev *dev = port->dev;
struct saa7164_buffer *b;
struct list_head *c, *n;
dprintk(DBGLVL_DVB, "%s()\n", __func__);
if (port->type != SAA7164_MPEG_DVB)
BUG();
/* Remove any allocated buffers */
mutex_lock(&port->dmaqueue_lock);
list_for_each_safe(c, n, &port->dmaqueue.list) {
b = list_entry(c, struct saa7164_buffer, list);
list_del(c);
saa7164_buffer_dealloc(b);
}
mutex_unlock(&port->dmaqueue_lock);
if (dvb->frontend == NULL)
return 0;
dvb_net_release(&dvb->net);
dvb->demux.dmx.remove_frontend(&dvb->demux.dmx, &dvb->fe_mem);
dvb->demux.dmx.remove_frontend(&dvb->demux.dmx, &dvb->fe_hw);
dvb_dmxdev_release(&dvb->dmxdev);
dvb_dmx_release(&dvb->demux);
dvb_unregister_frontend(dvb->frontend);
dvb_frontend_detach(dvb->frontend);
dvb_unregister_adapter(&dvb->adapter);
return 0;
}
/* All the DVB attach calls go here, this function get's modified
* for each new card.
*/
int saa7164_dvb_register(struct saa7164_port *port)
{
struct saa7164_dev *dev = port->dev;
struct saa7164_dvb *dvb = &port->dvb;
struct saa7164_i2c *i2c_bus = NULL;
int ret;
dprintk(DBGLVL_DVB, "%s()\n", __func__);
/* init frontend */
switch (dev->board) {
case SAA7164_BOARD_HAUPPAUGE_HVR2200:
case SAA7164_BOARD_HAUPPAUGE_HVR2200_2:
case SAA7164_BOARD_HAUPPAUGE_HVR2200_3:
case SAA7164_BOARD_HAUPPAUGE_HVR2200_4:
case SAA7164_BOARD_HAUPPAUGE_HVR2200_5:
i2c_bus = &dev->i2c_bus[port->nr + 1];
switch (port->nr) {
case 0:
port->dvb.frontend = dvb_attach(tda10048_attach,
&hauppauge_hvr2200_1_config,
&i2c_bus->i2c_adap);
if (port->dvb.frontend != NULL) {
/* TODO: addr is in the card struct */
dvb_attach(tda18271_attach, port->dvb.frontend,
0xc0 >> 1, &i2c_bus->i2c_adap,
&hauppauge_hvr22x0_tuner_config);
}
break;
case 1:
port->dvb.frontend = dvb_attach(tda10048_attach,
&hauppauge_hvr2200_2_config,
&i2c_bus->i2c_adap);
if (port->dvb.frontend != NULL) {
/* TODO: addr is in the card struct */
dvb_attach(tda18271_attach, port->dvb.frontend,
0xc0 >> 1, &i2c_bus->i2c_adap,
&hauppauge_hvr22x0s_tuner_config);
}
break;
}
break;
case SAA7164_BOARD_HAUPPAUGE_HVR2250:
case SAA7164_BOARD_HAUPPAUGE_HVR2250_2:
case SAA7164_BOARD_HAUPPAUGE_HVR2250_3:
i2c_bus = &dev->i2c_bus[port->nr + 1];
port->dvb.frontend = dvb_attach(s5h1411_attach,
&hauppauge_s5h1411_config,
&i2c_bus->i2c_adap);
if (port->dvb.frontend != NULL) {
if (port->nr == 0) {
/* Master TDA18271 */
/* TODO: addr is in the card struct */
dvb_attach(tda18271_attach, port->dvb.frontend,
0xc0 >> 1, &i2c_bus->i2c_adap,
&hauppauge_hvr22x0_tuner_config);
} else {
/* Slave TDA18271 */
dvb_attach(tda18271_attach, port->dvb.frontend,
0xc0 >> 1, &i2c_bus->i2c_adap,
&hauppauge_hvr22x0s_tuner_config);
}
}
break;
default:
printk(KERN_ERR "%s: The frontend isn't supported\n",
dev->name);
break;
}
if (NULL == dvb->frontend) {
printk(KERN_ERR "%s() Frontend initialization failed\n",
__func__);
return -1;
}
/* register everything */
ret = dvb_register(port);
if (ret < 0) {
if (dvb->frontend->ops.release)
dvb->frontend->ops.release(dvb->frontend);
return ret;
}
return 0;
}
| gpl-2.0 |
lyfkevin/Wind_iproj_JB_kernel_old | arch/mn10300/lib/bitops.c | 9118 | 1087 | /* MN10300 Non-trivial bit operations
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/module.h>
#include <asm/bitops.h>
/*
* try flipping a bit using BSET and BCLR
*/
void change_bit(unsigned long nr, volatile void *addr)
{
if (test_bit(nr, addr))
goto try_clear_bit;
try_set_bit:
if (!test_and_set_bit(nr, addr))
return;
try_clear_bit:
if (test_and_clear_bit(nr, addr))
return;
goto try_set_bit;
}
/*
* try flipping a bit using BSET and BCLR and returning the old value
*/
int test_and_change_bit(unsigned long nr, volatile void *addr)
{
if (test_bit(nr, addr))
goto try_clear_bit;
try_set_bit:
if (!test_and_set_bit(nr, addr))
return 0;
try_clear_bit:
if (test_and_clear_bit(nr, addr))
return 1;
goto try_set_bit;
}
| gpl-2.0 |
Abhinav1997/kernel_cyanogen_msm8916 | arch/mn10300/kernel/gdb-io-serial.c | 9118 | 3903 | /* 16550 serial driver for gdbstub I/O
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/nmi.h>
#include <asm/pgtable.h>
#include <asm/gdb-stub.h>
#include <asm/exceptions.h>
#include <asm/serial-regs.h>
#include <unit/serial.h>
#include <asm/smp.h>
/*
* initialise the GDB stub
*/
void gdbstub_io_init(void)
{
u16 tmp;
/* set up the serial port */
GDBPORT_SERIAL_LCR = UART_LCR_WLEN8; /* 1N8 */
GDBPORT_SERIAL_FCR = (UART_FCR_ENABLE_FIFO | UART_FCR_CLEAR_RCVR |
UART_FCR_CLEAR_XMIT);
FLOWCTL_CLEAR(DTR);
FLOWCTL_SET(RTS);
gdbstub_io_set_baud(115200);
/* we want to get serial receive interrupts */
XIRQxICR(GDBPORT_SERIAL_IRQ) = 0;
tmp = XIRQxICR(GDBPORT_SERIAL_IRQ);
#if CONFIG_GDBSTUB_IRQ_LEVEL == 0
IVAR0 = EXCEP_IRQ_LEVEL0;
#elif CONFIG_GDBSTUB_IRQ_LEVEL == 1
IVAR1 = EXCEP_IRQ_LEVEL1;
#elif CONFIG_GDBSTUB_IRQ_LEVEL == 2
IVAR2 = EXCEP_IRQ_LEVEL2;
#elif CONFIG_GDBSTUB_IRQ_LEVEL == 3
IVAR3 = EXCEP_IRQ_LEVEL3;
#elif CONFIG_GDBSTUB_IRQ_LEVEL == 4
IVAR4 = EXCEP_IRQ_LEVEL4;
#elif CONFIG_GDBSTUB_IRQ_LEVEL == 5
IVAR5 = EXCEP_IRQ_LEVEL5;
#else
#error "Unknown irq level for gdbstub."
#endif
set_intr_stub(NUM2EXCEP_IRQ_LEVEL(CONFIG_GDBSTUB_IRQ_LEVEL),
gdbstub_io_rx_handler);
XIRQxICR(GDBPORT_SERIAL_IRQ) &= ~GxICR_REQUEST;
XIRQxICR(GDBPORT_SERIAL_IRQ) =
GxICR_ENABLE | NUM2GxICR_LEVEL(CONFIG_GDBSTUB_IRQ_LEVEL);
tmp = XIRQxICR(GDBPORT_SERIAL_IRQ);
GDBPORT_SERIAL_IER = UART_IER_RDI | UART_IER_RLSI;
/* permit level 0 IRQs to take place */
arch_local_change_intr_mask_level(
NUM2EPSW_IM(CONFIG_GDBSTUB_IRQ_LEVEL + 1));
}
/*
* set up the GDB stub serial port baud rate timers
*/
void gdbstub_io_set_baud(unsigned baud)
{
unsigned value;
u8 lcr;
value = 18432000 / 16 / baud;
lcr = GDBPORT_SERIAL_LCR;
GDBPORT_SERIAL_LCR |= UART_LCR_DLAB;
GDBPORT_SERIAL_DLL = value & 0xff;
GDBPORT_SERIAL_DLM = (value >> 8) & 0xff;
GDBPORT_SERIAL_LCR = lcr;
}
/*
* wait for a character to come from the debugger
*/
int gdbstub_io_rx_char(unsigned char *_ch, int nonblock)
{
unsigned ix;
u8 ch, st;
#if defined(CONFIG_MN10300_WD_TIMER)
int cpu;
#endif
*_ch = 0xff;
if (gdbstub_rx_unget) {
*_ch = gdbstub_rx_unget;
gdbstub_rx_unget = 0;
return 0;
}
try_again:
/* pull chars out of the buffer */
ix = gdbstub_rx_outp;
barrier();
if (ix == gdbstub_rx_inp) {
if (nonblock)
return -EAGAIN;
#ifdef CONFIG_MN10300_WD_TIMER
for (cpu = 0; cpu < NR_CPUS; cpu++)
watchdog_alert_counter[cpu] = 0;
#endif
goto try_again;
}
ch = gdbstub_rx_buffer[ix++];
st = gdbstub_rx_buffer[ix++];
barrier();
gdbstub_rx_outp = ix & 0x00000fff;
if (st & UART_LSR_BI) {
gdbstub_proto("### GDB Rx Break Detected ###\n");
return -EINTR;
} else if (st & (UART_LSR_FE | UART_LSR_OE | UART_LSR_PE)) {
gdbstub_proto("### GDB Rx Error (st=%02x) ###\n", st);
return -EIO;
} else {
gdbstub_proto("### GDB Rx %02x (st=%02x) ###\n", ch, st);
*_ch = ch & 0x7f;
return 0;
}
}
/*
* send a character to the debugger
*/
void gdbstub_io_tx_char(unsigned char ch)
{
FLOWCTL_SET(DTR);
LSR_WAIT_FOR(THRE);
/* FLOWCTL_WAIT_FOR(CTS); */
if (ch == 0x0a) {
GDBPORT_SERIAL_TX = 0x0d;
LSR_WAIT_FOR(THRE);
/* FLOWCTL_WAIT_FOR(CTS); */
}
GDBPORT_SERIAL_TX = ch;
FLOWCTL_CLEAR(DTR);
}
/*
* send a character to the debugger
*/
void gdbstub_io_tx_flush(void)
{
LSR_WAIT_FOR(TEMT);
LSR_WAIT_FOR(THRE);
FLOWCTL_CLEAR(DTR);
}
| gpl-2.0 |
buglabs/bug20-2.6.35-linaro | arch/frv/mb93090-mb00/flash.c | 12702 | 2338 | /* Flash mappings for the MB93090-MB00 motherboard
*
* Copyright (C) 2009 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#define MB93090_BOOTROM_ADDR 0xFF000000 /* Boot ROM */
#define MB93090_BOOTROM_SIZE (2 * 1024 * 1024)
#define MB93090_USERROM_ADDR 0xFF200000 /* User ROM */
#define MB93090_USERROM_SIZE (2 * 1024 * 1024)
/*
* default MTD partition table for both main flash devices, expected to be
* overridden by RedBoot
*/
static struct mtd_partition mb93090_partitions[] = {
{
.name = "Filesystem",
.size = MTDPART_SIZ_FULL,
.offset = 0,
}
};
/*
* Definition of the MB93090 Boot ROM (on the CPU card)
*/
static struct physmap_flash_data mb93090_bootrom_data = {
.width = 2,
.nr_parts = 2,
.parts = mb93090_partitions,
};
static struct resource mb93090_bootrom_resource = {
.start = MB93090_BOOTROM_ADDR,
.end = MB93090_BOOTROM_ADDR + MB93090_BOOTROM_SIZE - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device mb93090_bootrom = {
.name = "physmap-flash",
.id = 0,
.dev.platform_data = &mb93090_bootrom_data,
.num_resources = 1,
.resource = &mb93090_bootrom_resource,
};
/*
* Definition of the MB93090 User ROM definition (on the motherboard)
*/
static struct physmap_flash_data mb93090_userrom_data = {
.width = 2,
.nr_parts = 2,
.parts = mb93090_partitions,
};
static struct resource mb93090_userrom_resource = {
.start = MB93090_USERROM_ADDR,
.end = MB93090_USERROM_ADDR + MB93090_USERROM_SIZE - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device mb93090_userrom = {
.name = "physmap-flash",
.id = 1,
.dev.platform_data = &mb93090_userrom_data,
.num_resources = 1,
.resource = &mb93090_userrom_resource,
};
/*
* register the MB93090 flashes
*/
static int __init mb93090_mtd_init(void)
{
platform_device_register(&mb93090_bootrom);
platform_device_register(&mb93090_userrom);
return 0;
}
module_init(mb93090_mtd_init);
| gpl-2.0 |
ska/linux-fsl | arch/um/drivers/stdio_console.c | 159 | 4907 | /*
* Copyright (C) 2000, 2001 Jeff Dike (jdike@karaya.com)
* Licensed under the GPL
*/
#include <linux/posix_types.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/types.h>
#include <linux/major.h>
#include <linux/kdev_t.h>
#include <linux/console.h>
#include <linux/string.h>
#include <linux/sched.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/hardirq.h>
#include <asm/current.h>
#include <asm/irq.h>
#include "stdio_console.h"
#include "chan.h"
#include <irq_user.h>
#include "mconsole_kern.h"
#include <init.h>
#define MAX_TTYS (16)
static void stdio_announce(char *dev_name, int dev)
{
printk(KERN_INFO "Virtual console %d assigned device '%s'\n", dev,
dev_name);
}
/* Almost const, except that xterm_title may be changed in an initcall */
static struct chan_opts opts = {
.announce = stdio_announce,
.xterm_title = "Virtual Console #%d",
.raw = 1,
};
static int con_config(char *str, char **error_out);
static int con_get_config(char *dev, char *str, int size, char **error_out);
static int con_remove(int n, char **con_remove);
/* Const, except for .mc.list */
static struct line_driver driver = {
.name = "UML console",
.device_name = "tty",
.major = TTY_MAJOR,
.minor_start = 0,
.type = TTY_DRIVER_TYPE_CONSOLE,
.subtype = SYSTEM_TYPE_CONSOLE,
.read_irq = CONSOLE_IRQ,
.read_irq_name = "console",
.write_irq = CONSOLE_WRITE_IRQ,
.write_irq_name = "console-write",
.mc = {
.list = LIST_HEAD_INIT(driver.mc.list),
.name = "con",
.config = con_config,
.get_config = con_get_config,
.id = line_id,
.remove = con_remove,
},
};
/* The array is initialized by line_init, at initcall time. The
* elements are locked individually as needed.
*/
static char *vt_conf[MAX_TTYS];
static char *def_conf;
static struct line vts[MAX_TTYS];
static int con_config(char *str, char **error_out)
{
return line_config(vts, ARRAY_SIZE(vts), str, &opts, error_out);
}
static int con_get_config(char *dev, char *str, int size, char **error_out)
{
return line_get_config(dev, vts, ARRAY_SIZE(vts), str, size, error_out);
}
static int con_remove(int n, char **error_out)
{
return line_remove(vts, ARRAY_SIZE(vts), n, error_out);
}
/* Set in an initcall, checked in an exitcall */
static int con_init_done = 0;
static int con_install(struct tty_driver *driver, struct tty_struct *tty)
{
return line_install(driver, tty, &vts[tty->index]);
}
static const struct tty_operations console_ops = {
.open = line_open,
.install = con_install,
.close = line_close,
.write = line_write,
.put_char = line_put_char,
.write_room = line_write_room,
.chars_in_buffer = line_chars_in_buffer,
.flush_buffer = line_flush_buffer,
.flush_chars = line_flush_chars,
.set_termios = line_set_termios,
.throttle = line_throttle,
.unthrottle = line_unthrottle,
.cleanup = line_cleanup,
.hangup = line_hangup,
};
static void uml_console_write(struct console *console, const char *string,
unsigned len)
{
struct line *line = &vts[console->index];
unsigned long flags;
spin_lock_irqsave(&line->lock, flags);
console_write_chan(line->chan_out, string, len);
spin_unlock_irqrestore(&line->lock, flags);
}
static struct tty_driver *uml_console_device(struct console *c, int *index)
{
*index = c->index;
return driver.driver;
}
static int uml_console_setup(struct console *co, char *options)
{
struct line *line = &vts[co->index];
return console_open_chan(line, co);
}
/* No locking for register_console call - relies on single-threaded initcalls */
static struct console stdiocons = {
.name = "tty",
.write = uml_console_write,
.device = uml_console_device,
.setup = uml_console_setup,
.flags = CON_PRINTBUFFER|CON_ANYTIME,
.index = -1,
};
static int stdio_init(void)
{
char *new_title;
int err;
int i;
err = register_lines(&driver, &console_ops, vts,
ARRAY_SIZE(vts));
if (err)
return err;
printk(KERN_INFO "Initialized stdio console driver\n");
new_title = add_xterm_umid(opts.xterm_title);
if(new_title != NULL)
opts.xterm_title = new_title;
for (i = 0; i < MAX_TTYS; i++) {
char *error;
char *s = vt_conf[i];
if (!s)
s = def_conf;
if (!s)
s = i ? CONFIG_CON_CHAN : CONFIG_CON_ZERO_CHAN;
if (setup_one_line(vts, i, s, &opts, &error))
printk(KERN_ERR "setup_one_line failed for "
"device %d : %s\n", i, error);
}
con_init_done = 1;
register_console(&stdiocons);
return 0;
}
late_initcall(stdio_init);
static void console_exit(void)
{
if (!con_init_done)
return;
close_lines(vts, ARRAY_SIZE(vts));
}
__uml_exitcall(console_exit);
static int console_chan_setup(char *str)
{
line_setup(vt_conf, MAX_TTYS, &def_conf, str, "console");
return 1;
}
__setup("con", console_chan_setup);
__channel_help(console_chan_setup, "con");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.